Visual Basic Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘method’

PRB: “System.Messaging.MessageQueueException” Error Message When You Run the MessageQueue.Send Method MSDN Sample Code or When You Run the MessageQueue.Receive Method MSDN Sample Code

Symptoms
When you run the sample code that appears on certain Microsoft Developer Network (MSDN) Web sites, you may receive the following error message:

An unhandled exception of type ‘System.Messaging.MessageQueueException’ occurred in system.messaging.dll
Additional information: External component has thrown an exception.The following MSDN Web sites are affected:
MessageQueue.Send Method
http://msdn2.microsoft.com/en-us/library/system.messaging.messagequeue.send(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/system.messaging.messagequeue.send(vs.71).aspx)
MessageQueue.Send Method (Object)
http://msdn2.microsoft.com/en-us/library/aa329510(VS.71).aspx(http://msdn2.microsoft.com/en-us/library/aa329510(VS.71).aspx)
MessageQueue.Send Method (Object, MessageQueueTransaction)
http://msdn2.microsoft.com/en-us/library/aa329511(VS.71).aspx(http://msdn2.microsoft.com/en-us/library/aa329511(VS.71).aspx)
MessageQueue.Receive Method
http://msdn2.microsoft.com/en-us/library/system.messaging.messagequeue.receive(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/system.messaging.messagequeue.receive(vs.71).aspx)
MessageQueue.Receive Method (MessageQueueTransaction)
http://msdn2.microsoft.com/en-us/library/aa329505(VS.71).aspx(http://msdn2.microsoft.com/en-us/library/aa329505(VS.71).aspx)
MessageQueue.Receive Method (TimeSpan, MessageQueueTransaction)
http://msdn2.microsoft.com/en-us/library/aa329508(VS.71).aspx(http://msdn2.microsoft.com/en-us/library/aa329508(VS.71).aspx)
Resolution
The sample code that appears on these MSDN Web sites contains the following code that may cause you to receive the System.Messaging.MessageQueueException error message.
Microsoft Visual Basic .NET

myQueue.Send(“My Message Data.”, New _MessageQueueTransaction())Microsoft Visual C# .NET

myQueue.Send(“My Message Data.”, newMessageQueueTransaction());Microsoft Visual C++ .NET

myQueue->Send(S”My Message Data.”, new MessageQueueTransaction());You receive the error message because the call to the myQueue.Send method uses a MessageQueueTransaction object without starting a transaction. Additionally, even if you start a transaction before calling the myQueue.Send method, your application may wait indefinitely to receive the sent message. However, your application does not receive a sent message unless the corresponding transaction is committed.
Note The MessageQueue.Send(Object, MessageQueueTransaction) method applies only to transactional queues. Therefore, you receive the error message that is mentioned in the “Symptoms” sectiononly if you use transactional queues.

How to implement the Dispose method in a derived class in Visual Basic .NET or in Visual Basic 2005

Symptoms
When you author a class that extends a base class, you need to somehow handle the release of allocated resources. To do this, the Dispose method from the base class should be overridden in the derived classes.This article discusses common problems encountered in this scenario, how to properly override the Dispose method, and is meant to clarify some of the subtleties in the following Visual Basic .NET help article:
http://msdn2.microsoft.com/en-us/library/fs2xkftw(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/fs2xkftw(vs.71).aspx) Refer to this Help document for detailed information about error handling and for general examples of the Dispose method.
Resolution
A base class needs to contain an overloaded set of Dispose methods.The first instance of the sample code that follows is a version without parameters, and the second instance accepts a Boolean parameter:

‘Method that is called by Public to ensure TRUE is passed to DisposePublic Overloads Notoverridable Sub Dispose()Dispose( TRUE )’ Take yourself off of the finalization queue.GC.SuppressFinalize(Me)End Sub’Method that does the actual disposal of resourcesProtected Overloads Overridable Sub Dispose(ByVal disposing As Boolean)’Clean Up ResourcesEnd Sub
Dispose() is the method that is called when an object is disposed of in the code in which the object was created. This is a Public method, and therefore it can be used when an instance of the class exists.The Dispose() method then calls the Dispose(Boolean) method and passes a value of TRUE. The Dispose(Boolean) method is responsible for cleaning up the resources of the class.
When a class is derived from a base class, only the Dispose(Boolean) method needs to be overridden. All resource-cleanup for the derived class will be performed in this overridden method, and then the Dispose(Boolean) method for the base class is called. The following is a primitive example of the function overriding the base class:

