in

vbCity Blogs

New (temp) place for vbCity Blogs

Mike McIntyre's .NET Journal

  • Visual Basic 2008 - Create a DataTable From Linq Query Results

    Below is a class that contains a method that can create a DataTable object form Linq Query Results. I find the LINQToDataTable method really handy when I am creating Crystal reports. Crystal Reports love to report on DataTables.

    The Imports are essential to the LINQToDataTable method in the LinqUtilities class.

    Imports System.Data
    Imports System.Linq
    Imports System.Reflection
     
    Public Class LinqUtilities
        Friend Shared Function LINQToDataTable(Of T)(ByVal iEnumerableList As IEnumerable(Of T)) As DataTable
            Dim newDataTable As New DataTable()
            Dim thePropertyInfo As PropertyInfo() = Nothing
            If iEnumerableList Is Nothing Then
                Return newDataTable
            End If
     
            For Each item As T In iEnumerableList
                If thePropertyInfo Is Nothing Then
                    thePropertyInfo = (DirectCast(item.[GetType](), Type)).GetProperties()
                    For Each propInfo As PropertyInfo In thePropertyInfo
                        Dim columnDataType As Type = propInfo.PropertyType
                        If (columnDataType.IsGenericType) AndAlso (columnDataType.GetGenericTypeDefinition() Is GetType(Nullable(Of ))) Then
                            columnDataType = columnDataType.GetGenericArguments()(0)
                        End If
                        newDataTable.Columns.Add(New DataColumn(propInfo.Name, columnDataType))
                    Next
                End If
     
                Dim dr As DataRow = newDataTable.NewRow()
                For Each pi As PropertyInfo In thePropertyInfo
                    dr(pi.Name) = If(pi.GetValue(item, Nothing) Is Nothing, DBNull.Value, pi.GetValue(item, Nothing))
                Next
     
                newDataTable.Rows.Add(dr)
            Next
            Return newDataTable
        End Function
     
    End Class

    Below is example code that uses Linq to query for all the buttons on a Windows Forms form and calls the LINQToDataTable method to put the query results into a DataTable.

    Dim newDataTable As DataTable = _
            LinqUtilities.LINQToDataTable(From btn In Me.Controls _
                Where TypeOf (btn) Is Button Select btn)
    
    

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • SQL Join Summary Query Example

    Heres a short exmaple to get you thinking about how query results can be joined to tables for purposes such as attaching summary data.

    The example below shows how a query that sums total sales for a product can be joined to a query that selects product ID and product name from the Products table in Microsoft's Adventure Works sample database.

    SELECT
    PROD.ProductID,
    PROD.[Name],
    ISNULL(SALES.ProductSales,0) ProductSales
    FROM Production.Product PROD
    LEFT JOIN
    (
    SELECT ProductId,
    SUM(LineTotal) ProductSales
    FROM Sales.SalesOrderDetail SOD
    GROUP BY ProductID
    ) SALES
    ON PROD.ProductID = SALES.ProductID 

    The SELECT query within the parentheses returns a result with two columns: 1) ProductID and 2) ProductSales.

    The query within parentheses is assigned the alias 'SALES' which is used to construct the ON clause that joins SALES to the Product table.

    Because the SALES query returns ProductID (SALES.ProductID) it can be joined to PROD.ProductID.

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Visual Studio 2010 - Changes to Help System

    There are changes to the Visual Studio 2010 help system that you'll want to learn about.

    For example, the new 'Manage Help Settings' menu item:

    The menu item opens the new 'Help Library Manager' dialog:

    From MSDN: "The Help Library Manager (HLM) application allows you to manage product documentation in the local Microsoft Help 3.0 content store. Using HLM, you can find and install new content from the web or from media, go online to get updates for your offline content, and remove offline content. The Help Library Manager also manages settings that allow you to customize your help experience."

    Read more at: Help Library Manager

     

  • Silverlight 3 - Enabling the Silverlight 'Out of Browser' Experience

     Silverlight 3 applications can be installed as local applications on PCs and MACs.

    This is a brief 'how to' for enabling, installing, and removing a Silverlight 3 out of browser applications.

    1. Use Visual Studio 2008 or 2010 to create a Silverlight 3 project.

    2. Open the Silverlight 3 project's properties dialog. Select the 'Silverlight' tab. Check the 'Enable running application out of the browser'. Click the 'Out-of-Browser Settings...' button.

    3. The 'Out-of-Browser Settings' dialog opens. Use it to configure your Silverlight 3 application for out of browser installation.

    4. Run your application.  Right-click a page in your application and select 'Install..' menu item.

    5. The 'Install application' dialog opens. Use it to install short cuts to your application.

    6. The Silverlight 3 out of browser application short cut on the desktop:

    7. Use the short cut to launch the application on the computer. Here's a screen shot of my sample application running locally on my computer:

    8 To remove the Silverlight 3 out of browser application from your computer: run it, right-click a page in the application, and select the 'Remove this application...' menu item.

  • Visual Basic 2010 and .NET Framework 4 Deliver Beta 2 in Final Stretch to March 22 Launch

     Read all about it at:  Final Stretch

  • Search for Files with a Specific Extension in and below a System Special Folder

    The Visual Basic My.Computer.FileSystem GetFiles method can be used to search for files with a specific extension in or below a specific directory:

    Below is a function for that purpose:

        Private Function GetFilePathList(ByVal specialDirectoryPath As String, ByVal fileExtension As String) _
                        As List(Of String)
            ' Instantiate a list of type String.
            Dim filePathList As New List(Of String)
            ' Use the My.Computer.FileSystem GetFiles method to search for files with a specific file
            '   extension in or below a specific directory.
            ' Note the use of the FileIO.SearchOption SearchAllSubDirectories to request all directories
            '   below the specifified directory be searched too.
            For Each filePath As String In My.Computer.FileSystem.GetFiles(specialDirectoryPath, _
                        FileIO.SearchOption.SearchAllSubDirectories, fileExtension)
                filePathList.Add(filePath)
            Next
            Return filePathList
        End Function

    Here's an example show how to call the function above:

    Dim fileList As List(Of String) = GetFilePathList(My.Computer.FileSystem.SpecialDirectories.MyPictures, "*.png")

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Validation and the Windows Forms ErrorProvider

    Download source code here ->  Validation and the Windows Forms ErrorProvider Component

    I've noticed that not a lot of people take advantage of the Windows Forms built in user interface for indicating that a control on a form has an error associated with it - the ErrorProvider component.

    The ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it. If an error description string is specified for the control, an icon appears next to the control. The icon flashes in the manner specified by BlinkStyle, at the rate specified by BlinkRate. When the mouse hovers over the icon, a ToolTip appears showing the error description string.

    Typically, you use ErrorProvider in association with data-bound controls. When using ErrorProvider with data-bound controls, you must specify the ContainerControl, either in the constructor or by setting the ContainerControl property.

    The Visual Studio project download at the link above demonstrates how to combine validation with the ErrorProvider.

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Visual Basic 2010 - Nullable Optional Parameters

     Nullable types were a welcome addition to Visual Basic 2008.  In Visual Basic 2010 you can use them as parameters.  Here are two examples:

        ' Assign Nothing as the default value for nullable optional parameter.

        Sub Add(ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Integer? = Nothing)

            ' code removed for brevity

        End Sub

     

        ' Assign an integer value to a nullable optional paramter of type Double.

        Sub Process(ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Double? = 4)

            ' code removed for brevity

        End Sub

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Visual Basic 2010 - Array Literals

     Visual Basic 2010 array litererals provide a shortcut mechanism for declaring and filling arrays for types that can be inferred by the compiler.  Here a three examples:

            ' Examples

            Dim a = {1, 2, 3} 'infers Integer()

            Dim b = {1, 2, 3.5} 'infers Double()

            Dim c = {"1", "2", "3"} 'infers String()

    Becareful not to mix in types the compiler can not infer: 

            ' WARNING: Make sure you used types that can be inferred.

            ' The next example will generation a warning if OPTION STRICT ON

            '   or infer a type of Object if OPTION STRICT OFF

            Dim d = {1, "123"} 'infers Object() (warning with Option Strict On)

    Create multidimensional arrays with array literals:

            ' Create multidimensional arrays by nesting array array literals:

            'Nested array literals can be used to produce multidimensional arrays:

            Dim f = {{1, 2, 3}, {4, 5, 6}} 'infers Integer(,)

            Dim g = {({1, 2, 3}), ({4, 5, 6})} 'infers Integer()() (jagged array)

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Visual Basic 2010 - Multiline Function Lambdas

    A multiline Function lambda is a lambda expression that represents a Function containing one or more statements. 

    The “Function” keyword can be used to create a multiline lambda that returns a value.  The following examples how to create mutiline Function lambdas.  The first creates a multiline Function lambda and assigns it to a variable.  The second uses a multiline Function lamda inline.

     

            ' A multiline Function lambda created and assigned to a variable.

            ' Note: Does not require line continuation characters.

            Dim x = Function(n As Integer)

                        If n Mod 2 = 0 Then

                            Return 3

                        Else

                            Return 3.14

                        End If

                    End Function

            ' Use the lamda and display it's result.

            MsgBox(x(33).ToString & " is the answer.")

     

            ' A multiline Function lambda created and used inline.

            Dim theAnswer = Function(n As Integer)

                                If n Mod 2 = 0 Then

                                    Return 3

                                Else

                                    Return 3.14

                                End If

                            End Function

            ' Use the lamda and display it's result.

            MsgBox(x(14).ToString & " is the answer.")

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Visual Basic 2010 - Multiline Sub Lambdas

    A multiline Sub lambda is a lambda expression that represents a Sub containing one or more statements. 

    Visual Basic 9.0 only supported lambdas that were a single expression that returned a value; for example, the following line was an error:

     

        'Error - Console.WriteLine doesn't return a value

        Array.ForEach(nums, Function(n) Console.WriteLine(n))

     

    With Visual Basic 10.0, lambdas can now contain expressions that do not return a value:

     

       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            ' Delcare an array of integers named number filled with four numbers.

            Dim numbers() = {1, 6, 9, 4}

            ' Use a multiline Sub lambda to iterate the array elements and print them to the Results window.

            Array.ForEach(numbers, Sub(n)

                                       Console.Write("Number: ")

                                       Console.WriteLine(n)

                                   End Sub)

        End Sub

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • VB 20010 - Continuing a Statement over Multiple Lines after a Comma

    Visual Basic 2010 provides mechanisms to continue lines of a statment without the traditional _ (underline) character.

    One mechanism is to contiue the statement on a new line after a comma.

    Here's and example:

        Private Function ProcessOrder(ByVal customer As Person,

                                      ByVal orderDate As DateTime,

                                      ByVal ship As Boolean) As ProcessResult

            Dim processResults As New ProcessResult

            '  Processing code omitted for brevity.

            Return processResults

        End Function

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • 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

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