Create and configure Azure Functions

If you want to build a single endpoint which is capable of performing business and performance critical and high available process behind the scene and at the same time it should be accessible to all the ecosystem and development approach right from Mobile to REST calls and Cloud Apps "Azure Function" has it all.

Microsoft Azure as evolved(ing) to give best it can from PaaS, IaaS and Azure Functions as FaaS(Function as a Service).

The biggest advantage of using Azure Function is its server-less. So, no configuration and maintenance of infrastructure is needed. In this way we can only  pay for resource we consume, But still Azure provides you the ability to configure fixed service plan for better dedicated performance for your function.

So i leave it up to you to choose the plan by considering not paying for un-utilized or under utilized server cost or consumption based plan. 

Create Azure Functions using Visual Studio

Install "Azure Functions" template from Visual Studio Market place.








Create first Precompiled Azure Functions

Now we will create a precompiled C# Azure function to get Encrypt/Decrypt based on given CryptoKey

Helper class's

CryptoResult.cs

using System;

namespace CryptoFunction.Helper
{
    public class CryptoResult
    {
        public string Value;

        public bool HasError;

        public string Error;
    }
}

CryptoHelper.cs

public class CryptoHelper
{
        static CryptoResult result = new CryptoResult();

        /// <summary>
        /// Encrypts given text with key
        /// </summary>
        /// <param name="textToEncrypt"></param>
        /// <param name="key"></param>
        /// <returns>CryptoResult Object</returns>
        public static CryptoResult Encrypt(string textToEncrypt, string key)
        {
            try
            {
                result = new CryptoResult();

                //Omitted for clarity
                result.Value = <encryptedvalue>;
                result.HasError = false;
            }
            catch (Exception x)
            {
                result.HasError = true;
                result.Error = x.Message;
            }
            return result;
        }

        /// <summary>
        /// Decrypts provided cryptoText with given key
        /// </summary>
        /// <param name="cryptoText"></param>
        /// <param name="key"></param>
        /// <returns>CryptoResult Object</returns>
        public static CryptoResult Decrypt(string cryptoText, string key)
        {
            try
            {
                result = new CryptoResult();

                //Omitted for clarity
                result.Value = <decryptedvalue>;
                result.HasError = false;
            }
            catch (Exception x)
            {
                result.HasError = true;
                result.Error = x.Message;
            }
            //return cryptTxt;
            return result;
        }
}

CryptoFunction.cs

[FunctionName("Crypto")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string action = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "action", true) == 0)
            .Value;

    string cryptoKey = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "cryptokey", true) == 0)
        .Value;

    string value = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "value", true) == 0)
        .Value;

    CryptoResult result = new CryptoResult();

    switch (action.ToUpper())
    {
        case "ENCRYPT":
            {
                result = CryptoHelper.Encrypt(value, cryptoKey);
                break;
            }
        case "DECRYPT":
            {
                result = CryptoHelper.Decrypt(value, cryptoKey);
                break;
            }
        default:
            {
                result.HasError = true;
                result.Error = "No matching action/key/value found";
                break;
            }
    }

    return result.HasError == true
        ? req.CreateResponse(HttpStatusCode.BadRequest, result.Error)
        : req.CreateResponse(HttpStatusCode.OK, result);
}

Deploy Azure functions using Visual Studio




Update CORS in Azure functions

Enter different application url with domain to allow access to this function call.
use "*" to allow from all domains.



Get function Endpoint Url


Test Azure functions

https://ratsubfunctions.azurewebsites.net/api/Crypto?
code=<secret code>
&action=encrypt
&cryptoKey=123
&value=Welcome to Azure functions testing
https://ratsubfunctions.azurewebsites.net/api/Crypto?
code=<secret code>
&action=decrypt
&cryptoKey=123
&value=HS8KMLX8VsQ0lSNK4jAA+PpVroM0xNhKfDExjxbRMaqUfC7pFb1eMDHOExOvGtWVTBvee2V47+B2Qh8B+mSNxfT/gQnrfJBA0aBwwViXZLA=

Test in fiddler




-Ratsub

Comments

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…!!..Azure Online Course Hyderabad

    ReplyDelete

Post a Comment

Enter your comments..

Popular posts from this blog

Secure When a HTTP request is received Power Automate a.k.a MS Flow

People picker Control in PowerApps

Upload attachment to SharePoint list item using Microsoft Flow

Modern page provisioning using page template

Approval and auto escalation with time out in Microsoft Flow

Developing custom reusable components in PowerApps

Headless-Daemon calling AAD secured API

Step-By-Step Azure AD App Registration

HTML field & Date Time formatting in powerapps

REST call returns XML instead of JSON in SharePoint