Sunday, July 5, 2015

Dependency Injection with Autofac: Keyed Registration

This will going to be a fifth post in my Dependency Injection series with Autofac. If you have not gone through all the previous post of this series then I would like to encourage you to go through it. Following is a list of blog posts.
Dependency Injection with Autofac : Getting Started
Dependency Injection with Autofac : Constructor Injection
Dependency Injection with Autofac : Module Feature
Dependency Injection with Autofac : Registration Ordering
Dependency Injection with Autofac: Named Registration

Keyed Registration:

There are multiple ways of register and resolving type in Autofac and keyed registration is one of them. Just liked named registration here you can resolve a type with a key. That key can be a valid C# object. Let’s create a sample console application for it. I have added reference of Autofac via NuGet package as did in my previous blog post. Following is a Customer class that I’ve created for the Keyed registration demo.


After creating Customer class following is a code that I’ve written for demo of Keyed Registration with Autofac.
If you see above code carefully, You can see that first I have created a object of customer as keyCustomer then I’ve register customer type with that keyCustomer Object.  After that I’ve resolved customer with that keyCustomer object and assigned few properties and then Print that customer with “PrintCustomer” object.
One thing to note that when you register type with Keyed Registration It can not be resolve without it. You can only resolve that type with same key you have registered.
Now when you run this application. You will following output as expected.

autofac-keyed-registration-output
That’s it. Hope you like it. Stay tuned for more!!.
You can find complete source code of this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Friday, July 3, 2015

Dependency Injection with Autofac : Named Registration

I’m really having fun with Autofac and It is a great IOC container.  As its tag line suggest it it a addictive IOC container.  This post will be a part of Autofac series. If you have not gone through my previous blog post then I would suggest you go through it. Following is a list of blog post I’ve written for Autofac series.

Dependency Injection with Autofac : Getting Started
Dependency Injection with Autofac : Constructor Injection
Dependency Injection with Autofac : Module Feature
Dependency Injection with Autofac : Registration Ordering

Named Registration:

Named registration can be very useful when you have to create multiple object of same type with different states. Autofac provides that functionalities with Named Registration. I’m going to create a sample console application and added Autofac via Nuget package.  To demonstrate named registration I’ve created customer class like following.


Now let’s write some code to create named instance like following.
As you can see in above code, I have created a named registration with build container and then I have resolve the instance with same name which I have done registration for it. Then I populated properties of Customer and Printed that customer with “Print” function.
One thing to note here that when you register types with named instance then it can not be resolved without name. If try to resolve it it will give error.
Now when you run this application. It will print Customer as expected.

Autofac-named-registration

That’s it. Hope you like it. Stay tuned for more!.
You can find complete source code of  this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Thursday, July 2, 2015

I’m Microsoft MVP again. Thank you all

Today is one of the great day in my life. I’m again an Microsoft MVP for .NET and I’m happiest person on the earth and proud of it. Today’ I got this award for fourth time. Earlier I got this award for year 2010,2011 and 2012 for Visual C#.

I would like to thank all of you readers for making my blog so much popular. Thank you my family who has sacrificed lot of time for writing blog and other community activities. Also  I would like to Mention few people without their support and encouragement it would not have been possible. So special thanks to Mahesh Dhola, Kaushal Bhavsar, Ahmedabad .NET User group , Biplab Paul  and Gandharv Rawat.

I would also like to thank my current and previous Employers who has providing excellent opportunity to be part of .NET Technology world.

11034899_10153010450113437_8068327835173356049_n

Thank you all!.  Stay tune fore more!!.
Share:
Tuesday, June 30, 2015

Dependency Injection with Autofac: Registration Ordering

This post will be part of on going series for Dependency Injection with Autofac. If you have not gone through my previous post I would encourage you to go through it. Followings are links for that.

Dependency Injection with Autofac – Getting Started
Dependency Injection with Autofac – Constructor Injection
Dependency Injection with Autofac- Modules Feature

In this this blog we are going to learn about Registration ordering in Autofac.  If you register same interface multiple times then by default the last registration will be preserved. So when you resolve things it will be resolved by last registration. You can also prevent that via “PreserveExistingDefaults” method which is a second behaviour where first registration will be preserved. We will look both in details in this post.

Registration Ordering:


To demonstrate registration ordering, We are going to create a simple Employee class like below.

After creating a Employee class following is a code for my console application.

If you see code carefully, The important thing is two functions “DefaultBehaviour” and “AnotherBehaviour”. First function I’ve register two employee object one by one then. I tried to resolve employee object and with the help of "PrintEmployee" method I have printed Employee object.  Here I’ve used default behaviour so it will print secondEmployee as last registration will be resolved.

While in “AnotherBehaviour” function, I have used “PreserveExistingDefaults” function while registering secondEmployee object. So it will preserve first registration. So when you resolve object it will resolve first registration. So when you print employee object with “PrintEmployee” method it will print firstEmployee object.

When you run this console application. Following will be output as expected.

autofac-registration-ordering

That’s it. Hope you like it. Stay tuned for more!.
You can find complete source code this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Sunday, June 28, 2015

Dependency Injection with Autofac : Modules feature

