VB Magic


Displaying Formatted XML in an ASP.net Razor Web Page

Filed under: .NET, ASP.NET MVC, VB.NET — Tags: , , , — vbmagic @ 4:10 pm

A quick post for those looking to display a formatted XML document on an ASP.net Razor web page. The following code is in the controller and used to create the string to get passed through to the view. This example is based on displaying the information pulled from the Azure Management API as mentioned in previous blogs. The data is stored in a SQL Server database.

    Function ShowRawXML(serviceOperationId As String, subscriptionName As String) As ActionResult
        Dim model As New ShowRawXMLViewModel

        Dim op = (From o In _db.ServiceOperations
                  Where o.ServiceOperationId = serviceOperationId And o.Subscription.FriendlyName = subscriptionName
                  Select o).Single

        model.RawXML = vbCr & Server.HtmlEncode(op.RawXML)
        model.SubscriptionName = subscriptionName
        model.SubscriptionID = op.Subscription.SubscriptionID
        model.ServiceOperationID = serviceOperationId
        model.ServiceOperationType = op.Type.Name

        Return View(model)
    End Function

In the view, we are going to use the @Html.Raw function so we used the Server.HtmlEncode function to make it safe to display in HTML. Next we get to the razor view…

@ModelType AzureManager.Domain.ShowRawXMLViewModel

    ViewData("Title") = "ShowRawXML"
End Code

<h2>Subscription ID [@Model.SubscriptionID] @Model.SubscriptionName</h2>

<h3>Show Raw XML for Service Operation @Model.ServiceOperationID</h3>
<h3>Operation Type: @Model.ServiceOperationType</h3>


    @Html.ActionLink("Back to List", "ServiceOperations", New With {.Id = Model.SubscriptionName})

Here you notice we display the raw XML inside a <pre></pre> tag. This will preserve the white space in the string. More information on this here: HTML <pre> Tag


Parsing the HTTPResponse from the Azure Management API

Filed under: .NET, Azure, VB.NET — Tags: , , , , , — vbmagic @ 5:50 pm

Ok, after that last example I ended up pulling what hair I had left in my head out trying to parse the XML that got returned. I have come across this problem before but my memory being what it is I had totally forgotten about it so have written this blog post to help remind myself next time this happens.

I couldn’t seem to be able to get at the elements in the data. I was doing this:

            ' Parse the web response
            responseStream = httpResponse.GetResponseStream
            reader = New StreamReader(responseStream)
            Dim rawOutput As String = reader.ReadToEnd
            Dim xdoc As XDocument = XDocument.Parse(rawOutput)

            Dim serviceOperations = From s In xdoc.Descendants("SubscriptionOperation")
                                    Select s

            For Each s In serviceOperations
                Dim email = s.Descendants("UserEmailAddress").Value
                Dim operation = s.Descendants("OperationName").Value
                Dim opDate = s.Descendants("OperationStartedTime").Value
                Console.WriteLine(String.Format("User: {0} Did: {1} On: {2}", email, operation, opDate))

And stepping through the code I found that ServiceOperations resolved to nothing. After a couple of hours of poking and prodding and then searching the internet I came across the solution in this post: Fetching Hosting Services Name Using Windows Azure Management API

Namespaces! Memory starts ticking over and I remember hitting this before. So here is the revised code (In full) which will get Subscription details (Basically audit information) from the Management API

