Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

Friday, May 18, 2012

Belgium eID Card Reader Application

A friend of mine, Tim, asked me to write up a simple application
that's able to read out the Belgium ID cards.

This is what I ended up with...
A few things you need to know:
  • Reference the Interop.EIDLIBCTRLLib.dll
  • Target the x86 platform (the dll only exists in a 32bit flavour)




























eID Reader Binaries
eID Reader Source Code

The actual eID Object : were all the “Magic” Happens…

Friend Class eIDObject

#Region "Events"

    Protected Friend Event Init_Failed()
    Protected Friend Event Exit_Failed()
    Protected Friend Event Finished_InfoRetrieval()

#End Region

#Region "Variables"

    Protected Friend ErrorMessage As String

    Private lHandle As Integer = Nothing
    Private Eidlib1 As New EIDLIBCTRLLib.EIDlib
    Private RetStatus As EIDLIBCTRLLib.RetStatus = Nothing
    Private MapColPicture As New EIDLIBCTRLLib.MapCollection
    Private MapColID As New EIDLIBCTRLLib.MapCollection
    Private MapColAddress As New EIDLIBCTRLLib.MapCollection
    Private CertifCheck As New EIDLIBCTRLLib.CertifCheck

#End Region

#Region "BEID Properties"

#Region "BEID Card Info"

    Private strCardNumber As String
    Protected Friend ReadOnly Property CardNumber() As String
        Get
            Return strCardNumber
        End Get
    End Property

    Private strChipNumber As String
    Protected Friend ReadOnly Property ChipNumber() As String
        Get
            Return strChipNumber
        End Get
    End Property

    Private strIssuingMunicipality As String
    Protected Friend ReadOnly Property IssuingMunicipality() As String
        Get
            Return strIssuingMunicipality
        End Get
    End Property

    'START DATE - INITIAL DATE
    Private dateBeginValidityDate As Date
    Protected Friend ReadOnly Property BeginValidityDate() As Date
        Get
            Return dateBeginValidityDate
        End Get
    End Property

    Private strBegVal As Object

    Private strBegValDag As String
    Protected Friend ReadOnly Property BeginValidityDay() As String
        Get
            Return strBegValDag
        End Get
    End Property

    Private strBegValMaand As String
    Protected Friend ReadOnly Property BeginValidityMonth() As String
        Get
            Return strBegValMaand
        End Get
    End Property

    Private strBegValJaar As String
    Protected Friend ReadOnly Property BeginValidityYear() As String
        Get
            Return strBegValJaar
        End Get
    End Property

    'END DATE - EXPIRE DATE
    Private dateEndValidityDate As Date
    Protected Friend ReadOnly Property EndValidityDate() As Date
        Get
            Return dateEndValidityDate
        End Get
    End Property

    Private strEndVal As Object
    Private strEndValDag As String
    Protected Friend ReadOnly Property EndValidityDay() As String
        Get
            Return strEndValDag
        End Get
    End Property

    Private strEndValMaand As String
    Protected Friend ReadOnly Property EndValidityMonth() As String
        Get
            Return strEndValMaand
        End Get
    End Property

    Private strEndValJaar As String
    Protected Friend ReadOnly Property EndValidityYear() As String
        Get
            Return strEndValJaar
        End Get
    End Property

#End Region

#Region "BEID Person Info"
    Private strName As String
    Protected Friend ReadOnly Property Name() As String
        Get
            Return strName
        End Get
    End Property

    Private strFirstName1 As String
    Protected Friend ReadOnly Property FirstName() As String
        Get
            Return strFirstName1
        End Get
    End Property

    Private strFirstName2 As String
    Protected Friend ReadOnly Property FirstName2() As String
        Get
            Return strFirstName2
        End Get
    End Property

    Private strBirthPlace As String
    Protected Friend ReadOnly Property BirthPlace() As String
        Get
            Return strBirthPlace
        End Get
    End Property

    Private strBirthDate As String
    Protected Friend ReadOnly Property BirthDate() As String
        Get
            Return strBirthDate
        End Get
    End Property

    Private strGender As String
    Protected Friend ReadOnly Property Gender() As String
        Get
            Return strGender
        End Get
    End Property

    Private strNationality As String
    Protected Friend ReadOnly Property Nationality() As String
        Get
            Return strNationality
        End Get
    End Property

    Private strNationalNumber As String
    Protected Friend ReadOnly Property NationalNumber() As String
        Get
            Return strNationalNumber
        End Get
    End Property
#End Region

