Getting Windows Mobile Device ID

by Ken Tucker 26. March 2009 21:10

I got email today asking me how to get the device ID from a pocket pc with vb

 

Imports System.Text

Public Class Form1

    <System.Runtime.InteropServices.DllImport("coredll.dll")> _
Private Shared Function GetDeviceUniqueID(ByVal appdata As Byte(), ByVal cbApplictionData As Integer, ByVal dwDeviceIDVersion As Integer, ByVal deviceIDOuput As Byte(), ByRef pcbDeviceIDOutput As Integer) As Integer
    End Function

    Private Function GetDeviceId(ByVal appData As String) As Byte()

        Dim appDataBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(appData)
        Dim outputSize As Integer = 20
        Dim output(19) As Byte

        Dim result As Integer = GetDeviceUniqueID(appDataBytes, appDataBytes.Length, 1, output, outputSize)

        Return output

    End Function

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sbId As New StringBuilder

        Dim bID() As Byte = GetDeviceId("MyAppName")

        For Each b In bID
            sbId.Append(String.Format("{0:x2}", b))
        Next

        Debug.WriteLine(sbId.ToString)
    End Sub
End Class

 

References

 

http://www.peterfoot.net/GetDeviceUniqueIDForVB.aspx

http://msdn.microsoft.com/en-us/library/ms893522.aspx

Getting Windows Mobile Device ID

by Ken Tucker 26. March 2009 21:10

I got email today asking me how to get the device ID from a pocket pc with vb

 

Imports System.Text

Public Class Form1

    <System.Runtime.InteropServices.DllImport("coredll.dll")> _
Private Shared Function GetDeviceUniqueID(ByVal appdata As Byte(), ByVal cbApplictionData As Integer, ByVal dwDeviceIDVersion As Integer, ByVal deviceIDOuput As Byte(), ByRef pcbDeviceIDOutput As Integer) As Integer
    End Function

    Private Function GetDeviceId(ByVal appData As String) As Byte()

        Dim appDataBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(appData)
        Dim outputSize As Integer = 20
        Dim output(19) As Byte

        Dim result As Integer = GetDeviceUniqueID(appDataBytes, appDataBytes.Length, 1, output, outputSize)

        Return output

    End Function

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sbId As New StringBuilder

        Dim bID() As Byte = GetDeviceId("MyAppName")

        For Each b In bID
            sbId.Append(String.Format("{0:x2}", b))
        Next

        Debug.WriteLine(sbId.ToString)
    End Sub
End Class

 

References

 

http://www.peterfoot.net/GetDeviceUniqueIDForVB.aspx

http://msdn.microsoft.com/en-us/library/ms893522.aspx

Space Coast .Net Winter 09 Tiki Hut Tour

by Ken Tucker 25. January 2009 14:43

MSDN Tiki Hut Roadshow

Wednesday, February 18, 2009 6:30 PM - Wednesday, February 18, 2009 9:30 PM Eastern Time (US & Canada)
Welcome Time: 6:00 PM

Space Coast Credit Union Corporate Headquarters

8045 N. Wickham Road
Melbourne Florida 32940
United States

 

Session 1 – jQuery with ASP.NET - JQuery is an open source JavaScript library that has a passionate following among Ajax developers. Microsoft is integrating the open source JQuery library into both the ASP.NET Web Forms and ASP.NET MVC frameworks and providing full product support. Learn how you can take advantage of JQuery to build richly interactive client-side Ajax applications when developing either ASP.NET Web Forms or ASP.NET MVC applications. Also see how JQuery works in combination with ASP.NET AJAX to provide the best framework for building Ajax applications.

Session 2 – Data Services - OnPremise and Off - In the near future, applications will be developed using a combination of custom application code and online building block services, including data-centric services. In this session we discuss advancements in the Microsoft development platform and online service interfaces to enable seamless interaction with data services both on-premises (e.g., ADO.NET Data Services Framework over on-premises SQL Server) and in the cloud (e.g., SQL Server Data Services). Learn how you can leverage existing know-how related to LINQ (Language Integrated Query), data access APIs, data-binding, and more when building applications using online data.