I’m having fun with Autofac as IOC containers and this is third post in series. In this blog post we are going to learn about Autofac modules. If you have not gone through first two blog posts then I would encourage you to go through it. Followings are link for that.

Dependency Injection with Autofac- Getting Started
Dependency Injection with Autofac – Constructor Injection

What is Autofac Modules?

Autofac modules provides greater flexibility  for structuring large application. Register all the component in single class will work for small applications. But for larger applications that will be quite difficult class. In this situation Autofac modules can help.  Autofac modules allow us to break registrations of component in different classes. Then later all you can load all the modules at single places.

So what we are waiting for, Let’s write some code to demonstrate the power of Autofac Modules. For that I’ve created a simple console application called “AutofacModules” and added Autofac nuget package to get reference of application. In this application we are going to create two separate module for “Student” and “Teachers”. So lets start by creating student model class like following.


Following is a student repository interface which contains a "Print" Method to print Student.
 And here is the implementation for Student Repository Inteface.

Now it's time to create Teacher model class like following.

Following is a interface created for Teacher repository which contains "Print" Method to print Teacher.
And here is the implementation of Teacher repository interface.
Now we are done with creating basic classes and interfaces for Student and Teacher It's time to create a modules for them. To created a module for them we need to create a separate class for Teacher and Student Module which got inherited from the Autofac module class. Following is a code of Student module.
And same for teacher module.
 If you see code of both classes carefully then you will realize that it is inherited from the Module classes and It's got a Load method override where we have done registration of repositories. Now our modules are also ready so It's time to write our main console application code. Following is a code for that.
If you see above code carefully the important thing is "BuildContainer" method where I've registered our module with RegisterModule method.Rest I have created teacher and student object and created object with Autofac Container and print respective objects. When you run application following is a output as expected.

autofac-module-console-application-output

That’s it. Hope you like it. Stay tuned for more post about Autofac features.
You can find whole source code of this Autofac series at Github on following location -https://github.com/dotnetjalps/AutofacSamples
Share:
Saturday, June 27, 2015

Dependency Injection with Autofac : Constructor Injection

Recently I’m playing with Autofac and I’m having fun with it. This blog post a part of same series. In this blog post we are going to look into how we can do constructor injection with Autofac. If you are not familiar with Autofac you can go through my introductory blog at following location.

Dependency Injection with Autofac: Getting Started

In this blog, We are going to see how we can do constructor injection with Autofac. So for that I’ve created a small console application. After creating a application, first thing you need to do is to add reference of Autofac via Nuget Package. You can do that via following nuget package.



Now it’s time to write some code. I’ve created a sample basic “Employee” model class like following.



After that I’ve created a interface “IEmployeeRepository” which has one method to print employee and expects Employee object parameter.


And following is a implementation class for Employee Repository.


Now it’s time to write Employee Service class code like following.


If you see above class carefully, You can see that it’s expect a constructor parameter of Employee Repository parameter and there we need to constructor injection.  So let’s write some Autofac code for constructor injection like following.


Here in the above code, You can see I have “BuildContainer” static method. Which created a Container Builder object and It’s register type of employee repository and employee service and it’s return a container object. In main method code I’ve resolve employee service class object with container and it’s automatically inject our constructor requirement of employee service class. Then I’ve created a employee class object and print it with print method. Once you run the application. You will get following output as expected.

constructor-injection-autofac-output

That’s it. You can see it’s very easy to do constructor injection with Autofac. In future post we are going to look at some other features provided by Autofac. Stay tuned for more.
You can find complete example of above blog post at following location on github- https://github.com/dotnetjalps/AutofacSamples
Share:

Dependency injection with Autofac : Getting started

I have been using dependency injection a lot in my projects. As it’s provide great flexibility to wire up things. Recently in free time I have been looking into some of open source architecture like Orchard and Nopcommerce. Both are using Autofac as dependency injector. As this IOC container are used in one of top successful project I got interested in Autofac and I started learning Autofac. I thought it will be a good idea to start a blog series for my learning so other can get benefit of it.

What is Autofac?

As per Autofac.org a site for Autofac
Autofac is an addictive Inversion of Control container for .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps.
It is used in lots of application and one of the most popular IOC container in .NET world.  As per official documentation here is the basic pattern for integrating Autofac in your application.
  • Structure you application with Inversion of Control in mind
  • Add Autofac references( I prefer it using Nuget Package).
  • At application startup create a container builder
  • Register a component
  • Build container and store it for a later use.
  • Create lifetime scope of container during application execution.
  • Use lifetime scope to resolve instances of application.

Autofac Example:

So what we are waiting for, Let’s create a simple example. I’m going to create a sample application like following.

AutofacBasicConsoleApplication

After creating application, I have created a my interface IPrintService as following.
namespace AutoFacBasic
{
    public interface IPrintService
    {
        void PrintSomething(string text);
    }
}

Here is the implementation of interface in class like following.
using System;

namespace AutoFacBasic
{
    public class PrintService : IPrintService
    {
        public void PrintSomething(string text)
        {
            Console.WriteLine(text);
        }
    }
}

Now, We have done with basic stuff so it’s time to wire up component with Autofac. To add references for Autofac I’m going to use following nuget package.