Imports System.Net
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        ' X.509 certificate variables
        Dim certStore As X509Store
        Dim certCollection As X509Certificate2Collection
        Dim certificate As X509Certificate2

        ' Request and response variables
        Dim httpRequest As HttpWebRequest
        Dim httpResponse As HttpWebResponse

        ' Stream variables
        Dim responseStream As Stream
        Dim reader As StreamReader

        ' URI variable
        Dim requestURI As Uri


            ' specify time range
            Dim startTime As String = "2012-11-11"
            Dim endTime As String = "2012-11-13"

            ' The ID for the Windows Azure subscription.
            Dim subscriptionId As String = "{Your Subscription}"

            ' The thumbprint for the certificate. This certificate would have been
            ' previously added as a management certificate within the Windows
            ' Azure management portal.
            Dim thumbPrint As String = "{Your Thumbprint}"

            ' Open the certificate store for the current user.
            certStore = New X509Store(StoreName.My, StoreLocation.CurrentUser)

            ' Find the certificate with the specified thumbprint
            certCollection = certStore.Certificates.Find(

            ' close the certificate store

            ' Check to see if mat
            If certCollection.Count = 0 Then
                Throw New Exception("No certificate found containing thumbprint " & thumbPrint)
            End If

            ' A matching certificate was found.
            certificate = certCollection(0)
            Console.WriteLine("Using certificate with thumbprint: " & thumbPrint)

            ' create new request
            requestURI = New Uri(
                              subscriptionId, startTime, endTime)

            httpRequest = HttpWebRequest.Create(requestURI)

            ' add certificate to requrest

            ' Specify the version information in the header
            httpRequest.Headers.Add("x-ms-version", "2012-03-01")
            httpRequest.ContentType = "application/xml"

            ' Make the call using the web request
            httpResponse = httpRequest.GetResponse

            ' Display the response status code
            Console.WriteLine("Response status code: " _
                              & httpResponse.StatusCode)

            ' Display thr request ID returned by windows azure
            If httpResponse.Headers IsNot Nothing Then
                Console.WriteLine("x-ms-request-id: " & httpResponse.Headers("x-ms-request-id"))
            End If

            ' Parse the web response
            responseStream = httpResponse.GetResponseStream
            reader = New StreamReader(responseStream)
            Dim rawOutput As String = reader.ReadToEnd
            Dim ns As XNamespace = "http://schemas.microsoft.com/windowsazure"

            Dim xdoc As XDocument = XDocument.Parse(rawOutput)

            Dim serviceOperations = From s In xdoc.Descendants(ns + "SubscriptionOperation")
                                    Select s

            For Each s In serviceOperations
                Dim email = s.Descendants(ns + "UserEmailAddress").Value
                Dim operation = s.Descendants(ns + "OperationName").Value
                Dim opDate = s.Descendants(ns + "OperationStartedTime").Value
                Console.WriteLine(String.Format("User: {0} Did: {1} On: {2}", email, operation, opDate))

        Catch ex As Exception
            Console.WriteLine("Error encountered: " & ex.Message)
        End Try
    End Sub

End Module

This can be used as an example to pull audit information from Azure. I hope this helps others not make my silly mistake 😉

P.s. I hope you like the new theme. Thanks to the above blog post (Debugmode.net) for showing it to me. It makes reading source code much better on wider monitors.


Azure Queues

I’ve been learning about using Queues in Azure and thought the best way to learn was to start writing an application to test this. My example site will probably only run on single instances; but I decided from the start to write something that will be scalable so came up with the following principle

The client/website can only READ from the database. Anything that requires updating the database must be done via the back end. The client/website must be able to cope with the fact that the requested update will not happen immediately.

The upshot of this, I came up with a job system that uses Azure queues to pass work to the back end worker role. For the moment, I decided to have one queue which handled multiple types of jobs. This lead to me creating a job base class which will cover the common things that the different jobs required. I also decided to use an XML format to describe the job. I need to make sure though that the jobs do not grow bigger than the size allowed for an Azure Queue job (8k).

Below is the base class which is inherited in the actual job classes:

Imports Microsoft.WindowsAzure
Imports Microsoft.WindowsAzure.StorageClient
Imports Microsoft.WindowsAzure.ServiceRuntime

Public MustInherit Class tjob

    ' Enable database access
    Protected Friend _db As New TyranntDB
    ' A place holder for the user information
    Protected Friend _usr As tUser
    ' setup variables to allow for access to Azure Queues
    Protected Friend _storageAccount As CloudStorageAccount
    Protected Friend _jobQueue As CloudQueue

    ' A sample of a job entry in the Queue
    Private sample = <job type="email" user="102">

    ' the user ID which is used to pull the user information
    Private _userID As Int64

    ' Initialise the job from the XML String
    Public Sub New(jobStr As String)
        Dim jobXML As XElement = XElement.Parse(jobStr)
        _JobType = jobXML.@type
        Dim usrstr As String = jobXML.@userid
        UserID = Convert.ToInt64(usrstr)
    End Sub

    ' Create a blank job, this is used for creating a job to
    ' put onto the queue.
    Public Sub New()
        _JobType = ""
        _userID = -1
    End Sub

    ' Job type. Used to create the correct object.
    Public Property JobType As String

    ' The user ID. If this is being set then it
    ' will look up the user from the database
    Public Property UserID As Integer
            Return _userID
        End Get
        Set(value As Integer)
            _userID = value
            If _userID > 0 Then
            End If
        End Set
    End Property

    ' This is the code that "Processes" the job. Each job type must
    ' implement this code.
    Public MustOverride Function Process() As Boolean

    ' A general variable for storing any errors that
    ' occur. If it's empty then no errors are assumed.
    Public Property ErrorMessage As String

    ' This will generate an XML element that describes the job.
    Public MustOverride Function ToXML() As XElement

    ' This will generate a string version of the XML
    ' which describes this job.
    Public Overrides Function ToString() As String
        Return ToXML.ToString
    End Function

    ' This routine will pull the user information from the
    ' database and store the user detals in the _usr object.
    Protected Friend Sub GetUserDetails()
        Dim q = From u In _db.users
              Where u.ID = _userID
              Select u
        If q.Count > 0 Then
            _usr = q.Single
        End If
    End Sub

    ' If the job is being created. This function will add the job
    ' to the Azure Queue.
    Public Sub AddJobToQueue()
        ' Get the azure storage account object.
        _storageAccount = CloudStorageAccount.Parse( RoleEnvironment.GetConfigurationSettingValue(TyranntSupport.Constants.STORAGE_CONNECTION))
        ' Now get the queue client.
        Dim client As CloudQueueClient = _storageAccount.CreateCloudQueueClient
        _jobQueue = client.GetQueueReference(Constants.QUEUE_JOBS)
        ' Create the queue if it doesn't exist.
            ' Now add the job details to the queue.
            Dim msg As New CloudQueueMessage(Me.ToString)
        Catch ex As Exception
            _ErrorMessage = ex.Message
        End Try
    End Sub
End Class

The TyranntDB class is an Entity Framework code first class that allows access to the SQL Azure database. Any class prefixed with a t (E.g. tUser) is a database table class. You will notice a Sample variable using XML Literals. This is just as an example to show how that job is formed in XML. Each inherited class will have it’s own sample.

All job classes need to be able to add themselves to the Azure Queue. They also need to be able to access the SQL Azure database. These features were written into the base class. All job classes must also have a way of being “Processed” which meant adding a MustOverride function called Process. They must also be able to export themselves as an XML document which is why the MustOverride function called ToXML is added.

The website uses Forms Authentication to enable it to validate users. But I also have a site specific user table to add extra information too. As this involves updating the database, this is the first “Job” that needs creating:

Public Class tjNewUser
    Inherits tjob

    ' an example of a new user job
    Private sample = <job type="newuser" user="-1">
                         <user name="{username}" email="{user)@{domain}">Full Name</user>

    ' Extra data required by this class
    Public Property userName As String
    Public Property email As String
    Public Property fullName As String

    Public Sub New(jobStr As String)
        ' initialise basic information
        Dim jobXML As XElement = XElement.Parse(jobStr)
        ' now initialise new user information
        _userName = jobXML...<user>.@name
        _email = jobXML...<user>.@email
        _fullName = jobXML...<user>.Value
    End Sub

    Public Sub New()
        ' initialise the base information
        JobType = "newuser"
        _userName = ""
        _email = ""
        _fullName = ""
    End Sub

    ' Create the new user in the database
    Public Overrides Function Process() As Boolean
        ' first check to see if the user already exists

        Dim r = From u In _db.users
              Where u.username = _userName
              Select u

        If r.Count > 0 Then
            ' User already exists so do not continue
            ' return true in this case as request
            ' has been processed more than one.
            Return True
        End If
        ' create a new user
        Dim usr As New tUser
        ' populate the generic information
        usr.username = _userName
        usr.email = _email
        usr.fullname = _fullName
        ' now set the user group to be member
            Dim grp As tUserGroup = _db.GetUserGroup("member")

            If IsNothing(grp) Then
                usr.usergroup = _db.GetUserGroup("member")
                usr.usergroup = grp
            End If
        Catch ex As Exception
            ErrorMessage = ex.Message
            Return False
        End Try

        ' now save the user
        Catch ex As Exception
            ErrorMessage = ex.Message
            Return False
        End Try

        ' Now that the user was sucessfully created,
        ' generate a new user email job
        Dim jb As New tjEmail
        jb.EmailType = "newuser"
        jb.From = "mail@me.uk"
        jb.UserID = usr.ID
        ' Add the job to the Azure job queue
        If jb.ErrorMessage = "" Then
            Return True
            ErrorMessage = jb.ErrorMessage
            Return False
        End If
    End Function

    Public Overrides Function ToXML() As XElement
        Return <job type="newuser" userid=<%= UserID %>>
                   <user name=<%= _userName %> email=<%= _email %>><%= _fullName %></user>
    End Function

End Class

I’ve added the extra properties required for adding a new user and the extraction of these properties from the XML. The process function is also created which will create the user row in the users table. Hopefully the comments in the code should explain the process to do this. This routine also makes use of XML Literals which is a VB only thing at time of writing. (For example used in the ToXML and New functions.

As you can see at the end of the processing, we need to send a confirmation email to the user who has created the account. This kind of thing is also ideal for the back end to deal with hence being handled by the job queue system:

Imports System.Net.Mail

Public Class tjEmail
    Inherits tjob

    ' a sample email job
    Private sample = <job type="email" user="102">
                         <email from="mail@me.uk" type="newuser"/>

    ' setup extra information required by this job
    Private _from As String
    Private _emailType As String

    ' The is the from email address
    Public WriteOnly Property From As String
        Set(value As String)
            _from = value
        End Set
    End Property

    ' This will be the email type e.g. newuser
    Public WriteOnly Property EmailType As String
        Set(value As String)
            _emailType = value
        End Set
    End Property

    ' If the job XML already exists this will set up
    ' the information automatically
    Public Sub New(jobStr As String)
        Dim jobXML As XElement = XElement.Parse(jobStr)
        _from = jobXML...<email>.@from
        _emailType = jobXML...<email>.@type
    End Sub

    ' Create an empty email job if creating a new job
    Public Sub New()
        JobType = "email"
        _from = ""
        _emailType = ""
    End Sub

    ' Send the email
    Public Overrides Function Process() As Boolean
        Dim email As MailMessage
        ' Generate the correct body of the email
        Select Case _emailType
            Case "newuser"
                email = GenerateNewUserEmail()
            Case Else
                ErrorMessage = String.Format("Email Type [{0}] not recognised", _emailType)
                Return False
        End Select

        ' Now set up the SMTP server client to send the email.
        Dim smtp As New SmtpClient(My.Resources.smtpServer, Integer.Parse(My.Resources.smtpPort))
        ' Pull the smtp login details.
        smtp.Credentials = New Net.NetworkCredential(My.Resources.smtpUser, My.Resources.smtpPass)
        Catch ex As Exception
            ErrorMessage = ex.Message
            Return False
        End Try
        Return True
    End Function

    ' This will generate the subject and body of the newuser email
    Private Function GenerateNewUserEmail() As MailMessage
        Dim email As New MailMessage(_from, _usr.email)
        email.Subject = My.Resources.Resources.TyranntAccountCreated
        email.BodyEncoding = System.Text.Encoding.Unicode
        email.IsBodyHtml = False
        email.Body = String.Format(My.Resources.newUserEmail, _usr.username)
        Return email
    End Function

    Public Overrides Function ToXML() As XElement
        Return <job type="email" userid=<%= UserID %>>
                   <email from=<%= _from %> type=<%= _emailType %>/>
    End Function

End Class

The process function in this job will generate an email and pull the smtp server details out of a resource file and depending on the type of email, will take the email body from resources too.

Now these job classes are created, they can be added to the job queue by using {job}.AddJobToQueue() method as shown in the tjNewUser class. But how will they be processed. This is where the WorkerRole comes into play. As all the work is done by the job classes themselves, only a very simple piece of code is required to process the queues:

    Public Overrides Sub Run()

        Trace.WriteLine("TyranntDogsbody entry point called.", "Information")

        ' Loop forever
        While (True)
            ' Get the next message from the queue
            Dim msg As CloudQueueMessage = Nothing
            msg = _jobQueue.GetMessage(TimeSpan.FromSeconds(30))

            If IsNothing(msg) Then
                ' If message doesn't exist then seep for 1 minute
                ' Message exists so process the message
            End If
        End While
    End Sub

    Private Sub ProcessMessage(msg As CloudQueueMessage)

            ' Turn the message into an XML element
            Dim xmlMsg As XElement = XElement.Parse(msg.AsString)
            ' Extract the message type from the element
            Dim type As String = xmlMsg.@type

            ' Now we create a job
            Dim job As tjob
            Select Case type
                ' Use the message type to see what kind of job is required
                Case "newuser"
                    job = New tjNewUser(msg.AsString)
                Case "email"
                    job = New tjEmail(msg.AsString)
                Case Else
                    Exit Sub
            End Select
            ' Process the job.
            If job.Process() = True Then
                ' The job succeeded so write a trace message to say this and
                ' delete the message from the queue.
                Trace.WriteLine(String.Format("{0} succeeded", type), "Information")
                ' The job failed so write a trace error message saying why the job failed.
                ' This will leave the job on the queue to be processed again.
                Trace.WriteLine(String.Format("{0} failed: {1} ", type, job.ErrorMessage), "Error")
            End If
        Catch ex As Exception
            ' something big has gone wrong so write this out as an error trace message.
            Trace.WriteLine(String.Format("Failed to parse xml message: [{0}]", msg.AsString), "Error")
            Exit Sub
        End Try
    End Sub

As you can see from the above code. There very little extra code required to process the job as all the work is done inside the job class.

This may be refined in the future but I hope it’s helpful for some people.



Quick post about XML Literals

Filed under: .NET, VB.NET — Tags: , , — vbmagic @ 9:41 pm

Just a quick post as I’ve decided to write a simplified standalone version of a game to get some game mechanics designed. As a way of storing information that would have been stored I though I would use XML for the “Static” information which brings me to the great XML literals addition to vb.NET. Makes the code so much more readable and it also allows auto complete and error checking while you type it.

Below is a snippet of code to give an example of how the data is generated.

        Dim classes As XElement =
                <class description="A Character trained in weapons and armour">Fighter</class>
                <class description="A Character trained in Ranged and close quarters combat">Rogue</class>
                <class description="A Character trained in the arcane arts of combat">Mage</class>
                <class description="A Character trained in the arcane arts of healing and defence">Priest</class>

        Dim mobs As XElement =
                <mob strength="1d4+2" constitution="1d6" dexterity="1d4" intelligence="3"
                    weapon="Rats Teeth">Giant Rat</mob>

        Dim items As XElement =
                <item type="weapon" value="1d4" action="stabs">Dagger</item>
                <item type="weapon" value="1d4+1" action="strikes">Staff</item>
                <item type="weapon" value="1d6" action="Shoots">Bow</item>
                <item type="weapon" value="1d6" action="swings">Short Sword</item>
                <item type="defence" value="1" action="">Robes</item>
                <item type="defence" value="2" action="">Leather Armour</item>
                <item type="defence" value="1d4-2" action="">Shield</item>
                <item type="potion" value="1d4" action="quaffs" stat="mana">Mana Potion</item>
                <item type="potion" value="1d4" action="quaffs" stat="hp">Health Potion</item>

                <item type="weapon" value="1d4-1" action="bites">Rats Teeth</item>

        Dim spells As XElement =

        Dim maps As XElement =
                <map name="test" rows="10" cols="10">
                    <row number="0">##########</row>
                    <row number="1">#*#f...g>#</row>
                    <row number="2">#.#.######</row>
                    <row number="3">#a#.#....#</row>
                    <row number="4">#+#.#.##.#</row>
                    <row number="5">#.#..e##.#</row>
                    <row number="6">#.######.#</row>
                    <row number="7">#.#....+d#</row>
                    <row number="8">#b+c...###</row>
                    <row number="9">##########</row>
                    <event type="message" description="As you were walking along the field, the ground shook and split appart and you landed in what looks to be an old mine tunnel">*</event>
                    <event type="message" description="You notice bones on the floor">a</event>
                    <event type="message" description="You hear scratching noises through the door">b</event>
                    <event type="fight" description="Giant rats run at you as you enter the room" mob="Giant Rat" mobcount="1d4">c</event>
                    <event type="item" description="You find a health potion on the floor" item="Health Potion" itemcount="1">d</event>
                    <event type="fight" description="Giant Rats swarm round the corrner of the tunnel" mob="Giant Rat" mobcount="1d4+4">e</event>
                    <event type="message" description="You feel a breeze from the end of the corridor">f</event>
                    <event type="message" description="You see a ladder ahead leading out of the tunnel">g</event>


Dynamically creating pivot items and populating with data

Filed under: Learning — Tags: , , , , , , , — vbmagic @ 5:01 pm

I’ve spent the weekend trying to work out how to create the pages you see on a Pivot Page dynamically through code. It took a lot of web searching and trial and errors but I seem to have managed to get the basics of this worked out. I’m posting this to help other people who are trying to do the same thing. In this case it works, but if anyone else has a better/more efficient way of doing this I would be interested in looking at it.

The database/Web server has a directory full of images which the web service will pass back to the client using XML. Each image can belong to a image type. Each of these types will be a Pivot Item in the Pivot page. The list of images for each of these types will be displayed on each of these Pivot items.

I started by creating a pivot page and deleted any pivot items that where in the XAML. I then created the following Page Load event code:

    Private _client As New adminServiceReference.AdminServiceClient

    Private Sub PhoneApplicationPage_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        ' setup the event handlers for retrieving image types and image lists
        AddHandler _client.GetImageTypesCompleted, AddressOf client_GetImageTypesCompleted
        AddHandler _client.GetImagesCompleted, AddressOf client_GetImagesCompleted

        ' request the image types
        Dim str As New StrType
        str.TokenGUID = GetToken()
    End Sub

    Private Function GetToken() As Guid
        Dim result As Guid
        If _phoneAppService.State.TryGetValue("token", result) Then
            Return result
            MessageBox.Show("Failed to retrieve token")
            Return Nothing
        End If
    End Function

This will call the GetImageTypes web service on the server (I will document these in another post)
Once the request has been completed, all the image types will be sent back to the client in XML format.

    ' Routine to handle the Get Image Types completed event.
    Private Sub client_GetImageTypesCompleted(ByVal sender As Object, ByVal e As adminServiceReference.GetImageTypesCompletedEventArgs)
        If e.Error Is Nothing Then
            Dim types = e.Result
            ' did the server side report an error?
            If types.ErrorMessage = "" Then
                ' no so loop through each Image type in the xml result
                For Each ele In types.xml...<type>
                    ' We need to create a new Pivot item for each image type
                    Dim p As New PivotItem
                    ' set the header name to the lowercase version of the type name
                    ' this is to fit in with the standard way of showing pivot items
                    p.Header = ele.Value.ToLower
                    ' add the pivot item to the pivot page
                    ' now request all the images under of that type
                    Dim str As New StrType
                    str.text = ele.Value
                ' The server side got an error so display the error
                ' to aid in debugging.
            End If
            ' the request to the webservice caused an error so
            ' display this error to try and help debug the problem.
        End If
    End Sub

The comments in the above code should lead you through the creation and titling of the PivotItem and used XML Literals a very handy feature in VB to make code more readable when interacting with XML. (This should be implemented in C#)

For each image type pivot item created it will also request all the images for that image type which the following code will handle.

    ' a routine to handle the Get Images completed event.
    Private Sub client_GetImagesCompleted(ByVal sender As Object, ByVal e As adminServiceReference.GetImagesCompletedEventArgs)
        ' Did the request cause an error
        If e.Error Is Nothing Then
            Dim imgs = e.Result
            ' Did the web server get an error while processing the request.
            If imgs.ErrorMessage = "" Then
                ' no error so start searching the PivotItems to find the one matching
                ' the type that we requested the images for.
                For Each pg As PivotItem In imagePivotControl.Items
                    If pg.Header.ToString = imgs.type.ToLower Then
                        ' We have a match so create a listbox item to hold the details
                        Dim lb As New ListBox
                        ' we need a counter to display next to the image
                        ' this is only temorary until we have an image there
                        Dim cnt As Integer = 0
                        ' Loop through all the image elements in the returned XML
                        For Each ele In imgs.xml...<image>
                            ' We need to create a grid to store the information in the
                            ' list box item this is the equivilent to the following XAML
                            '   <grid>
                            '       <Grid.RowDefinitions>
                            '           <RowDefinition Height="Auto"/>
                            '       </Grid.RowDefinitions>
                            '       <Grid.ColDefinitions>
                            '           <ColDefinition Width="100"/>
                            '           <ColDefinition Width="Auto"/>
                            '       </Grid.RowDefinitions>
                            '    </grid>

                            ' Create the grid object
                            Dim grd As New Grid
                            ' Create the row definition objec
                            Dim rowdef As New RowDefinition
                            ' the row definition object uses a object called gridlength
                            ' we create one of these and set it to Auto
                            Dim glen As New GridLength
                            glen = GridLength.Auto
                            ' we add the height information to the row definition
                            rowdef.Height = glen
                            ' now we add the row definition to the list of row definitions
                            ' in the grid object
                            ' Now we need to create a column definition
                            Dim coldef As New ColumnDefinition
                            ' the first column has a width of 100 pixels for now, it will
                            ' contain an image eventually and we can leave it set to auto.
                            coldef.Width = New GridLength(100)
                            ' add the column definition to the list of column definitions in
                            ' the grid object.
                            ' we now create the second column definition to auto which is the
                            ' same as we used with the row definiton so lets just re-use
                            ' this object.
                            coldef = New ColumnDefinition
                            coldef.Width = glen
                            ' add the final column definition to the collection of column
                            ' definitions in the grid object.

                            ' Now we start to add the data, first we create a textblock that
                            ' will be used to hold the count.
                            ' This is the equivilent to the following XAML.
                            '   <TextBox Grid.Column="0" Grid.Row="0" Text="{cnt.string}"/>
                            Dim tb = New TextBlock
                            ' we set the row and column of the textblock to make it appear in
                            ' the correct loctation
                            Grid.SetColumn(tb, 0)
                            Grid.SetRow(tb, 0)
                            ' set the text property of the text block to the current count
                            tb.Text = cnt.ToString
                            ' add the textblock to the children objects of the grid.
                            ' Now we add a new text block which will display the name of the
                            ' image file on the server.
                            ' This is the equivilent to the following XAML
                            '   <TextBox Grid.Column="1" Grid.Row="0" Text="{ele.value}"/>
                            tb = New TextBlock
                            ' set the row and column information of the text block.
                            Grid.SetColumn(tb, 1)
                            Grid.SetRow(tb, 0)
                            ' pull the content of the image item ( <image>value</image> ) and
                            ' put this into the text property of the text block
                            tb.Text = ele.Value
                            ' add the text block to the child objects of the grid.

                            ' Now we create the list box item to add to the list box in
                            ' the pivot item.
                            Dim lbi As New ListBoxItem
                            ' add the grid to the listbox item
                            lbi.Content = grd
                            ' and add the list box item to the list box
                            ' increment the counter
                            cnt += 1
                        ' add the list box to the pivot item.
                        pg.Content = lb
                    End If
                ' the server produced and error so display to aid in debugging
            End If
            ' the request caused and error so display this to aid in debugging
        End If
    End Sub

Again I have commented the code to lead you through how the listbox and listbox items are created from the XML results and used to populate the pivot item for each image type.


Blog at WordPress.com.