Wednesday, June 15, 2022

BlobTrigger in azure function ,Resize files after uploading in blob

 In previous post we saw how to create azure function for HttpTrigger. Now lets see another use of azure function.

Scenario - Suppose you are uploading file in blob either directly from azure portal or through .net code and after upload you want to create thumbnail or resize that file . For this if you will do during upload in .net code then it might take time and user will not be happy with system performance . So to tackle such kind of scenario azure has provided BlobTrigger function. which automatically trigger and resize your file after uploading in blob. if you want to know more about azure function from start please see the previous post.

So Lets see how we can achieve this.

1. Open Visual Studio -> Create New Project -> Search for Azure functions Templates and click Next

1.Enter project name “AzureFunBlobTrigger” and click Next

2.In next section you need to select Trigger Type ,so select Blob Trigger and keep storage emulator in right side , if you want to use azure storage you can browse and choose.



in Solution explorer you will see below




Local.settings.json : In this file configure storage account and runtime framework. It has key-value code. open this file and paste the below code

{

    "IsEncrypted": false,

  "Values": {

    "AzureWebJobsStorage": "your storgate connection string",

    "FUNCTIONS_WORKER_RUNTIME": "dotnet",

    "fnBlob": "your storgate connection string"

  }

}

fnBlob is the key which you are going to use for blob connection.

Function1.cs: Open the function.cs and paste the below code

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.IO;

namespace AzureFunBlobTrigger
{
    public static class Function1
    {
        [FunctionName("Function1")]
         public static void Run(
               [BlobTrigger("mycontainer/{name}", Connection = "fnBlob")] Stream inputBlob, string name,
               [Blob("resized/{name}", FileAccess.Write, Connection = "fnBlob")] Stream outputBlob, TraceWriter log)
        {
            log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {inputBlob.Length} Bytes");
         
            ResizeImage( inputBlob, outputBlob, 300,150);
         
        }
        private static void ResizeImage(Stream input, Stream output, int width,int height)
        {
            using (Image image = Image.Load(input))
            {
                image.Mutate(x => x
                        .Resize(new ResizeOptions
                        {
                            Mode = ResizeMode.BoxPad,
                            Size = new Size(width, height) // you can define size what u need
                        }).BackgroundColor(new Rgba32(0, 0, 0)));

                image.Save(output, new JpegEncoder());
            }
        }

    }
}


L Lets understand the below code block

