Using the. NET Core 2.1 Azure WebJobs

Source: Internet
Author: User
Tags app service

Webjobs is not a new thing in Azure and. Net. There is even a default Azure Webjob template for the complete. NET Framework in Visual Studio 2017. However, a similar template for webjobs in. NET core is omitted in some way in Visual studio. In this article, I used the. NET Core 2.1来 to create the webjobs.

Creating Webjob in. NET core is not difficult, but you have to know some tricks, especially if you want to use some of the. NET core features, such as logs and Di.

In this article, we'll build a webjob and publish it to Azure using the visual Studio,azure Portal and VSTS.

What is Webjobs

Webjob is a program that runs in the background of the app service. It runs in the same environment as your Web application, at no additional cost. Maybe you need to do some hourly tasks or do some cleanup work 1 o'clock in the morning every day. Azure Application Insights uses Webjob to report statistics about your application.

Webjobs can be arranged by the hour or day, but can also be triggered. A trigger can be a file upload or a new message on a queue.

WebJobs contrast Functions

I often compare between webjobs and azure functions. To some extent, functions is the successor of Webjobs. Functions (typically) is a small piece of code running in Azure, like webjobs, that fires in an event, including an HTTP trigger.

Functions is usually a good substitute for webjobs, but if you already have a Web application, you can use Webjob. This also makes deployment very easy, especially if you want to share code or settings between Webjob and Web applications , because they run in the same context.

Create a Storage account

before we go on, let's deal with it first. Webjob requires an Azure storage account . I'll walk you through the creation process quickly.

In Azure, find "Storage Azure (Storage account)" and add one. You must select a name that is unique in azure. In addition, you can leave the default values.

Once your Storage account is ready, select it and find your access keys. One of the two connection strings we'll need later.

Create Webjob

As already mentioned , the complete. NET Framework has a webjob template. I suggest you take a look. First create an ASP. NET Web application, and then add a new webjob. If you try to create webjob immediately, you receive an error message stating that the project needs to be saved first (although it does create a webjob).

This article is written on the webjob of. NET Core. First, create an ASP. NET core Web application, and then add the new. NET Core Console Application project to your solution.

The first thing we need to do is install the Microsoft.Azure.WebJobs package from NuGet. We should also install Microsoft.Azure.WebJobs.Extensions. The latest stable version of these libraries depends on the full. NET Framework, so we will need the 3.0.0-BETA5 version (at the time of this writing), which is fully compatible with. NET Core.

The other NuGet packages we need are Microsoft.Extensions.Options.ConfigurationExtensions (it also provides Microsoft.Extensions.Options packages we also need), Microsoft.ex Tensions. Dependencyinjection and Microsoft.Extensions.Logging.Console. Make sure that you install the 2.1.0 version of these packages because there seems to be an error in. NET Core 2.1 that prevents you from using a package that contains a patch version, such as 2.1.1.

Add to Program.cs file

The next thing we need to do is change our Program.cs file. If you created Webjob with a. NET framework template, you only need to copy and paste the Program.cs file that was generated there (you may need to change the namespace).

usingMicrosoft.Azure.WebJobs;namespacenetcorewebjob.webjob{//to learn more about the Microsoft Azure WebJobs SDK, please seego.microsoft.com/fwlink/?linkid=320976    Internal classProgram {//Please set the following connection strings in app. Config for this WebJob to run://Azurewebjobsdashboard and Azurewebjobsstorage        Private Static voidMain () {varConfig =Newjobhostconfiguration (); if(config. isdevelopment) {config.            Usedevelopmentsettings (); }            varHost =NewJobHost (config); //The following code ensures that the WebJob'll be running continuouslyhost.        Runandblock (); }    }}

Add Configuration and Dependencies

You'll use the good features in. NET core, such as logs and Di. The Console app does not have any functionality by default, but you can add it yourself.

Private Static voidMain () {iservicecollection Services=Newservicecollection ();     Configureservices (services); // ...} Private StaticIConfiguration Configuration {Get;Set; } Private Static voidconfigureservices (iservicecollection services) {varEnvironment = Environment.getenvironmentvariable ("aspnetcore_environment"); Configuration=NewConfigurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json", Optional:false, Reloadonchange:true)        . Addjsonfile ($"appsettings. {Environment}.json", Optional:true, Reloadonchange:true)        . Addenvironmentvariables ().     Build (); Services.    Addsingleton (Configuration); Services. AddTransient<functions, functions>(); Services. Addlogging (Builder=Builder. Addconsole ());}

Next, create a Appsettings.json file and set the copy to output directory property to always copy. The Appsettings.json file should have two connection strings, as described in the Program.cs template file. These are the storage account connection strings that we created earlier.

{  "Logging": {    "LogLevel": {      "Default":"Warning"    }  },  "ConnectionStrings": {    "Azurewebjobsdashboard":"[Your Storage account connection string]",    "Azurewebjobsstorage":"[Your Storage account connection string]"  }}

What we need next is a custom ijobactivator that can be used to inject dependencies into our class. It needs to be set on the jobhostconfiguration of the program class.

usingMicrosoft.Azure.WebJobs.Host;usingMicrosoft.Extensions.DependencyInjection;usingSystem;namespacenetcorewebjob.webjob{ Public classJobactivator:ijobactivator {Private ReadOnlyIServiceProvider Services;  PublicJobactivator (IServiceProvider services) { This. Services =services; }          PublicT createinstance<t>()        {            returnServices. Getservice<t>(); }    }}
var New  New jobactivator (services. Buildserviceprovider ());
Add trigger (Trigger)

After that, create a class and name it functions (just like in the Webjob template). The functions class will contain the actual code for the webjob.

Of course, we need to add a trigger. This differs from the full. NET framework. After all, the template uses static methods, which makes di impossible to implement. Speaking of Di, note that we also add the functions class itself to the Di container.

For simplicity, we'll use Timertrigger, which is triggered by a so-called cron expression. This simply means that it triggers at a certain minute, hour, day, etc. In this example, it will trigger every minute.

We also need to configure timers on the jobhostconfiguration.

usingMicrosoft.Azure.WebJobs;usingMicrosoft.Extensions.Logging;usingSystem;namespacenetcorewebjob.webjob{ Public classFunctions {Private ReadOnlyIlogger<functions>logger;  PublicFunctions (ilogger<functions>logger) {             This. Logger =logger; }          Public voidProcessqueuemessage ([Timertrigger ("* * * * *")]timerinfo timerinfo) {logger.        Loginformation (DateTime.Now.ToString ()); }    }}
var New  New  jobactivator (services. Buildserviceprovider ()); config. Usetimers ();
Run the sample

If you do all of the work correctly, or if you are running my code from GitHub, you should now be able to run the console application. If you interrupt in an exceptional situation or you are watching the Output window, you may notice a lot of storageexceptions. Don't worry about them, ignore them. This is an error in the Webjobs library and does not affect your program. It may take a minute for your trigger to disappear, so be a little patient.

If you go to an Azure storage account, you should see two blob containers, "azure-jobs-host-output" and "azure-webjobs-hosts". There's a lot of stuff here, but you can ignore it. I find that my webjob triggers do not disappear for some reason, and it is often helpful to delete a BLOB container. Obviously, some of the states stored there are not always handled correctly when re-adding and deleting webjobs.

Publish to Azure

The next thing we want to do is deploy Webjob to Azure. In order to run webjob, you need some executable scripts that you can use to run. Many file types are supported, but for our Windows users, use Exe,cmd,bat or PowerShell files.

The console application was once an EXE file, but in. NET core it generates a regular DLL file that we need to start manually. So create a file and name it "Run.cmd" and make sure it doesn't have a BOM with UTF-8 encoding (you can check with things like Notepad + +). It only requires one line of code, "Dotnet NetCoreWebJob.WebJob.dll". This will run your console app. Make sure that the copy to output directory of the file is set to always copy.

The last thing, for some reason, is that Azure webjobs needs all the dependencies of webjob, which means all of the. NET core packages that we use to build it. You can edit the csproj file and add "<CopyLocalLockFileAssemblies> true </copylocallockfileassemblies>" to the first < Propertygroup> (under "<TargetFramework>") to complete this operation.

Before we deploy webjob, we need to deploy our Web application. Right-click the ASP. NET project, and then click Publish .... Just follow the wizard and Visual Studio will deploy your application for you. You can create a new Web application or select an existing application. This step is not strictly necessary because you can host a standalone webjobs, but this should be familiar, and it gives you the app Service that we can use for webjob.

Publishing with Visual Studio

Deploying Webjobs with Visual Studio should be easy. In fact, you may already know how to do this (although not doing so). Right-click the Webjob project, and then click Publish .... The following wizard looks much like the publication of the Web application we just made. You can choose "Select Existing" and select the Azure Web application we just created.

Unfortunately, Microsoft screwed up this feature in the worst way. Visual Studio will deploy WebJob with the same name as the project, that is, "netcorewebjob.webjob", except that the dot is an illegal character in the WebJob name! This messed up my project very badly I had to manually edit it to make my solution run again.

So that's what you do. At the beginning of the wizard, you can select a new or existing app Service, click the arrow next to publish Now, and then select Create Profile. You can now change the name of the Webjob in the settings before you deploy. Make sure you do not select "Delete other files for destination", or you will delete your Web application.

Now, browse to the Azure portal and find your Web application. You will find "WebJobs" in the menu. You'll see your webjob, but it's not doing anything. You need to run it manually by selecting it and clicking Run. The status should be updated to "running." You can now view the log to make sure it is actually valid. You may see errors about connection strings, but you can ignore them. If you switch the output, you will still see a log written to the console, letting you know how it works! If you don't see the log immediately, try to wait two minutes and don't forget to manually refresh the output.

Azure webjobs diagram

Publishing with Azure Portal

When adding a new webjob, you need to fill in some options. You can make some names, set the type to triggered, and set the trigger to manual. Your choice is a "continuous" WebJob, it just runs and shuts down (unless you implement an infinite loop in your application); and "scheduled" trigger work, which is basically what we have, unless we implement the plan ourselves.

"File Upload" requires some explanation. From here, you can upload a zip file containing webjob. Therefore, go to Visual Studio and build your solution. Then go to the output folder of the Webjob project, for example "MyProject \ bin \ [Debug | Release] \ netcoreapp2.1, and put all the contents of the folder into a zip file. Then select it in the "file upload" of the new Webjob.

Add WebJob

Azure takes a few seconds to create your webjob, so keep it refreshed before you refresh. After that, you must manually start it again, and you can view the logs.

Publishing with VSTS

In the end, we want to add our webjob to the CI/CD pipeline in VSTS. Unfortunately, this feature is not ready to use. Fortunately, this is not very difficult.

When you're in the Azure Portal, find app service editor (preview) for your app service. This allows you to browse all the files in the app service. One thing we notice is that your webjob is located in "app_data \ jobs \ triggered \ [webjob name]". Since your webjob is actually just the output of the Webjob project build, simply copy the Webjob file to App_Data.



webjob File Location

Build

So go to VSTS and create a new version. Select the repository, branch, and then select "ASP. NET Core" as the template. We just need to change two things here. We need to change the existing release task and add a new ". NET Core" task to publish our webjob.

Change the name of an existing publishing task to publish Web application, uncheck the Publish Web Project check box, and then enter the project path, or * */netcorewebjob.csproj. In addition, uncheck the "Zip Published Projects" and "ADD project name to publish path" checkboxes, as they will eventually break our version.

After that, create a new. NET core task, set Command to publish, and change the task name to publish Web job. Again, cancel the Publish Web project and set the project path, which is * */NetCoreWebJob.WebJob.csproj. Again, do not compress the published project or add the project name to the publishing path. The final step here is the "Arguments" field, which can be copied/pasted from other publishing steps, except we want to add a point: "-Configuration $ (buildconfiguration)-Output $ (build. artifactstagingdirectory) \ app_data file \ \ job thrown \ webjobvsts.

VSTS Webjob Build

Release

Last but not least, publish. Create a new version in VSTS, select the Azure App Service Deployment template and fill in the blanks, which are azure settings in artifacts and environments. Because we didn't compress our build, we just need to change one setting. The Deploy Azure Application service task is a "package or folder" setting with a default value of "[...]/*. zip", which obviously does not work. Instead, use the browser (button with "...") and select your Drop folder.

Save, click on the new version and select the latest version. If all goes well, you should see the new webjob! in the Azure portal

Conclusion

Like this article on it! Do not copy the past directly Oh! Original address and source code: Azure WebJobs with. NET Core 2.1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.