nuget-package-autofac

After adding a Autofac reference via nuget package. I have written following code for that sample console application.
using Autofac;
using System;

namespace AutoFacBasic
{
    class Program
    {
        static void Main(string[] args)
        {
            //registering interface with class that implemented
            var builder = new ContainerBuilder();
            builder.RegisterType<PrintService>().As<IPrintService>();

            //Resolving inteface with autofac
            var container = builder.Build();
            var printService = container.Resolve<IPrintService>();
            printService.PrintSomething("Hello World");
            Console.ReadKey();
        }

    }
}

Here in the above code, If you see carefully. First I have created a object of Container Builder and then I have register type with print service. Then I have build container builder to get container object. After that I have resolved print service with container and get the object of printer service. Then I have printed Hello world with PrintSomeThing method. When you run application. Here is the output as expected.

autofac-console-application-output

That’s it. You can see how easily we can wire up things with Autofac. In future posts we will see some advance features of Autofac. Stay tuned for more!!.

You can find complete source code of this application at following location at github- https://github.com/dotnetjalps/AutofacSamples/
Share:
Wednesday, June 24, 2015

Completed 725 blog post and still counting

I’m not a fan of counting milestones but today it was huge one so I could not resist myself to write a blog post about it. Today this blog has been completed 725 Blog post.

I still could not believe this blog has come so far!. This will would not have been possible without you guys.

I promise that I try to keep updated this blog in weekly.  Also on this occasion I would also like to thank my family. Specially my wife who is continuously supporting me and sacrifice her time for my blog post.

Thanks you all again! . Also today I have changed my blog theme to a modern look. Hope you like it. Stay tuned for more. Keep reading my blog. 
Share:
Saturday, June 13, 2015

Double quotes not working with Visual Studio

Recently, In one of the development machine with Windows 7, I was having strange problem with Visual Studio 2013, When I type double quote first time it was not there and then after once again type I type then it was there. I was wondering what is going on. After digging into little deep, We figure out it was due to language settings and that is creating problem. After fixing languages I was able to fix this issue. I thought it will be good idea to write a blog post about it. So other can be benefits also.

So problem I was having is I have to type double quotes two times. To fix that problem first thing you need to do is Goto  control panel-> region and language options. There you need to go to Keyboard tab. In windows 8.1 Go to search and search for language preferences.

Once you go to language preferences select English US Keyboard. Set that as default.
Now once you are done with your control panel settings. It’s time to make settings changes in Visual Studio. To Change the settings in visual studio go to Tools –> Options –> Environment Settings –> International Settings.
Share:
Wednesday, May 13, 2015

Visual Studio 2015 Github tools

I love open source and that’s why I’m making all the source code of my blog post on Github. Now with Visual studio 2015 RC Microsoft and Github released a GitHub tools for visual studio. So now you can directly interact with your Github repositories from team explorer itself. Working with Github never be easy now.

Once you install, Github tools for Visual studio with visual studio 2015 installation. It will be available on Team explorer like below.

githu-tools-for-visual-studio

Share:
Saturday, May 2, 2015

My sample code for 2015 Global Azure Bootcamp Ahmedabad

Lots of people ask for my sample code application for my presentation on “Azure Storage Services”.  So here is source code(Sample application) for 2015 Global Azure Bootcamp, Ahmedabad.

Source code of sample application for  2015 Global Azure Bootcamp , Ahmedabad:

You can find source of sample application which I have created at following location on GitHub.
https://github.com/dotnetjalps/GlobalAzureBootcampDemo
Share:

Azure Frequently Ask Questions: How to create a storage account with new portal

After presenting About Azure Storage Services at Global Windows Azure boot camp at Ahmedabad. I got lot of feedback and questions. One of the frequently asked question was how we can create a storage account with new Azure portal Preview. So I thought it would be a great idea to write a walk through post for it.

As you know, Before few months Microsoft has launched a new Azure portal in preview mode. It’s amazing there are lots of features available. You can find azure portal at portal.azure.com. You can do lots of stuff and monitoring that were not possible with current portal. I've tried and really like it. Please do try it and tell community about your feedback.

How to create a storage account with new azure portal:

So what we are waiting for let’s start our walk through of creating a storage account with new portal. So once you put url in browser it will be ask for login with your azure live account.

Share:
Sunday, April 19, 2015

Structure and Operator overloading in C#

Recently I have been playing with structure and It’s fun. In this blog post we are going to learn how we can use operator overloading with structure in C#.  You can find my blog post that I have already written about structure  at following location.

Structure in C#
Structure with constructor in C#
Structure with Interface in C#

So as usual I've created a console application to demonstrate operator overloading in C#. Here I have created a structure with equals operator overloading and following is a code for that.
Share:

Structure with Interface in C#

Recently I have been playing with Structure and it is fun. I have written couple of blog post about structure. Following are links for that.

Structure in C#
Structure with constructor in C#

In this blog post we are going to learn how we can use structure with interface. So like earlier example I’ve created a console application. Now it’s time to write interface which we can implement with structure. Following is a code for that.
using System;

