Solved

VB .NET Problem

Posted on 2004-03-29
6
932 Views
Last Modified: 2012-06-21
I have converted a VB6 code to VB .NET with a help from some guy here, but the code gives me errors.

Search for "new code" in the following code to find the changed vb6 to vb .net code.
after running it gives me this error. Which is:
An unhandled exception of type 'System.InvalidCastException' occurred in TSQ.exe
Additional information: Specified cast is not valid.

Code:

Option Strict Off
Option Explicit On
Imports System.Runtime.InteropServices
Friend Class Form1
      Inherits System.Windows.Forms.Form
#Region "Windows Form Designer generated code "
      Public Sub New()
            MyBase.New()
            If m_vb6FormDefInstance Is Nothing Then
                  If m_InitializingDefInstance Then
                        m_vb6FormDefInstance = Me
                  Else
                        Try
                              'For the start-up form, the first instance created is the default instance.
                              If System.Reflection.Assembly.GetExecutingAssembly.EntryPoint.DeclaringType Is Me.GetType Then
                                    m_vb6FormDefInstance = Me
                              End If
                        Catch
                        End Try
                  End If
            End If
            'This call is required by the Windows Form Designer.
            InitializeComponent()
      End Sub
      'Form overrides dispose to clean up the component list.
      Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
            If Disposing Then
                  If Not components Is Nothing Then
                        components.Dispose()
                  End If
            End If
            MyBase.Dispose(Disposing)
      End Sub
      'Required by the Windows Form Designer
      Private components As System.ComponentModel.IContainer
      Public ToolTip1 As System.Windows.Forms.ToolTip
      Public WithEvents List1 As System.Windows.Forms.ListBox
      Public WithEvents Command1 As System.Windows.Forms.Button
      'NOTE: The following procedure is required by the Windows Form Designer
      'It can be modified using the Windows Form Designer.
      'Do not modify it using the code editor.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
            Me.components = New System.ComponentModel.Container()
            Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
            Me.ToolTip1.Active = True
            Me.List1 = New System.Windows.Forms.ListBox
            Me.Command1 = New System.Windows.Forms.Button
            Me.Text = "TSQ"
            Me.ClientSize = New System.Drawing.Size(424, 317)
            Me.Location = New System.Drawing.Point(4, 23)
            Me.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.BackColor = System.Drawing.SystemColors.Control
            Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable
            Me.ControlBox = True
            Me.Enabled = True
            Me.KeyPreview = False
            Me.MaximizeBox = True
            Me.MinimizeBox = True
            Me.Cursor = System.Windows.Forms.Cursors.Default
            Me.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.ShowInTaskbar = True
            Me.HelpButton = False
            Me.WindowState = System.Windows.Forms.FormWindowState.Normal
            Me.Name = "Form1"
            Me.List1.Size = New System.Drawing.Size(369, 202)
            Me.List1.Location = New System.Drawing.Point(24, 24)
            Me.List1.TabIndex = 1
            Me.List1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.List1.BackColor = System.Drawing.SystemColors.Window
            Me.List1.CausesValidation = True
            Me.List1.Enabled = True
            Me.List1.ForeColor = System.Drawing.SystemColors.WindowText
            Me.List1.IntegralHeight = True
            Me.List1.Cursor = System.Windows.Forms.Cursors.Default
            Me.List1.SelectionMode = System.Windows.Forms.SelectionMode.One
            Me.List1.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.List1.Sorted = False
            Me.List1.TabStop = True
            Me.List1.Visible = True
            Me.List1.MultiColumn = False
            Me.List1.Name = "List1"
            Me.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            Me.Command1.Text = "Command1"
            Me.Command1.Size = New System.Drawing.Size(97, 49)
            Me.Command1.Location = New System.Drawing.Point(8, 256)
            Me.Command1.TabIndex = 0
            Me.Command1.BackColor = System.Drawing.SystemColors.Control
            Me.Command1.CausesValidation = True
            Me.Command1.Enabled = True
            Me.Command1.ForeColor = System.Drawing.SystemColors.ControlText
            Me.Command1.Cursor = System.Windows.Forms.Cursors.Default
            Me.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.Command1.TabStop = True
            Me.Command1.Name = "Command1"
            Me.Controls.Add(List1)
            Me.Controls.Add(Command1)
      End Sub
