Programmatic Web Search – Screen scraping – Web Page Input

To open a web page

Dim process3 As New Process
process3.StartInfo.FileName = Webpage
process3.Start()

To open a google search

use following plus search words separated by +

http://www.google.co.uk/search?q=

To read web page source – for screen scraping


Public Sub ReadWebPageSource()

Dim request As WebRequest = WebRequest.Create(Me.WebPage)
‘ If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials
‘request.Timeout = 3000

Try
‘ Get the response.
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
‘ Display the status.
‘Console.WriteLine(response.StatusDescription)
‘ Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
‘ Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
‘ Read the content.
Me.Source = reader.ReadToEnd()
‘ Display the content.
‘Console.WriteLine(responseFromServer)

‘ Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()

Catch ex As Exception
Me.Source = “”
MsgBox(ex.Message)
End Try

End Sub

WebBrowser and Set Inner Text

tag id=”lst-ib” is Googles search text box

WebBrowser1.Navigate(“http://www.google.co.uk“)
WebBrowser1.Document.GetElementById(“lst-ib”).InnerText = InnerTextTextBox.Text
WebBrowser1.Document.GetElementById(“lst-ib”).Focus()

VB.Net programming of SQL Server Replication

The article http://msdn.microsoft.com/en-us/library/ms146869.aspx suggests that Microsoft.SQLServer.Replication.dll is in the .Net references. For me it was not, it could however be found at:
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies

Also needed:

  1. Microsoft.SQLServer.Rmo
  2. Microsoft.SQLServer.Replication
  3. Microsoft.SQLServer.Replication.BusinessLogicSupport
  4. Microsoft.SQLServer.ConnectionInfo

Reading Command line arguments in VB.NET

Nice clear entry at:

http://forum.codecall.net/visual-basic-tutorials/16661-reading-command-line-arguments-visual-basic-net.html

In Project > My Project > Publish > Options > Deployment
Uncheck “Use “.deploy” file extension

Now after publishing you will get the .exe file. If you create a shortcut to this .exe file you can add command line arguments to it as shown in the image below:

 Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs

 

For i As Integer = 0 To CommandLineArgs.Count - 1
     MessageBox.Show(CommandLineArgs(i))
Next

There maybe reasons why you may not want to uncheck this. Namely:

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(MICROSOFT.VISUALSTUDIO.PUBLISH.CLICKONCEPROVIDER.DIALOG.OPTIONS);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22)&rd=true

 

VS Bug on FormClosing datagridviewcomboboxcell value is not valid

Error message may be “Field called xxx does not exist”

Try this on Form closing

Private Sub frm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Me.MyGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
End Sub

I would hazard to suggest thatVisual Studio does not dispose of the datagridview in the correct sequence

This sometimes occurs when my personal code > SetUpDataGridView may programmatically set the AutoSizeRowsMode.

—–

This link http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/88c3adee-ed2a-41ee-9407-c3314588e08a/
Suggests it may be something to do with autosize, when there is a combobox created. The order of creation and setting may be important.

“If you autosize the column but have not provided the combo box column with a valid datasource or you haven’t yet added items to the combo box column’s items collection then you’ll get this error at startup because autosizing requires the cell’s FormattedValue to be requested. Requesting the FormattedValue of a combo box cell is where the check is done that may raise the data error exception you are seeing.

Set the autosize mode after you fill the combo box and things should be ok.

Mark Rideout – DataGridView Program Manager – Microsoft”

Or create the comboboxcolumn then clear the autosize modes > run > re-set the autosize mode.
Or programattically set the autosize after form has designer InitialiseComponent code has loaded.

How to use windows api in VB.Net


'Imports System.Runtime.InteropServices

'Public Class aClass
' Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
' End Function
' Private Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
' End Function
'End Class

How to Open a Process and Send Keys to that Process ( e.g. MS Word )

Following works fine opens document, ctrl + g = go to in word, book mark “StockControl”

Dim process1 As New Process
process1.StartInfo.FileName = String.Concat(My.Settings.DocumentationDirectory, My.Settings.HelpWordFile)
process1.Start()
process1.WaitForInputIdle()
'Dim hwnd = process.MainWindowHandle
Threading.Thread.Sleep(1000)
SendKeys.Send("^g")
SendKeys.Send("+{TAB}")
SendKeys.Send("b")
SendKeys.Send("{TAB}")
SendKeys.Send("StockControl")
SendKeys.Send("{ENTER}")
SendKeys.Send("{ESC}")

LINQ and Entity Framework binding to ComboBox and DataGridViewComboBox