namespace StructureWithMethodAndInterface
{
    interface IPrintable
    {
        void Print();
    }
}
Here you can see that I have simple interface IPrintable which has simple print method. Now let’s create a structure which implement this interface. Following is a code for that.
Share:
Friday, April 17, 2015

Structure with constructor in C#

Before some time , I have written basic introduction post about Structure in C#. In this blog post we are going to see how we can have constructor with Structure. As we all know structure is a value type so it stored on stack. So let’s create a structure like follow with constructor.
public struct Customer
{
    #region Fields

    public int CustomerId;
    public string FirstName;
    public string LastName;

    #endregion 

    #region Constructor

    public Customer(int customerId, string firstName, string lastName)
    {
        CustomerId = customerId;
        FirstName = firstName;
        LastName = lastName;
    }

    #endregion
}
Here you can see I have created Stucture with parameter. As we all know structure is a value type so when initialize the it at that time we need to give values to its elements so that’s why default constructor without parameter is not supported in C#.

Share:
Wednesday, April 15, 2015

Structure in c#

In this blog post we are going to learn about Structure Data structure in C#. In C# Structure is value type which stores on Stack. It is a composite value type that contain other types. You can also create object of structure like class. In C# structure can  contains fields, properties, constants, constructors, properties, Indexers, operators and even other structure types.

So enough theory. Let’s create a sample console application to learn about structure.

structure-in-csharp

Share:
Tuesday, April 7, 2015

Entity Framework Code First and MySql on Azure

We have used Entity framework with SQL Servers mostly. In this blog post we are going to see how we can use Entity framework with MySql on Azure.

How to create MySql database on Azure:

On azure MySql is not maintained by Microsoft itself. It is provided their partner cleardb. So You need to search at Azure Market Place and then add it like below.

market-place-azure-my-sql-database

Share:
Sunday, April 5, 2015

Best coding standards checklist for C# and ASP.NET

Before some time I have written a blog post about coding standard Why coding standards are important?. It was appreciated by lots of people and few people asked me whether do you have coding standard checklist or not? So Today, In this blog post I’m going to shared few link for coding standard checklist which I follow.

Aviva C# coding guidelines:

An awesome guideline for the C# 3.0,4.0 and 5.0. It’s very good and open sources. You can find that following link on code plex.

https://csharpguidelines.codeplex.com/

Do Factory do and don’ts for C#:

A great list of do and don’ts of C# coding standards that all we should follow.

http://www.dofactory.com/reference/csharp-coding-standards

Encodo C# Handbook:

It’s having so many coding standard and most of relevant to naming conventions and formatting. You can download that via following link.

http://code.msdn.microsoft.com/encodocsharphandbook/Release/ProjectReleases.aspx?ReleaseId=3352

Microsoft All one code framework:

I have been using this for a while. It’s an awesome library which display best practices how we can write code.

http://1code.codeplex.com/

There are lots others are also available but I think it’s if you follow and practice above mentioned resources your code will be perfect.
Share:

Entity Framework Internals: Connection Resiliency

When you use cloud services to deploy your application and database it might be possible that transient connection will be a problem between database server and web servers. When you use on premise servers that uses the database server and web server on same data centre. When you use cloud there will be huge infrastructures and you never know where it is deployed even if it deployed on same data centre there will more connection like network load balancers etc. When you use cloud services that will be shared by lots of users which means its responsiveness can be affected by them. And your access to the database might be subject to throttling. Throttling means the database service throws exceptions when you try to access it more frequently than is allowed in your Service Level Agreement (SLA).

So in cloud service there will be transient problems which will be resolved in short period of time. So when you got such kind of errors then you can wait for some time and then you have retry. For that kind of operation Entity Framework provides connection resiliency feature.

The connection resiliency features must be configured for proper database services. It has to know which exceptions are likely to be transient problem and which exceptions are caused by our code. It has to wait for an appropriate amount of time between retries of failed operation. Also it has to try number of times before giving up.

Share:
Thursday, April 2, 2015

Quick Tip–How to get time difference in C#

Recently, One of the reader of this asked me about, how we can get time difference between two dates or two times? So I thought it will be a good idea to write a blog post about that. So that other use can also get benefit from that.

For that I have created sample console application like below.
using System;

namespace TimeDifferenceCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime firstDate = DateTime.Parse("12:50");
            DateTime secondDate = DateTime.Parse("10:40");

            TimeSpan difference = TimeSpan.Parse(firstDate.Subtract(secondDate).ToString());

            Console.WriteLine(difference.Hours);
            Console.WriteLine(difference.Minutes);
        }
    }
}
In above example, If you see it carefully I have taken two dates with different time. Then I have used subtract method DateTime class to find different of both and then I parse it to TimeSpan class. After that I have printed hours and minutes for  via Console.Writeline method.

Now let’s run this application. You will see output as following.

time-difference-in-csharp

That’s it.Hope you like it.

You can find complete source code of this blog post at github on- https://github.com/dotnetjalps/TimeDifferenceInCSharp
Share:

Quick tip- How to change menu bar letter style in visual studio 2013 and 2015

When Microsoft has introduced, Visual Studio 2012 with Upper case menu, There were so many reactions from the developers. So with Visual Studio 2013 Microsoft has provided that settings to Turn of capital letters for menu. I have just came to know that accidentally. You can find that settings in Tools->Options-General settings.