#End Region
#Region "Upgrade Support "
      Private Shared m_vb6FormDefInstance As Form1
      Private Shared m_InitializingDefInstance As Boolean
      Public Shared Property DefInstance() As Form1
            Get
                  If m_vb6FormDefInstance Is Nothing OrElse m_vb6FormDefInstance.IsDisposed Then
                        m_InitializingDefInstance = True
                        m_vb6FormDefInstance = New Form1()
                        m_InitializingDefInstance = False
                  End If
                  DefInstance = m_vb6FormDefInstance
            End Get
            Set
                  m_vb6FormDefInstance = Value
            End Set
      End Property
#End Region
      
      Private Const WTS_CURRENT_SERVER_HANDLE As Short = 0
      
      Private Enum WTS_CONNECTSTATE_CLASS
            WTSActive
            WTSConnected
            WTSConnectQuery
            WTSShadow
            WTSDisconnected
            WTSIdle
            WTSListen
            WTSReset
            WTSDown
            WTSInit
      End Enum
      
      Private Structure WTS_SESSION_INFO
            Dim SessionID As Integer
            Dim pWinStationName As Integer
            Dim state As Form1.WTS_CONNECTSTATE_CLASS
      End Structure
      
      Private Declare Function WTSEnumerateSessions Lib "wtsapi32.dll"  Alias "WTSEnumerateSessionsA"(ByVal hServer As Integer, ByVal Reserved As Integer, ByVal Version As Integer, ByRef ppSessionInfo As Integer, ByRef pCount As Integer) As Integer
      
      Private Declare Sub WTSFreeMemory Lib "wtsapi32.dll" (ByVal pMemory As Integer)
      
      'UPGRADE_ISSUE: Declaring a parameter 'As Any' is not supported. Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1016"'
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef Destination As Object, ByRef Source As Object, ByVal length As Integer)
      
      Private Declare Function lstrlenA Lib "kernel32" (ByVal lpString As String) As Integer
      
      Private Declare Function lstrcpy Lib "kernel32"  Alias "lstrcpyA"(ByVal lpString1 As String, ByVal lpString2 As Integer) As Integer
      
      Private arrWTSSessions() As Form1.WTS_SESSION_INFO
      
      Private Function GetWTSSessions() As Form1.WTS_SESSION_INFO()
            Dim RetVal As Integer
            Dim lpBuffer As Integer
            Dim Count As Integer
            Dim p As Integer
            Dim arrSessionInfo() As Form1.WTS_SESSION_INFO
            
            RetVal = WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, lpBuffer, Count)
            If RetVal Then
                  ' WTSEnumerateProcesses was successful.
                  
                  p = lpBuffer
            ReDim arrSessionInfo(Count - 1)

            'Old code
                  'UPGRADE_ISSUE: LenB function is not supported. Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1040"'
                  'UPGRADE_WARNING: Couldn't resolve default property of object arrSessionInfo(). Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1037"'
            'CopyMemory(arrSessionInfo(0), p, Count * LenB(arrSessionInfo(0)))
            ' Free the memory buffer.

            'New code
            Dim p_objTarget As IntPtr
            p_objTarget = Marshal.AllocHGlobal(Marshal.SizeOf(arrSessionInfo(0)))
            CopyMemory(p_objTarget, p, Count * Marshal.SizeOf(arrSessionInfo(0)))
            Marshal.PtrToStructure(p_objTarget, arrSessionInfo(0))
            Marshal.FreeHGlobal(p_objTarget)


                  WTSFreeMemory(lpBuffer)
                  
            Else
                  ' Error occurred calling WTSEnumerateProcesses.
                  ' Check Err.LastDllError for error code.
                  MsgBox("An error occurred calling WTSEnumerateProcesses.  " & "Check the Platform SDK error codes in the MSDN Documentation " & "for more information.", MsgBoxStyle.Critical, "ERROR " & Err.LastDllError)
            End If
            GetWTSSessions = VB6.CopyArray(arrSessionInfo)
      End Function
      
      Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
            Dim i As Short
            
            arrWTSSessions = VB6.CopyArray(GetWTSSessions)
            For i = LBound(arrWTSSessions) To UBound(arrWTSSessions)
                  List1.Items.Add(("Session ID: " & arrWTSSessions(i).SessionID))
                  List1.Items.Add(("Machine Name: " & PointerToStringA(arrWTSSessions(i).pWinStationName)))
                  List1.Items.Add(("Connect State: " & arrWTSSessions(i).state))
                  List1.Items.Add(("***********"))
                  
                  
                  'Debug.Print "Session ID: " & arrWTSSessions(i).SessionID
                  'Debug.Print "Machine Name: " & PointerToStringA (arrWTSSessions(i).pWinStationName)
                  'Debug.Print "Connect State: " & arrWTSSessions(i).state
                  'Debug.Print "***********"
            Next i
      End Sub
      
      Public Function PointerToStringA(ByVal lpStringA As Integer) As String
            Dim nLen As Integer
            Dim sTemp As String
            
            If lpStringA Then
                  nLen = lstrlenA(CStr(lpStringA))
                  If nLen Then
                        sTemp = New String(vbNullChar, nLen)
                        lstrcpy(sTemp, lpStringA)
                        PointerToStringA = sTemp
                  End If
            End If
      End Function
End Class
0
Comment
Question by:MaKaVeLi_Da_DoN
  • 2
  • 2
6 Comments
 
LVL 14

Expert Comment

by:ptakja
ID: 10715599
Hard to tell off hand.  I would enable Option STRICT and then look at that section of code to see what the IDE ( I'm assuming you are using Visual Studio) underlines.  An invalid cast simply means that you are trying to use a variable in a method in which it can't be used.  In other words, if you are passing an Integer pointer into a function that expects a float pointer.  The compiler can't cast an integer into a float.
0
 
LVL 1

Author Comment

by:MaKaVeLi_Da_DoN
ID: 10721493
Ok
In the following piece of code i get the error.
The problem is that I am a beginner and i don't know what to do.

code:

            p_objTarget = Marshal.AllocHGlobal(Marshal.SizeOf(arrSessionInfo(0)))
            CopyMemory(p_objTarget, p, pCount * Marshal.SizeOf(arrSessionInfo(0)))
at "p_objTarget" I get - Option Strict On disallows implicit conversions from 'System.Object' to 'System.IntPtr'.
at "p" I get - Option Strict On disallows implicit conversions from 'System.Object' to 'Integer'.
            Marshal.PtrToStructure(p_objTarget, arrSessionInfo(0))
            Marshal.FreeHGlobal(p_objTarget)
            WTSFreeMemory(ppSessionInfo)
at "ppSessionInfo" - Option Strict On disallows implicit conversions from 'System.Object' to 'Integer'.

I don't know how to correct this and what "System.Object" is.
0
 
LVL 1

Author Comment

by:MaKaVeLi_Da_DoN
ID: 10721680
I am kind if stupid, you know.
I dind't noticed that "System.Object" is a type.
However when converting from object to integer the CopyMemory function fails, and I don't know why
0
 
LVL 14

Accepted Solution

by:
ptakja earned 250 total points
ID: 10723995
First off, you're not stupid because you can't figure this out on your own.  If you've never programmed in a very type-strict environment (like C++, for example), these kinds of errors can drive you insane.

Now, on to the problem at hand.  An implicit conversion is a data type conversion where the compiler is left to determine what data type it needs to convert a value from based on the arguments expected in the function or operation you are performing.

According to your code above, the CopyMemory function requires an Object.  It appears that your code is trying to pass it an Integer.  WIith option Strict enabled, implicit type conversions are not allowed.  You have to tell the complier how to convert the type.

So, try this:

CopyMemory(CType(p_objTarget, System.Object),  CType(p, System.Object),  pCount * Marshal.SizeOf(arrSessionInfo(0)))

Here we are telling the compiler (using the CType function) to convert the Integer into an Object)

Also, I am not familiar with the IntPtr data type.  Where did that come from?

System.Object is the base class for all .NET data types.  Everything in .NET eventually inherits from System.Object.  It is the most basic data type in the system.

Let me know if this helps.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem to setup 18 80
dividesSelf challange 15 81
listing all functions in JavaScript 19 114
Adoquery sql  left join does not work 25 50
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now