Book: Visual Studio 2013 and .Net 4.5 Expert Cookbook

Let’s start with a very short story. Oh ! It’s about you. You bought a latest mobile phone from the market that you haven’t used earlier. Excited to use it. Did some phone calls and text messages. What’s so exciting about it? After all, every mobile phone is supposed to provide those basic functionality. What else? How to learn other features? Yes, you need a guide or references or help manual.

Earlier this month, I got installed Visual Studio 2013 in my laptop and found this particular book to be my true guide in application development and learning new features introduced with Visual Studio 2013 & .Net framework 4.5. It has uncovered many exciting and time saving new features of VS 2013.

News: You can download Visual Studio 2013 Community Edition for free [from here]

The book is authored by Abhishek Sur, a Microsoft MVP since last 4 years who is also a renowned public speaker and also the author of book Visual Studio 2012 and .NET 4.5 expert Development Cookbook. You can purchase the book from Packtpub or . You can even view few pages for free [here] .

If you want to be more productive and upgraded to the changes in .Net 4.5 & VS 2013 then this is just that perfect book you are looking for.


With the first chapter the book teaches, how to debug better with your new IDE. You’ll find a great in-depth analysis of each features. Debugging is a very essential part of Application Development and one can definitely use these tips to sharpen their debugging skill.
For Example, I was unknown about
“The debugger stores the information of the line number and source code file inside the DB file (known as the program database)

Second chapter is about the Enhancements to WCF. It also teaches to write RESTful services with WCF with few simple and excellent examples. There is a separate chapter on developing Windows Phone 8 apps . Again there is also a separate chapter on “Extending the Visual Studio IDE” which teaches procedure to extend the IDE by applying your changes. From other chapters, you can learn about TFS enhancements, Testing using VS2013, Windows Azure with in-depth analysis and suitable examples.

It was a very good learning experience for me and if you are a passionate .Net developer who loves to learn more then my recommendation is to get it quickly.

Thanks !

Book: Visual Studio 2012 and .NET 4.5 Expert Development Cookbook

