Windows Azure Scheduler Creation in my application through .NET SDK

Getting Started

As with any good SDK, it helps to know how you could get started using it by taking a look at some code. No code should ever be written to solve a problem that doesn’t exist, so let’s start with a decent, but simple, problem statement:
We will create a new cloud service through Windows Azure Scheduler SDK. First of all we need to populate a valid Windows Azure credentials with a management certificate configured properly. The code below retrieved the management certificate from local machine and initialized a certificate cloud credential instance by specifying its thumbprint.

Azure API server side to authenticate the request

  1. Download the publishsettings file from:https://manage.windowsazure.com/publishsettings/index?client=vs&schemaversion=2.0 (This is a XML file, you can open it with notepad)
  2. Find ManagementCertificate property, copy the value to a string. That a Base64 encoded string, you can use this string create a certificate: string base64Cer="The value of ManagementCertificate "
  3. Use this string create a certificate. var certificate = new X509Certificate2(base64Cer);
although this last step is not exactly like passing the string directly (as the string is too long and will cause an exception) but rather is as follows: var cert = new X509Certificate2(Convert.FromBase64String(base64cer));

     private static X509Certificate2 GetStoreCertificate(string thumbprint)
        {
            List<StoreLocation> locations = new List<StoreLocation>
  { 
    StoreLocation.CurrentUser, 
    StoreLocation.LocalMachine
  };
          string  p = "D:\\LogiticksSchedulerApp\\Scheduler\\Scheduler\\my";
            foreach (var location in locations)
            {
                X509Store store = new X509Store(p, location);
                try
                {
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    X509Certificate2Collection certificates = store.Certificates.Find(
                      X509FindType.FindByThumbprint, thumbprint, false);
                    if (certificates.Count == 1)
                    {
                        return certificates[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
            throw new ArgumentException(string.Format(
              "A Certificate with Thumbprint '{0}' could not be located.",
              thumbprint));
        } 

Windows Azure Scheduler Management Library on NuGet

Currently Windows Azure Scheduler SDK is still in preview phase on NuGet. So if we search the package from Visual Studio Manage NuGet Packages dialog we will not be able to find it.
Hence we must open the Package Manager Console window in Visual Studio and install it in command-line mode with the preview flag specified. Let's create a new console application and open the Package Manager Console then type of command as below. Do not forget the last "-Pre" argument.


Install-Package Microsoft.WindowsAzure.Management.Scheduler -Pre

static void Main(string[] args)
  {
      // retrieve the windows azure managment certificate from current user
       var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadWrite);
      var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "{THE-CERTIFICATE-THUMBPRINT}", false)[0];
      store.Close();
   
   }

Then I created a subscription credential from this certificate and its Windows Azure Subscription ID.
static void Main(string[] args)

    // retrieve the windows azure managment certificate from current user
    ... ...
    
        // create management credencials and cloud service management client
     var credentials = new CertificateCloudCredentials("SUBSCRIPTION-ID", certificate);
       var cloudServiceMgmCli = new CloudServiceManagementClient(credentials);
   
  }

Now we would be able to create a cloud service for our Windows Azure Scheduler from the management client. In the code below I created a new cloud service located at South Center US.

static void Main(string[] args)

     // retrieve the windows azure managment certificate from current user
      ... ...
   
      // create management credencials and cloud service management client
      ... ...
   
      // create cloud service
      var cloudServiceCreateParameters = new CloudServiceCreateParameters()
      {
        Description = "shaun-wasch-demo",
          Email = "jfarrio@gmail.com",
         GeoRegion = "South Central US",
          Label = "shaun-wasch-demo"
    };
      var cloudService = cloudServiceMgmCli.CloudServices.Create("shaun-wasch-demo", cloudServiceCreateParameters);
  }

Create Job Collection and Job