menu-capital-settings-visual-studio-2013-15

Once you check it. Upper case will turn off like below.

upper-case-turn-off-visual-studio

That’s it. Hope you like it. Stay tuned for more!.
Share:
Wednesday, April 1, 2015

Entity Framework Internals: Private setters and private constructors

I have been heavily learning Domain Driven Design recently and In that there is a concept called “Anemic Domain Model” which we used to use in our project. In simple terms Anemic Domain Models are those classes that do not have any behaviour with them and most of created with properties. You can use them as container for your data from database. While Domain driven design is all about behaviours. So we need to make our models incorporate behaviours also which is called  “Rich Domain models”.

One of step to convert your Anemic Domain Models to Rich Domain Models is to create parameterised constructors. For example an Employee must have FirstName and LastName. So instead of doing validation at the insertion time on UI we should not allow Employee to be created without FirstName and Lastname. The only way to do this to make this properties setters private and assign value of those properties via parameters constructors like below.
public class Employee
{
        public Employee(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
            
        public int EmployeeId { get; set; }
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public string Designation { get; set; }
}
Now, If you want to do DDD with any Object Relational Mappers there will be a problem as most of Object Relational Mappers create properties with public setters. Entity Framework is such a Object Relational mapper and I love to work with Entity Framework.

Share:
Thursday, March 26, 2015

Fluent Nhibernate : Create Table from Code(Class- CodeFirst)

Now days,  Convention over configured is more preferred and that’s why Fluent Nhibernate got more popularity Because with Fluent Nhibernate we don’t have to write and maintain mapping in xml. You can write classes to map your domain objects to your database tables. If you want to learn how we can do this with existing database and Fluent Nhibernate, I have also written a blog post about CRUD operation with Fluent Nhibernate and ASP.NET MVC . After writing this blog post I was getting a lots of emails about how we can create database from the Fluent Nhibernate as we can do same with Entity Framework Code First. So I thought it’s a good idea to write a blog post about it instead of writing individual emails.

How to create tables from class via Fluent Nhibernate:

To Demonstrate how we can create tables based mapping classes create we’re going to create a console application via adding new project like below.

Share:
Sunday, March 22, 2015

Entity Framework Internals: Enum Support

In .NET world, We all are using Enums in our code. It’s makes our code more readable then using hardcoded numbers of strings. Entity Framework 5.0 or higher version has support for Enums. In this blog post we are going to see how we can use Enums with entity framework.

We are going to create a console application to see how it’s works. I’m going to create a console application for the same.

entity-framework-enum-support-console-application

After creating a application I’ve added Entity framework via Nuget package.

Share:
Saturday, March 21, 2015

Entity Framework internals :IEnumerable and IQueryable

Now days, Entity framework is one the most used ORM in .NET world. Still I can see lots of people confused with IQueryable and IEnumerable. If they dont' know what is difference between them then they are going to make mistakes .When you first look at it both looks same. But there are quite differences and If you don’t understands internals of it then it will impact your query performance also.

IEnumerable vs IQueryable:

Here is the basic difference between IEnumerable and IQueryable. When you write queries with IEnumerable it executes queries on Server and load data in memory and then filter data on client side. This will be a problem when you are fetching large amount of data. While IQueryable executes queries on server side with all filters and then load all data into memory.

Example:

Sound complex!. Let’s write a simple example to understand it better. I am going to create a simple table in database called student table.

Share:
Friday, March 13, 2015

NSubstitute Introduction and Why I like it

Recently I am heavily learning Test Driven Development and Domain Driven design. As you know With TDD you need to have a mocking libraries. So after doing on research on internet they are three libraries available in Microsoft.NET development world which are quite mature.

  1. Rhino Mocks
  2. NSubstitute
  3. Moq
I have gone through all of above three and then After doing research and I choose NSubstitute.

Why I Choose NSubstitute:

Following are the reasons why I have chosen NSubstitute.

  1. It is super easy to use. I don’t have to write very complex lamda expressions to mock objects.
  2. It works really fine with all framework of Test Driven Development
  3. As it is super easy to use you need to write very less code to mock objects.
  4. With other Visual Studio plugins like Resharper, Telerik Justcode its works perfectly and they are able to generate code for the same.
  5. It’s got fluent syntax and very easy to understand.
  6. It’s perfect for some one who is not mature enough for Test Driven Development.
Share:
Thursday, February 5, 2015

Shared project in Visual Studio 2015

Shared project is new feature that was added in Visual Studio 2013 update 2 but in visual studio 2015 it is coming by default. In this post we are going to learn about Shared Project and how it is different from class library.

Shared project in Visual Studio 2015:

Shared project is a new feature that is introduced with Visual Studio 2013 update 2 and it’s comes by default with Visual Studio 2015. So with shared project you can share your common code with any number of applications. You can use that in another project via adding project reference. So let’s see how we can use Shared project in multiple application.

To understand how Shared project works, I have create a blank solution like following.

blank-solution-for-shared-project-visual-studio-2015

Share:
Wednesday, February 4, 2015

Why coding standards are important?

Yesterday, I had a discussion with friend about coding standard are important and why you need it?  So I thought it will be a good idea to write a blog post about it. Followings are some reasons why coding standard are so important.

  • Readability:  coding standard will increase overall code readability means if you follow you coding standard defined other people also know that what you have written. They don’t need to debug the code to know what function this code will perform.
  • Code Style: Every programmer have different style of writing code. So if we don’t have coding standard then Programmer ‘A’ can write variable in camel casing while other  will prefer to use Pascal case. So different modules have different coding styles.Which makes code hard to understand.
  • Code Reviews: Code review is an important part of any software development. If you don’t have a coding standard defined then it will take more time to do code review.
  • Error handling/Exception handling : The another benefits of coding standard is standardized way of handling errors. If you don’t have coding standard defined then each programmer will handle errors in unique way that could create a problem of identification of a bug  in software development .
  • Maintenance: Large enterprise software's will have  long life span. So if there is any enhancement or maintenance work is required with the help of coding standard any people can understand code easily and easily do the some changes.
That’s it. Hope you like it. Stay tune for more!
Share:

What is MongoDB and Why MongoDB?

Recently I have playing a lot with MongoDB and it’s  one of the favourite document database. In this blog post we are going to learn about MongoDB in details.

What is MongoDB?

Those who don’t know MongoDB here is what documentation on MongoDB says about it.

MongoDB is a document database that provides high performance, high availability, and easy scalability. Document Database. Documents (objects) map nicely to programming language data types. Embedded documents and arrays reduce need for joins.
A MongoDB is one of popular database. A standard deployment can hold many databases. A database holds a set of collections. It's like similar to tables in relational databases. A collection holds a set of documents just like rows in relational database tables. A document is a set of Key value pair. It’s stores data in such a way that there is no relation is required. It was created by company called 10gen.

MongoDB supports almost all the languages and there are lits of drivers are available for MongoDB and it open sourced at Github at following location.

Share:
Sunday, February 1, 2015

Grid view row span in ASP.NET

I know for some one it will sound like a very basic code for the row span of grid view but still there are lots of people that does not about that. So I thought it will be a good idea to write a blog post about it. So in this blog post we are going to learn How we can use row span in ASP.NET Grid Views.

So what we are waiting for Let’s take a small example of sample ASP.NET Web forms application. So Let’s start by creating an empty ASP.NET Webforms application like below.

GridViewColSpan

After that I have added a page web page like below.

Share:

Project.json file in ASP.NET 5(vNext)

Recently Microsoft has released the preview version of ASP.NET 5(vNext) as a Part of Visual Studio 2015 CTP. As this whole .NET framework is rewritten from the scratch so there are lots of change there. One of most exciting changes in ASP.NET 5(vNext) is moving all changes in Project.json file instead of solution. This Project.json file will have lots information related to dependencies, configuration and lots of other stuff.

Project.json file in ASP.NET 5(vNext)

Let’s create a ASP.NET 5(vNext) application from File –> New  Project

aspnet-5-starter-app

Once you create ASP.NET 5 application, It will create a sample project with Project.json like this.

Share:
Saturday, January 31, 2015

Install Go Language and Lite IDE on Ubuntu

Note: I’m not moving to Another world. Still C# and ASP.NET is my bread and butter.
Recently I have installed Ubuntu as Virtual OS in Oracle Virtual Box. This was one of first exposure I got Linux base operating system.  Earlier I have used Linux when I was doing my masters as part of their curriculum.  So far I am having fun Ubuntu and other Linux base operating system has come far.

After installing Linux, I thought why should I try some other language which is completely different then which I am working right now. This make me Polyglot  programmer and I could learn something from trying a new language and so I gone through various language and choose Go language.

Why Go Language?

Here are the reasons why I have choose to learn GO programming language.
  • It’s backed by Google so will not go away near future.
  • High performance :  Makers of Go language claims that it will perform as fast C and C++ language.
  • Fairly easy language to run.
  • Statically typed just like C#.
  • It has Garbase collection so I don’t have to worry about memory management like C and C++
  • Concurrency is in built
To know more about go language you can visit following site. It has got ton of resources.
http://golang.org/
Share:
Monday, January 26, 2015

Setting up development environment for ASP.NET 5(vNext) on Ubuntu

I am really enjoying working on Ubuntu. In previous post, We have learn how to install Sublime Text and in this blog post we are going to learn how we can setup development environment for ASP.NET 5(vNext). So what we are waiting for let’s go.

Note: First thing you need to make sure that Python 3.0 or higher version is installed. I have installed latest version of Ubuntu which already has Python preinstalled.

Setting up package manager control:

The first thing you need to is to install/setup package manager control. To Install package control, We need to go from View- > Show console menu. It will load package control. You need to run following command from the console. It will install the package manager control.
import urllib.request,os,hashlib;
h = '2deb499853c4371624f5a07e27c334aa' + 'bf8c4e67d14fb0525ba4f89698a6d7e1';
pf = 'Package Control.sublime-package'; 
ipp = sublime.installed_packages_path();
urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) );
by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s),
please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)
You can also copy this command from the this url- https://packagecontrol.io/installation

Share:
Sunday, January 25, 2015