Private context As BC.SWT.EntityModel.SOPEntities

Private Sub LoadLookupData()

Try

    Dim EntityConnectionString = Configuration.ConfigurationManager.ConnectionStrings(“SOPEntities”).ConnectionString
    context = New BC.SWT.EntityModel.SOPEntities(EntityConnectionString)

    Dim CustomerQuery As ObjectQuery(Of Customer) = context.Customers
    ‘CustomerIDComboBox.DataSource = CustomerQuery.Execute(MergeOption.AppendOnly) ‘works but includes all columns
    Dim results = From a In CustomerQuery Select a.CustomerID, a.Customer1 Order By Customer1
    CustomerIDComboBox.DataSource = results
    CustomerIDComboBox.DisplayMember = “Customer1”

    CustomerIDDataGridViewComboBoxColumn.DataSource = results.ToList
    CustomerIDDataGridViewComboBoxColumn.DisplayMember = “Customer1”
    CustomerIDDataGridViewComboBoxColumn.ValueMember = “CustomerID”
    CustomerIDDataGridViewComboBoxColumn.DataPropertyName = “CustomerID”

Catch ex As Exception
    MessageBox.Show(ex.Message, Me.Text)
End Try

End Sub

XML. Get from SQL. Dataset.ReadXML(filePath) Publish

How do I get XML data from an SQL Select statement

SELECT [ID],[Name],[Notes],[Example],[DateInput] FROM [SystemDesign].[dbo].[Connections]
FOR XML PATH(‘Connection’), ROOT(‘Connections’)

The output could be copied into a new XML file in Visual Studio

How do I read XML data into a DataSet

Dim filePath = String.Concat(My.Application.Info.DirectoryPath, “\XMLData\Connections.xml”)
Dim filePathSchema = String.Concat(My.Application.Info.DirectoryPath, “\XMLData\Connections.xsd”)
Using ds As New DataSet
ds.ReadXmlSchema(filePathSchema)
ds.ReadXml(filePath)
Me.dsObjectControl1.Connections.Merge(ds.Tables(0))
End Using

How do I distribute and Publish the MyFile.xml and MyFile.xsd

Make sure that on the properties of both these files that:
“Build Action” = “Content”
“Copy to Output Directory” is “Copy if Newer” or “Copy Always”
On Project > Properties > Publish > Application Files > Find <FileName>.xml file and set Publish Status to “Include”

What other considerations are there?

Dataset.ReadXMLSchema(filepath) normally first
Otherwise Dataset.ReadXML will return a table, but the columns are probably of the wrong datatype
So in the above example, the merge will not work because the strongly type dsObjectControl.Connections uses a proper schema.

For the same reason if you hard-code bind the newly created ds.Tables(0) to a bindingsource, this may not work if the schema is important.

How do I get an xsd file?

There is a tool in Visual Studio on Add new item > Data > XML to Schema

How do I validate my xml file against a xsd file?

Possible by adding . See Toolkit.sln. Also links here:
http://msdn.microsoft.com/en-us/library/ms759142(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms757051(v=VS.85).aspx

How do I get my new dataset to hold the schema from the xml file

TODO currently only by using the Dataset.ReadXMLSchema(filepath) as listed above. It does not get it right on it’s own.

How do I convert my xsd file into a dataset

Was able to do this, mostly by opening it. Also by adding the Custom Tool.

Set ComboBox to an item when bound to objects

Use Object.Equals.
Then set the combobox selecteditem to a new instance of the object with the required ID or other.
Sample Equals

Public Overrides Function Equals(obj As Object) As Boolean
    If obj Is Nothing Then
        Return False
    End If
    Return CType(obj, Customer).ID = Me.ID
End Function

Deleted row information cannot be accessed through the row. Including with Lambda functions.

Error message
Deleted row information cannot be accessed through the row.
This may occur when using Lambda functions and in other scenarios as well.

Problem
Dim dtTotal = dsBusiness1.InvoiceDetail.Where(Function(r1) r1.InvoiceNo = cInvoice.InvoiceNo AndAlso r1.RowState <> DataRowState.Deleted)

Solution 1
Dim dtTotal = dsBusiness1.InvoiceDetail.Where(Function(r1) r1.RowState <> DataRowState.Deleted AndAlso r1.InvoiceNo = cInvoice.InvoiceNo)

Solution 2
Use AcceptChanges on datatable to force deletions to clear

Try

Me.MyBindingSource.RemoveCurrent()
Me.MyBindingSource.EndEdit()
Me.ds1.MyTable.AcceptChanges()

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try