VB Magic

2013/10/23

Accessing Jenkins API from VB.net

Filed under: .NET, ASP.NET MVC, VB.NET — Tags: , , , , , , — vbmagic @ 3:17 pm

As this was one of those things it took a while to track down I though a quick post would help others trying the same.

I have an up-to-date Jenkins server running builds and I would like to pull a list of failed jobs from the server and display them on a website.
First you need to look up the correct URL to access the list of jobs so after seeing a few posts in blogs and going to the Jenkins Website I worked out it follows this principle.

http{s}//{your Jenkins URL}/api/{xml/json}

If you leave off the xml/json parameter you will get a help page.

I my case I wanted the result in XML as VB.net has good xml integration. So my URL is:

http://mydomain.com:8080/api/xml

This will return something similar to the following XML code:

<hudson>
  <assignedLabel/>
  <mode>NORMAL</mode>
    <nodeDescription>the master Jenkins node</nodeDescription>
  <nodeName/>
  <numExecutors>2</numExecutors>
  <job>
    <name>ProjectBuild</name>
    <url>http://myhost.com:8080/job/ProjectBuild/</url>
    <color>blue</color>
  </job>
  <job>
    <name>IntegrationTests</name>
    <url>http://myhost.com:8080/job/IntegrationTests/</url>
    <color>red</color>
  </job>
  <overallLoad/>
  <primaryView>
    <name>All</name>
    <url>http://myhost.com:8080/</url>
  </primaryView>
  <quietingDown>false</quietingDown>
  <slaveAgentPort>0</slaveAgentPort>
  <unlabeledLoad/>
  <useCrumbs>false</useCrumbs>
  <useSecurity>true</useSecurity>
  <view>
    <name>All</name>
    <url>http://myhost.com:8080/</url>
  </view>
  <view>
    <name>Status</name>
    <url>http://myhost.com:8080/view/Status/</url>
  </view>
</hudson>

We can see that the job information is under the job element so the following code goes into the controller action. This code can be easily modified to work in a non ASP.net MVC environment.

        (...)
        Dim jenkinsURI As New Uri("http://myhost.com:8080/api/xml")
        Dim request As HttpWebRequest
        Dim xmlJobList As XElement
        model.failedJobs = New List(Of JenkinsJob)
        Try
            request = WebRequest.Create(jenkinsURI)
            Dim res As HttpWebResponse = request.GetResponse
            Dim reader As New StreamReader(res.GetResponseStream)
            xmlJobList = XElement.Parse(reader.ReadToEnd)
            reader.Close()
            For Each job In xmlJobList...<job>
                Dim c As String = job.<color>.Value
                If c = "red" Then
                    Dim jj As New JenkinsJob
                    jj.Name = job.<name>.Value
                    jj.URL = job.<url>.Value
                    jj.failed = True
                    model.failedJobs.Add(jj)
                End If
            Next
        Catch ex As Exception
            ' ignore for now
        End Try

        Return View(model)

It will loop through all the job nodes and if the color element is set to red then this indicates a filed job so add the name and URL to the view model to pass to the view.

This is the section of the view which will display the failed job. It uses the new bootstrap template that ships with Visual Studio 2013 and will only appear if the are any failed jobs.

    (...)
    @If Model.failedJobs.Count > 0 Then
        @<div class="col-md-3">
            <h2 class="alert-danger"><a href="http://myhost.com:8080/view/Status/" target="_blank" title="http://myhost.com:8080/view/Status/">Failed Jenkins Jobs</a></h2>
            <table cellpadding="2">
                <tr>
                    <th>Job Name</th>
                </tr>
                @For Each job In Model.failedJobs
                    @<tr>
                        <td><a href="@job.URL" title="@job.URL">@job.Name</a></td>
                    </tr>
                Next
            </table>
        </div>
    End If
    (...)

2013/01/30

MVC4 Templates and latest nuget javascript updates causes error in jquery.unobtrusive-ajax.js

Filed under: .NET, ASP.NET MVC — Tags: , , , , , — vbmagic @ 2:21 pm

I updated the nu-get packages for my newly created MVC4 website and I started to get lots of JavaScript errors as shown below.

Error Dialogue

It took a bit of web searching but I found a solution. A feature used in the MVC templates has been removed (Previously it was deprecated) from the latest version of JQuery (1.9)

I found a solution to this on Stack Overflow

Basically you need to add the jQuery.Migrate package to your solution via the package manager:

PM> Install-Package jQuery.Migrate

And then modify the BundleConfig.vb found in the App_Start folder in you project so that it references the jQuery.Migrate package.

Public Class BundleConfig
    ' For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
    Public Shared Sub RegisterBundles(ByVal bundles As BundleCollection)
        bundles.Add(New ScriptBundle("~/bundles/jquery").Include(
                   "~/Scripts/jquery-{version}.js",
                   "~/Scripts/jquery-migrate-1.0.0.js"))

This should fix the problem until the templates get updated.

2012/11/28

Adding in an Extra Tier

Filed under: .NET, ASP.NET MVC, Learning — Tags: — vbmagic @ 10:16 am

After thinking about making clients to access the game and the fact that it is probably easier to create a generator tool on a desktop client (Thinking Windows 8 here); I thought it would probably be best to create an Web API web role now rather than later. The website after all is basically a Client as well.
So new way of thinking. All clients including the website don’t know anything about Entity Framework or Azure Service bus. All they need to know about is how to access the API. Having this as an extra Tier will also allow easier scaling in future.
Looks like I’ll be hitting the Pluralsight ASP.NET Web API course this weekend.

2012/11/22

I feel a project coming together

As a way of trying to put all the stuff that I am learning together. I’ve come up with a project. I have been attempting to write a game for ages and have decided to make it using all the new Microsoft technologies. (You may have seen some of the preliminary work resulting in blog posts here.)

So this project will be a web based RPG game (With mobile clients to come later hopefully). It will be hosted in Azure and it will make use of Web Roles, Worker roles, SQL Azure, Azure Service Bus/ACS and Azure Storage. It will be written in Visual Basic .Net.

This is the website: https://www.tyranntrpg.org/

The front page has more details on what is going on and I hope to update the progress regularly here on this blog.

The current site doesn’t do too much as most of the work is going on behind the scenes. But the Codex part will get updates as things progress. In the images section of the codex you can see some of the artwork done by http://www.battleaxegfx.com/
This is one of the images (It will eventually be the Something has gone wrong image)
Dragon and Warrior

This project has been going on for a few years using different tools to create hence the collection of artwork and ideas.

Hopefully this time I’ll get it finished 🙂

2012/11/19

Hit a 404 error with a dot in an MVC 4 URL

Filed under: .NET, ASP.NET MVC — Tags: , , , , , — vbmagic @ 6:13 pm

Another quick post regarding passing a parameter that contains a “.” in it.

For example the below URL

http://myhost/home/edituser/me@mail.com

Started to cause a 404 error. I wasn’t sure why this was happening and after a lot of web surfing I came across the following information on Stack Overflow

Adding the following line into the HTTP <handlers> section for the path that contains the error:

<system.webServer>
    ....
    <handlers>
      ....
      <add name="ApiURIs-ISAPI-Integrated-4.0" path="/home/edituser/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

Will fix the issue.

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

@Code
    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>

<pre>
    @Html.Raw(Model.RawXML)
</pre>

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

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

2012/11/07

Windows Azure, Service Bus Queue between Webrole and Worker role

In a previous post I showed Azure Storage Queues being used to send messages between a Webrole and a Worker role.

I’ve got back onto this project to learn more about MCV 4 and Windows Azure Service Bus Queues. So I modified the original classes to use the SB Queues instead of Azure Storage queues. Behind the scenes Entity Framework Code First is being used to access the database. I’m loving the ability to change the classes and then run update-database to modify the SQL Azure database. Back to the queues.

First you need to create a queue which this article can walk you you through.

Once the queue is created put the connection string into the Azure Service Configuration file.

Below is the base class for a Job for this application.

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Net
Imports System.Threading
Imports Microsoft.ServiceBus
Imports Microsoft.ServiceBus.Messaging
Imports Microsoft.WindowsAzure
Imports Microsoft.WindowsAzure.Diagnostics
Imports Microsoft.WindowsAzure.ServiceRuntime
Imports Microsoft.WindowsAzure.Storage