How to install Sublime Text 3 in Ubuntu

I am quite having fun with Ubuntu on Oracle virtual box.In last blog post, I have already shown you how you can run ASP.NET 5 (vNext) app in Ubuntu. Now we are going to setup development environment for ASP.NET 5(vNext) and my preferred choice of editor is sublime text. If you have not heard about Sublime Text you should visit following link.

http://www.sublimetext.com/3

As we all know Sublime Text is a popular editor and  now Sublime Text3 is available with beta version for both registered users and general public. The Webupd8 team created a Personal Package repository containing the installer for Ubuntu and Linux. So we can install it very easily on Ubuntu.

So first thing we need to do is add PPA repository to Ubuntu via running following command.
sudo add-apt-repository ppa:webupd8team/sublime-text-3
It will load PPA repository into Ubuntu like below.

ppa-webupdate8-team

Share:

ASP.NET 5(vNext) on Ubuntu 14.4(Linux)

As we all know Microsoft has recently launched ASP.NET 5 and Microsoft has made announcement that it will work on any version of Linux and OSx. So in this post we are going to learn how we can use ASP.NET 5 on Ubuntu.

Installing Ubuntu on Oracle Virtual Box:

As I don’t have spare computer where I can install Ubuntu so that I’m going to install it on Oracle Virtual Box. If you don’t know about Virtual Box then it it a powerful x86 and AMD/Intel 64  virtualization product for enterprise or home box. It is freely available as GNU Licence.

You can find more about  Oracle Virtual Box here- https://www.virtualbox.org/

There are few things you to consider before going this route.
  • You need to first make sure that your computer supports virtualization or not. There are some utilities available for that like Intel processor identification utility – You can download from the here- https://downloadcenter.intel.com/Detail_Desc.aspx?DwnldID=7838. It will tell you whether your processor supports Virtualization or not.
intel-processor-utility
  • After checking whether your processor supports virtualization, you need to enable virtualization from Bios. That is different as per your Processor and you can learn how you can enable virtualization on your pc via searching on internet.
  • Make sure you have at least 4 GB ram to run this virtual OS smoothly. If you less RAM then it will work but thing will be slow.
Share:
Saturday, January 24, 2015

Recent updates to C# 6.0 syntax with new version of Visual Studio 2015 CTP

This blog post is part of C# 6.0 Features Series.
Recently, Microsoft has announced new version of Visual Studio 2015 and I have downloaded it. At the same time I was checking what’s new in Visual Studio 2015 CTP newer version and and I have found that suddenly my c# 6.0 new features solutions  stopped working.

The first problem it got is with static class using features. Following was my code.
using System.Console;

namespace StaticClassUsing
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("With using statement");
        }
    }
}

Now when you run this it was giving error like following.

Share:
Tuesday, January 13, 2015

Intellisense for Bower and NPM in Visual Studio 2015


Microsoft has recently launched the Visual Studio 2015 Preview with ASP.NET 5(vNext) and it’s got ton of features. In this blog post we are going to learn about Intellisense feature for Bower and NPM.

What is Bower and NPM:

 

Bower: Bower is a package manager for JavaScript libraries that allow you to define, version and retrieve your dependencies. It works on top of NPM. You can find more about that at following link.

http://bower.io/
https://egghead.io/lessons/bower-introduction-and-setup

NPM: NPM stands for Node Package Manager- It’s a kind of package manager for the installing node.js packages just like NuGet packages.  You can find more information about following location.

https://docs.nodejitsu.com/articles/getting-started/npm/what-is-npm
http://en.wikipedia.org/wiki/Npm_(software)

Share:
Sunday, January 11, 2015

Dependency Injection Series–DotNetJalps

I have written couple of blog post about dependency injection. So I thought it will be a good idea to write a summary blog post where it contains all the post about dependency injection.

Implementing dependency injection pattern in .NET
StructureMap–Getting Started
Dependency Injection with Simple Injector
Dependency Injection with ASP.NET MVC and Simple Injector

Hope you like it. Stay tuned for more.
Share:
Thursday, January 8, 2015

C# 6.0–Dictionary Initializers

This blog post is part of C# 6.0 Features Series.
As we know c# 6.0 provides some cool new features and syntax sugar. Dictionary Initializers is one of them.  Till C# 5.0 we used to have collection initializers for collections but now C# 6.0 provides new way of initializing dictionary . This initialization features is available for there collections which supports index.

Following is a code for new way of initializing dictionary.
using System;
using System.Collections.Generic;

namespace DictionaryInitializer
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> Person = new Dictionary<int, string>()
            {
                [1] = "Jalpesh Vadgama",
                [2] = "Vishal Vadgama"
            };
            foreach (var person in Person)
            {
                Console.WriteLine("Key:{person.Key}, Value={person.Value} ");
            }
        }
    }
}

Share:
Wednesday, January 7, 2015

Continuous Integration Series–DotNetJalps

I have written couple of point related to Continuous Integration and this post will server as a list of posts related to continuous integration.

Why continuous integration is your friend?
Continuous integration with visualstudio.com and TFS
Continuous Integration with visualstudio.com,Unit Test(Test Driven Development) and TFS

