Sunday, 14 July 2019

Azure | How to disable functions in Azure Functions


How to disable functions in Azure Functions


Disabling A Single Function in Azure Functions Deployed From Visual Studio

Issue:
·       You have one Precompiled (developed through Visual Studio) Azure function app.
·       You disabled it through Portal Manually
·       Even after disabling that function it is triggering.

Solution:

It is very easy to disable function if you create it through portal. You can simply set

 "disabled": true

in function.json file.

You face challenge when it is Precompiled function (which you developed through Visual Studio and appears as read only in portal).

You have to use “Disableattribute in the code.



The Disabled attribute is the only way to disable a class library function. The generated function.json file for a class library function is not meant to be edited directly. If you edit that file, whatever you do to the disabled property will have no effect.
The same goes for the Function state switch on the Manage tab, since it works by changing the function.json file.
Also, note that the portal may indicate the function is disabled when it isn't.

You can get more details in below URL,


References,



I believe this helps. Please share your feedback.

Thursday, 11 July 2019

Azure Function App Graceful Shutdown


Azure Function App Graceful Shutdown


Issue:
·       My function app is about to terminate, how can I notify my function code.
·       My function should not terminate unexpectedly.
·       How to detect host shutdown?
·       When my function app stop/restart then my code should notify and should be able to handle it.

Solution:

You can resolve these types of issue using “Cancellation Token”.

You can specify the CancellationToken parameter which will notify you code whenever function is going to terminate. You can use this notification to make sure the function doesn't terminate unexpectedly in a way that leaves data in an inconsistent state.


Ref:



Example code:

I created one HTTP Trigger function and passed CancellationToken

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Threading;

namespace FunGraceShut
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =>
            {
                log.LogInformation("Function app is stopping");               

            });
            string name = req.Query["name"];
            if (!cancellationToken.IsCancellationRequested)
            {
                for (int i = 0; i < 100; i++)
                {

                    log.LogInformation("C# HTTP trigger function processed a request.");
                    Thread.Sleep(8000);
                    log.LogInformation("Normal processing for queue message={0}", name);
                }

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;

                return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
                // the code to process the item goes here
            }
            return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}



You can refer below image when I stopped it while it was running.


Function App Graceful Shutdown

Ref:




Hope this helps. Please share your feedback.


Wednesday, 10 July 2019

Azure App Service : Automate Start/Stop/Restart web app


Azure App Service : Automate Start/Stop/Restart web app



Start/Stop/Restart web app through code/program 


Issue:
·       I want to stop/start/Restart my web app through code.
·       I want to restart my web app everyday at some certain time.
·       How can I automate it?

Solution:
A common ask from may app services users is, Is there any way to stop/start or restart web app programmatically. Once we have logic and program then we can simply automate that also.

Good news is you can write code to perform this operation. I am explaining this using PowerShell, but same approach can be used with other languages like C#.

Points to remember,
·       When we Stop, Start or Restart the web app from Portal, we internally call the REST API.
·       If we can call those REST API or http endpoint programmatically then our purposed can be fulfilled.

But the challenge is, you can’t simply call those REST API. You must pass authentication information also with the request. This authentication information can be username/password or Bearer token.
It is not the good practice to hardcode username/password in the code hence we should generate BEARER token at run time and will pass that.

We can use the concept of “Service Principal” to generate bearer token.
Please refer below URL to create service principal,

Once we have Application ID and Client secret then we can use following Power Shell command to automate this process.


$Auth = Invoke-RestMethod -Uri "https://login.microsoftonline.com/<Your Tenant ID>/oauth2/token?api-version=1.0" -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "<Your Application ID>"; "client_secret" = "<Your Client Secret ID>”}

$HeaderValue = "Bearer " + $Auth.access_token

#Stop
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/stop?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  

#Start
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/start?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  



Please replace values according to your web app and configuration. (highlighted in yellow). Please modify this script according to your requirement.

You can get the list of other REST API in resource explorer feature of your web app.
Ref: 

You can use this script in your web job or function app or anywhere else to automate this process.

Hope this helps. Please share your feedback.

Thursday, 20 June 2019

Azure Restore deleted web app


Azure Restore deleted web app


Issue:
·       I deleted my web app, how to restore it?
·       Can I undo my delete web app operation?

Solution:

Good news!

Azure has launched the feature which can help you to restore the deleted web app but it can undelete the site which is deleted in last 30 days.

You can restore the content and configuration both.

Using Power Shell
-------------------------------------------------
·       Get the deleted site info,

Get-AzDeletedWebApp -Name "deleted site name"

·       Next you can restore it,

Restore-AzDeletedWebApp -ResourceGroupName "RG Name" -Name "deleted site name" -TargetAppServicePlanName "ASP Name"
-------------------------------------------------
You can also use Azure CLI.

Ref: 


Tuesday, 11 June 2019

Azure App Service - Code changes made to your app


Azure App Service - Code changes made to your app


Issue:
·       How to identify code changes in my app?
·       Who made the change and what was changed?


Solution:
Azure App Service has announced “Change Analysis” feature. E.g. Whatever changes you make on a file via KUDU - > The diff. of it will get reflected under the “Change Analysis” blade under “Diagnose and solve problems” tab.

You can more information in below URLs,


Friday, 15 March 2019

Azure PowerShell - Request to a downlevel service failed


Azure PowerShell - Request to a downlevel service failed


Issue:
·       Sometime when we run the PowerShell command, we get following error message,
o   Request to a downlevel service failed
·       Example: Switch-AzureWebsiteSlot

Solution:

The reason for error message “Request to a downlevel service failed” is Deprecating Service Management APIs.

Issue was happening because your CmdLets are using the Service Management API which is deprecated for Azure App Service.

You can get more information on below URLs,

To resolve this, You should implement the ARM equivalent.

Your command should have “RM” e.g. Switch-AzureRmWebAppSlot instead of
Switch-AzureWebsiteSlot

I hope this helps.

Azure Functions: Invalid Length for a Base-64 char array or string


Azure Functions: Invalid Length for a Base-64 char array or string


Issue:
·       My function is throwing error - Invalid Length for a Base-64 char array or string
·       My function is using Storage Queue trigger/binding

Solution:

This issue happens when you have storage queue trigger function.
When you send message to storage queue, it expects you to send in base64 encoded string.
Functions expect a base64 encoded string. Any adjustments to the encoding type (in order to prepare data as a base64 encoded string) need to be implemented in the calling service.
This can also be seen on portal when you send message to queue manually.

Invalid Length for a Base-64 char array or string



You should send message in Base64 format.
For example, if you have JavaScript function then you can use btoa module for converting your message to base64 format.


Your function exception will disappear once you send message in base64 format.
I hope this helps.

Azure Functions | Microsoft.Azure.WebJobs.Script.WebHost: Repository has more than 10 non-decryptable secrets backups

Microsoft.Azure.WebJobs.Script.WebHost: Repository has more than 10 non-decryptable secrets backups Issue : ·        The function runtime is...