Azure

Creating And Deploying Microsoft Azure WebJobs

What’s Microsoft Azure WebJobs?

Azure WebJobs lets you run applications or scripts in your web site as background processes. It runs and scales as a part of Azure Net Websites.

What Scheduling Choices are supported by Microsoft Azure WebJobs?

Azure WebJobs can run repeatedly, on-demand, or on a schedule.

In what language/scripts are WebJobs written?

Azure WebJobs might be created utilizing the next scripts.

  1. .cmd, .bat, .exe (utilizing Home windows cmd)
  2. .ps1 (utilizing PowerShell)
  3. .sh (utilizing bash)
  4. .php (utilizing PHP)
  5. .py (utilizing python)
  6. .js (utilizing node)

This text demonstrates the usage of the c# command line app.

Creating and Deploying WebJobs utilizing Visual Studio

Creating WebJobs

In Visual Studio 2013 Replace 3, WebJobs might be created and deployed immediately from Visual Studio itself.

To get began, simply create a brand new mission, Below C#, choose Microsoft Azure WebJobs. On this instance, a “HelloTNWiki” mission is created.

A traditional console utility is created and the entry level to this system is Fundamental(). This instance shall simply show “Hiya TN Wiki!”.

utilizing System;

class Program
{
    static void Fundamental()
    {
        Console.WriteLine("Hiya TN Wiki!");
    }
}

Deploying WebJobs

To deploy the WebJob, right-click on the mission and choose Publish as Azure WebJob.

Publish as Azure WebJob

Choose when the WebJob shall run and click on OK. On this instance, the job might be run on demand.

WebJob shall run

Choose a publish goal, on this instance, the goal might be an Azure WebSite.

Azure WebSite

You shall be required to register and enter your Microsoft Azure credentials.

Sign in

As soon as signed in, it’s possible you’ll choose which WebSite the Job is to run.

WebSite the Job

Click on on OK, then choose Publish.

Publish web

Now, when you go the the Microsoft Azure portal, and navigate to your WebSite, you shall see a brand new WebJob created and deployed.

New WebJob created and deployed

Utilizing earlier variations of Visual Studio.

Creating WebJobs

In Visual Studio, create a Console Utility.

The entry level of the applying continues to be Fundamental(). This instance shall simply show “Hiya TN Wiki!”.

Console application

class Program
{
    static void Fundamental()
    {
        Console.WriteLine("Hiya TN Wiki!");
    }
}

Deploying WebJobs

The next steps should be carried out to deploy the WebJob.

  1. Construct the applying.
  2. Go to the Bin/Debug path of the Utility and add all of the contents in a .zip file.
    Zip file
  3. Go to the Azure portal, choose your WebSite, then go to WebJobs and choose ADD a job.
    ADD a job
  4. Enter a Job identify, choose the .zip file, choose when the job shall run, and click on okay.
    Enter a Job name
  5. Look forward to the Job to be uploaded and created,
    Uploaded and created

Operating a Job and Viewing the outcome within the WebJob Dashboard

Operating a job

To run an on-demand WebJob as defined above, choose the job and click on on Save on the backside of the web page.

Click on Save

When the run completes the outcome shall be displayed on the Final Run Consequence tab.

Last Run Result tab

WebJob Dashboard

The WebJobs dashboard within the Azure administration portal supplies highly effective administration capabilities that offer you full management over the execution of WebJobs, together with the flexibility to invoke particular person features inside WebJobs.

The dashboard additionally shows perform runtimes and output logs.

To entry the dashboard web page, click on on the hyperlink below the Log Column.

Access the dashboard page

This opens the dashboard web page which incorporates particulars and statistics concerning the WebJob.

Contains details

By deciding on a selected run, statistics concerning the job along with the Job Log might be obtained.

As per the results of the instance above, “Hiya TN Wiki!” is displayed within the Job Log.

Toggle output

WebJobs SDK

The WebJobs SDK makes it simpler to make use of Azure Storage.

The WebJobs SDK has a binding and set off system that works with Microsoft Azure Storage Blobs, Queues, and Tables in addition to Service Bus Queues.

Putting in the WebJob SDK

To make use of the WebJob SDK in Visual Studio, the next NuGet Package deal must be put in.

Utilizing the SDK to create and save a file in an Azure Storage Account

Making a Storage Account on Microsoft Azure

From the Azure Portal go to Knowledge Providers, Storage, Fast-Create, and fill within the required info.

As soon as the storage account is provisioned, the subsequent factor to do is to get the keys. Click on on the Handle Keys button like the next.