Protected Overloads Overrides Sub Dispose(disposing As Boolean)’Clean Up ResourcesMyBase.Dispose( disposing )End Sub The derived class does not need a Dispose() method, because that method is inherited from the base class. When Dispose() is called on an instance of the derived class, Dispose() uses the Dispose(Boolean) of the derived class rather than the one in the base class. It is then important that the Dispose(Boolean) method of the derived class calls the Dispose(Boolean) method of the base class. This is done by means of the MyBase.Dispose(disposing) method. The Dispose(Boolean) method for the base class must be called to ensure that the resources of the base class are also disposed of.
Dispose() is meant as an entry point for public access to the disposal of an object and to ensure that TRUE is passed to the Dispose(Boolean) method. FALSE should be passed only when the Dispose(Boolean) method is called by the runtime or Finalize method. When FALSE is passed, only the unmanaged resources will be disposed. When TRUE is passed, both the managed and unmanaged resources are disposed.
The Visual Studio Development Environment inserts the code to override the Dispose() method into a class that inherits a system object (for example, Inherits System.Windows.Forms.TextBox). This is performed from the menus (at the top of the code window, by default) by selecting Overrides and then clicking Dispose(). The code that is inserted looks something like the following:

Public Overloads Overrides Sub Dispose()’Clean Up ResourcesEnd Sub If this is done, no compile errors are raised. However, when the derived class is loaded at runtime, you receive a runtime error message similar to the following:

An unhandled exception of type ‘System.TypeLoadException’ occurred in system.windows.forms.dll.
Additional information: Declaration referenced in a method implementation can not be a final method. Type: ClassLibrary1.UserControl1. Assembly: Dispose.NOTE: The Type value will be different from that in the preceding example. That is merely the name of the class that attempted to use an improperly overridden Dispose() method.
To correct this issue, just overload the Dispose(Boolean) method instead of Dispose(), and make sure that a call is made to the Dispose(Boolean) method of the base class and that TRUE is passed to it.
NOTE: In Visual Basic .NET or in Visual Basic 2005, the Overridable keyword is used like the Virtual keyword in C# and C++.Methods are, by default, NotOverridable.

How to enumerate the running processes of an application by using Visual Basic .NET or Visual Basic 2005

Symptoms
A process is the running instance of an application. A thread is the basicunit of a process. To retrieve information that corresponds to processes that are running on a local computer or on a remote computer, use the following methods:The GetProcesses() method retrieves information aboutthe processes that are running on a local computer. This method creates an array of process components and then associates the processesthat are running with these process components. The GetProcesses() method never returns an empty array.The GetProcesses(String) method retrieves information about the processes that are running on a local computer or on a remote computer. You must pass the computer name or the computer Internet Protocol(IP) address to the GetProcesses(String) method to retrieve the processes that are running on a remote computer. Also, you must have administrative rights on theremote computer to retrieve the processes that are running on that computer.
Resolution
This step-by-step article describes how to enumerate running instances of applications by using Microsoft Visual Basic .NET.

RequirementsThis article assumes that you are familiar with the following topics: Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 programming
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003. Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, or Microsoft Visual Studio 2005.
Process definitionA process is the running instance of an application. A thread is the basic unit of a process. The operating system allocates processor time to a thread so that thethread can run any part of the process code. A process can create one or more threads to run any part of the code that is associated with the process.
You can use a process component to start, to stop, to control, and to monitor a process. You can use aprocess component to obtain the list of processes that are running on a computer. After you initialize a process component, you can obtain informationabout the set of threads, about the loaded modules, and about the performance forall the running processes. You can also obtain information about processes that are running on a remote computer.

