64 Bit Detection

22. May 2012 17:53

 

I’ve used this code on a few projects which needed to know if they were running on a 64 bit host.

 

  Private Shared Function Is64BitOs() As Boolean
        If IntPtr.Size = 8 Or (IntPtr.Size = 4 And Is32BitProcessOn64BitProcessor()) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Shared Function Is32BitProcessOn64BitProcessor() As Boolean
        Dim retVal As Boolean = False
        Try
            ' clear any exising error
            SetLastErrorEx(0, 0)
            If IsWow64Process(Process.GetCurrentProcess.Handle, retVal) Then
                Return retVal
            Else
                ' function call failed
                Throw New Exception(String.Format("IsWow64Process failed, lastError = {0}", Marshal.GetLastWin32Error))
            End If
        Catch ex As Exception
            Throw
        End Try
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True, CallingConvention:=CallingConvention.Winapi)> _
    Private Shared Function IsWow64Process( _
                    ByVal hProcess As IntPtr, _
                    ByRef wow64Process As Boolean) As <MarshalAs(UnmanagedType.Bool)> Boolean

    End Function

    <DllImport("user32.dll")> _
    Private Shared Sub SetLastErrorEx(ByVal dwErrCode As UInteger, ByVal dwType As UInteger)
    End Sub

Initialize Object Instance From Dataset Using Reflection

14. April 2012 17:21

 

I was recently working on a project which has an existing legacy data access layer. The data access layer retrieves fifteen or so configuration and settings datatables which are then used throughout the system. There is a lot of code dealing with the dataset containing these tables retrieving a table, looping through the rows, etc. A decision was made to turn these tables into classes to reduce the effort of retrieving a single property as well as make the code more readable and easier to follow.

 

Creating the configuration classes is pretty straight forward. Populating them from the dataset also turned out to be pretty easy using reflection. But before going there, lets look at one less than ideal way to go about it. And stepping back just bit, here are a couple of simple example configuration classes used in the examples.

 

Public Class Square

    Public Property SideLength As Double

    Public Property FillColor As String

    Public Overrides Function ToString() As String
        Return String.Format("Square SideLength:{0}, FillColor:{1}", Me.SideLength, Me.FillColor)
    End Function

End Class

Public Class Circle

    Public Property RadiusLength As Double

    Public Property OutlineColor As String

    Public Overrides Function ToString() As String
        Return String.Format("Circle RadiusLength:{0}, OutlineColor:{1}", Me.RadiusLength, Me.OutlineColor)
    End Function

End Class

Now for a less than ideal way to populate the properties of a couple of instances of these classes from a dataset. In the below code, there is a basic loop through the data table and a case statement to set each property. In this simple example it isn’t a huge amount of code and hassle, but the real system has many more tables, with many more properties.

 

        Dim square As Square = New Square()
        Dim circle As Circle = New Circle()

        Dim ds As DataSet = CreateNameValueDataSet()

        For Each dr As DataRow In ds.Tables("Square").Rows
            Select Case dr("Name")
                Case "SideLength"
                    square.SideLength = CType(dr("Value"), Double)
                Case "FillColor"
                    square.FillColor = CType(dr("Value"), String)
                Case Else
                    Console.WriteLine("Unrecognized square property: {0}", dr("Name"))
            End Select
        Next

        For Each dr As DataRow In ds.Tables("Circle").Rows
            Select Case dr("Name")
                Case "RadiusLength"
                    circle.RadiusLength = CType(dr("Value"), Double)
                Case "OutlineColor"
                    circle.OutlineColor = CType(dr("Value"), String)
                Case Else
                    Console.WriteLine("Unrecognized circle property: {0}", dr("Name"))
            End Select
        Next

 

Now using a little reflection, the code is much simpler.

 

Dim square As Square = New Square()
Dim circle As Circle = New Circle()

Dim ds As DataSet = CreateNameValueDataSet()

PopulateInstanceFromDataTable(ds.Tables("Square"), square)

PopulateInstanceFromDataTable(ds.Tables("Circle"), circle)

And the PopulateInstanceFromDataTable is where the reflection fun comes in. The method uses the GetProperties method to retrieve the properties of the passed in type, and then assigns the value of the data row with a matching name to the property.

 

    Private Sub PopulateInstanceFromDataTable(dt As DataTable, ByRef nvInstance As Object)

        If dt Is Nothing Then Throw New ArgumentNullException("dt")

        Dim pi() As Reflection.PropertyInfo = 
nvInstance.GetType().GetProperties(Reflection.BindingFlags.DeclaredOnly 
Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)

        If dt.Columns.Contains("Name") AndAlso dt.Columns.Contains("Value") Then

            For Each dr As DataRow In dt.Rows

                If IsDBNull(dr("Name")) = False AndAlso IsDBNull(dr("Value")) = False Then

                    Dim propName As String = dr("Name")

                    For Each i As Reflection.PropertyInfo In pi

                        If i.Name.Equals(propName, StringComparison.InvariantCultureIgnoreCase) Then

                            ' todo deal with other expected types here
                            If i.PropertyType.Equals(GetType(Double)) Then
                                i.SetValue(nvInstance, Double.Parse(dr("Value")), Nothing)
                            Else
                                i.SetValue(nvInstance, dr("Value"), Nothing)
                            End If

                            Exit For

                        End If

                    Next

                End If

            Next

        End If

    End Sub

This function (one very similar) to it saved me a bunch of time and code to solve the problem of populating all of the configuration classes from the dataset.

About the author

I'm a .NET developer, a husband and a father of three beautiful girls.

Month List