#Region "BEID Adres Info"
    Private strStreet As String
    Protected Friend ReadOnly Property Street() As String
        Get
            Return strStreet
        End Get
    End Property

    Private strStreetNumber As String
    Protected Friend ReadOnly Property StreetNumber() As String
        Get
            Return strStreetNumber
        End Get
    End Property

    Private strZIPCode As String
    Protected Friend ReadOnly Property ZIPCode() As String
        Get
            Return strZIPCode
        End Get
    End Property

    Private strMunicipality As String
    Protected Friend ReadOnly Property Municipality() As String
        Get
            Return strMunicipality
        End Get
    End Property

#End Region

#Region "BEID Picture Info"

    Private imgPicture As Global.System.Drawing.Image
    Protected Friend ReadOnly Property Picture() As Global.System.Drawing.Image
        Get
            Return imgPicture
        End Get

    End Property

#End Region

#End Region

#Region "Constructor"

    Protected Friend Sub New()
    End Sub

#End Region

#Region "Methods"

    Private Function eID_Init() As Boolean
        Try
            RetStatus = Eidlib1.Init("", 0, 0, lHandle)
            If (RetStatus.GetGeneral = 0) Then
                Return True
            Else
                ErrorMessage = "Unable to initialize eID Reader!"
                RaiseEvent Init_Failed()
                Return False
            End If
        Catch ex As Exception
            ErrorMessage = "Unable to initialize eID Reader!" + vbCrLf + GetErrorInfo(ex)
            RaiseEvent Init_Failed()
            Return False
        End Try
    End Function

    Private Function eID_Exit() As Boolean
        Try
            RetStatus = Eidlib1.Exit()
            Return True
        Catch ex As Exception
            ErrorMessage = "Unable to exit eID Reader!" + vbCrLf + GetErrorInfo(ex)
            RaiseEvent Exit_Failed()
            Return False
        Finally
            'release all objects
            RetStatus = Nothing
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try
    End Function

    Protected Friend Function RetrieveInformation() As Boolean
        'reset errormessage
        ErrorMessage = ""
        Try
            If eID_Init() Then
                ' get the info stored on the Belgium eID card & populate the properties
                RetStatus = Eidlib1.GetID(MapColID, CertifCheck)

                'card
                strChipNumber = MapColID.GetValue("ChipNumber")
                strCardNumber = MapColID.GetValue("CardNumber")
                strBegVal = MapColID.GetValue("BeginValidityDate")
                strEndVal = MapColID.GetValue("EndValidityDate")
                strIssuingMunicipality = MapColID.GetValue("IssuingMunicipality")
                '        'Opsplitsen begindatum
                strBegValDag = Microsoft.VisualBasic.Right(strBegVal, 2)
                strBegValMaand = Microsoft.VisualBasic.Mid(strBegVal, 5, 2)
                strBegValJaar = Microsoft.VisualBasic.Left(strBegVal, 4)
                '        'Opsplitsen einddatum
                strEndValDag = Microsoft.VisualBasic.Right(strEndVal, 2)
                strEndValMaand = Microsoft.VisualBasic.Mid(strEndVal, 5, 2)
                strEndValJaar = Microsoft.VisualBasic.Left(strEndVal, 4)
                dateBeginValidityDate = CDate(strBegValDag & "/" & strBegValMaand & "/" & strBegValJaar)
                dateEndValidityDate = CDate(strEndValDag & "/" & strEndValMaand & "/" & strEndValJaar)
                'person
                strName = MapColID.GetValue("Name")
                strFirstName1 = MapColID.GetValue("FirstName1")
                strFirstName2 = MapColID.GetValue("FirstName2")
                strBirthDate = MapColID.GetValue("BirthDate")
                'transform birthdate
                Dim d As String = ""
                Dim m As String = ""
                Dim y As String = ""

                d = Microsoft.VisualBasic.Right(strBirthDate, 2)
                m = Microsoft.VisualBasic.Mid(strBirthDate, 5, 2)
                y = Microsoft.VisualBasic.Left(strBirthDate, 4)
                strBirthDate = CDate(d & "/" & m & "/" & y)
                strBirthPlace = MapColID.GetValue("BirthPlace")
                strGender = MapColID.GetValue("Gender")
                strNationality = UCase(MapColID.GetValue("Nationality"))
                strNationalNumber = MapColID.GetValue("NationalNumber")
                'address
                RetStatus = Eidlib1.GetAddress(MapColAddress, CertifCheck)
                strStreet = Trim(MapColAddress.GetValue("Street")) 'Neerhofstraat 26
                'get street number
                strStreetNumber = strStreet.Substring(strStreet.LastIndexOf(" ") + 1)
                'get street
                strStreet = strStreet.Substring(0, strStreet.LastIndexOf(" "))
                strZIPCode = MapColAddress.GetValue("ZIPCode")
                strMunicipality = MapColAddress.GetValue("Municipality")
                'get picture
                Dim s As IO.MemoryStream = Nothing
                Dim o() As Byte = Nothing
                Dim raw As EIDLIBCTRLLib.Raw = Nothing
                Try
                    Eidlib1.GetRawData(raw)
                    raw.GetPictureData(o)
                    s = New IO.MemoryStream(o)
                    imgPicture = Global.System.Drawing.Image.FromStream(s)
                    s.Dispose()
                    s = Nothing
                Catch ex As Exception
                    ErrorMessage = "Unable to retrieve picture from eID card!" + vbCrLf + GetErrorInfo(ex)
                Finally
                    If Not s Is Nothing Then
                        s.Dispose()
                        s = Nothing
                    End If
                End Try
            Else
                Return False
            End If
            Return True
        Catch ex As Exception
            ErrorMessage = "Unable to retrieve information from eID card!" + vbCrLf + GetErrorInfo(ex)
            Return False
        Finally
            eID_Exit()
            RaiseEvent Finished_InfoRetrieval()
        End Try
    End Function

    Protected Friend Function ExportInformationToFile(ByVal filename As String) As Boolean
        Dim txtwriter As IO.StreamWriter = Nothing
        Try
            If Not String.IsNullOrEmpty(filename) Then

                txtwriter = New IO.StreamWriter(filename)
                txtwriter.WriteLine("CARDNUMBER=" + Me.CardNumber)
                txtwriter.WriteLine("BEGINVALIDITY=" + Me.BeginValidityDate)
                txtwriter.WriteLine("ENDVALIDITY=" + Me.EndValidityDate)
                txtwriter.WriteLine("ISSUINGMUNICIPALITY=" + Me.IssuingMunicipality)
                txtwriter.WriteLine("FIRSTNAME=" + Me.FirstName + IIf(Me.FirstName2 = "", "", " " + Me.FirstName2))
                txtwriter.WriteLine("SURNAME=" + Me.Name)
                txtwriter.WriteLine("GENDER=" + Me.Gender)
                txtwriter.WriteLine("NATIONALITY=" + Me.Nationality)
                txtwriter.WriteLine("BIRTHDATE=" + Me.BirthDate)
                txtwriter.WriteLine("BIRTHPLACE=" + Me.BirthPlace)
                txtwriter.WriteLine("NATIONALNUMBER=" + Me.NationalNumber)
                txtwriter.WriteLine("STREET=" + Me.Street)
                txtwriter.WriteLine("STREETNUMBER=" + Me.StreetNumber)
                txtwriter.WriteLine("ZIP=" + Me.ZIPCode)
                txtwriter.WriteLine("CITY=" + Me.Municipality)
                txtwriter.Close()
                Return True
            Else
                ErrorMessage = "Export Filename is empty!"
                Return False
            End If
        Catch ex As Exception
            ErrorMessage = "Unable to write eID card Information to file : " + filename + GetErrorInfo(ex)
            Return False
        Finally
            If Not txtwriter Is Nothing Then
                txtwriter.Dispose()
                txtwriter = Nothing
            End If
        End Try
    End Function

    Protected Friend Function ExportPictureToFile(ByVal filename As String) As Boolean
        Try
            If Not Me.Picture Is Nothing Then
                Me.Picture.Save(filename, Drawing.Imaging.ImageFormat.Jpeg)
                Return True
            Else
                ErrorMessage = "No picture found!"
                Return False
            End If
        Catch ex As Exception
            ErrorMessage = "Unable to export the picture to : " + filename + GetErrorInfo(ex)
            Return False
        End Try
    End Function