Hope you like it. Stay tuned for lots more about Continuous Integration and Continuous Deployment related post.
Share:

C# 6.0–Expression Bodied Members

This blog post is part of C# 6.0 Features Series.
There are lots of great features added to C# 6.0 and Expression bodied members are one of them. It’s provide great syntax sugar which will help you make your code more beautiful and readable.  In earlier versions of C# type definitions were always been tedious and we need to provide a curly braces and return type even if that function contains one single line. Expression bodied function will help you in such scenarios.

Let’s take a example to understand it. Following is a code to understand it.
using System;

namespace ExpressionBodiedMemebers
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person
            {
                FirstName = "Jalpesh",
                LastName = "Vadgama"
            };
            Console.WriteLine(person.GetFullName());
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetFullName()
        {
            return string.Format("{FirstName} {LastName}");
        }
    }
}

Share:
Sunday, January 4, 2015

Understanding KRE,KVM,KLR and KPM in ASP.NET 5(vNext)

ASP.NET 5(vNext) is a new upcoming version of ASP.NET that Microsoft has redesigned from the scratch. Recently Microsoft has released Visual Studio 2015 Preview and with that they have released ASP.NET VNext.  In ASP.NET 5 (vNext) it comes with new runtime environment called KRE(K Runtime Environment) . With this version you can also run your application through command prompt using various commands. In this blog post we are going to learn about all terms related K Runtime Environment.

KVM(K Version Manager):

K version manager is one of the first thing you need to run command . KVM is responsible for installing and updating different version of KRE. It’s a PowerShell script used to get and manage multiple version of KRE being it on same time on same machine. So one application can now have one version of KRE and another application can have another version of KRE on same time. You can find more information at https://github.com/aspnet/Home/wiki/version-manager
Share:

Assembly Neutral Interface in ASP.NET 5(vNext)


Recently Microsoft has open sourced it’s entire ASP.NET next version stack on GitHub and I have been closely watching this for a quite a some time to understand how they have created architecture of it and how they organize everything in such a large stack.

I have seen  [AssemblyNeutral] attribute in few of interfaces and I was curious why it was required. So I dig into it and learned about it.

Why we need Assembly Neutral Interfaces?

In earlier version of ASP.NET and Microsoft.NET Interfaces are bind to a assembly where it is declared. Let’s say I have written a interface under DotNetJalps namespace for my framework.
namespace DotNetJalps
{
    public interface ILogger
    {
        DoAmazingStuff();
    }
}
Now after some time this framework is super popular and everybody loves abstraction I have created and now they wants same abstraction so there are two ways we can do this.

  1. Convenience me to write this abstraction.
  2. Write implementation themself and maintain that.
Share:

C# 6.0–New feature series

This post will be aggregator post for all C# 6.0 feature series. Here you can find all of my blog posts about what’s new in C# 6.0.

Till now, I have written following blog posts.

C# 6.0–nameof Operator
C# 6.0–Auto implemented property initializer
C# 6.0–Static class using statement
C# 6.0–String Interpolation
C# 6.0- Null Conditional Operator
C# 6.0–Exception Filters
C# 6.0–String Interpolation
C# 6.0–Expression Bodied Members
C# 6.0–Dictionary Initializers
Recent updates to C# 6.0 syntax with new version of Visual Studio 2015 CTP

Hope you like it. Stay tuned for lot more about new Microsoft.NET technologies!!
Share:
Saturday, January 3, 2015

C# 6.0–String Interpolation

This blog post is part of C# 6.0 Features Series.
As we all know, C# 6.0 provides lots of small enhancements to the language and string interpolation is one of them. In this blog post we are going to learn how this small new feature can help us for string concatenation.

So let’s take small example, Where I have created a new example of string concatenation. Following is a code for that.
using System;
namespace StringInterpolation
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Jalpesh Vadgama";

            //Old way of string concentaionation 
            Console.WriteLine("My name is" + name);
            Console.WriteLine("My name is {0}", name);

            //New way of doing this
            Console.WriteLine("My name is {name}");
        }
    }
}
Share:
Friday, January 2, 2015

Happy New year 2015

New year passed so fast and that I have not feel as its a big time. On this occasion I would like to thank you all my readers for reading my blog and encourage me via putting lots of comments. I promise I will keep writing this blog whenever I get a chance.

Wishing every one a happy new year!!
Share:
Thursday, January 1, 2015

C# 6.0–Exception Filters

This blog post is part of C# 6.0 Features Series.
C# 6.0 contains lots of small features and one of them is Exception filters. It is already there with VB.NET earlier but now it is available in C# also. In exception filters now if exception is combined with Exception statement and If condition of if satisfy then it will execute that block.

Let’s take a simple example to understand it better. Following is a code for a simple console application. Before exception filters we were able to write a code like following.
using System;

namespace ExceptionFilters
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("Jalpesh");
            }

            catch (Exception ex)
            {
                if(ex.Message =="Jalpesh")
                    Console.WriteLine("Exception with Message Jalpesh is executed");
                else
                    Console.WriteLine("Exception with Message DotNetJalps executed");
            }
        }
    }
}
In above example, I have thrown a exception in try block and in catch block I have written if-else block to check message and based on that it will print some method.

Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews