Azure Resource Manager Template Deployment

Posted by nilay on December 11, 2015No Comments

Have you tried template deployment for your resources such as VM, Sotrage, Network and many other supported resources in Microsoft Azure Cloud ?

It’s really quick and well-organized approach for your resources deployment to Azure. Quickly deploy and setup your dev/ test/ production environments. You just need to create your resources structure in JSON format, and for that too you will get many quick-start templates publicly available  @

Your template will majorly contain four parts, define your resources hierarchy and then supply parameters and variables required to those resources, you can also construct outputs at the end of the deployment.

Looks like below-

 "$schema": "",
 "contentVersion": "",
 "parameters": { },
 "variables": { },
 "resources": [ ],
 "outputs": { }

How it works once you deploy your template ?

ARM Templates

ARM Templates

Know more about Azure Resource Manager (ARM) Template at MSDN:

New to cloud computing ? Refer:

New to Microsoft Azure ? Refer:

Knockout js

Posted by nilay on December 6, 2015No Comments

Knockout is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using *observers *to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering *declarative bindings *somewhat like Silverlight but without the browser plugin.

So, what distinguishes this from all the other similar-sounding JavaScript libraries?

Well, Knockout combines some different ideas that open up very powerful possibilities:


  • Automatic dependency tracking: At the heart of Knockout is a system of observable variables and other variables computed as functions of them. For example, if you have firstName and lastName and then define fullName by concatenating these together, the framework knows that whenever either firstName or lastName changes, it must re-evaluate fullName. You don’t have to configure this – it’s inferred from your code execution, even if you have chains of observables referencing other observables.
    This makes it easy to build sophisticated view models in which changes to a few key properties automatically ripple out to all other affected parts of the model.


  • Declarative bindings: By adding a data-* attribute (part of the HTML 5 spec, and works fine in older browsers, including IE 6) you can quickly bind appearance and behaviour in your HTML to properties on a view model. For example, you can write , and then the element will display the value in your model property as text, automatically updating if any of the underlying data changes. Besides text, I’ve included a range of commonly useful declarative bindings (e.g., visible, click, and css), and you can easily plug in custom ones.


  • Nested templates: When you have a rich structure of view model data to display, it makes sense to display it using a template to keep your code simple. Knockout handles this easily by letting you bind a DOM node to a template and some data. Whenever either changes, the template gets re-rendered and your UI is updated. You can use data-bind attributes from inside templates (referencing any variable in scope at that point during template execution, such as foreach loop variables) to concisely add further interactivity. Plus, you can bind to templates from within templates, creating chains of nested templates. Because of how dependency tracking works, if the underlying data changes, Knockout knows it only needs to re-render the innermost templates affected by the change, so it’s efficient. Knockout uses the jquery-tmpl template engine by default, but you can plug in another template engine if you prefer some other template syntax.

These features together, combined with following the MVVM design pattern, mean you can apply sophisticated UI behaviors in a clean, concise, and organized way. It’s also possible to combine custom bindings and templates to create reusable controls (or plugins).

Extremely Trivial Example

OK, code. You could set up a view model as follows:

<script type="text/javascript">
    var myViewModel = {
        personName : ko.observable("Bert") // Initial state

Then, you could bind it to an HTML UI as follows:

Enter your name:
<input id="source" data-bind="value: personName, valueUpdate: 'keyup'" />
<div data-bind="visible: personName().length > 5">
    Wow, what a long name you have.

Now, the text box will take its value from personName, and will automatically update its value whenever personName changes. The binding is two-way, so when you type into the text box, this updates personName.

The DIV with the “what a long name” message will be made visible whenever the name length exceeds 5 characters, and hidden otherwise. By referencing an observable value in a binding, you’ve implicitly set up notifications.

Where do I go from here?

For more details, examples, source, and downloads, see the project’s homepage at

Reference: Steven Sanderson’s Blog Link

Parallel.ForEach() Vs Foreach() Loop in C#

Posted by nilay on November 15, 2015No Comments

Foreach loop
Foreach loop runs upon a single thread and processing takes place sequentially one by one. Foreach loop is a basic feature of C# and it is available from C# 1.0. Its execution is slower than Parallel.Foreach in most of the cases.


Parallel.ForEach loop
Parallel.ForEach loop runs upon multiple threads and processing takes place in a  parallel way. Parallel.ForEach loop is not a basic feature of C# and it is available from C# 4.0 and above. Before C# 4.0 we cannot use it. Its execution is faster than foreach in most of the cases. To use Parallel.ForEach loop we need to import System.Threading.Tasks namespace in using directive.
See Example at:


If you are doing any bulk task inside the foreach loop then parallel.foreach is very fast. But if you just iterating and doing a very little task inside loop then go for traditional for loop.

But you know your application well and you can decide which one you want to use.



Nullable Int

Posted by nilay on October 12, 2015No Comments

Nullable Int. A nullable int can store null. Nullable types are constructed by specifying the question mark after a value type in a declarator statement. The nullable int can be specified with the syntax “int?”.
Example. First, this example program demonstrates a use of the nullable integer type. This type is specified with the “int?” syntax. You can use a question mark at the end of a value type to transform the type into a nullable type.

Here:We see a null int type, the HasValue and Value properties. We use the nullable type to acquire the value of the instance.

Based on: .NET 4.5

C# program that uses nullable int type

using System;

class Program
    static void Main()
	// Create a local variable of type nullable integer.
	// ... It is initially assigned to null.
	// ... The HasValue property is false.
	int? value = null;
	// Assign the nullable integer to a constant integer.
	// ... The HasValue property is now true.
	// ... You can access the Value property as well.
	value = 1;
	if (value == 1)



Question mark suffix. The Main entry point uses a statement list in its method body that includes a local variable of type nullable int. Nullable integers are specified with the “int?” type.

Also:The int type is actually aliased to the System.Int32 type, and using “System.Int32?” would work as well.

Tip:When you use a type such as int?, you have access to extra properties such as HasValue and Value.

The HasValue property returns a bool that indicates whether the nullable instance contains a set value. If the type is null, it does not have a value and HasValue is false. If the type is assigned to an integer, HasValue is true.

Also:If the HasValue property is true, you can access the Value property without an exception.
Implementation. Let’s examine the implementation of the nullable generic struct in the base class library. When you use a type such as int?, the C# compiler actually uses the Nullable<T> struct, where T is the value type you are using such as int.

Tip:Structs in the C# language are allocated in continuous memory for performance reasons, and this makes nullable types fairly efficient.

However:There is overhead to using nullable types and this translates to reduced performance over raw value types in some cases.

Summary. Nullable types are described in the C# language specification as being value types that are wrapped inside the nullable type. Nullable ints can be useful when you want to add another state (invalid or uninitialized) to a value type.

Posted in C#Tags:

Asynchronous Methods in C#

Posted by nilay on October 5, 2015No Comments

Async, await. Many methods do not immediately return. A method may need to query an external source. This takes time—and other code could run.
With async and await, we formalize and clarify how asynchronous, non-blocking methods begin and end. An async method can return only void or a Task.

Task:A Task returns no value (it is void). A Task<int> returns an element of type int. This is a generic type.

Note:An async method will be run synchronously if it does not contain the await keyword.
This program uses the async and await keywords to asynchronously run a method. The program begins a long-running method (HandleFileAsync).

First:We create a Task instance with the ProcessDataAsync method as the argument. We Start this task, and Wait for it to finish.

Messages:The method displays a status message after it starts. When it ends, the results are displayed.

ProcessDataAsync:In ProcessDataAsync, we call the HandleFileAsync method. We write a status message to the screen.

HandleFileAsync:In HandleFileAsync, we use the StreamReader type and await the ReadToEndAsync method. We perform some computations.

Based on: .NET 4.5

C# program that uses async, await, Task

using System;
using System.IO;
using System.Threading.Tasks;

class Program
    static void Main()
	// Create task and start it.
	// ... Wait for it to complete.
	Task task = new Task(ProcessDataAsync);

    static async void ProcessDataAsync()
	// Start the HandleFile method.
	Task<int> task = HandleFileAsync("C:\\enable1.txt");

	// Control returns here before HandleFileAsync returns.
	// ... Prompt the user.
	Console.WriteLine("Please wait patiently " +
	    "while I do something important.");

	// Wait for the HandleFile task to complete.
	// ... Display its results.
	int x = await task;
	Console.WriteLine("Count: " + x);

    static async Task<int> HandleFileAsync(string file)
	Console.WriteLine("HandleFile enter");
	int count = 0;

	// Read in the specified file.
	// ... Use async StreamReader method.
	using (StreamReader reader = new StreamReader(file))
	    string v = await reader.ReadToEndAsync();

	    // ... Process the file data somehow.
	    count += v.Length;

	    // ... A slow-running computation.
	    //     Dummy code.
	    for (int i = 0; i < 10000; i++)
		int x = v.GetHashCode();
		if (x == 0)
	Console.WriteLine("HandleFile exit");
	return count;

Output: initial

HandleFile enter
Please wait patiently while I do something important.

Output: final

HandleFile enter
Please wait patiently while I do something important.
HandleFile exit
Count: 1916146

Above, the slow computation done in HandlFileAsync is for demonstration. If you change the path to a large text file that exists on your computer, the program should work.

Note:We can do something (such as write a message) after the async method starts. This is not possible with synchronous methods.
Simple example. This program runs a computation asynchronously on every line entered in the console. It keeps accepting lines even when computations are running.

Action:A lambda expression is specified as the argument to Task.Run. This is an action delegate.

Allocate:This method does a slow-running computation. But when run asynchronously, it does not cause the program to freeze.

Result:Many user inputs can be handled while the computation is running. Each Allocate() call finishes at its own pace.

C# program that uses async computation

using System;
using System.Threading.Tasks;

class Program
    static void Main()
	while (true)
	    // Start computation.
	    // Handle user input.
	    string result = Console.ReadLine();
	    Console.WriteLine("You typed: " + result);

    static async void Example()
	// This method runs asynchronously.
	int t = await Task.Run(() => Allocate());
	Console.WriteLine("Compute: " + t);

    static int Allocate()
	// Compute total count of digits in strings.
	int size = 0;
	for (int z = 0; z < 100; z++)
	    for (int i = 0; i < 1000000; i++)
		string value = i.ToString();
		if (value == null)
		    return 0;
		size += value.Length;
	return size;


You typed: hello
You typed: good
You typed: day
Compute: 588889000
You typed: friend
Compute: 588889000
Compute: 588889000
Compute: 588889000
Compute: 588889000

Main method. The async keyword cannot be used on the Main method. So we will need to add a second method before using an await call.

C# program that causes compile-time error

using System;
using System.Threading.Tasks;

class Program
    static async void Main()


error CS4009: 'Program.Main()': an entry point cannot be marked
    with the 'async' modifier

A pattern. Async and await are a code pattern—they allow methods to asynchronously run. They are a form of syntactic sugar. They make code that uses threads easier to read.
Complexity. With async and await, the compiler helps with asynchronous code. We return a Task or void from an async method. Visual Studio reports warnings or errors on incorrect methods.
Types (StreamReader, HttpClient) contain “Async” methods. These should be called with the await keyword. And the await keyword must be used within an async method.

Task.Start:The first async method call can occur with the Task Start method. This is an instance method.

Also:Event handlers can be used with async methods. This is not currently shown here.
Asynchronous. This term does not mean multithreaded code. By default, code written with async and await is single-threaded. But threaded code works well here.
Task.Run. With the Task.Run method, we can make code that uses async and await multithreaded. Asynchronous code is code that returns upon completion.

And:Other code can execute (even on the same thread) after an asynchronous task has started.

The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread.

Async, await: MSDN
Concept. Programs are full of methods that do not immediately return. Sometimes an external slowdown, as from a network, is the cause, not processor usage.
With these keywords, we run methods in an asynchronous way. Threads are optional. This style of code is more responsive. A network access can occur with no program freeze.


TypeScript – Javascript with Type and Tools

Posted by nilay on August 19, 2015No Comments


Unless you’ve been hiding under a bush all week, you’ve no doubt encountered TypeScript; Microsoft’snew language for application-scale JavaScript development. There’s plenty of mis-information flying around, so I thought I’d join in…

First, TypeScript is not a replacement for JavaScript. TypeScript is to JavaScript as C++ is to C. It’s an extension of the language rather than a new syntax in its own right.

TypeScript is compiled (“pre-processed” or “transcompiled” would be a better description) into native JavaScript code. It’s a similar concept to CoffeeScript except TypeScript is far closer to JavaScript’s existing syntax; JavaScript++ if you like.

TypeScript Features

TypeScript offers static typing; you can define the data type of variables. The syntax is slightly unusual for those coming from C-inspired languages in that the type is specified after the variable, e.g.

function Hello(name: string) {
	return "Hello " + name;

Many developers will be overjoyed to find class declarations and inheritance, e.g.

// base class
class Language {
    private hasClasses: boolean;

	constructor(hasClasses: boolean) {
        this.hasClasses = hasClasses;

    ClassSupported() {
		return (this.hasClasses ? "yes" : "no");

// JavaScript language
class JavaScript extends Language {

// TypeScript language
class TypeScript extends Language {

var js = new JavaScript();
alert(js.ClassSupported()); // no

var ts = new TypeScript();
alert(ts.ClassSupported()); // yes

We also have interfaces:

interface Website {
	name: string;
	url: string;

function ShowSite(site Website) {
	return + " at http://" + site.url + "/";

alert(ShowSite({ name: "SitePoint", url: "" }));

Interestingly, an object doesn’t have to explicitly state it’s implementing an interface; it only need match the expected definition.

Finally, TypeScript implements modules, e.g.

module Say {
	export function Hello(text: string) {
        return "Hello " + text + "!";

All code translates directly to JavaScript, e.g.

var Say;
(function (Say) {
    function Hello(text) {
        return "Hello " + text + "!";
    Say.Hello = Hello;
})(Say || (Say = {}));


Microsoft has provided a great online playground to help you evaluate the syntax:

I Like TypeScript Because…

Let’s look at the good stuff.

Developers new to JavaScript often struggle with the concept of prototypal inheritance. It’s a different mindset to classical inheritance concepts used in languages such as C# and Java. TypeScript offers reassuring comfort.

Sensibly, TypeScript uses the proposed ECMAScript Harmony class syntax. When that becomes widely available (don’t hold your breath), the TypeScript compiler won’t need to convert classes and your code will still run.

Static typing permits better IDE features such as auto-completion, refactoring and debugging. A plugin has been released for Visual Studio, Sublime Text, Vim and Emacs with more on the way. In other words, it should be easier to develop complex JavaScript applications.

TypeScript can be used on the client or server in Node.js. It’s a superset of JavaScript and compiles to raw, non-obfuscated code. Unlike Google’s Dart language, TypeScript doesn’t attempt to replace JavaScript entirely, require other browser vendors to add features or need chunky runtime libraries when it’s transcompiled. It has a far better chance of success.

The language has been designed by Anders Hejlsberg who brought us the excellent C#. TypeScript is open source and provided under the Apache 2.0 license at

Finally, the TypeScript compiler is written in TypeScript. That’s brain-achingly cool.

For more information about TypeScript, head over to

Backup Windows Server Using Windows Azure Backup

Posted by nilay on August 19, 2015No Comments

What is Windows Azure Backup?

Windows Azure Backup helps protect server data against loss and corruption by enabling backup to offsite cloud storage in Windows Azure. It provides a consistent experience configuring, monitoring, and recovering backups across local disk and cloud storage, integrating with the in-box backup program in Microsoft Windows Server or System Center Data Protection Manager.

Windows Azure Backup encrypts and protects your backups in offsite cloud storage with Windows Azure, adding a layer of protection in case data loss or disaster impacts your servers. It can integrate with the backup tools in Windows Server or System Center Data Protection Manager.  You can manage cloud backups from these familiar tools to configure, monitor, and recover backups across local disk and cloud storage with ease. Windows Azure Backup delivers efficient data protection.  It minimizes network bandwidth use, provides flexible data retention policies, and provides a cost-effective data protection solution that can be Geo replicated with ease. Data stored in Windows Azure is geo-replicated among Windows Azure data centers, for additional protection. Your data is encrypted before it leaves your premises, and remains encrypted in Windows Azure – only you have the key. Incremental backups provide multiple versions of data for point-in-time recovery.  Plus, you can recover just what you need with file-level recovery.

How is Windows Azure Backup Deployed?

Windows Azure Backup is deployed by configuring or enabling the services on Windows Azure then installing an agent on the server that communicates with the service.  In this Step-By-Step post we will go through the entire process Step By Step so you can easily deploy in your environment. Special Thanks to Blain Barton for his work in helping put together this Step-By-Step guide.

Here we go with the details…

0) Prerequisites

  1. Create or Login to your Microsoft Account (LiveID): How To Sign up for a Free Microsoft Account (aka LiveID) Step-By-Step
  2. Signup for a Windows Azure Account: Getting Started With Windows Azure–Step-By-Step
  3. You may have to disable IE Enhanced Security: Click Server Manager – Local Server – IE Enhanced Security Configuration – change the On to Off for administrators – Close browser then reopen browser.

1) Create a self-signed computer certificate

Certificate will be used for authentication between the host to be backed up and the Windows Azure Backup Vault.  How To Create A Self-Signed Computer Certificate using PowerShell Step-By-Step

  1. Run PowerShell from the machine you want to create certificate on: Start then type PowerShell then Right-Click on PowerShell icon and select Run as Administrator.
  2. Download the text file, open it … Highlight the text in right-click select copy
  3. Right-click the PowerShell window to paste and watch the magic
  4. Navigate to c:\ to see your new certificate which will be called “GuruCert_YourMachineName” Make a note of this location, you will need it later.

2) Login to Windows Azure Management Portal

You should see Recovery Services on the left pane (you may need to scroll down – Scroll bars are hidden in the right part of the blue NavBar [hover to activate the scroll bar])

3) Configure Windows Azure Backup Feature

  1. Create a Windows Azure Backup Vault: select Recovery Services from the left navigation sidebar in the Windows Azure portal.
  2. Click Create A New Vault.
  3. Enter a name for your Backup Vault (eg. TestBackup) and select the closest Region to your location. Click Create Vault to continue.
  4. After a few seconds the Vault is successfully creation and it is Active
  5. Click on the Vault name (eg. TestBackup) to view the Quick Start screen
  6. Click on Manage Certificate (under “Upload your public certificate to the backup vault” or in the bottom taskbar)
  7. Click the folder to upload your certificate. Browse to your certificate location (eg. C:\GuruCert_YourMachineName), select the certificate file, and click the Circled Checkmark to continue.
  8. You will get a message that says “Successfully uploaded the certificate to the vault.” Click the checkmark near OK

4) Install the Windows Azure Backup Agent.

  1. While logged into the server you will be backing up to Azure, go ahead and add a file to the desktop so we can confirm that it can be restored. Right-Click Desktop – New – Text Document – Enter.  There is now a new text document on the deskop.
  2. In the Windows Azure portal, you should still be on the Quick Start screen for your Backup Vault after you uploaded your certificate. If not, navigate to Recovery Services, then click on the name (TestBackup) of your backup vault.
  3. Click on Download Agent. For either Windows Server or Windows Server Essentials depending on what flavor you are running.

Go through the agent installation. After you have installed the Agent, click the Circled Checkmark to close the pop-out window. The Agent installation program will create a Desktop icon and Start Screen tile.Click Run to install the Windows Azure Backup Agent.

  1. Launch the Windows Azure Backup Agent from Desktop
  2. In the Actions pane on the right, click Register Server. The Register Server Wizard will launch.
  3. Proxy Configuration: Set your appropriate settings if necessary.  Click Next.
  4. Vault Identification. Click Browse and select the certificate that was just uploaded to Azure (eg. C:\GuruCert_YourMachineName)
  5. Select your certificate and click OK.
  6. After you select the certificate, select your Backup Vault from the drop-down menu. Click Next.
  7. Encryption Settings. Enter your own paraphrase or click Generate Paraphrase.  Select the location to store the paraphrase txt file.  Click Register.
  8. After the server has been successfully registered, click Close.
  9. Your server has now been successfully registered with your Windows Azure Backup Vault.

5) Configure the Windows Azure Backup Agent:

After your server has been successfully registered, you have to configure the Windows Azure Backup Agent to be able to test the backup function.

  1. You should still be in the Backup Agent. In the Actions Pane, select Schedule Backup. The Schedule Backup Wizard is launched.
  2. Getting started. Click Next.
  3. Select Items to Backup. Select Add Items to continue.  For the purpose of this lab just select c:\users only Click Next.
  4. Specify Backup Time. Choose your Days and Times to backup.
  5. Click Next.
  6. Specify Retention Setting. Choose your setting or select the default.  Click Next.
  7. Confirmation. Click Finish to create the scheduled backup job.
  8. Completed. Click Close.
  9. Now that you have created a scheduled backup job, the Back Up Now option becomes available. So, let’s run a backup.
  10. In the Actions pane on the right, select Back Up Now. The Back Up Now Wizard is launched. Click Back Up.
  11. Back Up Now completed. Click Close.
  12. You will have a completed job in the Jobs pane.
  13. Congratulations! You have successfully backed up to Windows Azure

6) Restore Files from Window Azure:

You ALWAYS have to test your backup to make sure it is working so let’s do that.

  1. From your backed up server, right-click the “New Text Document” on the desktop and select Delete. We will restore this file
  2. Launch the Windows Azure Backup Agent from Desktop
  3. In the Actions Pane, Click Recover Data
  4. Getting Started click Next
  5. Select Recovery Mode Click Next
  6. Select the volume, choose c:\ Click Next (note the date options available)
  7. Select Items to recover, expand c:\Users\username\Desktop Select “New Text Document.txt” Click Next
  8. On Recovery Options, take a look at options then just click Next (don’t need to change anything)
  9. Confirmation: Click Recover
  10. When finished, click Close; Note that the file you deleted in step a. above has been restored 🙂