in

vbCity Blogs

New (temp) place for vbCity Blogs

Mike McIntyre's .NET Journal

  • Floating Along in Visual Studio 2010

     

    For example, see the two floating document windows on my 24 inch wide monitor below. 

     VS2010 is in the middle. 

    The Properties and Toolbox windows have been pulled of the VS2010 IDE and floated to the left and right of the VS2010 IDE.

    To float windows you can right-click a windows title, as shown below, or use the windows title to drag the window out of the VS2010 IDE.

     

    Mike McIntyre's .Net Journal

    getdotnetcode.com

  • Use a WCF Service to fill a Silverlight 3 ComboBox

    Source Code: Use a WCF Service to Fill a Silverlight 3 ComboBox

    The solution demonstrates a very simple example of calling a WCF service from a Silverlight 3 application.

     Web Site WCF Service <-> Silverlight 3 Client

    The three main elements of the example are the WCF service contained in the examples web project, the XAML of the Silverlight 'MainPage', and the code of the 'Main Page'.

    The WCF service:

     A Silverlight-enabled WCF Service was added to the web project.  This template is available if you are using the latest version of Silverlight 3.

    An operation contract, GetCountries, was added.

    Imports System.ServiceModel

    Imports System.ServiceModel.Activation

     

    <ServiceContract(Namespace:="")> _

    <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _

    Public Class SL3_WCF_Service

     

        <OperationContract()> _

        Public Function GetCountries() As List(Of Country)

            Dim db As New LightSpeedClassesDataContext

            Return (From c In db.Countries Select c).ToList

        End Function

     

    End Class

    The MainPage's XAML with the ComboBox declaration:

    <UserControl x:Class="SL3_WCF_ComboBox.MainPage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">

      <Grid x:Name="LayoutRoot">

        <ComboBox x:Name="CountryComboBox" Height="30" Width="150"></ComboBox>

      </Grid>

    </UserControl>

     

    The MainPages code behind:

    The code behind:

    1. Instantiates a SL3_WCF_Service_Ref.SL3_WCF_ServiceClient object.

    2. Adds a handler to receive the results of calling the WCF service.

    3. Calls the service's GetCountriesAsync method to request country objects from the server.

    4. Assigned the country objects returned to an overservable collection.

    5. Binds the observable collection to a ComboBox.

    Imports System.Collections.ObjectModel

     

    Partial Public Class MainPage

        Inherits UserControl

     

        'Declare and instantiate the WCF service.

        Public m_SL3_WCF_Service As SL3_WCF_Service_Ref.SL3_WCF_ServiceClient = New SL3_WCF_Service_Ref.SL3_WCF_ServiceClient

     

        Public Sub New()

            InitializeComponent()

            LoadCountryComboBox()

        End Sub

     

        Private Sub LoadCountryComboBox()

            ' Add handler for WCF service's GetCountriesCompleted results.

            AddHandler m_SL3_WCF_Service.GetCountriesCompleted, AddressOf GetCountriesCompleted

            ' Call the WCF service's GetCountriesAsync method to call the service and ask for the countries.

            m_SL3_WCF_Service.GetCountriesAsync()

        End Sub

     

        Private Sub GetCountriesCompleted(ByVal sender As Object, ByVal e As SL3_WCF_Service_Ref.GetCountriesCompletedEventArgs)

            ' Declare an observable collection to contain the results of the call to the GetCountriesAsync method.

            Dim countriesObservableCollection As ObservableCollection(Of SL3_WCF_Service_Ref.Country)

            ' Assign the List(Of Country) returned by the service to the observable collection.

            countriesObservableCollection = e.Result

            ' Set the CountryComboBox's ItemsSource to the observable collection.

            CountryComboBox.ItemsSource = countriesObservableCollection

            ' Set the CountryComboBox's DisplayMemberPath (what the user will see) to Title (a property of the Country class)

            CountryComboBox.DisplayMemberPath = "Title"

            ' Set the CountryComboBox's SelectedItem to the first country in the countriesObservableCollection.

            CountryComboBox.SelectedItem = countriesObservableCollection(0)

        End Sub

     

    End Class

     

  • Free Visual Studio 2010 Beta 2 Training Kit

    Want to get ahead of the curve?  Want to be prepared for Visual Studio 2010?

    If so, Microsoft has a training kit for you:

    Training Kit

    I've spent the last two weeks working through the kit.

    It's been worth the effort. Even though I had already spent a lot of time with Visual Studio 2010,  I learned a lot more about it from the kit.  It was fun. 

    I recommend the kit to anyone who plans to use Visual Studio 2010.

  • 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

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