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 Amazon.in . 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
Book Title
: Visual Studio 2012 and .Net 4.5 Expert Development Cookbook
Author: Abhishek Sur (www.abhisheksur.com)
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 abhisheksur.com 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 packtpub.com or amazon.com

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.

Problem:

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.

Solution:

[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">
     <ItemTemplate>
     <asp:LinkButton ID="lnkDownload" Text='<%#Eval("FileNameOriginal")%>' runat="server" OnClick="lnkDownload_Click" />
     <asp:HiddenField ID="hfDownload" runat="server" Value='<%#Eval("FileNameActual")%>' />
     </ItemTemplate>
     </asp:TemplateField>
    
    
  • 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()));
     Response.End();
    
    

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 http://stackoverflow.com/questions/1029740/get-a-mime-from-an-extension

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";

}
}

Conclusion:

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


c-sharp

 

 


Assumption:

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);
else
    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);

Analysis:
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.
Ex:

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("______________________________");
  PlusPlus(num);
  Console.WriteLine("______________________________");
  Console.WriteLine("Final Value in num: {0}", num);
  Console.ReadLine();
}

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]);
  }
  Console.WriteLine("_________________________________________");
  PlusPlus(arrNum);
  Console.WriteLine("_________________________________________");
  for (int i = 0; i < 3; i++)
  {
    Console.WriteLine("Final Value in arrNum["+i+"] : {0}", arrNum[i]);
  }
  Console.ReadLine();
}

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("______________________________");
  ChangeString(str);
  Console.WriteLine("______________________________");
  Console.WriteLine("Final Value in str: {0}", str);
  Console.ReadLine();
}

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.