Monday, December 26, 2011

Unit Test Initialization and Cleanup for Windows Azure Storage Emulator

My unit tests add and delete entities from local Windows Azure dev storage,  at their most basic. If the Azure Storage emulator isn’t started, the tests don’t fail quickly – they just sit there acting like the test framework is hung. In order to ensure that the tests proceed, I needed to make sure the emulator was started before the tests ran.

 

I started with code found in this thread on StackOverflow. I needed to make sure the Storage Emulator is started before the test classes are called and that the emulator is shut down when the tests are done. I wrote this class and added it as a separate file to my test assembly.

 

More information about CSRun.exe and the Process class are available in MSDN.

 

// -----------------------------------------------------------------------
// <copyright file="AssemblySpecific.cs" company="BerryIntl">
// Berry International 2011
// </copyright>
// -----------------------------------------------------------------------

namespace Wp7AzureMgmt.Dashboard.Test
{
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Linq;
    using System.Diagnostics;
    using System.IO;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Class containing assembly specific test initialization and cleanup
    /// </summary>
    [TestClass]
    public class AssemblySpecific
    {
        /// <summary>
        /// Location of csrun.exe - may be different base on install point and azure sdk version
        /// </summary>
        private const string AzureSDKBin = @"C:\Program Files\Windows Azure Emulator\emulator";

        /// <summary>
        /// Code to run before ClassInitialize or TestInitialize
        /// </summary>
        /// <param name="context">TestContext context</param>
        [AssemblyInitialize]
        public static void MyAssemblyInitialize(TestContext context)
        {
            List<Process> processStatus = Process.GetProcessesByName("DSService.exe").ToList();

            if (( processStatus == null ) || ( processStatus.Count == 0 ))
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo()
                {
                    FileName = Path.Combine(AzureSDKBin, "csrun.exe"),
                    Arguments = "/devstore",
                };
                using (Process process = Process.Start(processStartInfo))
                {
                    process.WaitForExit();
                }
            }
        }

        /// <summary>
        /// Code to run before ClassCleanup or TestCleanup
        /// </summary>
        [AssemblyCleanup]
        public static void MyAssemblyInitialize()
        {
            List<Process> processStatus = Process.GetProcessesByName("DSService.exe").ToList();

            if ((processStatus != null) || (processStatus.Count > 0))
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo()
                {
                    FileName = Path.Combine(AzureSDKBin, "csrun.exe"),
                    Arguments = "/devstore:shutdown",
                };
                using (Process process = Process.Start(processStartInfo))
                {
                    process.WaitForExit();
                }
            }
        }
    }
}

Thursday, December 8, 2011

Simple Azure Web and Worker Roles–Running the code

This is a continuation of the simple series. Links for other posts in the series are at the bottom of this post. Download Visual Studio Solution here.

 

This series explains the Windows Phone 7 requesting data from a Windows Azure web service. The phone tile and toast are supported by a background agent on the phone while the web service is supported by a continuous worker role on Windows Azure.

Document 1

The phone calls the WebRole REST API from both the phone app and the phone app’s background agent. Each request is different though. The App’s request is fetching a list of items to show in the app while the background agent is fetching the count of items since the last fetch and the very last item. This information will be displayed in the popup toast and the app’s start screen pinned tile.

 

Azure Only

This post will cover the Azure web  and worker roles only. The Windows Phone 7 app-to-Azure communication will be covered in a separate post. Grab the Visual Studio solution available for download. Running the project doesn’t require that you have an Azure account but you will need the Azure SDK installed.

 

Prerequisites

In order to make this simple sample work, you need to have the following installed:

  • Visual Studio (not Express)
  • Azure SDK 1.4

The AzureSample Solution

The Azure Visual Studio solution has several projects:

 

image

 

The Solution Items project contains a text file of blog post URLs that I found helpful. The Azure project is where the Azure configuration settings are stored. Since this sample enters data into Azure Storage tables, you will notice that the Azure project ServiceConfiguration.Local.cscfg file uses local developer storage.

<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="Azure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="1" osVersion="*">
  <Role name="MvcWebRole">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
    </ConfigurationSettings>
  </Role>
  <Role name="WorkerRole">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

The next project in the AzureSample Solution is the AzureSharedLibrary which is where the main code for the solution is shared between the Web Role and the Worker Role projects. The MvcWebRole project contains both the REST API answering the phone’s requests as well as an HTML page that refreshes to display the top 100 chronological rows in Azure Storage. The last project is the WorkerRole which periodically cycles to enter data into the table.

 

Both the MvcWebRole and the WorkerRole have as little code in them as possible. I did this on purpose so that you could see what I added and how it pulled together from the shared library.

 

What does the Sample Do?

If you let the sample run, you will see the web page refreshes with new data every few seconds. Both the web page (in the web role) and the worker role are inserting information into the Azure Storage table. Granted this isn’t the typical scenario, it is just an example. In a future post, I’ll connect a Windows Phone 7 app and background agent to this AzureSample and they will all work together.

In my current development project, the worker role is polling a 3rd party web site for new information and inserting the information into the Azure Storage table. Then the phone app is requesting that new information either through the phone’s app or background process.

 

Running the Code

Start Visual Studio with elevated permissions: right click on the VS program and select Run as Administrator.

image

 

Make sure the Azure project is set as the start project then start to debug. The Azure emulators should start if they weren’t already. The default web page should display revealing the data inserted by both roles.

 

Viewing the Data

Once the solution is started, the web page for the MvcWebRole will display. After a few seconds of running, it should show some lines of data that include the process name and the UTC date it was entered.

 

image

 

Even though the local storage emulator is used, you can view the data via the Visual Studio server explorer or a third party tool such as Azure Storage Explorer. Both work with the local storage emulator.

 

Visual Studio Server Explorer

image

 

Azure Storage Explorer

image

 

 

Summary

This blog post showed how to allow a web and worker role to access the same Azure Storage table. The web role provides both web page and REST access to the data while the worker role only inserts the data into the table. In the next post, I’ll go through the code for these two roles.

 

Simple Series