[FunctionName("Function1")]
         public static void Run(
               [BlobTrigger("mycontainer/{name}", Connection = "fnBlob")] Stream myBlob, string name,
               [Blob("resized/{name}", FileAccess.Write, Connection = "fnBlob")] Stream outputBlob, TraceWriter log)


     [FunctionName("Function1")] - function name which you can change with any name .

   [BlobTrigger("mycontainer/{name}" -BlobTrigger is the attribute which trigger the function when any file will get upload in container "mycontainer".

    Connection = "fnBlob")] - storage connection string name which I have defined in local.setting.json

    [Blob("resized/{name}", another container where file will be save after resizing. you dont need to create ,it will be automatically created if not.

   In the above code I have created one function called ResizeImage where I am passing input blob(which has been uploaded ,output blob path and name , size.

   To resize image I am using nuget package called SixLabors.ImageSharp which you can add from package manager. I found this package more clean ,fast and easy to implement.

   Thats all about coding part.

   Lets try to upload file in container from azure portal and see what happens

L   1. Login to azure portal and go to storage account -> container -> mycontainer -> select upload and upload one file. as soon as you upload your file automatically your function will trigger in your local visual studio and resize the file and save in the output folder.

    Before that just run your project from visual studio . you will see below logs if your function run successfully in vs.

   Now let put our debugger in code just to make sure our function is triggered after uploading image in blob.


Now go to mycontainer and upload one image and you will see your local function got triggered.
   


   now you can see your function gets trigger in the code and resize uploaded image and push to resized container.

   This is the resized container.


   We are done with blob trigger azure function and this might be the real case for you where you can use azure function  ..

   Thanks and good luck.


Tuesday, June 14, 2022

Create and Use Azure functions in .Net Core

 Azure functions  

What : Azure function is a small pieces of code/small program which runs on cloud. Azure function is serverless i.e. no need to worry about infrastructure ,scaling etc. everything handled by provider for you. Basically it’s a Event triggered code.Keep in mind you should not write huge block of code or use as a replacement of webapi ,function should be lightweight and small piece of code.

Why to Use- We can use azure function when we have requirement to run program which might takes time.

o   File Processing

o   Scheduled Tasks

o   Reminders and Notifications

o   Sending background emails

o   Running background backup tasks

Language/script support

 All types of programming language support like C#,Java, JavaScript etc.

Types :Event triggered code

  •       HTTP trigger
  •       Timer Trigger
  •       Blob Trigger
  •       Event Grid Trigger
  •       Event Hub Trigger
  •       Queue Trigger
  •       Service Bus Trigger and so many other triggers through which azure function can run.

Prerequisites:

  •     Install azure development sdk in visual studio

Here we are going to focus Http trigger and Blob Trigger only.

Http Trigger- As per naming it a http request call , function execute when we send http request

Lets see how to create and use this ,good thing is that we don’t need to deploy azure function for testing during development in visual studio there is storage emulator which can be used for development and testing :

To create follow the steps :

Open Visual Studio -> Create New Project -> Search for Azure functions Templates and click Next

1.      .


1.Enter project name “azfunctionHttpTrigger” and click Next

2.In next section you need to select Trigger Type ,so select HttpTrigger and keep storage emulator in right side , if you want to use azure storage you can browse and choose.

3.In authorization field leave default one i.e function 

 



In solution explorer you can see project created with 3 files

  •       Function1.cs
  •       Host.json
  •       local.settings.json



Let see uses of these files

Local.settings.json : In this file configure storage account and runtime framework. It has key-value code.

{

    "IsEncrypted": false,

    "Values": {

        "AzureWebJobsStorage": "UseDevelopmentStorage=true",

        "FUNCTIONS_WORKER_RUNTIME": "dotnet"

    }

}

AzureWebJobsStorage : can be replaced with azure storage connection string otherwise for development you can keep as it is.


Host.json : I will explain bit later.

Function1.cs: This is the class where you will put your logic what you want to get done from this app.Since we selected HttpTrigger ,automatically added template .just need to replace required code in the code block. 

Lets rename function name as ‘azhttpTriggeredFunction

Default :

public static class Function1

    {

        [FunctionName("Function1")]

        public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,

            ILogger log)

        {

            log.LogInformation("C# HTTP trigger function processed a request.");
            string name = req.Query["name"];
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;
            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";
            return new OkObjectResult(responseMessage);

        }
    }

 

Now lets run and see if function is working or not.press F5 and see the output.

.

If you observe the above output  ,you can see the url for http call. Copy this url and paste in browser

http://localhost:7071/api/azhttpTriggeredFunction and you can see the below output



Now Lets see details in this function :

[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]


Http request method -get ,post. At template creation time it added by default. Can be removed one of them as required.

Route – This is the endpoint for http request.You can change the route name as "routeName"/{name}(query string). So url with new route name will be formed.

If you have noticed in the url http://localhost:7071/api/azhttpTriggeredFunction  ,

api has been appended . this is the default route prefix which is added. If you need to change this you can change in host.json.



Lets change route prefix as apiPrefix

http://localhost:7071/apiPrefix/azhttpTriggeredFunction new url with changed prefix.

Pass query string value in the url http://localhost:7071/apiPrefix/azhttpTriggeredFunction?name=%27manoj%27 and out put will be below

 



Thats it for httpTriggered function .In next section will see BlobTriggered.


 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples

Friday, June 10, 2022

Call WebJob from .Net Core Web Api

In previous tutorial we had created a webjob which can be run manually by click on Run in azure portal. But most of the cases we need to trigger this job when an event gets triggered. See the previous tutorial to create web jobs Create webjobs in .net core. I will use same web jobs here.

In this tutorial we will see how to call webjob from our web api call

Its a simple as we call any other services/api . 

1. Go to azure portal -> appservice->webjob-> click on proprties .from right panel copy webhook ,username and password in you local . 

Now open visual studio and create webapi project and paste below code 

 [HttpPost]
        [Route("webjobstest")]
        public async Task<IActionResult> CallWebJobs()
        {
            HttpClient _httpClient = new HttpClient();
            _httpClient.BaseAddress = new System.Uri("xxxxxxxx.scm.azurewebsites.net/api/");
            var bytArray = Encoding.ASCII.GetBytes("username:pwd");
            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytArray));
            var response = await _httpClient.PostAsync("triggeredwebjobs/azwebjoblearn/run", null);

            return Ok(response);
       
        }

Now when you call the api above webjob will be triggered , in case of success we get response  202(accepted) code.






Thursday, June 9, 2022

Create and deploy Azure web job in .net core

 Create and deploy Azure web job in .net core

What: WebJob is the program which runs in background . In another word it’s a kind of scheduler which can be run based on cron, or manual call.

Type – there are 2 types of webjob

A.     Continuous – run 24X7 immediately after publish

B.     Triggered – can run based on corn setting or can be triggered manually by webhook/ directly from azure portal.

