пятница, 11 мая 2012 г.

What is ASP.NET MVC TempData


Simply said, ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

By default, the TempData saves its content to the session state.

ASP.NET MVC TempData vs Sessions

This is a very common question asked – When do I use TempData Vs Session in my ASP.NET MVC app?

The answer lies in your usage. TempData is available only for a user’s session, so it persists only till we have read it and gets cleared at the end of an HTTP Request. A scenario that fits the usage of TempData, is when data needs to persist between two requests – a redirect scenario. Another scenario I can think of is to return an error message after a POST operation fails.

Show me an Example

Let’s see a scenario where TempData fits well. We are assuming that we are in a page that saves Customer data

[HttpPost]
  public ActionResult DoSomething(Customer c) {

   // write your logic here to save Customer Data

   TempData["custdetails"] = 
    string.Format("Customer Address{0}", c.Address);

 return RedirectToAction("Index");

}

Here’s some razor code in your template, that be used in any view (in our case Index)

@if (TempData["custdetails"] != null) { @TempData["custdetails"]
}

Why did we use TempData above?

When an action returns a RedirectToAction result, a HTTP redirect occurs. ViewBag cannot be used in this scenario since it is a redirect and it won’t be able to hold data beyond the current HTTP Request. Similarly with Sessions, we would have to do some maintenance work to remove it and it’s kind of an overkill just to be used to pass data. TempData fits best in this scenario as data can be preserved in the TempData property (dictionary) of the controller for the duration of that single HTTP redirect request. Once the Data is read in the view to which the user has been redirected, it gets deleted.

четверг, 3 мая 2012 г.

An Introduction to New Features in C# 5.0


Introduction of New Features in C# 5.0

1. C# Evolution Matrix
Microsoft just published a new version of C# : 5.0 beta with CLR version 4.5 (Visual Studio 11 beta).
In order to get a big picture of the whole evolution of C# language, I summarized all the key features
into a C# Evolution Matrix for your reference as below diagram shows:


In C# version 5.0, there are two key features: Async Programming and Caller Information.
2. Async Feature
Two new key words are used for Async feature: async modifier and await operator. Method marked
with async modifier is called async method. This new feature will help us a lot in async programming.
For example, in the programming of Winform, the UI thread will be blocked while we use
HttpWebRequest synchronously request any resource in the Internet. From the perspective of user
experience, we cannot interact with the form before the request is done.
private void
btnTest_Click(object sender, EventArgs e)

{

var request = WebRequest.Create(txtUrl.Text.Trim());

var content=new MemoryStream();

using (var response = request.GetResponse())

{

using (var responseStream = response.GetResponseStream())

{

responseStream.CopyTo(content);

}

}

txtResult.Text = content.Length.ToString();

}


In the above example, after we clicked the Test button, we cannot not make any change to the form
before the txtResult textbox shows the result.
In the past, we can also use BeginGetResponse method to send async request as this sample in MSDN
shows:
http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.begingetresponse(v=vs.80).aspx. But it
will takes us a lot effort to realize it.
Now, we can simply use below code to do request asynchronously :
private async void
btnTest_Click(object sender, EventArgs e)

{

var request = WebRequest.Create(txtUrl.Text.Trim());

var content = new MemoryStream();

Task responseTask = request.GetResponseAsync();

using (var response = await responseTask)

{
using (var
responseStream = response.GetResponseStream())

{

Task copyTask = responseStream.CopyToAsync(content);

//await operator to supends the excution of the method until the task is completed. In the meantime,
the control is returned the UI thread.

await copyTask;

}

}

txtResult.Text = content.Length.ToString();

}
The await operator is applied to the returned task. The await operator suspends execution of the
method until the task is completed. Meanwhile, control is returned to the caller of the suspended
method.
3. Caller Information
Caller Information can help us in tracing, debugging and creating diagnose tools. It will help us
to avoid duplicate codes which are generally invoked in many methods for same purpose, such
as logging and tracing.
We could get the below information of caller method :
Below example are a common practice prior to the new feature of Caller Information:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;
namespace
ConsoleApplicationTest

{

class Program

{

static void Main(string[] args)

{

InsertLog("Main");

MethodB();

Console.ReadLine();

}
static void MethodA()


{

InsertLog("MethodA");

MethodB();

}
static void MethodB()


{ }
static void
InsertLog(string methodName)

{

Console.WriteLine("{0} called method B at {1}", methodName,
DateTime.Now);

}

}

}
In both Main and MethodA methods, method InsertLog is invoked for logging. Now we can change the
codes to be as per below lines:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.CompilerServices;

using System.Text;

using System.Threading.Tasks;
namespace
ConsoleApplicationTest

{

class Program

{

static void Main(string[] args)

{

//InsertLog("Main");

MethodB();

Console.ReadLine();

}
static void MethodA()


{

//InsertLog("MethodA");

MethodB();

}
static void MethodB(

[CallerMemberName] string memberName = "",

[CallerFilePath] string sourceFilePath = "",

[CallerLineNumber] int sourceLineNumber = 0)

{

InsertLog(memberName);

}
static void
InsertLog(string methodName)

{

Console.WriteLine("{0} called method B at {1}", methodName,
DateTime.Now);

}

}

}
4. Summary
The new features in C# 5.0 will help us to code more easily and improve the productivity. Have a nice
experience with the new release of Visual Studio 11!