#End Region
   
End Class

GetErrorInfo Function VB.NET

Simple & useful Error Reporting Function... Thought I'd share if with you guys :-)

Module mFunctions
    Public Function GetErrorInfo(ByVal ex As Exception) As String
        Dim sb As New System.Text.StringBuilder()
        Dim st As New System.Diagnostics.StackTrace(ex, True)
        Dim FileName As String = ""
        Dim Method As String = ""
        Dim LineNumber As String = ""

        sb.AppendLine("")
        For Each frame As System.Diagnostics.StackFrame In st.GetFrames()
            FileName = frame.GetFileName
            Method = frame.GetMethod().ToString
            LineNumber = frame.GetFileLineNumber
            If FileName <> "" Then sb.AppendLine("Filename : " + FileName)
            If Method <> "" Then sb.AppendLine("Method : " + Method)
            If LineNumber <> "" Then sb.AppendLine("LineN° : " + LineNumber)
        Next
        Return sb.ToString()
    End Function
End Module

Thursday, May 3, 2012

Create Shortcuts using late binding

Simply create a new shortcut using some late binding, instead of having to reference the Windows Scripting Host : IWshRuntimeLibrary

Usage:
Shortcut.Create_Shortcut(PathtoExecutable, PathToShortcutFolder, ShortCutName,ExecutableFolderPath, Description, "", 0, 0)

 
Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic.CompilerServices
Public Class Shortcut
Public Shared Function Create_Shortcut(ByVal Target_Path As String, ByVal Shortcut_Path As String, ByVal Shortcut_Name As String, _
ByVal Working_Directory As String, ByVal Description As String, ByVal Arguments As String, ByVal Window_Style As Integer, ByVal Icon_Num As Integer) As Boolean
Try
Dim objectValue As Object = RuntimeHelpers.GetObjectValue(Interaction.CreateObject("WScript.Shell", ""))
Dim objectValue2 As Object = RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(objectValue, Nothing, _
"CreateShortcut", New Object() {Shortcut_Path & "\" & Shortcut_Name & ".lnk"}, Nothing, Nothing, Nothing))
NewLateBinding.LateSet(objectValue2, Nothing, "TargetPath", New Object() {Target_Path}, Nothing, Nothing)
NewLateBinding.LateSet(objectValue2, Nothing, "WorkingDirectory", New Object() {Working_Directory}, Nothing, Nothing)
NewLateBinding.LateSet(objectValue2, Nothing, "Arguments", New Object() {Arguments}, Nothing, Nothing)
NewLateBinding.LateSet(objectValue2, Nothing, "WindowStyle", New Object() {Window_Style}, Nothing, Nothing)
NewLateBinding.LateSet(objectValue2, Nothing, "Description", New Object() {Description}, Nothing, Nothing)
NewLateBinding.LateSet(objectValue2, Nothing, "IconLocation", New Object() {Target_Path & "," _
& Conversions.ToString(Icon_Num)}, Nothing, Nothing)
NewLateBinding.LateCall(objectValue2, Nothing, "Save", New Object() {}, Nothing, Nothing, Nothing, True)
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class

A special thanks to Tirthraaj Gobin for comming up with this solution...
http://social.msdn.microsoft.com/Forums/en-US/vbide/thread/126c09a2-6f38-4747-9ddd-55ff977fcba0?prof=required

Sunday, June 19, 2011

Retrieve Environment Variables

   1: ''' <summary>
   2: ''' Class to retrieve environment variables and custom declared variables with following format %VARIABLE%
   3: ''' </summary>
   4: ''' <remarks>A class used to read a string and transform all known variables with format %VARIABLE%,returning the converted string</remarks>
   5: Public Class VariableRetriever
   6:  
   7:     #Region "Methods"
   8:  
   9:     ''' <summary>
  10:     ''' Converts all known variables with format %VARIBALE% in the provided string
  11:     ''' </summary>
  12:     ''' <param name="str">Provide a string to transform</param>
  13:     ''' <returns>Returns the converted string</returns>
  14:     ''' <remarks>If an error occurs an empty string will be returned</remarks>
  15:     Protected Friend Shared Function GetAllVarFromString(ByVal str As String) As String
  16:         'try to get all the special %xxx% from the string
  17:         'replace and rebuild string
  18:         Try
  19:         
  20:             Dim split() As String = Nothing
  21:             Dim i As Integer = 0
  22:             Dim var As String = Nothing
  23:             Dim firstindex As Integer = Nothing
  24:             Dim secondindex As Integer = Nothing
  25:             If Not String.IsNullOrEmpty(str) Then
  26:                 If str.Contains("%") Then
  27:                     Do Until str.Contains("%") = False
  28:                         firstindex = Nothing
  29:                         secondindex = Nothing
  30:                         var = Nothing
  31:  
  32:                         firstindex = str.IndexOf("%")
  33:                         If Not firstindex = -1 Then
  34:                             secondindex = str.IndexOf("%", firstindex + 1)
  35:                             If Not secondindex = -1 Then
  36:                                 var = str.Substring(firstindex + 1, secondindex - firstindex - 1)
  37:                                 ReDim Preserve split(i)
  38:                                 split(i) = str.Substring(0, firstindex)
  39:                                 i = i + 1
  40:                                 ReDim Preserve split(i)
  41:                                 split(i) = GetVar(var)
  42:                                 str = str.Remove(0, secondindex + 1)
  43:                                 i = i + 1
  44:                             End If
  45:                         End If
  46:                     Loop
  47:                     ReDim Preserve split(i)
  48:                     split(i) = str
  49:                     If Not split.Length > 0 Then
  50:                         Return str
  51:                     Else
  52:                         Return Join(split, "")
  53:                     End If
  54:                 Else
  55:                     Return str
  56:                 End If
  57:             Else
  58:                 Return str
  59:             End If
  60:         Catch ex as Exception
  61:             Return ""
  62:         End Try
  63:     End Function 'End Method GetAllVarFromString
  64:  
  65:     ''' <summary>
  66:     ''' Converts a %VARIABLE% to it's value
  67:     ''' </summary>
  68:     ''' <param name="variable">Provide a variable %VARIABLE% as string</param>
  69:     ''' <returns>Returns converted string</returns>
  70:     ''' <remarks></remarks>
  71:     Protected Friend Shared Function GetVar(ByVal variable As String) As String
  72:         Try
  73:             If Not String.IsNullOrEmpty(variable) Then
  74:                 variable = RemoveProcents(variable)
  75:                 'Here you can add some variables
  76:                 'A few examples %APPPATH% will return the application startup path
  77:                 '%APPNAME% just gets the filename without extension
  78:                 Select Case UCase(variable)
  79:                     Case "APPPATH"
  80:                         Return Application.StartupPath
  81:                     Case "APPNAME"
  82:                         Return IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
  83:                     Case Else
  84:                         Return Environment.GetEnvironmentVariable(RemoveProcents(variable))
  85:                 End Select
  86:             Else : Return variable
  87:             End If
  88:  
  89:         Catch ex As Exception
  90:             Return ""
  91:         End Try
  92:     End Function 'End Method GetVar
  93:     
  94:     ''' <summary>
  95:     ''' Removes all % characters in a string
  96:     ''' </summary>
  97:     ''' <param name="str">Provide a string</param>
  98:     ''' <returns>Returns a string with % characters stripped</returns>
  99:     ''' <remarks></remarks>
 100:     Private Shared Function RemoveProcents(ByVal str As String) As String
 101:         If Not String.IsNullOrEmpty(str) Then
 102:             str = Replace(str, "%", "")
 103:         End If
 104:         Return str
 105:     End Function 'End Method RemoveProcents
 106:  
 107: #End Region 'Methods
 108:  
 109: End Class 'End Type VariableRetriever
 110:  

Monday, January 24, 2011

How to identify if string contain a number?

System.Text.RegularExpressions.Regex.IsMatch(input, "\d")

So times you will need to check a string, to see if it contains a number.
What’s the best way to do this?


There are several solutions like this function :

TryParse approach:



Public Shared Function IsNumeric(Expression As Object) As Boolean
    Dim isNum As Boolean
    Dim retNum As Double
    isNum = [Double].TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, retNum)
    Return isNum
End Function

Check Characters in String approach:



Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function IsNumeric(s As String) As Boolean
        For Each c As Char In s
            If Not Char.IsDigit(c) AndAlso c <> "."C Then
                Return False
            End If
        Next
 
        Return True
    End Function
End Class

What about locales where '.' is the group separator, not the comma (e.g. pt-Br)? What about negative numbers?
Group separators (commas in English)? Currency symbols?
TryParse() can manage all of these as required using NumberStyles and IFormatProvider.

Regular Expressions approach:



System.Text.RegularExpressions.Regex.IsMatch(input, "^\d+$")

This will return true if input is all numbers


If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and$.



System.Text.RegularExpressions.Regex.IsMatch(input, @"\d")

Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

Summary


In my opinion the winner is the Regular Expressions Method

Tuesday, December 7, 2010

VB.NET : Check TextBox For Non-Numeric Values

Public Function CheckTextBox(ByVal textb As TextBox, ByVal key As KeyPressEventArgs, Optional ByRef err As String = "") As Boolean
 
       Select Case Asc(key.KeyChar)
           Case 8 To 15
               Return True
           Case 48 To 57
               Return True
           Case 127
               Return True
           Case Else
               err = "Illegal characters have been put in!" + vbCrLf + "Please only use numeric characters."
               Return False
       End Select
   End Function