in

vbCity Blogs

New (temp) place for vbCity Blogs

Mike McIntyre's .NET Journal

September 2009 - Posts

  • MS SQL Server - Use Transact SQL CASE Expression To Sort Query Results

    The Transact SQL 'CASE' expression is useful for a lot of things but did you know you can use it to sort your query results in special ways? Here's a simple example that sorts by a customer's primary email address if it is not null else by the customer's other email address:

    SELECT

    LastName,

    CASE WHEN PrimaryEmailAddress IS NOT NULL THEN PrimaryEmailAddress

    ELSE OtherEmailAddress END AS EmailAddress

    FROM Customer

    ORDER BY CASE WHEN PrimaryEmailAddress IS NOT NULL THEN PrimaryEmailAddress

    ELSE OtherEmailAddress END

     

    For more info ->  Transact SQL CASE Expression

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

     

    Posted Sep 28 2009, 08:00 PM by Mike McIntyre
    Filed under: , ,
  • Case Insentive Comparrisons with Visual Basic

     The .Net String class' ToUpper function can be used with Visual Basic code for case insensitve comparrisons.  Here's an example:

            Dim string1 As String = InputBox("Enter some text:", "", "cat on a hot tin roof")
            Dim string2 As String = InputBox("Enter a word:", "", "Hot")
            ' Use the String.ToUpper method for a case insensitive comparrison:
            If string1.ToUpper.Contains(string2.ToUpper) Then
                MsgBox("Case insensitive match")
            Else
                MsgBox("No case insensitive match")
            End If

    For more info:  ToUpper 

    Mike McIntyre

    getdotnetcode.com

  • Read a Comma Delimited File with the Visual BasicTextFieldParser Class

    This blog post provides an example that shows how to use the VisualBasic TextFieldParser class to read in data from a comma delimited files.

    Private Sub ReadCommaDelimtedFile()

            Dim filePath As String = GetTextFilePath()

            ' If a valid file path to a .txt file has been selected....

            If Not String.IsNullOrEmpty(filePath) Then

                ' Declare a variable named 'reader' as a VisualBasic TextFieldParser

                '   calling the My.Computer.FileSystem.OpenTextFieldParser method to create the reader.

                Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(filePath)

                ' Set the reader's TextFieldType to delimited so it can read a delimited text file.

                reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited

                ' Set the readers Delimiters to a comma (,)

                reader.Delimiters = New String() {","}

                Dim currentRow As String()

                ' Ready to read the file....

                While Not reader.EndOfData

                    Try

                        currentRow = reader.ReadFields()

                        Dim currentField As String

                        For Each currentField In currentRow

                            MsgBox(currentField)

                        Next

                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException

                        MsgBox("Line " & ex.Message & _

                        "is not valid and will be skipped.")

                    End Try

                End While

            End If

        End Sub

     

        Private Function GetTextFilePath() As String

            Dim textOpenFileDialog As New OpenFileDialog

            ' Allow only .txt files to be opened.

            textOpenFileDialog.Filter = "txt files (*.txt)|*.txt"

            If textOpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

                Dim filePath As String = textOpenFileDialog.FileName

                ' If file exists return file path else return empty string.

                Return If(File.Exists(filePath), filePath, String.Empty)

            End If

            Return ""

        End Function

     

    Mike McIntyre

    getdotnetcode.com

  • Get List of Ports with Visual Basic My and Linq

    There are many ways to combine the Visual Basic My feature with LINQ.  Heres an example that gets a list the ports on a computer:

     Dim portsList As List(Of String) = (From p In My.Computer.Ports.SerialPortNames Select p).ToList()
    
    
    
    

  • Matching Strings to Patterns with the Linq to Sql TranslateVBLikePattern Function

    This post explains how to implement Visual Basic "Like" behavior in Linq To Sql queries.

    The Visual Basic Like operator has been around for a long time. I really like the simplicity of using the Visual Basic.Net Like Operator for string pattern matching.  For example, its simple to check to see if a string matches a U.S. social security number pattern like this:

        Private Function SSNMatch(ByVal value As String)
            Return If(value Like "###-##-####", True, False)
        End Function

    The System.Data.Linq.SqlClient.SqlHelpers class' TranslateVBLikePattern method provides a way to use Visual Basic 'Like' pattern matching in Linq To Sql queries.

        Private Function LinqToSqlVbLikeMatch(ByVal pattern As String) As List(Of Customer)
            ' Use the SqlHelpers TranslatedVBLikePattern shared method to create a pattern
            '  to pass into a SqlMethods.Like call.
            Dim vbPattern As String = SqlHelpers.TranslateVBLikePattern(pattern, "")
            ' Use the VB Like pattern in a Linq to Sql call to the SqlMethods.Like method.
            Return (From c In m_DALDataContext.Customers Select c _
                        Where SqlMethods.Like(c.HomePhone, vbPattern + "%") Select c).ToList()
        End Function

    Here's an example of some code that uses the method above to find customer records where home phone has been entered in a pattern of numbers, a space, and a dash (-):

            ' Get a list of customers where home phone number has been 
            '  entered like nnn nnn-nnnnn (numbers with space after
            '  first three numbers and a dash (-) as character eight.
            Dim customerList As List(Of Customer)
            customerList = LinqToSqlVbLikeMatch("### ###-####")

     

  • Use Linq To Count Occurrences of a Character in a String

     Here's an example showing how to count the occurrences of a character in a string: 

            Dim searchString As String = "This is the dawning of the age."
            Dim count As Integer = (From s In searchString.ToCharArray Where s = "i" Select s).Count

     

    Posted Sep 09 2009, 09:48 PM by Mike McIntyre
    Filed under:
  • Visual Basic 2010 Auto-Implemented Properties - A Closer Look

    Auto-implemented properties are a time saving feature that is new in Visual Basic 2010 - a short-cut for creating class properties.

    Auto-implemented properties enable you to declare a class property in a way that leaves it up to Visual Studio to create a private backing field and the Get and Set parts of the property for you.

    For example, when you type the following into the Visual Basic 2010 code editor:

    Property CustomerId() As Integer

    you get a property that is equivalent to declaring a property like this:

        Private _CustomerId As Integer

        Property CustomerId() As Integer

            Get

                Return _CustomerId

            End Get

            Set(ByVal value As Integer)

                _CustomerId = value

            End Set

        End Property

    but all you see is:

    Property CustomerId() As Integer

    You can include a default value:

    Property CustomerName() As String = "New"

    The backing field name is the auto-implemented property name preceded by an underscore (_). For example, if you declare an auto-implemented property named ID, the backing field is named _ID. Be careful - if you include a member of your class that is also named _ID, you produce a naming conflict and Visual Basic reports a compiler error.

    Auto Implement Property Rules

    The access modifier for the backing field is always Private, even when the property itself has a different access level, such as Public.

    If the property is marked as Shared, the backing field also is shared.

    Attributes specified for the property do not apply to the backing field.

    The backing field can be accessed from code within the class and from debugging tools such as the Watch window. However, the backing field does not show in an IntelliSense word completion list.

    You cannot initialize an auto-implemented property that is a member of an Interface, or one that is marked MustOverride.

    When you declare an auto-implemented property as a member of a Structure, you can only initialize the auto-implemented property if it is marked as Shared.

    When you declare an auto-implemented property as an array, you cannot specify explicit array bounds. However, you can supply a value by using an array initializer, as shown in the following examples.

    Property Grades As Integer() = {90, 73} Property Temperatures As Integer() = New Integer() {68, 54, 71}

    You have to use expanded property-definition syntax if you want to do any one of the following:

    Add code to the Get or Set procedure of a property, such as code to validate incoming values in the Set procedure. For example, you might want to verify that a string that represents a telephone number contains the required number of numerals before setting the property value.

    Specify different accessibility for the Get and Set procedure. For example, you might want to make the Set procedure Private and the Get procedure Public.

    Create properties that are WriteOnly or ReadOnly.

    Use parameterized properties (including Default properties). You must declare an expanded property in order to specify a parameter for the property, or to specify additional parameters for the Set procedure.

    Place an attribute on the backing field.

    Provide XML comments for the backing field.

    How to expand an Auto-Implemented Property

    The Visual Basic Code Editor can automatically generate the the visual Get and Set procedures and End Property statement for the property.

    Put the cursor on a blank line following the Property statement, type a G (for Get) or an S (for Set) and press ENTER. The Visual Basic Code Editor automatically generates the Get or Set procedure for read-only and write-only properties when you press ENTER at the end of a Property statement.

  • Control Arrays - LINQ and Generic List Alternative

    Next time you think you need a control array consider using a generic list and LINQ instead.

    Here's an example that demonstrates how to declare and fill a list of type TextBox and then use the list to clear all the text boxes on a Windows Form.

    Note: This example applies to Visual Basic 2008 or newer.

            ' Create a list of type TextBox that contains all the text boxes on a Windows Form.
            Dim textBoxList As List(Of TextBox) = From t In Me.Controls Where TypeOf (t) Is TextBox
            ' Use the list to clear the text boxes.
            For Each tb In textBoxList
                tb.Clear()
            Next

  • Comparing times with the DateTime TimeOfDay Method

    The .Net Framework's DateTime 'TimeOfDay' method can be used to determine if two or more times are equal.

            ' Create three DateTime objects to experiment with.
            Dim date1 As New DateTime(2009, 9, 2, 9, 0, 0)
            Dim date2 As New DateTime(2009, 9, 1, 9, 0, 0)
            Dim date3 As New DateTime(2009, 9, 2, 10, 0, 0)
            ' Test TimeOfDay equality between date1 and date2.
            '    Even though the date is different, TimeOfDay is equal.
            If date1.TimeOfDay = date2.TimeOfDay Then
                MessageBox.Show("Times are equal.")
            Else
                MessageBox.Show("Times are not equal.")
            End If
            ' Test TimeofDay equality between date1 and date3
            '    Dates are the same but TimeOfDay is not.
            If date1.TimeOfDay = date3.TimeOfDay Then
                MessageBox.Show("Times are equal.")
            Else
                MessageBox.Show("Times are not equal.")
            End If

  • Visual Basic 2010 - Generate From Usage Feature

    Visual Basic 2010 includes a feature for generating code from usage.

    The Generate From Usage feature enables you to use classes and members before you define them. You can generate a stub for any class, constructor, method, property, field, or enum that you want to use but have not yet defined. You can generate new types and members without leaving your current location in code. This minimizes interruption to your workflow.

    Generate From Usage supports programming styles such as test-driven development.

    A wavy underline appears under each undefined identifier, and a short underline appears under the rightmost character. When you rest the mouse pointer on the identifier, an error message appears in a tooltip.

    When you rest the mouse pointer on the short underline, a Smart Tag (a small rectangle) appears. You can also press CTRL+. to display the Smart Tag.

    Click the Smart Tag, and the appropriate options appear. Depending on the context, those options can include the following:

    • Generate property stub

    • Generate method stub

    • Generate class

    • Generate interface

    • Generate other (for a Class, Enum, Structure, Interface, or Delegate)

    Example:

Copyright 1998-2009 vbCity.com LLC
Powered by Community Server (Non-Commercial Edition), by Telligent Systems