Book Title
: Visual Studio 2012 and .Net 4.5 Expert Development Cookbook
Author: Abhishek Sur (
About Author: Abhishek Sur is a Microsoft MVP in Client App Dev since 2011. He is an architect in the .NET platform.  He is also a renowned public speaker and owns one of the most active  Microsoft user group named Kolkata Geeks.  His website guides both budding and experienced developers to understand the details of languages and latest technology. You may also follow him at Facebook or Twitter .

The very first thing I like about this book is its conciseness. Even though it is a 380 pages book you will find every aspect of the enhancement & new features introduced with Visual Studio 2012 and .Net 4.5 has been  explained extensively with proper examples. Starting with the Visual Studio IDE features, author marches us through the enhancement to ASP.Net, WPF etc. It has a dedicated chapter on memory management too.

I always go for the shortcuts while developing applications and also love to use features provided by my IDE for faster development. This book is a good educator of  IDE features and shortcuts introduced in Visual Studio 2012 which will help you in saving development time.
The key component of the book is, everything comes with a proper example. With this book, one can also learn –

  • In-depth memory management helps to to grasp under the hood happenings.
  • Asynchronous programming has become very important in the last few years and the book explains all about the necessity and usage of Asynchronous Programming in .Net
  • Enhancement to ASP.Net includes support for HTML5, Web Socket, JQuery and been explained beautifully.
  • Enhancement to WPF
  • Building Windows 8 style applications and communication & sharing between apps and devices.

In case you want to check it out before buy, you can download Chapter-1: Introduction to Visual Studio IDE features for free.

You can buy it from or

Honestly speaking, I have been immensely benefited from C# internal series by the author on his blog DOT NET TRICKS and this book further helped me to discover the roots.
It is not conclusive by any means and there is a much more to grab. At last, if you are a .Net developer and a technology loving person then you’ll definitely love to add this book to your bookshelf.

ASP.Net: Disable TabIndex Focusing

If you need to disable/restrict focusing on one or more controls in a page then just mention TabIndex=”-1″.

This is useful particularly when you have some read only controls in your WebForm and you don’t want the control to move(focus) to those controls.

This is known to most of the web-developers but hopefully it will be useful to others.

ASP.Net: Download files from server with their original name

Introduction :

Purpose of writing this post is to share a way to resolve a very common but important issue with uploading-downloading file in ASP.Net. I don’t claim it to be the most efficient way but it works for me.


While uploading a file to the server we may save it with its original file name and may code like-

FileUploader1.SaveAs(Server.MapPath("UploadedFiles/" + FileUploader1.FileName));

But, problem is if we upload another file with same name as previous file then the previous one will be replaced with the latest one. Now all the links for downloading both theses files will reference to the same file on the server.
Again we may resolve this issue by saving files with unique name on the server and may code like-

FileUploader1.SaveAs(Server.MapPath("UploadedFiles/" + DateTime.Now.ToString("yyyyMMddhhmmssfffffff") + System.IO.Path.GetExtension(FileUploader1.FileName);));

By doing this we will lose the original file name forever. But, in some or, more scenarios user may expect the file to be downloaded to his/her hard-disk with the original file name with which he/she uploaded the file to the server. (Example: Uploading-Downloading multiple resumes of a candidate).

We can solve this issue by storing both the names of a file i,e original & unique name on server.

The actual headache now comes in to picture. File is saved on the server with some unique name but we want the to change it’s name to the original name while user downloading it to his/her hard-disk.


[View Demo]

The above said problem can be solved by following few steps. For the illustration I am taking a Gridview to show files for downloading and LinkButton for the download links.

  • Store both actual and unique names of the file in Database
  • Use a Hidden Field to store actual(unique) file name in the gridview
    <asp:TemplateField HeaderText="Uploaded File">
     <asp:LinkButton ID="lnkDownload" Text='<%#Eval("FileNameOriginal")%>' runat="server" OnClick="lnkDownload_Click" />
     <asp:HiddenField ID="hfDownload" runat="server" Value='<%#Eval("FileNameActual")%>' />
  • Now, put following code in the link button click event
    LinkButton lnkDwnload = (LinkButton)sender;
     GridViewRow grow = (GridViewRow)lnkDwnload.Parent.Parent;
     HiddenField hfDownload = (HiddenField)grow.FindControl("hfDownload");
     Response.AddHeader("Content-Disposition", "attachment;filename=" + lnkDwnload.Text);
     Response.ContentType = GetContentType(Server.MapPath("~/UploadedFiles/" + hfDownload.Value.ToString()));
     Response.TransmitFile(Server.MapPath("~/UploadedFiles/" + hfDownload.Value.ToString()));

Note that I have used a method GetContentType() to get the content type/MIME type of the file to be downloaded.

private string GetContentType(string fileName)
 string contentType = "application/octetstream";
 string ext = System.IO.Path.GetExtension(fileName).ToLower();
 Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
 if (registryKey != null && registryKey.GetValue("Content Type") != null)
 contentType = registryKey.GetValue("Content Type").ToString();
 return contentType;

Note : Microsoft.Win32 is OS specific MSDN

For a universal solution we may use another way of getting the MIME type.

private string GetContentType(string fileName)
 string ext = System.IO.Path.GetExtension(fileName).ToLower();
 switch (fileName)

//add as many extensions of file types you expect to be uploaded

//for a complete list you may visit

case ".doc": return "application/msword";

case ".docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

case ".jpeg": return "image/jpeg";

case ".jpg": return "image/jpeg";

case ".bmp": return "image/bmp";

default: return "application/octet-stream";



This works very fine for me. If you are facing problem then drop a comment, it will be my pleasure to help you. Any better idea is welcome.

Thanks for reading !

C Sharp: Find greater of two numbers





int num1 =double.Parse(Console.ReadLine());
int num2 = double.Parse(Console.ReadLine());

Supplied numbers are not equal.

Way 1:(Using Relational operator)

if (num1 > num2)
    Console.WriteLine("Max is:{0}", num1);
    Console.WriteLine("Max is:{0}", num2);

Way 2:(Using Conditional operator)

Console.WriteLine("Max is:{0}", num1>num2?num1:num2);

Way 3:(Using Math.Max())

Console.WriteLine("Max is:{0}", Math.Max(num1,num2));

Way 4:(Using Math.Abs())

Console.WriteLine("Max is:{0}", ((num1+num2)+Math.Abs(num1-num2))/2);

Among these ways I don’t think the first three solutions need any explaination. But what we will anayse here is the Way 4. The half of the summation of sum of two numbers and their absolute difference results the greater of the two. Similarly we can get the lower among them as the half of the substraction between the sum of the two numbers and their absolute difference.

Console.WriteLine("Min is:{0}", ((num1+num2)-Math.Abs(num1-num2))/2);

ASP.NET: Reference type as parameter to a method

Introduction :

This post is about passing reference type (like array) to a method. Whatever I have written below is purely based on my experiments and the knowledge I gained from MSDN etc. So, if somebody reading this post has a better idea then please comment.  Before I write something, let quickly look at the following 3 snippets of code. For a quick demo I have used Console Application but, the concept below holds good for either ASP.Net or Windows Application or any other. As C# is the most advanced and mostly used programming language, I have decided to use it for my demonstration.

Have a look at the code :

Snippet 1 :

//Demonstration with Integer parameter
static void Main(string[] args)
  int num = 1000;
  Console.WriteLine("Initial Value in num: {0}", num);
  Console.WriteLine("Final Value in num: {0}", num);

static void PlusPlus(int numFormal)
  numFormal += 1;
  Console.WriteLine("Value in numFormal: {0}", numFormal);

Output Of Snippet 1 :

Initial Value in num: 1000


Value in numFormal: 1001


Final Value in num: 1000

Snippet 2 :

//Demonstration with Array(Int) parameter
static void Main(string[]  args)
  int[] arrNum = { 1000, 2000, 3000 };
  for(int i=0;i  {
    Console.WriteLine("Initial Value in arrNum["+i+"] : {0}", arrNum[i]);
  for (int i = 0; i < 3; i++)
    Console.WriteLine("Final Value in arrNum["+i+"] : {0}", arrNum[i]);

static void PlusPlus(int[] arrNumFormal)
  for (int i = 0; i < 3; i++)
    arrNumFormal[i] += 1;
    Console.WriteLine("Value in arrNumFormal["+i+"]: {0}", arrNumFormal[i]);

Output Of Snippet 2 :

Initial Value in arrNum[0]: 1000
Initial Value in arrNum[1]: 2000
Initial Value in arrNum[2]: 3000
Value in arrNumFormal[0]: 1001
Value in arrNumFormal[1]: 2001
Value in arrNumFormal[2]: 3001
Final Value in arrNum[0]: 1001
Final Value in arrNum[1]: 2001
Final Value in arrNum[2]: 3001

Snippet 3 :

//Demonstration with string parameter
static void Main(string[] args)
  string str = "original string";
  Console.WriteLine("Initial Value in str: {0}", str);
  Console.WriteLine("Final Value in str: {0}", str);

static void ChangeString(string strFormal)
  strFormal = "changed string";
  Console.WriteLine("Value in strFormal: {0}", strFormal);

Output Of Snippet 3 :

Initial Value in str: original string
Value Of numFormal: changed string
Final Value Of num: original string

Analysis :

Analysis of Snippet 1 & its result :

In the Snippet no. 1, I have declared a local integer variable ‘num’ and assigned a value 1000 to it. Then after displaying(“Initial Value in num: 1000”) it on the screen I called a method PlusPlus(), which takes a single argument of type int. To this method I passed the variable ‘num’. The body of the static method PlusPlus() consists of only 2 lines of code. First line increments the formal parameter by 1 and then the second line of code prints(“Value in numFormal: 1001”) it on the screen.Then again I am printing(“Final Value in num: 1000”) the value hold by the variable ‘num’.
Thing to notice here is after passing the variable to the method PlusPlus() and there although I am incrementing it by 1, it did not change its original value. This is because when I am passing a int variable to a method, exactly I am passing the value hold by the variable as int is a value type and the method computes on the value passed to it, which is hold by the formal parameter not the actual parameter.

Analysis of Snippet 2 & its result :

I have repeated the same process as in the Snippet 1 except I have changed the local variable integer to a integer array. But, here the result is something different. The difference is- the changes I have done to the formal parameter in the method PlusPlus()  also reflects for the actual parameter or, the original integer array declared in the main() method. This is happened as array is a reference type so, when I am passing an array to a method, actually I am passing its reference and now the formal parameter holds the same reference as the actual parameter. So, when I am changing the value present in any of the indices of the array in the formal parameter it reflects in the actual parameter also.

Analysis of Snipet 2 & its result :

Once again I have repeated the same process as snippet 1 and 2 with the same little change in the datatype of the variable. Now, I want to see the result when I am using a string variable, which is of reference type. But the result is same as the snippet 1 where I had used integer variable.

Now, Question is- why this deviation ?

This is happened because, although string is a reference type but the class System.String or, its alias string is immutable. If you want to know more on immutable type you can search it in MSDN. I will discuss about mutable and immutable type in details in my next blog post but for now, you can consider the real meaning of the English word ‘immutable’ – ‘Not susceptible to change’. It means we can not change the value hold by a string variable. When we are changing the value hold by the string variable in the method ChangeString(), actually a new variable is created to store the new value. So, the changes did not reflect on the actual parameter or, the original variable.

Conclusion :

When we are passing an array as parameter we should understand that, the calling method can change its value.

Which is better – “” or string.Empty ?

Answer is string.Empty. Now you may ask, why?
OK. The answer to your WHY is – string is immutable i.e when we want to change a value, stored in a string variable, it creates a new copy in the memory and then the old memory space hold by that string variable is released by garbage collector.
Above process is followed when we do things like-
string str= “”;
But, in case of string str=string.Empty;
it doesn’t create a new copy.
So, avoid string assignment.

C Sharp: Under-utilized Padleft() method

What I am going to explain is not for a specific situation, we can use it in so many cases. I am talking about PadLeft() method of string class. To explain it, I am just showing you an example, which I found somebody doing while he is supposed to code for three dropdowns like Day,Month & Year. Following is the snippet of his code-

private void bindDay()
        ArrayList day = new ArrayList();
        for (var i = 1; i <= 31; i++)
            if (i > 0 && i < 10)
                var x = "0" + i;
        ddlDays.DataSource = day;        

Although this block of snippet may need improvements on some other line(s) of code but I am concentrating on the part inside the ‘for loop’. Yes, the if .. else .. block. Here, 5-7 lines of the code is intended to add days of date and with 2-digit format like 01,02,03..etc. I admit that there are so many ways to accomplish it, but I am just talking about the logic. In this code, it has a loop variable which checks the value to find if it is of single digit or two digits. Then if it is of 2-digits then no logic to go before adding it to the dropdownlist and if it is of 1-digit then it is to be padded with a ‘0’..This will work definitely fine for Day dropdown.

Now we can ask what happen when some body wants to form a dropdown with fixed no of 10 digits and a dumb answer will be -“Use 9-10 if..else conditions to do this”.

We can replace the whole if .. else .. by just using a simple method of System.String class – PadLeft(). Now after changing only the if else block with PadLeft(), the code will be like-

private void bindDay()
        ArrayList day = new ArrayList();
        for (var i = 1; i <= 31; i++)
        ddlDays.DataSource = day;        

Here , PadLeft() is taking 2 parameters- width of the resulted string and the character to be padded to the left when string is of length less than 2.
This can also be used to scenarios where you need to generate a code (like Employee Code,Book Code, etc) of a fixed length.