Skip to main content

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 4 min read

One of the highlight among the announcements made at Microsoft Build 2020 was announcement of the new Azure service in the keynote which is Azure App Static Web Apps. Azure Static Web Apps is a service that automatically builds and deploys full stack web apps to Azure from a GitHub repository. This service allow web developers to publish websites to a production environment by building apps from a GitHub repository for free. Developers can use modular and extensible patterns to deploy apps in minutes while taking advantage of the built-in scaling and cost-savings offered by serverless technologies.

It provides the killer features for developers such as:

  • Free web hosting for static content like HTML, CSS, JavaScript, and images.
  • Integrated API support provided by Azure Functions as backend APIS
  • First-party GitHub integration where repository changes trigger builds and deployments with Github Actions
  • Globally distributed static content, putting content closer to your users.
  • Free SSL certificates, which are automatically renewed.
  • Custom domains* to provide branded customizations to your app.
  • Seamless security model with a reverse-proxy when calling APIs, which requires no CORS configuration.
  • Authentication provider integrations with Azure Active Directory, Facebook, Google, GitHub, and Twitter.
  • Customizable authorization role definition and assignments.
  • Back-end routing rules enabling full control over the content and routes you serve.
  • Generated staging versions powered by pull requests enabling preview versions of your site before publishing.

How i deployed Meme-Generator App:

I was building this meme generator app for an angular session today with Azure cognitive service to detect persons in the image and also to generate a meme by adding a text as the user wanted. As soon as Azure static web apps was announced I wanted to check it out with this application on how easy it is to deploy. Experience was seamless and easy to deploy and generate a url in few seconds.

Let me explain, how i achieved this in quick time.

Step 1. Sign-in to the Azure Portal, Search for “Static Web Apps”, and click the Create button

Visit https://portal.azure.com, sign-in, and use the search box at the top to locate the Static Web Apps service (note that it’s currently in “preview”). click the Create button to get started.

Create Static Web App

In this step you’ll fill out the Static Web Apps form and sign-in to your Github account to select your repository.

  • Select your Azure subscription.
  • Create a Resource Group
  • Name your app , in my case its meme4fun
  • Select a region (as of now its not available in all regions)
  • Sign-in to Github and select your org, repo, and branch. 

Once you’re done filling out the form click the Next: Build > button.

Step 2: Define Angular App location, API, and Build Output

The next step is to define the path where my app is located in the repository, and i did not have any azure function integrated and i will keep it as empty, and the directory where my build artifacts (your bundles) are located(i.e dist/meme-4-fun). After entering that information click the Review + create button.

Defining Paths

Step 3:  Click the Create and Look for the Magic !

Once you are good with everything you can go ahead and click the create button and you will see the application successfully gets deployed and end point generated to access it public.

Deployment complete

Once the deployment is done, if you go the resource and click on overview you will see a configuration as follows,

Overview

It has the urls of the Github Actions and as well as Github source code and also the url of the application deployed. If you’d like to see the build in action on Github, click the Workflow file above.

You can access the meme generator application and create your own memes from https://lively-forest-0fd67f010.azurestaticapps.net/

Here are some great links you can visit to learn more. 

The above app is also available in the Microsoft's sample static web app Gallery.

If you're a web developer you definitely need to check out this cool service for sure. Cheers!

· 4 min read

One of the highlight among the announcements made at Microsoft Build 2020 was announcement of the new Azure service in the keynote: Azure App Static Web Apps. Azure Static Web Apps is a service that automatically builds and deploys full stack web apps to Azure from a GitHub repository. This service allow web developers to publish websites to a production environment by building apps from a GitHub repository for free. developers can use modular and extensible patterns to deploy apps in minutes while taking advantage of the built-in scaling and cost-savings offered by serverless technologies.

It provides the killer features for developers such as:

  • Free web hosting for static content like HTML, CSS, JavaScript, and images.
  • Integrated API support provided by Azure Functions as backend APIS
  • First-party GitHub integration where repository changes trigger builds and deployments with Github Actions
  • Globally distributed static content, putting content closer to your users.
  • Free SSL certificates, which are automatically renewed.
  • Custom domains* to provide branded customizations to your app.
  • Seamless security model with a reverse-proxy when calling APIs, which requires no CORS configuration.
  • Authentication provider integrations with Azure Active Directory, Facebook, Google, GitHub, and Twitter.
  • Customizable authorization role definition and assignments.
  • Back-end routing rules enabling full control over the content and routes you serve.
  • Generated staging versions powered by pull requests enabling preview versions of your site before publishing.

How i deployed Meme-Generator App:

I was building this meme generator app for an angular session today with Azure cognitive service to detect persons in the image and also to generate a meme by adding a text as the user wanted. As soon as Azure static web apps was announced I wanted to check it out with this application on how easy it is to deploy. Experience was seamless and easy to deploy and generate a url in few seconds.

Let me explain, how i achieved this in quick time.

Step 1. Sign-in to the Azure Portal, Search for “Static Web Apps”, and click the Create button

Visit https://portal.azure.com, sign-in, and use the search box at the top to locate the Static Web Apps service (note that it’s currently in “preview”). click the Create button to get started.

Create Static Web App

In this step you’ll fill out the Static Web Apps form and sign-in to your Github account to select your repository.

  • Select your Azure subscription.
  • Create a Resource Group
  • Name your app , in my case its meme4fun
  • Select a region (as of now its not available in all regions)
  • Sign-in to Github and select your org, repo, and branch. 

Once you’re done filling out the form click the Next: Build > button.

Step 2: Define Angular App location, API, and Build Output

The next step is to define the path where my app is located in the repository, and i did not have any azure function integrated and i will keep it as empty, and the directory where my build artifacts (your bundles) are located(i.e dist/meme-4-fun). After entering that information click the Review + create button.

Defining Paths

Step 3:  Click the Create and Look for the Magic !

Once you are good with everything you can go ahead and click the create button and you will see the application successfully gets deployed and end point generated to access it public.

Deployment complete

Once the deployment is done, if you go the resource and click on overview you will see a configuration as follows,

Overview

It has the urls of the Github Actions and as well as Github source code and also the url of the application deployed. If you’d like to see the build in action on Github, click the Workflow file above.

You can access the meme generator application and create your own memes from https://lively-forest-0fd67f010.azurestaticapps.net/

Here are some great links you can visit to learn more. 

The above app is also available in the Microsoft's sample static web app Gallery.

If you're a web dev you need to check out this cool service for sure. Cheers!

· 5 min read

Overview : 

Azure Service Bus is being used as one of the most reliable enterprise messaging services across different domains like health care, finance etc. Often, users do have uncertainties in handling the dead-letter messages. Before diving into the best practices, I would like to give you a quick introduction on dead-lettered messages.

Azure Service Bus Dead-letter Queue

Azure Service Bus queues and topic subscriptions provide a secondary sub-queue, called a dead-letter queue. The purpose of the dead-letter queue is to hold messages that cannot be delivered to any receiver, or messages that could not be processed. So, any message that resides in the dead-letter queue is called a dead-lettered message.

Best practices in handling Azure Service Bus dead-letter message

Most of the time we could notice that the message fails due to the following reasons;

  1. Dependent service not available
  2. Faulty message
  3. Process code issue

Dependent service not available

This could be one of the foremost and time after time reasons where the services that reply on message delivery may go down for a short period. For instance, the Redis or SQL connection issues may often happen.

Faulty Message

According to the business scenarios, you may configure the custom properties to you Azure Service Bus messages and validate with respect to the values that should contain in the custom/user defined properties.

If in case the message doesn’t have a mandatory parameter or some value is incorrect, then the message will end up in the dead-letter queue after the maxDeliveryCount is attained.

The failed delivery can also be caused by a few other reasons such as network failures, a deleted queue, a full queue, authentication failure, or a failure to deliver on time.

Here we can drill down the reasons into two ways:

  1. System level dead-lettering
  2. Application level dead-lettering

Reasons for System level dead-lettering

  • Header Size Exceeded
  • Error on processing subscription rule
  • Exceeding time to live value
  • Exceeding maxDeliveryCount
  • When Session id property is set to true (the default is false)

Reasons for Application level dead-lettering

  • Messages that cannot be properly processed due to any sort of system issue
  • Messages that hold malformed payloads
  • Messages that fail authentication when some message-level security scheme is used

In this second scenario, the best practice is to manually verify the dead-lettered messages (using Service Bus Explorer or Serverless360) to correct message data or sometimes to purge messages and clear the queue.

Message process code issue

This is a very rare case given a good number of resources in the community to fetch the flawless code. The developer should keep all the scenarios in the head and handle all the exceptions.

In the first and third scenario, the best practice is to use a flawless code that should run and reprocess the dead-lettered messages, you can find the sample code below;

internal class Program
{
private static string connectionString = ConfigurationSettings.AppSettings["GroupAssetConnection"];
private static string topicName = ConfigurationSettings.AppSettings["GroupAssetTopic"];
private static string subscriptionName = ConfigurationSettings.AppSettings["GroupAssetSubscription"];
private static string databaseEndPoint = ConfigurationSettings.AppSettings["DatabaseEndPoint"];
private static string databaseKey = ConfigurationSettings.AppSettings["DatabaseKey"];
private static string deadLetterQueuePath = "/$DeadLetterQueue";

private static void Main(string[] args)
{

try
{
ReadDLQMessages(groupAssetSyncService, log);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
finally
{
documentClient.Dispose();
}
Console.WriteLine("All message read successfully from Deadletter queue");
Console.ReadLine();
}

public static void ReadDLQMessages(IGroupAssetSyncService groupSyncService, ILog log)
{
int counter = 1;
SubscriptionClient subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName + deadLetterQueuePath);
while (true)
{
BrokeredMessage bmessgage = subscriptionClient.Receive(TimeSpan.FromMilliseconds(500));
if (bmessgage != null)
{
string message = new StreamReader(bmessgage.GetBody<Stream>(), Encoding.UTF8).ReadToEnd();
syncService.UpdateDataAsync(message).GetAwaiter().GetResult();
Console.WriteLine($"{counter} message Received");
counter++;
bmessgage.Complete();
}
else
{
break;
}
}

subscriptionClient.Close();
}
}

Myths to chunk out

Does the SequenceNumber of message added by Azure Service bus keeps on increasing on each failed attempt till it reaches maxDeliveryCount?

The sequence number can be trusted as a unique identifier since it is assigned by a central and neutral authority and not by clients. It also represents the true order of arrival and is more precise than a time stamp as an order criterion, because time stamps may not have a high enough resolution at extreme message rates and may be subject to (however minimal) clock skew in situations where the broker ownership transitions between nodes.

Setting maxDeliveryCount = 1, is that best practice to deal with poison messages so that consumer never attempt twice to process message once it failed?

It is not a best practice to set the maxDeliveryCount=1. Because if some network/connection issue occurs, the built-in retry will process and clear from the queue.

If you are reading messages in batch, a complete batch will re-process if an error occurred any of message.

Conclusion

In this blog, we have seen a sneak peek of Azure dead-lettered queues and various reasons for dead-lettering of messages. Further, we discussed the best practices on handling the dead-lettered messages. Finally, we looked into the myths to chunk out while dealing with Azure Service Bus dead-lettered messages.

I hope you enjoyed reading this article. Happy Learning!

This article was contributed to my site by Nadeem Ahamed and you can read more of his articles from here.