Session 3 – Architecting for the Cloud using Windows Azure - This session provides a tour of the Windows Azure cloud computing platform, an overview of its various components, and explains how these fit together to provide best-of-cloud experiences. We will explore the architecture that links many of the Microsoft .NET services and lets ISVs and businesses deliver compelling solutions. Learn how to compose these services with SQL Data Services to create applications in the cloud and connect them with on-premise systems. We will also examine the next generation of messaging, data, access control, and directory services, and how they fit together to provide a seamless integration into the cloud.

Speaker’s Bios:
Joe Healy ( http://www.devfish.net ) is the Developer Evangelist for Microsoft Gulf States Accounts, based out of Tampa Florida. Joe’s geographical responsibility is to provide ‘developer care’ for the state of Florida. Joe serves a multitude of clients, from corporate accounts to broad reach events and User Groups. He lectures on various development and architectural topics focused around the .Net Frameworks, Visual Studio.NET, and associated servers. Joe has also served time with eAngler.com, Arthur Andersen, Cap Gemini, EDS, and IBM in various capacities.

Jeff Barnes (Architecture: The Harmony of Mathematical Precision; http://blogs.msdn.com/jbarnes ) is the Microsoft Architect Evangelist for the Gulf States District where he engages with the local Architect community to help solve tough business problems with leading-edge technology. Jeff has been with Microsoft for over 10 years and has spent over 7 of those years as an architect in the Microsoft Consulting Services organization working with large enterprise customers throughout North America. He especially enjoys the freedom and flexibility that .NET brings to the table in order solve the next generation of tough technical challenges.

 

Register if you plan to attend this event

 https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032400629&culture=en-US

Making a REST service with VB and WCF

by Ken Tucker 13. January 2009 03:28

REST which stands for Representational State Transfer is a way of sending data over the Internet without an additional message layer.  Standard web services use soap for there message header.  In this example we will create a service that uses the northwind database to send a  list of the products for a category.

 

Lets start by create a new VB web application. In that web application add a Ado.Net Entities data model.  In that class add the northwind database's product class.

 

image

 

Now add a service named Service1 to the web application.  Lets start by modify the web.config for the service to support rest.  First remove the ServiceBehavior section and add a endpointBehaviors section for webHttp.  In the endpoint we have to change the binding to webHttpBinding and the behaviorConfiguration to the webBehavior we created.

 

    <system.serviceModel>
        <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="True"></serviceHostingEnvironment>
        <services>
            <service name="RestTest.Service1">
                <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="RestTest.IService1">
                </endpoint>
            </service>
        </services>
    </system.serviceModel>

 

When we added the service we got 2 items the wcf service and an interface for the service.  Before we go any further we need to add a reference to system.servicebehavior.web  

 

In the Interface we need to define the how the categoryId is passed to the service.  In this example it expects product/categoryID in the url for the service

 

Imports System.ServiceModel
Imports System.ServiceModel.Web 

<ServiceContract()> _
Public Interface IService1 

    <OperationContract()> _
    <WebGet(UriTemplate:="Product/{categoryID}", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Bare)> _
    Function GetProducts(ByVal categoryId As String) As List(Of Products) 

End Interface 

 

In the service we need to set the AspNetCompatibilityMode and write some code to return the products

 

Imports System.ServiceModel.Activation 

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
    Implements IService1 

    Public Function GetProducts(ByVal categoryId As String) As System.Collections.Generic.List(Of Products) Implements IService1.GetProducts
        Dim dc As New NorthwindEntities
        Dim q = From p In dc.Products Select p Where p.CategoryID = CInt(categoryId)
        Return q.ToList
    End Function
End Class 

 

To call the service you would use a url like http://localhost:2050/Service1.svc/Product/7

 

you will get an xml file like this returned

 

 

image

Snippet Editor

by Ken Tucker 31. December 2008 07:11

Bill McCarthy has moved the Snippet Editor project to Code Plex and added some nice new features


Features include:

  • Complete snippet file management
  • basic syntax coloring
  • replacement highlighting
  • drag and drop file organisation


The Snippet Editor is a stand-alone exe suitable for all versions
of Visual Studio 2005 and 2008 including the Express editions:


snippet_editor.png



The left hand pane provides for snippet collection management.
You can select which of your product collection to edit, filter the
collection based on a search phrase, add and remove snippets,
add existing folders, remove folders from the collection and
move snippets around by simple drag and drop.


snippet_navigation.png



The code editor provide basic syntax highlighting, and snippet
replacement highlighting, navigation, editing, adding and deleting.
Resize the code editor pane, collapse or expand the Properties,
Imports or References panes, and your layout is remembered for
next time you use the editor.



snippet_code.png

 

Download a copy today

http://www.codeplex.com/SnippetEditor


kick it on DotNetKicks.com

Publishing a VB Silverlight 2 Beta 2 app which uses a WCF service

by Ken Tucker 15. July 2008 19:54

Note this works with the released version of Silverlight 2

 

I created a Silverlight 2 beta 2 app which uses a WCF Silverlight service which worked fine localy but did call the service when I published it to my web host.  After playing around with the different settings I finally came across an entry in the Silverlight Forums by sladapter with a solution. 

 

http://silverlight.net/forums/t/19021.aspx 

 

So lets create a simple Silverlight 2 App to demo how to do this.  I created a silverlight app with a web application project.   I prefer web applications to web sites but a web site will work the same.  

 

Add a WCF Silverlight- enabled service named  service1 to the web application. 

 

This is the code I am using for the service

 

Imports System.ServiceModel
Imports System.ServiceModel.Activation

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

    <OperationContract()> _
    Public Function SayHello() As String
        ' Add your operation implementation here
        Return "Hello World"
    End Function
End Class

 

Lets add a TextBlock to the Page.xaml to display our message.

 

<UserControl x:Class="SilverlightApplication2.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
            <TextBlock x:Name="txt">Loading..</TextBlock>
    </Grid>
</UserControl>

 

Now run the app.  Once that is done we can add a service reference to our silverlight app.  Press the arrow on the Discover button and select services in the solution.  You should windup with something like this.

 

image

 

In the silverlight app open up the file ServiceReferences.ClientConfig

 

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                    maxReceivedMessageSize="65536">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_Service1" contract="ServiceReference1.Service1"
                name="BasicHttpBinding_Service1" />
        </client>
    </system.serviceModel>
</configuration>

 

In the endpoint address change the contract to include the project name.

 

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                    maxReceivedMessageSize="65536">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_Service1" contract="SilverlightApplication2.ServiceReference1.Service1"
                name="BasicHttpBinding_Service1" />
        </client>
    </system.serviceModel>
</configuration>

 

Now lets add some code to call the service. Page.Xaml.VB

 

Partial Public Class Page
    Inherits UserControl
    Dim current As String

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim ws As New ServiceReference1.Service1Client
        AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
        ws.SayHelloAsync()
    End Sub

    Private Sub HelloComplete(ByVal sender As Object, ByVal e As ServiceReference1.SayHelloCompletedEventArgs)
        txt.Text = e.Result
    End Sub

End Class

 

Now if we run the app you should see Hello World but when published you will only see loading.   So lets change how we create the service so that this will work once deployed.  Basically we tell the service to use the current web address.

 

Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
    Dim address = New Uri(Application.Current.Host.Source, "../Service1.svc")

    Dim ws As New ServiceReference1.Service1Client("BasicHttpBinding_Service1", address.AbsoluteUri)
    AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
    ws.SayHelloAsync()
End Sub

 

Hope this helps

Validating Data entered in a DataRepeater control

by Ken Tucker 7. May 2008 11:34

In this example I will show how to validate the data entered into a datarepeater control. For this example I am added the northwind SQL compact edition database to the project and created a typed dataset for the products table.  So from the toolbox drop a datarepeater on the form.  Inside the datarepeater drag the ProductName, UnitPrice, and Units in stock fields. Your form should look something like

 

image

 

Now in the drawitem event for the datarepeater we can add a handler to validating event.

Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) Handles DataRepeater1.DrawItem
    Dim currItem As DataRowView = DirectCast(ProductsBindingSource.Item(e.DataRepeaterItem.ItemIndex), DataRowView)
    Dim txt As TextBox = DirectCast(e.DataRepeaterItem.Controls("Unit_PriceTextBox"), TextBox)
    AddHandler txt.Validating, AddressOf TextBox_Validating
End Sub

Private Sub TextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
    Dim dec As Decimal
    If Not Decimal.TryParse(DirectCast(sender, TextBox).Text, dec) Then
        MessageBox.Show("Please enter a valid number")
        e.Cancel = True
    End If
End Sub

 

The complete code

 

Public Class Form1

    Private Sub ProductsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProductsBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.ProductsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.NorthwindDataSet)

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'NorthwindDataSet.Products' table. You can move, or remove it, as needed.
        Me.ProductsTableAdapter.Fill(Me.NorthwindDataSet.Products)

    End Sub

    Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) Handles DataRepeater1.DrawItem
        Dim currItem As DataRowView = DirectCast(ProductsBindingSource.Item(e.DataRepeaterItem.ItemIndex), DataRowView)
        Dim txt As TextBox = DirectCast(e.DataRepeaterItem.Controls("Unit_PriceTextBox"), TextBox)
        AddHandler txt.Validating, AddressOf TextBox_Validating
    End Sub

    Private Sub TextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
        Dim dec As Decimal
        If Not Decimal.TryParse(DirectCast(sender, TextBox).Text, dec) Then
            MessageBox.Show("Please enter a valid number")
            e.Cancel = True
        End If
    End Sub