Public MustInherit Class tjob


    ' Enable database access
    Protected Friend _db As New TyranntDb()
    ' A place holder for the user information
    Protected Friend _usr As Member
    ' setup variables to allow for access to Azure Queues
    Protected Friend _jobQueue As QueueClient

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

    ' 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

        Try
            UserID = Convert.ToInt64(usrstr)
        Catch ex As Exception
            ErrorMessage = ex.Message
            ReportError("tJob New Convert int64")
        End Try

    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
        Get
            Return _userID
        End Get
        Set(value As Integer)
            _userID = value
            If _userID > 0 Then
                GetUserDetails()
            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.Members
                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.
        _jobQueue = QueueClient.CreateFromConnectionString(CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"), "standard_queue")
        Try
            ' Now add the job details to the queue.
            Dim msg As New BrokeredMessage(Me.ToString)
            _jobQueue.Send(msg)
        Catch ex As Exception
            _ErrorMessage = ex.Message
            ReportError("AddJobToQueue")
        End Try
    End Sub

    Public Sub ReportError(location As String)
        Dim err As New ErrorMessage
        err.ErrorTime = DateTime.Now
        err.Location = location
        err.Message = Me.ErrorMessage
        _db.ErrorMessages.Add(err)
        _db.SaveChanges()
    End Sub
End Class

As you can see, this class must be inherited by another class which will perform the actual job. The base class will handle getting a users information from the database represented by the TyranntDB context class. I’ve added an error reporting system which will store any errors into a table in the database. The job information is stored in an XML format (The message queues allow for 64kb message which should be plenty for our purposes), so the inheriting class must implement a ToXml method. Also the inheriting job class must know how to do the job it is intended to perform so it must implement a Process method as well. Finally the class must be able to add its self to the message queue. So this base class has an AddJobToQueue method which makes use of the ToXml method the inheriting class has implemented to generate the message body to be added onto the queue. The service bus Imports at the top of the class will expose the QueueClient and the BrokeredMessage which is all that is required to add a message to the queue. You can see in the code how simple it is.

Next we need to add a new class that is derived from this base class to add a new member to the database. Below is the code that achieves this.

Public Class tjNewUser
    Inherits tjob

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

    ' 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
        MyBase.New(jobStr)
        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
        MyBase.New()
        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

        Try
            Dim r = From m In _db.Members
                          Where m.MemberAlias = _userName
                          Select m

            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.
                ErrorMessage = "User " & _userName & " Already exists"
                ReportError("tjNewUser Process")
                Return True
            End If
        Catch ex As Exception
            ErrorMessage = ex.Message
            ReportError("tjNewUser lynq query to get member ID")
        End Try

        ' create a new user
        Dim usr As New Member
        ' populate the generic information
        usr.EmailAddress = _email
        usr.Name = _fullName
        usr.MemberAlias = _userName
        usr.LastLogin = DateTime.Now
        ' now set the user group to be member
        Dim userType As MemberType

        Try
            userType = (From m In _db.MemberTypes
                     Where m.Name = "Member"
                     Select m).Single
        Catch ex As Exception
            ErrorMessage = ex.Message
            ReportError("tjNewUser Lynq query to get 'Member' member type")
            Return False
        End Try
        usr.Type = userType
        ' now save the user
        Try
            _db.Members.Add(usr)
            _db.SaveChanges()
        Catch ex As Exception
            ErrorMessage = ex.Message
            ReportError("tjNewUser Memebers.Add Save Changes")
            Return False
        End Try

        ' Now that the user was sucessfully created,
        ' generate a new user email job
        Dim jb As New tjEmail
        jb.EmailType = "NewAccount"
        jb.UserID = usr.ID
        ' Add the job to the Azure job queue
        jb.AddJobToQueue()
        If jb.ErrorMessage = "" Then
            Return True
        Else
            ErrorMessage = jb.ErrorMessage
            ReportError("tjNewUser Add Job to Queue produced error")
            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>
               </job>
    End Function

End Class

As you can see, this class has overrode the ToXML function and the Process Function which has the code that actually adds the user to the Members database. In the last part of the process function it creates a new job which will be used to send an email to the user about their newly created account. This job class is shown below.

Imports System.Net.Mail
Imports Microsoft.WindowsAzure

Public Class tjEmail
    Inherits tjob

    ' a sample email job
    Private sample = <job type="email" userid="102">
                         <email from="noreply@tyranntrpg.org" type="newuser"/>
                     </job>

    ' 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)
        MyBase.new(jobStr)
        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()
        MyBase.New()
        JobType = "email"
        _from = "noreply@tyranntrpg.org"
        _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 "NewAccount"
                email = GenerateNewUserEmail()
            Case Else
                ErrorMessage = String.Format("Email Type [{0}] not recognised", _emailType)
                ReportError("tjEmail Process")
                Return False
        End Select

        Dim smtp = New SmtpClient(CloudConfigurationManager.GetSetting("SMTPAddress"), Integer.Parse(CloudConfigurationManager.GetSetting("SMTPPort")))
        smtp.Credentials = New Net.NetworkCredential(CloudConfigurationManager.GetSetting("SMTPUser"), CloudConfigurationManager.GetSetting("SMTPPassword"))
        smtp.EnableSsl = True

        Try

            smtp.Send(email)

        Catch ex As Exception
            Me.ErrorMessage = ex.Message
            ReportError("tjEmail Send()")
            Return False
        End Try
        Return True
    End Function

    ' This will generate the subject and body of the newuser email
    Private Function GenerateNewUserEmail() As MailMessage
        If _usr Is Nothing Then
            ErrorMessage = "_usr is null"
            ReportError("GenerateNewUserEmail()")
            Return Nothing
        End If
        Dim email As New MailMessage(_from, _usr.EmailAddress)
        Dim subject As String = ""
        Dim body As String = ""
        Try
            Dim emailMsg = (From e In _db.EmailMessages
                            Where e.Name = "NewAccount"
                            Select e).Single
            subject = emailMsg.Subject
            body = String.Format(emailMsg.Body, _usr.Name)
        Catch ex As Exception
            ErrorMessage = ex.Message
            ReportError("GenerateNewUserEmail(), Lynq Query to _db.EmailMessages")
            Return Nothing
        End Try
        ErrorMessage = body
        email.Subject = subject
        email.Body = body
        Return email
    End Function

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

    Private Sub Smtp_SendCompleted(sender As Object, e As ComponentModel.AsyncCompletedEventArgs)
        If e.Error Is Nothing Then
            ErrorMessage = "Mail sent correctly"
            Me.ReportError("tjEmail SendCompleted")
        Else
            ErrorMessage = e.Error.Message
            Me.ReportError("tjEmail SendCompleted")
        End If
    End Sub

End Class

All the SMTP server information is held in the azure service configuration file. Again the overrode functions do all the work in this class.

Now onto the back end. This is uses the Worker Role With Service Bus Queue template (Shown Below)
New Worker Role Dialogue

As the job classes actually do all the work required, this is a very small piece of code.

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Net
Imports System.Threading
Imports Microsoft.ServiceBus
Imports Microsoft.ServiceBus.Messaging
Imports Microsoft.WindowsAzure
Imports Microsoft.WindowsAzure.Diagnostics
Imports Microsoft.WindowsAzure.ServiceRuntime
Imports Microsoft.WindowsAzure.Storage
Imports Tyrannt.Domain

Public Class WorkerRole
    Inherits RoleEntryPoint

    ' The name of your queue
    Const QueueName As String = "standard_queue"

    Private _db As New TyranntDb

    ' QueueClient is Thread-safe. Recommended that you cache 
    ' rather than recreating it on every request
    Dim Client As QueueClient
    Dim IsStopped As Boolean

    Public Overrides Sub Run()

        ' This is a sample implementation for Tyrannt.Backoffice. Replace with your logic.

        While (Not IsStopped)
            Try
                ' Receive the message
                Dim receivedMessage As BrokeredMessage = Client.Receive()

                If (Not receivedMessage Is Nothing) Then
                    ' Process the message
                    Trace.WriteLine("Procesing", receivedMessage.SequenceNumber.ToString())
                    ProcessMessage(receivedMessage)
                    receivedMessage.Complete()
                End If
            Catch ex As MessagingException
                If (Not ex.IsTransient) Then
                    Trace.WriteLine(ex.Message)
                    Throw ex
                End If
                Thread.Sleep(10000)
            Catch ex As OperationCanceledException
                If (Not IsStopped) Then
                    Trace.WriteLine(ex.Message)
                    Throw ex
                End If
            End Try
        End While

    End Sub

    Private Sub ProcessMessage(msg As BrokeredMessage)

        Dim msgBody As String = "msgBody not available"
        Dim errMsg As String = ""
        Try
            msgBody = msg.GetBody(Of String)()
            ' Turn the message into an XML element
            Dim xmlMsg As XElement = XElement.Parse(msgBody)
            ' Extract the message type from the element
            Dim type As String = xmlMsg.@type

            ' Now we create a job
            Dim job As tjob
            'ReportError("Processing job [" & type & "]", "WorkerRole.vb")
            Select Case type
                ' Use the message type to see what kind of job is required
                Case "newuser"
                    job = New tjNewUser(xmlMsg.ToString)
                Case "email"
                    job = New tjEmail(xmlMsg.ToString)
                Case Else
                    ReportError("job type [" + type + "] Not recognised", "WorkerRole.ProcessMessage()")
                    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")
            Else
                ' 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}]", msgBody, "Error"))
            ReportError(ex.Message, "WorkerRole.ProcessMessage()")
            Exit Sub
        End Try
    End Sub

    Public Overrides Function OnStart() As Boolean

        ' Set the maximum number of concurrent connections 
        ServicePointManager.DefaultConnectionLimit = 12

        ' Create the queue if it does not exist already
        Dim connectionString As String = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString")
        Dim namespaceManager As NamespaceManager = namespaceManager.CreateFromConnectionString(connectionString)
        If (Not namespaceManager.QueueExists(QueueName)) Then
            namespaceManager.CreateQueue(QueueName)
        End If

        ' Get a client to use the queue
        Client = QueueClient.CreateFromConnectionString(connectionString, QueueName)
        IsStopped = False
        Return MyBase.OnStart()

    End Function

    Public Overrides Sub OnStop()

        ' Close the connection to Service Bus Queue
        IsStopped = True
        Client.Close()
        MyBase.OnStop()

    End Sub

    Private Sub ReportError(msg As String, location As String)
        Dim err As New ErrorMessage
        err.ErrorTime = DateTime.Now
        err.Location = location
        err.Message = msg
        _db.ErrorMessages.Add(err)
        _db.SaveChanges()
    End Sub

End Class

I’ve added the ability to access the database to this class only for error reporting which helps tracking down any issues during development. The only subroutine aside from the error routines is the ProcessMessage. This function will get the message body. Work out what type of message it is and then generate the correct class and run the Process method. (Note: You can only use the GetBody method once, if you try more than once it will crash out.) In this example I complete the received message even if it fails to process (Failure gets added to the error table). In future I may end up doing more elaborate things.

I hope some people find this helpful.

2012/04/20

Free 1 month subscription to Pluralsight Training Course.

Filed under: .NET, ASP.NET MVC, Learning — vbmagic @ 3:28 pm

If you wanted to learn ASP.net MVC with a bit of Entity Framework Code First, HTML 5 and jQuery thrown in Pluralsight are offering a free months subscription to this course:

http://www.pluralsight-training.net/microsoft/Courses/TableOfContents?courseName=web-development

All you need to do is follow them on twitter https://twitter.com/#!/pluralsight

And then go to this web page on their web site: http://www.pluralsight-training.net/microsoft/TwitterOffer

And put in your twitter name.

I’ve been a subscriber to their courses for a while now and find them invaluable.

2011/08/10

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">
                         <type/>
                     </job>

    ' 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
        Get
            Return _userID
        End Get
        Set(value As Integer)
            _userID = value
            If _userID > 0 Then
                GetUserDetails()
            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.
        _jobQueue.CreateIfNotExist()
        Try
            ' Now add the job details to the queue.
            Dim msg As New CloudQueueMessage(Me.ToString)
            _jobQueue.AddMessage(msg)
        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>
                     </job>

    ' 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
        MyBase.New(jobStr)
        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
        MyBase.New()
        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
        Try
            Dim grp As tUserGroup = _db.GetUserGroup("member")

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

        ' now save the user
        Try
            _db.users.Add(usr)
            _db.SaveChanges()
        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
        jb.AddJobToQueue()
        If jb.ErrorMessage = "" Then
            Return True
        Else
            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>
               </job>
    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"/>
                     </job>

    ' 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)
        MyBase.new(jobStr)
        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()
        MyBase.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)
        Try
            smtp.Send(email)
        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 %>/>
               </job>
    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
                Thread.Sleep(60000)
            Else
                ' Message exists so process the message
                ProcessMessage(msg)
            End If
        End While
    End Sub

    Private Sub ProcessMessage(msg As CloudQueueMessage)

        Try
            ' 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")
                _jobQueue.DeleteMessage(msg)
            Else
                ' 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.

Jas

2011/07/25

Getting an ASP.NET MVC Razor site into the cloud

Filed under: ASP.NET MVC, Azure, Learning — Tags: , , , , , — vbmagic @ 12:53 pm

I started to work on a web role to test out experiments with ADO.net code first and ASP.NET MVC 3 with Razor. Out of the box, VS 2010 does not support ASP.net MVC 3 so I created the Azure project, then added a ASP.NET MVC 3 project separately. I then added that MVC project to the Azure project as a web role. Clicked run and all seemed to work fine.

But as with all things Azure, if it works in the developer environment, don’t expect it to automatically work in the cloud.

It didn’t. But I was expecting that. It was a bit hard to track down what the problems were as it only manifested as a web role that never seemed to get started.

Once I had worked out that meant it was missing core components for the web site, I was pleasantly surprised was how easy it was to fix this.

On your MVC 3 project right click the project solution and then select “Add Deployable Dependencies”

Then click the “ASP.NET MVC” and the “ASP.NET Web Pages with Razor syntax” check boxes and click ok.

You will then find a directory added to your project called _bin_deployableAssemblies.

All I did after this was “Deploy” the Azure Project and after waiting for the project to deploy into the cloud, it all started ok and worked.

I wish all problems were as easy to solve as this 🙂

Jas

Older Posts »

Blog at WordPress.com.