Wednesday, July 25, 2018

Scheduled Azure WebJobs Trigger Through C# Script

While you work with C# may get requirement to trigger a azure web job that is scheduled in azure which is displayed as triggered using your C# code.
Following steps show you how to trigger a web job using Web Job API.
  1. First we need to find site credentials(publish profile credentials).You can find site credentials by following Option 1 or Option 2.

Option 1:
  • Login to Azure portal(https://portal.azure.com) and go to web job tab of your site
  • Click on “Properties”,After that properties window will open
image
  • In properties window you can find site credentials
image

Option 2:
  • Login to Azure portal(https://portal.azure.com)
  • Go to App Services—>Select your site –>go to Overview—>click on Get publish profile.
  • After click on this you can download the document with publish settings.
  • In this document you can find site credentials(Username and Password).
image
2. After you find the site credentials you can trigger web jobs using following code
  • In first few lines you can see authentication details.
  • Then Create a web request instance by calling Create with URL
System.Net.WebRequest request = System.Net.WebRequest.Create(URL);
  • We use protocol method POST to send request data
  • Finally send the request to the server by calling GetResponse() method
System.Net.WebResponse response = request.GetResponse();
string userName = myusername;
string userPassword = mypassword";
string jobName = mywebjob;
var unEncodedString = String.Format($"{userName}:{userPassword}");
var encodedString = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(unEncodedString));string URL = "https://mywebappname.scm.azurewebsites.net/api/triggeredwebjobs/" + jobName + "/run";
System.Net.WebRequest request = System.Net.WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = 0;
request.Headers["Authorization"] = "Basic " + encodedString;
System.Net.WebResponse response = request.GetResponse();

No comments:

Post a Comment