Now we have a cloud service available, the next step is to create a job collection inside it. In the code below I initialized a new management client named "SchedulerManagementClient" which takes the responsible for managing the scheduler job collection as well as the resource provider.
Once we have "SchedulerManagementClient" ready we can create a new job collection with the plan and quota specified. Since I used "Free" plan so the quote must be smaller than once per hour, and assigned to the cloud service I had just created.
static void Main(string[] args)
   {
      // retrieve the windows azure managment certificate from current user
     ... ...
    
       // create management credencials and cloud service management client
       ... ...
     
        // create cloud service
        ... ...
     
       // create job collection
        var schedulerMgmCli = new SchedulerManagementClient(credentials);
      var jobCollectionIntrinsicSettings = new JobCollectionIntrinsicSettings()
      {
          Plan= JobCollectionPlan.Free,
          Quota = new JobCollectionQuota()
          {
              MaxJobCount = 5,
               MaxJobOccurrence = 1,
             MaxRecurrence = new JobCollectionMaxRecurrence()
              {
                  Frequency = JobCollectionRecurrenceFrequency.Hour,
                 Interval = 1
              }
            }
      };
      var jobCollectionCreateParameters=new JobCollectionCreateParameters()
      {
            IntrinsicSettings=jobCollectionIntrinsicSettings,
            Label = "jc1"
     };
      var jobCollectionCreateResponse = schedulerMgmCli.JobCollections.Create("shaun-wasch-demo", "jc1", jobCollectionCreateParameters);
   }
Finally I will create a new job in this job collection. To manage jobs I need to initialize "SchedulerClient" which can be used to create, update and delete jobs inside a job collection. In this example I defined this job with a HTTP polling action to this blog website once an hour, with the job named "poll_blog".

 static void Main(string[] args)
  {
      // retrieve the windows azure managment certificate from current user
      ... ...
   
      // create management credencials and cloud service management client
      ... ...
  
       // create cloud service
       ... ...
  
      // create job collection
      ... ...
   
      // create job
      var schedulerClient = new SchedulerClient(credentials, "shaun-wasch-demo", "jc1");
      var jobAction = new JobAction()
      {
          Type = JobActionType.Http,
         Request = new JobHttpRequest()
          {
              Uri = new Uri("http://blog.shaunxu.me"),
              Method = "GET"
          }
      };
      var jobRecurrence = new JobRecurrence()
     {
          Frequency = JobRecurrenceFrequency.Hour,
          Interval = 1
     };
      var jobCreateOrUpdateParameters = new JobCreateOrUpdateParameters()
     {
          Action = jobAction,
          Recurrence = jobRecurrence
      };
      var jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate("poll_blog", jobCreateOrUpdateParameters);
  }

Now let's execute this application. This will invoke Windows Azure Management API to create the job collection and job. Then we can back to Windows Azure portal to see a new job collection had been created at the region we defined.
image
Click into this job collection we will find the plan and quota is the same as what we wanted.
image
And the job we created from our application will be shown in "Jobs" tab with the name we specified.
image
And we will find that this job had been executed at least once after we submitted from the "History" tab.
image
If we back to the "Dashboard" tab of this job collection, we will find the URI display at the right side of the page. The cloud service was shown inside the URI as below.
image

View Job History and More

Besides the job creation, we can retrieve the job execution history through this SDK.

// retrieve job history
  var schedulerClient = new SchedulerClient(credentials, "shaun-wasch-demo", "jc1");
  var jobGetHistoryParameters = new JobGetHistoryParameters()
  {
      Skip = 0,
      Top = 100
  };
   var history = schedulerClient.Jobs.GetHistory("poll_blog", jobGetHistoryParameters);
   foreach(var action in history)
  {
       Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", action.Status, action.Message, action.RetryCount, action.RepeatCount, action.Timestamp);
   }

Summary

Windows Azure Scheduler allows us to define a time-based jobs in Windows Azure platform. We can use this feature to invoke a website or web service through HTTP request regularly. We can also let the job insert message into a Windows Azure Storage Queue so that some background worker roles can be trigger to start some backend processes, and this might be more useful in our application design and development.
For example in one of my project there will be some backend jobs which retrieve some data from some web services and insert into Windows Azure SQL Database, and some other jobs will be started hourly or monthly to process those data.


Search This Blog

Arsip Blog

Powered by Blogger.

Recent

Comment

Author Info

Like This Theme

Popular Posts

Video Of Day

jishnukanat@gmail.com

Sponsor

Most Popular