Getting started Unit Testing in {{AngularJS}} Contd. – Part 20

This post is in continuation of my previous post on Unit Testing in AngularJS where we discussed about the basics of Unit Test in AngularJS, setting up the infrastructure and then wrote couple of unit tests. First we started with test for plain JavaScript method then we wrote an angular application and added unit test for Angular controller. While writing unit test, we also learned basics of Jasmine framework. The link of my previous post is given below

Getting started with Unit Testing in {{AngularJS}} – Part 19

Today we will write unit tests for following components.

  • Angular Service
  • Custom Filters
  • Custom Directive

Note – This post is a part of series of posts on AngularJS and it is 20th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

Testing your Service

As we know that service is an independent object which does some specific work and can be reused at multiple places. We normally used to have many services in our application which does various tasks. These services are the first candidates which should be considered for writing unit test. Broadly in our service, we do two type of tasks, first where we take some input, write some logic and return the output accordingly. Second where we connect some third party services via AJAX , process the response and return it. First type of service can be tested easily as normal JavaScript function. We are going to write Unit Test for second type.

We will extend our previous application where we hard coded the values in Angular Controller. Now instead, we will be creating an Angular service which will get the data from server and return that. Lets see our service

homeModule.factory("TalksService", function ($http, $q) {
    return {
        getTalks: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/home/GetTalkDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;

Note – In this series of posts on AngularJS, I have written following post where we discussed about Angular Services. To learn more about services, you can refer that

Learning {{AngularJS}} with ASP.NET MVC – Part 4

We have added our service using Factory which uses $http service to get the data from the server. One of the key points is that we are returning a promise here. Now let’s make the required changes in the controller

After these changes, our application would run same as we are now returning the same data server via Web API. Now its time to write the Unit Test

Writing Unit Test

There are two new things here, usage of $http Service and returning promise. To test $http service, AngularJS provides a Fake implementation as $httpBackend which helps in mocking the service and setting up the response. To write the test, we need to initialize TalkService and httpBackend that we can inject at before each. Also we need to initialize homeModule as

var TalksServiceFactory, httpBackend;


beforeEach(inject(function($httpBackend, TalksService) {
    httpBackend = $httpBackend;
    TalksServiceFactory = TalksService;

And unit test

    it("Should Return four Talks", function () {
    var talks;
        // Setting the mock up mock http response 
        .expect('GET', '/home/GetTalkDetails')
        .respond(200, [
            { id: '1001', name: 'Real Time Web Applications with SignalR', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '45' },
            { id: '1002', name: 'Power of Node.js', speaker: 'Dhananjay Kumar', venue: 'Hall 2', duration: '75' },
            { id: '1003', name: 'Getting started with AngularJS', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '60' },
            { id: '1004', name: 'Microsoft Azure - Your cloud destination', speaker: 'Gaurav mantri', venue: 'Hall 1', duration: '45' }

        // calling service
        TalksServiceFactory.getTalks().then(function (response) {
            talks = response;

        // Flushing httpBackend

        // verification

Above code is self explanatory. First we are initializing the mock service, calling the service and finally verifying the response. We can configure httpBackend for different scenarios based on usage of $http in actual service.

Custom Filter

Filter is another one of the most used features of AngularJS. Here we are going to use one custom filter that we wrote in one of previous post where we discussed about Custom Filters. So let’s quickly see the Filter first

homeModule.filter('ConvertoPhone', function () {
    return function (item) {
        var temp = ("" + item).replace(/\D/g, '');
        var temparr = temp.match(/^(\d{3})(\d{3})(\d{4})$/);
        return (!temparr) ? null : "(" + temparr[1] + ") " + temparr[2] + "-" + temparr[3];

Note – In this series of posts on AngularJS, I have written following posts where we discussed about Filters and writing custom one. To learn more about it, you can refer the following links

Now to write unit test, we need to inject the $filter and then instantiate our custom filter in the init test. Let’s see our unit test

describe("Filter Tests ->;", function () {

    var filter;

    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;

    it('if the number formatted', function () {
        var phoneFilter = filter('ConvertoPhone');

       expect(phoneFilter('1234567891')).toEqual('(123) 456-7891');


Custom Directive

Directives are again one of the most important components for AngularJS. Writing Custom Directive is a complex task because it is not just another function which can be injected and called from anywhere. Custom Directives are declaratively used in HTML. As it directly changes the view and also designed in a way to be reused at different views, provided the scope is properly isolated based on requirement, these should be properly tested.

We are going to write two Custom Directives : First would be a simple one and another using isolate scope and we will write unit test for both the cases. First directive is an element directive which reads some information from scope and replaces the directive with the provide html in directive as

homeModule.directive('myelementdirective', function () {
    var directive = {};
    directive.restrict = 'E'; //restrict this directive to elements
    directive.template = "Hello {{name}} !! Welcome to this Angular App";
    return directive;

Note – In this series of posts on AngularJS, I have written following posts where we discussed about writing custom directives. To learn more about it, you can refer the following links

Writing Unit Test

Writing unit test is tricky for directives because every custom directive is first complied which renders the html then other actions like binding, any user actions are performed. There is a digest cycle which runs and responsible for any binding or any other initialization before a directive appears on page.  So when writing unit test we ourself need to compile the directive using compile service and create a specific scope if required. Then run the digest cycle to make it in similar state as on UI. For that we need to initialize the scope, compile service by injecting it using beforeEach. Now let’s see our test

 var compileService, rootScope;

    // Store references to $compile and $rootScope so they can
    // be uses in all tests in this describe block
    beforeEach(inject(function (_$compile_, _$rootScope_) {
        compileService = _$compile_;
        rootScope = _$rootScope_; = {
            name: 'abc', duration: '25m'
        }; = 'Brij' ;

    it('My element Custom Directive defined', function () {

        var compiledDirective = compileService(angular.element('<myelementdirective/>'))(rootScope);




Here we are compiling the directive and running the digest cycle and checking whether it is defines. Then we can write another test which checks whether the correct html is rendered or not as

    it('My element Custom Directive renders proper html', function () {

        var compiledDirective = compileService(angular.element('<myelementdirective/>'))(rootScope);


        expect(compiledDirective.html()).toContain("Hello Brij !! Welcome to this Angular App");
Angular App");

Testing Custom Directive with isolated scope

Now we are going to write another directive with isolate scope. If you know or referred my previous post then we find that three types of isolated scope are available in Custom Directives which is also known as Local scope properties. We are going to write two way binding scope where the data is always in sync with parent regardless where it is getting changed. So let’s see the custom directive first

homeModule.directive('bindcustomdirective', function () {
    var directive = {
        restrict: 'E', // restrict this directive to elements
        scope: { talkinfo: '=' },
        template: "<input type='text' ng-model=''/>" +

<div>{{}} : {{talkinfo.duration}}</div>

    return directive;

Here talkinfo gets initialize with the scope passed via an attribute while using Directive as

 <bindcustomdirective talkdetails="talk" />

As in the template, we have input which allows the to change the scope object, this reflects in the parent scope as well.

Writing Unit Test

To write the unit test, most of things would be same as above like initialization of compiler service, scope and assign some initial value to talk object in parent scope. So lets move to the test itself

 it('Bind Custom Directive defined', function () {

    var compiledDirective = compileService(angular.element(' <bindcustomdirective talkinfo="talk" />'))(rootScope);


    var isolatedScope = compiledDirective.isolateScope();


Here we got the compiled directive using compiler srevice and run the digest cycle same as earlier one. One extra line added to get the isolate scope from the compiled directive and checking whether talkInfo is defined.

We will write another test and here we will that if we change the isolated object’s property whether thats get reflected in parent scope or not as

it('Bind Custom Directive two way binding check', function () {
    var compiledDirective = compileService(angular.element(' <bindcustomdirective talkinfo="talk" />'))(rootScope);


    compiledDirective.isolateScope() = "Building modern web apps with ASP.NET2";

    expect("Building modern web apps with ASP.NET2");

We have written the unit tests few very important components of AngularjS. Although many more test could be written and even these components vary based on requirement, accordingly different unit test may be required. But in this post, I tried to provide the basics of writing unit test for these test. Do share your feedback or face any difficulty for writing unit test for any specific component. I will try to answer that.


Leveraging the Power of Asynchrony in ASP.NET

Asynchronous programming has had a lot of attention in the last couple of years and there are two key reasons for this: First it helps in providing a better user experience by not blocking the UI thread which avoids the hanging of the UI screen until the processing is done and second, it helps in scaling up the system drastically without adding any extra hardware.

But writing asynchronous code and managing the thread gracefully was a tedious task. But as the benefits are tremendous.. Read complete post on Infragistics blog

User Name availability check with AngularJS, ASP.NET MVC and ASP.NET Web API

User Name availability check is required in most of the registration forms where we allow user to choose a user name that one can use to login later. In some other scenarios, we allow user to use his/her email as login id/user name. In both the scenarios, we require to make sure that user name or email is not used earlier. In this post, I am going to discuss, how to achieve this feature in an application which is developed using AngularJS, ASP.NET MVC and ASP.NET Web API. I wont discuss in detail the Data Access part, where one can use any approach like Entity Framework, Identity Framework , Membership provider or ADO.NET.

In this post, we will create an empty ASP.NET project with MVC and Web API. We’ll start working on Web API  part where an API will be exposed which will take user’s entry for user name as input and return true and false based on its existence. After that we will work on MVC part where we will create a registration form where user will put its information. In last, we will focus on AngularJS and create the basic infrastructure including a Service which will call the Web API to check the user name existence then how will do the check on view we will discuss at later section.

I created an API folder under Controller and created an empty Web API controller (RegistrationController) which exposed an API IsUserNameAvailable which takes an username and returns true if available else returns false. It is as

    public class RegistrationController : ApiController
        public bool IsUserNameAvailable(string userName)
            IRepository rep = new SQLRepository();
            IList&amp;lt;UserAccount&amp;gt; users = rep.GetUser(userName);
            return users.Count == 0;


Inside the API, I have used a SQLRepository which connects to the database and returns a list of users based on it. If there is no match then list contains no items. Let’s have a look that our table in database form where the account is getting matched.


Now let’s just quickly check that whether our API is working properly. The simplest way to check any API Get request via browsing the URL itself. So let’s check the URL


So as we see that Brij exists in the database so it returns false.


Now let’s create an empty MVC controller (UserRegistrationController) and View for the Index action which has an input control to enter the username.

Now its time to introduce the AngularJS into the application. Let’s see that what all the AngularJS components we need to create to implement the feature.

  1. Angular Module – To bootstrap the application.
  2. Service – This service will connect to exposed Web API to check the user name availability. It will initiate the AJAX (http) call and get the appropriate response accordingly.
  3. Angular Controller- To add some logic
  4. Custom Directive – We will discuss it in later section

I have created a new folder Registration in scripts folder to put all the angular resources. I created an angular module (file name as RegModule) which has currently

var registrationModule = angular.module('registrationModule', []);

Now it time create a service which will connect to the server to check the user availability and return true or false accordingly. I am using Factory method for creating service as

registrationModule.factory("RegService", function ($http, $q) {
    return {
        IsUserNameAvailablle: function (userName) {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: 'api/Register/IsUserNameAvailable?userName=' + userName }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;

Now to handle the UI part, we have two options

1- Either we do all the UI manipulation using Angular controller and add the required code. Or

2- We can create an custom directive where all the logic will be put to check the uniqueness of the username and updating the UI.

Lets quickly see first option, where we will write the logic in Angular Controller  as

    $scope.checkUserAvailable = function () {
        RegService.IsUserNameAvailablle($scope.Registation.username).then(function (userstatus) {
            $scope.registrationForm.username.$setValidity('unique', userstatus);
        }, function () {
            alert('error while checking user from server');

Here we are using $setValidity of for the model and add the unique attribute and set it true/false based on the service response. This will set the validity of the input as true/false and we can show some messages based on that. So let’s see the form

<div class="container" ng-app="registrationModule">

<div class="row" ng-controller="regController">

<form name="registrationForm" role="form">
            <label for="username">User Name:</label>

<div class="form-group">
                <input type="text" name="username" id="username" ng-model="Registation.username" class="form-control" placeholder="Username" ng-blur="checkUserAvailable()" />
                <span class="alert alert-danger" ng-show="registrationForm.username.$dirty && registrationForm.username.$error.unique">
                    User name is not available




We are calling checkUserAvailable function in blur event so that it gets fired when user moves focus from the control after entering the data. We also added a span (p) to show the error message which checks the input control state and unique attribute that we added. Now let’s run the application and see


As Brij is already exists in the database so it is not available and if you enter any other username which is not available in database, it wont show the message.

Second option is much cleaner so we will create a custom directive (I have written 19 posts on AngularJS, you can go here to learn all the topics or for custom directives refer the Part -9 and Part -10)

So let’s create our custom directive. Here it will use the RegService and add an onblur event to the input which will be fired once user goes out of the control after entering the some data as

registrationModule.directive('useravail', ['RegService', function (RegService) {
    var directive = {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.on('blur', function (evt) {
                if (!ngModel || !element.val()) return;
                var curValue = element.val();

                .then(function (response) {
                        ngModel.$setValidity('unique', response);
                }, function () {
                    //If there is an error while executing AJAX
                    ngModel.$setValidity('unique', true);
    return directive;

Here we have used similar code that we wrote in angular controller. Here we added blur event to the input control in directive. So let’s see the form

<div class="container" ng-app="registrationModule">

<div class="row">

<form name="registrationForm" role="form">
            <label for="username">User Name:</label>

<div class="form-group">
                <input type="text" name="username" id="username" ng-model="Registation.username" class="form-control" placeholder="Username" useravail />
               // later code is same as first option so removed forbrevity

We have set the ng-model and added our custom directive useravail as an attribute at the end in the input element. When we will run this application, it will have same as first option.
So we have implemented User name check using AngularJS, ASP.NET MVC and Web API. We can change the look n feel based on our need. Complete code is attached with this post.


Getting started with Unit Testing in {{AngularJS}} – Part 19

Unit Testing one of the important activities in software development. It helps in reducing the number of bugs in the code and maintaining the code quality. As now a days we work on small releases and keep adding/updating features, Unit Test plays a vital role in maintaining the quality and helps in making sure that new changes does not break earlier functionality and reduces the testing effort. Unit Test becomes more important for languages like JavaScript because it is loosely typed and we don’t find issues until we run the functionality. Also testing and debugging JavaScript is another time consuming activity.

Note – This post is a part of series of posts on AngularJS and it is 19th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

What is Unit Testing

Unit Test is a snippet of code or function which tests a unit of code (function/API) and all the required dependencies are mocked. It means it just test the business logic written in the function and if any other dependent instance is required then mocked version is used. Unit test does not call any real service, database call etc.

What do we need in AngularJS to get started

Being a .NET developer, I have written thousands of unit tests using C# and Visual Studio. You might be knowing that to create and run an unit test, we require unit test framework where we can run our unit test (like NUnit, MSTest etc), Unit test APIs , Mocking framework  (like NMock, Rhino mock) and then these tests can be part of Continuous Integration system where we can run the unit tests on every check-in to the repository. Similar infrastructure set up we also need in AngularJS. There are many options but I am going to use the most recommended one’s. Let’s discuss all

  1. Jasmine – It is a behavior driven development framework for testing JavaScript code and preferred for Angular Applications. There are similar others like Qunit that we can use.
  2. Angular- mock – Angular provides its own mocking framework which helps in mocking the dependent objects.
  3. Test Runner –  One of the most used Test-runner in Karma but as we are fond of using Visual Studio, there is another nice test runner called Chutzpah which provides a plugin (Chutzpah Test Adapter) for Visual Studio which is very useful.

We have discussed the required tools. Now let’s set up our environment as

  1. Create a ASP.NET Project (I am starting with empty ASP.NET MVC Project with Unit Tests).
  2. Install Chutzpah Test Adapter plugin via Nuget manager
  3. Install Jasmine Nuget package.
  4. Add Angular mock (angular-mocks.js) library for mocking purposes.

Now we have set up our solution. First we will write a simple (addition) method and a unit test to verify the set up. Before writing test let’s understand the following three items which are minimum to write any unit test using Jasmine.

  1. describe – This is a global function that takes string and function as parameter which represents a suite of test. In another way, it provides us a way to group multiple tests.
  2. it – This is another function which is written inside global function and takes two parameter as above string and function and this function is actual test.
  3. expect – It takes the function that need to be tested as parameter and provide a list of matchers to match the result.

Let’s write a JavaScript  function and write unit test for that as

  1. Add a folder in scripts folder (say CustomAngular) and add new JavaScript file say Home.js .
  2. Write a Add function in the Home.js as
    function Add(firstnum, secondnum) {
        return firstnum + secondnum;
  3. Add a file Home.test.js in scripts folder of Unit Test project to write our unit tests cases.
  4. It’s time to write our unit test for the same as
    describe("My First Test -&amp;gt; ", function () {
        it("Add with two positive num", function() {
            expect(Add(2, 3)).toEqual(5);

So we have written our first test. I already explained the special key words used here. You also need to include the references of Jasmine library and Home.js here. To run this Unit test, we just need to build the solution and open the Test Explorer and run the Unit Test. After running the Unit Test it will show green as

TestExPSampleIt means we have set up our infrastructure correctly. So let’s move to real stuff. First we will create a MVC sample application then write unit test. This application would be similar to which we have created in our series of post. But we will take small steps to understand it better. Our MVC application looks as

ExampleLet’s see code quickly. Our MVC controller (HomeController) has just one Index method which returns a view. Our Index View is as

<h2>Talk Details</h2>

<div class="container">

<div class="row" ng-controller="talkController">

<table class="table table-bordered table-condensed table-hover">

<tr ng-repeat="talk in talks">

<td> {{}}</td>

<td> {{}}</td>

<td> {{talk.speaker}}</td>

<td> {{talk.venue}}</td>

<td> {{talk.duration}}</td>





Now let’s see our JavaScript file where we have put up our Angular code

var homeModule = angular.module("homeModule", []);

homeModule.controller("talkController", ['$scope', function ($scope) {

    $scope.talks =  [
        { id: '1001', name: 'Real Time Web Applications with SignalR', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '45' },
        { id: '1002', name: 'Power of Node.js', speaker: 'Dhananjay Kumar', venue: 'Hall 2', duration: '75' },
        { id: '1003', name: 'Getting started with AngularJS', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '60' },
        { id: '1004', name: 'Microsoft Azure - Your cloud destination', speaker: 'Gaurav mantri', venue: 'Hall 1', duration: '45' }


Also I have included Angular library, Home.js and added ng-app attribute as well. Now we will write the unit test for our Angular Controller.

First let’s understand our Angular controller. Here We have a module and a controller which takes one parameter $scope. So while writing test, we require these three items and these need to be initialized first before running the test. To initialize, Jasmine provides us beforeEach function which can be used to initialize the items which runs before the test. And we need Angular mock library to set up all. Let’s see the test and then discuss each

describe("Talk Controller Tests -> ", function () {
    var scope;
    var $ctrlCreator;

    beforeEach(inject(function ($controller, $rootScope) {
        $ctrlCreator = $controller;
        scope = $rootScope.$new();

    it("It should have four talks", function () {
        $ctrlCreator("talkController", { $scope: scope });



In the above code snippet, we first created two variables then initialized homeModule after that we injected controller and scope instance with the help of mock. In our Test, we are testing that length of talks returned by our controller is four. Now we can run our unit test via Test Explorer and it will pass. Similarly we can write many more tested for controller’s functions.


In this post, we talked about Unit test in angular. What are the basic things required to set up the project and get it started. Then we created a simple function Add and wrote unit test for that to check the setup. We continued writing the unit test of our controller and saw that how to initialized items before running the test. Hope you have enjoyed the post. In next Post we will continue talking about Unit Testing and write unit tests for some other components.


Singleton vs Static class : Key Differences and Usages

The debate about Singleton vs Static is quite old and it is still continuing and there are lots of confusion around this as well. In this post, I am trying to explain these two concepts, key differences and its usages.In this post I will not focus on the basics of Static and Singleton and how to write that. If you are new to these keywords, I will advise you to learn about these first to get more benefited.

So first we are going to understand the characteristics of each . Lets start with static class

Static Class :

  1. Static classes cannot be instantiated so it restricts us in many ways like it cannot implement Interfaces, inherit any class etc.
  2. Any other scenarios where this keyword is required, it cannot be used like indexer etc. Also it cannot be used as method parameter, local variable etc for the same reason.
  3. Static classes can have only static members – constructor, fields, methods, properties, events.
  4. One cannot control when static constructors are called. It’s always earlier than first access of the class. So no parameters can be passed as well.

Internally when compiler compiles static class, it marks it as a abstract and sealed. So that no instance can be created and cannot be extended as well. Now let’s talk about Singleton

Singleton Class :

  1. As name suggests it allows to have only one instance of a class.
  2. The constructor of this class are marked as private so that accidentally one cannot create multiple instances and provides a static function/property which first create one instance and returns the same each time.
  3. As singleton is a normal class, it allows us to leverage all that features of object oriented programming concepts.

Memory Management :

There is much confusion around memory management of static class and Singleton class. In simple words, any class whether it is itself static or any member if marked as static then it would not be collected by Garbage Collector.

Static variables/classes are not stored in normal Heap and there is a separate space in memory to store static resources which holds the static classes and variables.This space is beyond the scope of GC and memory get release only when corresponding process/AppDomain unloads.

Because singleton holds a static reference which cannot be collected by GC so the instance cannot be collected and both (Static and Singleton) gets destroyed with the AppDomain/Process.

Some Key common characteristics :

  • As both of the static and singleton instances are have just one copy in memory throughout the whole application, both used for holding global state in an application.
  • Both are initialized lazily, it means for static classes it is initialized only when accessed first time and for Singleton, it gets created only when it is accessed first time.

The Differences

  1. Very first difference is that Static is a language feature and Singleton is a architectural pattern so both belongs to difference arena altogether.
  2. Now a days everybody is behind using Dependency Injection and Static does not fit there because it is interface driven.
  3. Unit Testing is another topic where you can find some way to create a mock for singleton instances but testing static is a nightmare.
  4. Being singleton is a just another class, it enable you to use Object oriented concepts.

Singleton approach is much more flexible as we can see that from the differences itself. We can use interface with it and implement it in a class and use in our application. If some requirement changes and later we require to change the logic then we can just remove the older implementation and replace with new one without hiccups as long as the interface is same.. Also testing is another key benefit.

Static classes is mainly recommended for having grouping of a bunch of utility methods that can be called independently but again testing could be a problem and benefits of OOP is gone. So most of the time static should be avoided.

Having said that using global variable (like static class or singleton) makes a strong coupling between the global data and all the places where it is used.



Top 12 tricks to insert common code snippets : Productivity Tips

This post is in line with my previous post where I talked about how one can be more productive with Visual Studio. In last post, We discussed top 12 shortcuts that helps a lot while writing and reviewing code in day to day work. While writing code we need to follow to follow certain rules and constructs that also becomes very repetitive say, you are writing classes for your domain or adding properties or defining constructors or putting try block and lot more where we just need to write the code in similar pattern and are no brainer. Spending time in these types of code are kind of waste of time and energy. To see my previous post, use the link below

Top 12 Visual Studio short cuts – Productivity Tips

In this post, I am going discuss 12 tricks that can insert code snippets just by few keystrokes.

1- Writing a class is a one of the most common repetitive code we write. Use

  class press TAB





Once the snippet inserted, it puts the cursor at MyClass which allows to change the name of class instantly without any extra keystroke.

2- Writing constructor is also another task which is very common and many times we many constructor for the same class. To write constructor use

ctor press TAB





3- Now Class is created. Let’s add property now. Use

prop press TAB




Similar as 1st trick, it puts the cursor to change the type and after that change the property name itself. I found really cool when I used first.

It comes with many other flavor. Use propg  to create a auto implemented property with private set.

4- Second trick allows us to write auto-implemented property which requires less code but there could be many scenarios, when we need to write Full property definition that we used in earlier to C# 3.0 then use

propfull press TAB






Changing type and name can be done similar to above.

5- Need to write an indexer, use

indexer press TAB





6- Many times while code review we see that some part of code is not under try catch block or we need to write the block. Use

try press TAB






There is another flavor, if we just want try and finally then use tryf.

7- Want to create enum use

enum press TAB





Similarly use struct to insert struct block.

8- Want to create switch block, use

switch press TAB





Similarly use for, foreach, do, while etc to insert respective code blocks.

9- Many times we need to write our own custom exception class that should inherit from Exception class. It can written easily by

Exception press TAB

It creates a serializable class as

8- Exception







10- Want to override Equals method for your class. Use

equals press TAB

It will insert as












11- To write static void main, use

svm press TAB





Similarly you can use sim for static int main.

12 – last, many times we write console.writeline in our application. Just use

cw press TAB



In this post, how can we save lots of keystrokes and time while writing some very common repetive code. This is not complete list but very common ones that can be used a lot in our day to day coding. if you know any other snippet which is very useful, do share in comments.


Top 12 Visual Studio short cuts – Productivity Tips

Visual Studio is very Rich IDE and it provides in-numerous features that makes our day to day life easy. There are some very useful hot keys and tips which can increase our productivity significantly. Earlier I used few hot keys but recently I learned few which I found awesome which drastically reduce my time while writing/debugging/reviewing the code. So learn these and make a habit of these keys and feel super charged while writing code.

  1. While code review I find many time scattered and unaligned code which I hate. I use CTRL+K+D for aligning it.
  2. While debugging or testing the code, commenting/commenting codes are done a lot. Use CTRL+K+C/CTRL+K+U for the same.
  3. How do you up/down certain line of code. Select the code block and use ALT+up/down
  4. You have a used a lot F12 to go to Definition of class. Use CTRL – to go back.
  5. How do you resolve the classes by mouse click. Use CTRL+. to resolve it quickly.
  6. Refactoring is very important. Use CTRL+R+M for extracting a method.
  7. Find All References -> Use Shift + F12. Very helpful while debugging and fixing bugs.
  8. Want to put few lines of code in try block. Try Ctrl + K + S, it provides lot more options
  9. Ever tried selecting a rectangle code. Use ALT click drag.
  10. Lots of code in a single file. Use  CTRL + M + O and CTRL + M + X in collapse/expand code groups like regions, methods etc.
  11. Lots of code and there are no groups. Use CTRL+M+H/CTRL+M+U
  12. Another super sweet. ALT+F4 to close the window.

Try using the above in your day to day coding and be more productive.