End Class

Regular Expression Help

by Ken Tucker 28. April 2008 19:13

I got an regualr expression question today from one of my friends.  Basically she was using a regular expression  to validate a number was 4 or 6 digits long but the expression she was using ^\d{4,6}$ would validate numbers 5 digits long.  Lets look at this regular expression ^ means starts with. The \d means number and the {4,6} means 4 to 6 digits long.  The $ means ends with. The answer is to use a regular express with an or (the | means or)

Dim regNum As New Regex("^\d{4}$|^\d{6}$")

Debug.Print(regNum.IsMatch("1234").ToString)

Debug.Print(regNum.IsMatch(
"12345").ToString)

Debug.Print(regNum.IsMatch("123456").ToString)

Output

True

False

True

Print to PDF

by Ken Tucker 4. April 2008 20:07

The .Net framework provides a print document class for printing.  There are times that it would be nice to redirect what you are printing to a pdf.   In this example we are going to use the Sharp Pdf lib version 1.3.1 to print to a pdf. 

The sharp pdf lib allows you to add an image to a page in a pdf.  To make it possible to print to a pdf we are going to create a new print controller class which creates a bitmap and has the print document draw the page on the bitmap.  Then it adds the bitmap as a pdf page.  Once the document is done printing it saves the pdf to disk. 

 

http://sharppdf.sourceforge.net/

Update this Project is now available on CodePlex

http://www.codeplex.com/Print2Pdf

 

Imports sharpPDF

Public Class PdfPrintController
    Inherits Printing.PrintController
    Dim pdf As pdfDocument
    Dim bm As Image

    Private _Author As String = "Unknown"

    Public Property Author() As String
        Get
            Return _Author
        End Get
        Set(ByVal value As String)
            _Author = value
        End Set
    End Property

    Private _FileName As String = "Printed.pdf"
    Public Property FileName() As String
        Get
            Return _FileName
        End Get
        Set(ByVal value As String)
            _FileName = value
        End Set
    End Property

    Private _Title As String = "Unknown"
    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property

    Public Overrides ReadOnly Property IsPreview() As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides Function OnStartPage(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintPageEventArgs) As System.Drawing.Graphics
        bm = New Bitmap(e.PageBounds.Width, e.PageBounds.Height)
        Dim g As Graphics = Graphics.FromImage(bm)
        g.Clear(Color.White)
        Return g
    End Function

    Public Overrides Sub OnStartPrint(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintEventArgs)
        pdf = New pdfDocument(Title, Author)
        MyBase.OnStartPrint(document, e)
    End Sub

    Public Overrides Sub OnEndPage(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim p As pdfPage = pdf.addPage(e.PageBounds.Height, e.PageBounds.Width)
        p.addImage(bm, 0, 0)
        MyBase.OnEndPage(document, e)
    End Sub

    Public Overrides Sub OnEndPrint(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintEventArgs)
        pdf.createPDF(FileName)
        MyBase.OnEndPrint(document, e)
    End Sub

End Class

Here is a sample which creates a pdf of the Northwind product list.

Imports System.Data.SqlClient

Public Class Form1
    Public WithEvents p As New Printing.PrintDocument
    Dim iRecord As Integer = 0
    Dim fntPrice As New Font("Arial", 12)
    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strConn As String
        Dim conn As SqlConnection
        Dim da As SqlDataAdapter

        strConn = "Server = .\SQLEXPRESS;"
        strConn &= "Database = Northwind; Integrated Security = SSPI;"
        conn = New SqlConnection(strConn)
        da = New SqlDataAdapter("Select ProductName, UnitPrice From Products", conn)
        da.Fill(ds, "Products")

        DataGridView1.DataSource = ds.Tables("Products")
    End Sub

    Private Sub p_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles p.BeginPrint
        iRecord = 0
    End Sub

    Private Sub p_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles p.PrintPage
        Dim g As Graphics = e.Graphics
        Dim iPageHeight As Integer = e.PageBounds.Height
        Dim iPageWidth As Integer = e.PageBounds.Width
        Dim iFntHeight As Integer = CInt(g.MeasureString("Test", fntPrice).Height)
        Dim iLinesPerPage As Integer = iPageHeight \ iFntHeight - 15
        Dim yPos As Integer = 0
        Dim iTop As Integer
        Dim iMax As Integer = ds.Tables("Products").Rows.Count
        Dim strDescription As String
        Dim x As Integer
        Dim xPos As Integer
        Dim strPrice As String
        Dim fntTitle As Font = New Font("Microsoft Sans Serf", 14)
        Dim iCount As Integer = ds.Tables("Products").Rows.Count
        Dim strDate As String = Trim(Now.ToLongDateString)
        Dim sf As New StringFormat
        sf.Alignment = StringAlignment.Far

        xPos = CInt(iPageWidth - g.MeasureString("Price List", fntTitle).Width) \ 2
        g.DrawString("Price List", fntTitle, Brushes.Black, xPos, 10)
        yPos = 10 + CInt(g.MeasureString("Price List", fntTitle).Height)

        xPos = CInt(iPageWidth - g.MeasureString(strDate, fntPrice).Width) \ 2
        g.DrawString(strDate, fntPrice, Brushes.Black, xPos, yPos)
        yPos += 2 * iFntHeight
        g.DrawString("Product", fntPrice, Brushes.Black, 50, yPos)

        g.DrawString("Price", fntPrice, Brushes.Black, _
                New Rectangle(430, yPos, 100, 2 * iFntHeight), sf)

        yPos += iFntHeight
        g.DrawLine(Pens.Black, 0, yPos, iPageWidth, yPos)

        e.HasMorePages = True
        iTop = yPos

        For x = 0 To iLinesPerPage
            If iRecord < imax Then
                With ds.Tables("Products").Rows(iRecord)
                    strDescription = .Item("ProductName").ToString
                    strPrice = Convert.ToDecimal(.Item("UnitPrice")).ToString("c")
                End With
                Dim rName As New Rectangle(5, yPos, 400, iFntHeight)
                Dim rPrice As New Rectangle(430, yPos, 100, iFntHeight)

                g.DrawString(strDescription, fntPrice, Brushes.Black, rName)
                g.DrawString(strPrice, fntPrice, Brushes.Black, rPrice, sf)
            Else
                e.HasMorePages = False
            End If
            yPos += iFntHeight
            iRecord += 1
        Next
        fntTitle.Dispose()
        If e.HasMorePages = False Then iRecord = 0
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim pc As New PdfPrintController
        pc.Title = "Test Pdf"
        pc.Author = "Ken Tucker"
        pc.FileName = "Test.pdf"
        p.PrintController = pc
        p.Print()
    End Sub
End Class



kick it on DotNetKicks.com

VB Cascading Drop Down Example

by Ken Tucker 1. April 2008 16:53

Here is simple VB example of the AjaxToolkit's CascadingDropDown extender.  For this example I use the CarsService.Xml found in the AjaxToolkits sample site.  The xml file needs to be placed in the App_data directory

 

Here is the Pages Html

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="sm1" EnablePageMethods="true" runat="server">
        </asp:ScriptManager>
        <table>
            <tr>
                <td>
                    Make
                </td>
                <td>
                    <asp:DropDownList ID="DropDownList1" runat="server" Width="341px">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Model
                </td>
                <td>
                    <asp:DropDownList ID="DropDownList2" runat="server" Width="341px">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Color
                </td>
                <td>
                    <asp:DropDownList ID="DropDownList3" runat="server"  Width="341px">
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
    </div>
    <cc1:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
            Category="Make"  PromptText="Please select a make"  LoadingText="[Loading makes...]" ServiceMethod="GetDropDownContents">
    </cc1:CascadingDropDown>
    <cc1:CascadingDropDown ID="CascadingDropDown2" runat="server" TargetControlID="DropDownList2"
            Category="Model" PromptText="Please select a model" LoadingText="[Loading models...]"
            ServiceMethod="GetDropDownContents" ParentControlID="DropDownList1">
    </cc1:CascadingDropDown>
    <cc1:CascadingDropDown ID="CascadingDropDown3" runat="server" TargetControlID="DropDownList3"
            Category="Color" PromptText="Please select a color" LoadingText="[Loading colors...]"
            ServiceMethod="GetDropDownContents"
            ParentControlID="DropDownList2">
    </cc1:CascadingDropDown>
    </form>
</body>
</html>

 

In the code behind I am using a shared class so I only have to load the xml document once.

 

Imports System.Xml

Partial Class _Default
    Inherits System.Web.UI.Page

    <System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
 Public Shared Function GetDropDownContents(ByVal knownCategoryValues As String, ByVal category As String) As AjaxControlToolkit.CascadingDropDownNameValue()
        Dim knownCategoryValuesDictionary As StringDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)

        Return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(CarsInfo.Document, CarsInfo.Hierarchy, knownCategoryValuesDictionary, category)
    End Function
End Class


Public Class CarsInfo
    Private Shared _Doc As XmlDocument
    Private Shared _load As Boolean = True

    Public Shared ReadOnly Property Document() As XmlDocument
        Get
            If _load Then
                _Doc = New XmlDocument
                _Doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"))
                _load = False
            End If
            Return _Doc
        End Get
    End Property

    Public Shared ReadOnly Property Hierarchy() As String()
        Get
            Return New String() {"make", "model"}
        End Get
    End Property
End Class