The GetProcesses methodYou can use the GetProcesses method to obtain information about the processes that are running on local computers and on remote computers. This method creates an array of new process components and then associates these components with the existing process resources. The two overloaded versions of this method are as follows:The GetProcesses() method
The GetProcesses() method creates an array of new process components and associates the components with all the process resources that are on the local computer. The process resources must already exist on the local computer. This method does not create process resources. Instead, this method associates existing resources with application-generated process components. Because the operating system itself is constantly running background processes, this array is never empty.The GetProcesses(String) method
The GetProcesses(String) method accepts a string as a parameter. Typically, the string is the computer name or the IP address of a remote computer. However, you can pass a period (.) to this method to retrieve the list of processes that are running on your local computer. To retrieve information about the processes that are running on a remote computer, you must have administrative rights to map a network drive to a folder on the remote computer.
Step-by-step sampleNote You must have administrative rights on the remote computer to follow these steps.Start Visual Studio .NET or Visual Studio 2005.On the File menu, point to New, and then click Project.
The New Project dialog box appears.Under Project Types, click Visual Basic Projects.
Note In Visual Studio 2005, clickVisual Basic under Project Types. Under Templates, click Windows Application.In the Name box,type ProcessInfo, and then click OK.
By default, the Form1.vb file is created.Replace the existing code in the Form1.vb file with the following code:

Option Strict OnPublic Class Form1Inherits System.Windows.Forms.Form#Region ” Windows Form Designer generated code “Public Sub New()MyBase.New()’The Windows Form Designer requires this call.InitializeComponent()’Add any initialization after the InitializeComponent() call.End Sub’Form overrides dispose to clean up the component list.Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)If disposing ThenIf Not (components Is Nothing) Thencomponents.Dispose()End IfEnd IfMyBase.Dispose(disposing)End Sub’Required by the Windows Form Designer.Private components As System.ComponentModel.IContainer’NOTE: The Windows Form Designer requires the following procedure.’It can be modified by using the Windows Form Designer.’Do not modify the procedure by using the Code editor.Friend WithEvents Button1 As System.Windows.Forms.ButtonFriend WithEvents TextBox1 As System.Windows.Forms.TextBoxFriend WithEvents Label1 As System.Windows.Forms.LabelFriend WithEvents ListView1 As System.Windows.Forms.ListViewFriend WithEvents Button2 As System.Windows.Forms.ButtonFriend WithEvents process1 As System.Windows.Forms.ColumnHeaderFriend WithEvents Process2 As System.Windows.Forms.ColumnHeaderFriend WithEvents PageMemorySize As System.Windows.Forms.ColumnHeader<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()Me.Button1 = New System.Windows.Forms.Button()Me.TextBox1 = New System.Windows.Forms.TextBox()Me.Label1 = New System.Windows.Forms.Label()Me.ListView1 = New System.Windows.Forms.ListView()Me.Button2 = New System.Windows.Forms.Button()Me.SuspendLayout()”Button1′Me.Button1.Location = New System.Drawing.Point(8, 368)Me.Button1.Name = “Button1″Me.Button1.Size = New System.Drawing.Size(72, 32)Me.Button1.TabIndex = 1Me.Button1.Text = “Get Processes””TextBox1′Me.TextBox1.Location = New System.Drawing.Point(272, 368)Me.TextBox1.Name = “TextBox1″Me.TextBox1.Size = New System.Drawing.Size(160, 20)Me.TextBox1.TabIndex = 5Me.TextBox1.Text = “””Label1′Me.Label1.Location = New System.Drawing.Point(160, 376)Me.Label1.Name = “Label1″Me.Label1.Size = New System.Drawing.Size(112, 23)Me.Label1.TabIndex = 7Me.Label1.Text = “Remote Computer IP””ListView1′Me.ListView1.ImeMode = System.Windows.Forms.ImeMode.OnMe.ListView1.Location = New System.Drawing.Point(32, 32)Me.ListView1.Name = “ListView1″Me.ListView1.Size = New System.Drawing.Size(360, 288)Me.ListView1.TabIndex = 8Me.ListView1.View = System.Windows.Forms.View.DetailsMe.ListView1.Columns.Add(“Process”, 100, HorizontalAlignment.Left)Me.ListView1.Columns.Add(“ProcessID”, 150, HorizontalAlignment.Left)Me.ListView1.Columns.Add(“Page Memory Size”, 110, HorizontalAlignment.Left)”Button2′Me.Button2.Location = New System.Drawing.Point(88, 368)Me.Button2.Name = “Button2″Me.Button2.Size = New System.Drawing.Size(64, 32)Me.Button2.TabIndex = 9Me.Button2.Text = “Clear””Form1′Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)Me.ClientSize = New System.Drawing.Size(440, 422)Me.Controls.Add(Me.Button2)Me.Controls.Add(Me.ListView1)Me.Controls.Add(Me.Label1)Me.Controls.Add(Me.TextBox1)Me.Controls.Add(Me.Button1)Me.Name = “Form1″Me.Text = “Form1″Me.ResumeLayout(False)End Sub#End RegionDim Processes As Process()Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickTryDim myprocess As ProcessDim compName As String = TextBox1.TextIf compName = “.” ThenProcesses = process.GetProcesses()ElseProcesses = process.GetProcesses(compName)End IfDim proclength As IntegerFor proclength = 0 To Processes.Length – 1myprocess = Processes(proclength)Dim process(2) As Stringprocess(0) = myprocess.ProcessNameprocess(1) = myprocess.Id.ToString()process(2) = myprocess.PagedMemorySize.ToString()Dim process_Listview As ListViewItem = New ListViewItem(process)ListView1.Items.Add(process_Listview)NextCatch ex As ExceptionMessageBox.Show(ex.Message())End TryEnd SubPrivate Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.ClickListView1.Items.Clear()End SubEnd ClassNote You must change the code in Visual Basic 2005. By default, Visual Basic creates two files for the project when you create a Windows Forms project. If the form is named Form1, the two files that represent the form are named Form1.vb and Form1.Designer.vb. You write the code in the Form1.vb file. The Windows Forms Designer writes the code in the Form1.Designer.vb file. The Windows Forms Designer uses the partial keyword to divide the implementation of Form1 into two separate files. This behavior prevents the designer-generated code from being interspersed with your code.
For more information about the new Visual Basic 2005 language enhancements, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx(http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx)For more information about partial classes and the Windows Forms Designer, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/ms171843.aspx(http://msdn2.microsoft.com/en-us/library/ms171843.aspx)On the Build menu, click Build Solution.Switch to Visual Studio .NET or Visual Studio 2005, and then press F5 to run your application.
The Form1 Windows form appears.Click Get Processes.
Notice the list of processes that are running on your local computer.Click Clear.In the Remote Computer IP box, type the IP address of the remote computer, and then click Get Processes. You will get the processes that are running on the remote computer.

BUG: RestoreToolbar Method May Not Restore Toolbar Correctly

Symptoms
When you use the RestoreToolbar method to restore a Toolbar that was savedwith the SaveToolbar method after a user customized the Toolbar it does notrestore correctly.
Resolution
Make sure all buttons use an image. You can create a 16×16 (pixel) bitmapand set the Mask Property of an ImageList control so the user does not seethe image. Use a Timer control to restore a Toolbar when a form loads.

BUG: Error Message “Rows Must Be Released” with SQLOLEDB and ADO Recordset Events

Symptoms
If a user opens an ActiveX Data Object (ADO) recordset by using the OLE DB Provider for SQL Server, sets the CursorLocation property to adUseServer, uses the WithEvents keyword, updates the same record more than once, and then executes a Move method such as MoveNext, the following error message appears
in MDAC versions 2.5 and later:

80040e25: Row handles must be released before new ones can be obtainedin prior MDAC versions:

All HROWs must be released before new ones can be obtained
Resolution
This error message can be avoided in one of the following ways:Using a CursorLocation property of adUseClient.
-or-
Implementing code that moves off the changed record after each Update (for example, a MoveNext and MovePrevious method pair).
-or-
Executing the Requery method of the Recordset after each Update.

BUG: “InvalidOperationException” error message occurs when you consume a Web Service with an Out parameter

Symptoms
You can use Visual C# .NET to create a Web Service that has a Web Service method with an Out parameter. The Out parameter may appear before the In parameter or the Ref parameter. You must specify the SoapRpcMethodAttribute to the Web Service method to preserve the order of the parameters. The problem occurs when you subsequently use this Web service that you created in Visual C# .NET in a Visual Basic .NET application. You may receive the following error message when you call the Web Service method.

An unhandled exception of type ‘System.InvalidOperationException’ occurred in system.xml.dll
Additional information: There was an error generating the XML document.

Resolution
If the Web Service method has an Out parameter, and you generate the proxy by using Visual Basic .NET, then the Out parameter is generated as a ByRef parameter. This occurs because Visual Basic .NET does not support Out parameters. The reflection code cannot differentiate between a real ByRef parameter and a ByRef parameter that corresponds to an Out parameter. In the proxy class, the actual call to the Web service is completed by using the Invoke method. In the Invoke method call, the Out parameter is missing. However, the generated serializer expects the parameter. Therefore, you receive the error.