Language/script Support:

1.      cmd, .bat, .exe 

2.      .ps1 (using powershell)

3.      .sh (using bash)

4.      .php (using php)

5.      .py (using python)

6.      .js (using node)

 

Requirement

  •  Azure App service – each app service has webjob by default . no need to take separate service for webjob.
  • Azure Storage account –
  •  Make sure you have install azure sdk while installing Visual studio if not you can modify and choose azure..

How to create and deploy

We will create two type of webjobs

  •   Sending email to all subscriber
  •   Reszie the blob image after uploading via webjob

Lets Start with first one:

1- Assume we have list of subscribers and we need to send them email with new news/product get entered in the system. Here instead of locking thread from code we can use web job to send email from background which makes system faster and end user who submit news no need to wait  ..

In order to implement this lets follow below steps

 1.  Login to azure portal ->go to your storage account-> search access key -> copy you connection string and keep somewhere in you local computer , we need it later.





2.      Open Visual Studio and Create new web job project 



Basically, it’s a console application with program.cs and function.cs file.

3. Open app.config file and paste you azure storage connection string in below two section. Both AzurewebjobDashboard and AzurewebjobsStorage could be the same.




4. Now open function.cs file and write your logic to send email to all subscriber , in below code I am using gmail to send email. you can use whatever you want.

using Microsoft.Azure.WebJobs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;

namespace azwebjoblearn
{
    public class Functions
    {
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([QueueTrigger("queue")]
        string message, TextWriter log)
        {
           
            log.WriteLine(message);
        }
        [NoAutomaticTrigger]
        public void TriggerHandler(TextWriter log)

        {
            //here you  can put whatever your logic based on your requirement like fetch data from db,email, stock update etc.
            try
            {
                Console.WriteLine("web job function triggered");
                //   log.WriteLine("web job function triggered");
                 SendEmailToSubscriber();

            }
            catch (Exception ex)
            {
                log.WriteLine("Exception in Trigger Handler", ex);
                throw ex;
            }
        }

        private void SendEmailToSubscriber()
        {
            //subscriber list
            var subscripberList = new List<string>();
            subscripberList.Add("m222@gmail.com");
            subscripberList.Add("test1@gmail.com");
            subscripberList.Add("test2@gmail.com");
            subscripberList.Add("test3@gmail.com");
            subscripberList.Add("stes4@gmail.com");
            subscripberList.Add("test5@gmail.com");

            var mailMessage = new MailMessage();

            var fromAddress = new MailAddress("webjobtesting@gmail.com", "webjobs");
            foreach (var item in subscripberList)
            {
                mailMessage.To.Add(new MailAddress(item , "To Name"));
            }          
            mailMessage.From = fromAddress;
            mailMessage.Subject = "News posted for you";
            mailMessage.Body = "Dear subscriber , one news posted in portal";

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("hhhhhh.com", "knnnnn")
            };
            try
            {
               smtp.Send(mailMessage);
            }
            catch(Exception ex)
            {
               
                throw ex;

            }

         
        }

    }
}



5. Now Open the Program.cs and copy below code


namespace azwebjoblearn
{
    // To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var config = new JobHostConfiguration();
            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            var host = new JobHost(config);
            //host.call will call the triggerHandler function based on schedule or call          
            host.Call(typeof(Functions).GetMethod("TriggerHandler"));
            //to make it continuous use host.RunAndBlock(); and  pass timer parameter in TriggerHandler function
         //   host.RunAndBlock();
        }

    }
}

6. Open Settings.job file and put your required corn , u can keep all commented also ,depend on your requirement. 

{

  //    Examples:

  //    Runs every minute
      "schedule": "0 * * * * *"

  //    Runs every 15 minutes
  //    "schedule": "0 */15 * * * *"

  //    Runs every hour (i.e. whenever the count of minutes is 0)
  //    "schedule": "0 0 * * * *"

  //    Runs every hour from 9 AM to 5 PM
  //    "schedule": "0 0 9-17 * * *"

  //    Runs at 9:30 AM every day
  //    "schedule": "0 30 9 * * *"

  //    Runs at 9:30 AM every week day
  //    "schedule": "0 30 9 * * 1-5"
}

Here our coding part is done, need to publish now.

we can publish webjobs by three ways
1.directly from visual studio
2. make zip file and upload manually in azure app service
3.Through CI/CD
I am going to use first approach

1.select publish option and configure your select your azure subscription ->resource group->app service




After selecting your app service click finish. After published successfully go to Azure Portal -> App service- webjobs here you can see deployed web job -


Now you can click on Run and all subscriber should get email ..
In next section will see how to trigger this web job from web api..

Thanks 



Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...