Storage

Saving a file in Azure Blob storage

The next are the steps to avoid wasting a string to a blob utilizing C# code.

  1. Construct the connection string utilizing the keys retrieved above.
    string ConStr = "DefaultEndpointsProtocol=https;AccountName= xxx ;AccountKey=xxx ";
    
  2. Create an occasion of CloudStorageAccount. This represents a Home windows Azure Storage account.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConStr);
  3. Create an occasion of CreateCloudBlobClient.
  4. Gives a client-side logical illustration of the Home windows Azure Blob service. This consumer is used to configure and execute requests in opposition to the Blob service.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  5. Get a container within the Home windows Azure Blob service. Create the container if it doesn’t exist.
  6. This must be in decrease case.
    CloudBlobContainer container = blobClient.GetContainerReference("blobcontainer");
    container.CreateIfNotExists();
    
  7. Will get a reference to a block blob within the container and uploads a string textual content to it.
    CloudBlockBlob blob = container.GetBlockBlobReference("BlobFile.txt");
    blob.UploadText("HelloTNWiki");
    
  8. Run the WebJob.
  9. It’s possible you’ll now view the created container in your Storage Account > Containers within the Azure Portal.
    Storage Account
  10. By clicking on the container, it is possible for you to to see the newly created Blob and its contents.
    Blobcontainer

Instance. Day by day Gross sales

Having gone into the fundamentals of Azure WebJobs, the next is an instance of the place all of the ideas can be utilized and utilized.

Situation

Think about a state of affairs the place a gross sales WebApp is being deployed into Azure. The App shops gross sales info from a number of branches of a retailer.

The requirement is each day at a selected time within the morning, compile the full gross sales per area, save the report on blob storage, and e-mail the report back to the administrators.

Assume the Database schema of the Utility is like the next.

Table

Retrieving Day by day Gross sales from the Database

The code block beneath connects to an Azure Database and selects and aggregates the gross sales info as required.

public string GetDailySales(string date)
{
    dbconnect();

    string SalesDetails = "";

    strive
    {
        string StrCommand = @"choose area, sum(quantity) AMOUNT 
                                FROM SALES 
                                WHERE TRANDATE= '" + date + "' group by area";

        utilizing (SqlCommand command = new SqlCommand(StrCommand, con))
        utilizing (SqlDataReader reader = command.ExecuteReader())
        {
            whereas (reader.Learn())
            {
                SalesDetails = SalesDetails + reader.GetString(0) + "t" + reader.GetInt32(1) + "</br>";
            }
        }


        con.Shut();
    }
    catch (Exception e)
    {
        Console.WriteLine("Couldn't retrieve Info " + e.Message);

        throw;
    }

    Console.WriteLine("Info Retrieved Efficiently");

    return SalesDetails;
}

E-Mail outcome

The following step is to ship the outcomes by mail. That is completed by the next perform.

public void SendEmail(string msg)
{
    strive
    {
        MailMessage mail = new MailMessage();

        mail.From = new MailAddress(emailFrom);
        mail.To.Add(emailTo);
        mail.Topic = topic;
        mail.Physique = msg;
        mail.IsBodyHtml = true;

        utilizing (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
        {
            smtp.Credentials = new NetworkCredential(emailFrom, password);
            smtp.EnableSsl = enableSSL;
            smtp.Ship(mail);
            Console.WriteLine("E-mail despatched to " + emailTo + " at " + DateTime.Now);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("E-mail failed" + e.Message);
        throw;
    }
}

Saving the end in Blob Storage

The perform beneath creates a container if it doesn’t exist and saves the end in a blob.

public static void WriteToBlob(string salesreport)
{
    strive
    {
        string acs = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx";

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(acs);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("salesinfo");
        container.CreateIfNotExists();
        CloudBlockBlob blob = container.GetBlockBlobReference("DailyReport" + DateTime.Now + ".txt");
        blob.UploadText(salesreport);

        Console.WriteLine("File saved efficiently"); ;

    }
    catch (Exception e)
    {
        Console.WriteLine("Saving to blob failed " + e.Message);

        throw;
    }
}

View Consequence

Discover the usage of Console.WriteLine() in every perform. This shall assist to hint the execution course of and log errors in case of issues.

Thus the job log might be like the next.

Web job run detail

E-Mail obtained efficiently

Daily sales report

Gross sales Data container created and gross sales report saved to blob.

Salesinfo

References

Know extra about our firm at Skrots. Know extra about our companies at Skrots Providers, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button