Wednesday, 28 October 2015

Creating an Azure WebJob and persisting data to an Azure Storage table

This article will describe how you can create an Azure WebJob and persist some data to an Azure Storage table. First of, head over to the portal for Azure using Internet Explorer and log in using your subscription: Azure Portal Select Web Apps in the left menu and click Add. Enter a name for your Web App and select your Subscription, Resource Group and App Service plan/Location and hit Create. Afterwards, select the Web Apps in the left menu again and select the Web App you just created. Use the Settings and choose WebJobs. We are going to create a webjob here using Visual Studio, note that the WebJobs link will list your webjobs.
Next, create in VS 2013 or newer a new ASP.NET Web Application using File and New Project in the Main Menu of VS. Choose an Empty web application. Do the following next:
  • Right click the web project
  • Choose Add
  • Add ASP.NET folder
  • App_Data
    • Select Solution Explorer and choose the Solution and right-click and add a new project which is Console Application. Also create subfolder jobs, triggered and web-job-helloworldv5. We will drop the compiled contents of the Console Application project we will add next. Let's add two app settings in the Console Application app.config file:


      
      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <appSettings>
          <add key="StorageAccount" value="INSERT_STORAGE_ACCOUNT" />
          <add key="StorageKey" value="INSERT_STORAGE_KEY" />
        </appSettings>
          <startup> 
              <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
          </startup>
      </configuration>
      
      
      Obviously, we need to put into the two appsettings the storage account and storage primary key. In the left menu of Azure Portal select New and choose Data+Storage and choose Storage Account. This is needed to get started with Blobs, Tables and Queues and Choose Create Back in the left menu again, choose Browse and then Storage accounts (classic). Now we need the necessary connection details to this Storage Accounts. Select in the right menu Settings the link Keys. Copy the values for Storage account name and Primary Access Key. Add these two values into the two app settings earlier noted. Now we just need to make a simple WebJob and persist some data into Azure Storage Table. Let's calculate the first 100 prime numbers and then add these numbers to a Azure Storage Table. Into the Main method of Program.cs of the Console application we add the following code:
      
       static void Main(string[] args)
              {
                  Console.WriteLine("Starting prime number calculation..");
                  var primes = new List<int>(); 
                  foreach (var n in Enumerable.Range(0, 100))
                  {
                      int numberToCheck = (n*2) + 1;
                      bool isPrimes = IsPrime(numberToCheck);
                      if (isPrimes)
                      {
                          primes.Add(numberToCheck);
                      }
                  }
      
                  StoreToAzureTableStorage(primes, "primenumbersfound");
              }
      
              public static bool IsPrime(long num)
              {
                  for (long j = 2; j <= Math.Sqrt(num); j++) // you actually only need to check up to sqrt(i)
                  {
                      if (num%j == 0)
                      {
                          return false;
                      }
                  } //for
      
                  return true;
              }
      
      
      We need some plumbing code to get our CloudTableClient to work against our Azure Table:
      
      /// 
              /// Returns an instance of a Azure Cloud Table client 
              /// 
              /// 
              public static CloudTableClient GetCloudTableClient()
              {
                  string accountName = ConfigurationManager.AppSettings["StorageAccount"];
                  string accountKey = ConfigurationManager.AppSettings["StorageKey"];
      
                  if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(accountKey))
                      return null; 
      
                  try
                  {
                      var credentials = new StorageCredentials(accountName, accountKey); 
                      var cloudStorageAccount = new CloudStorageAccount(credentials, useHttps: true);
                      CloudTableClient client = cloudStorageAccount.CreateCloudTableClient();
                      return client;
                  }
                  catch (Exception ex)
                  {
                      return null;
                  }
              }
      
      
      Next we commit the data to our Azure Storage Table:
      
         public static void StoreToAzureTableStorage(List primes, string tableName)
              {
                  
                  try
                  {
      
                      CloudTableClient client = GetCloudTableClient();
                      CloudTable table = client.GetTableReference(tableName);
                      table.CreateIfNotExists();
      
                      foreach (int prime in primes)
                      {
                          var primeEntity = new PrimeNumberEntity(prime);
                          var insertOperation = TableOperation.Insert(primeEntity);
                          table.Execute(insertOperation);
                      }
      
      
                      var query = new TableQuery();
                      var primesFound = table.ExecuteQuery(query).OrderBy(p => int.Parse(p.RowKey)).ToList();
      
                      foreach (PrimeNumberEntity pf in primesFound)
                      {
                          Console.WriteLine(pf);
                      }
      
                  }
      
                  catch (Exception ex)
                  {
      
                      Console.WriteLine(ex);
      
                  }
      
      
                  Console.WriteLine("Done... press a key to end.");
      
              }
      
      
      We can now invoke our WebJob from the Azure portal:




      We can choose Web Apps and then our WebApp and next in the right menu WebJobs. Note that we can pin our WebApp to our Dashboard for quicker navigation using the pin symbol in Azure Portal. Now choose the WebJobs and right click and choose Run.



      We can inspect the data we inserted using Azure Storage Explorer. Download a Visual Studio 2013 solution with code above below, you will need create a Web App and a Storage account in Azure Portal and insert the necessary app settings as noted to run the example: Download VS 2013 Solution file (.zip) [69 MB]
      Share this article on LinkedIn.

1 comment: