Tuesday, September 25, 2012

How to use Asp.Net MVC TempData Properly ?

What is TempData ?

1. TempData is meant to be a very short-lived instance, and you should only use it
    during the current and the subsequent requests only.

2. Since TempData works this way, you need to know for sure what the next request will be, and
    redirecting to another view is the only time you can guarantee this.

3. Therefore, the only scenario where using TempData will reliably work is when
    you are redirecting.This is because a redirect kills the current request , then creates a
    new request on the server to serve the redirected view.

4. Simply said, Asp.Net MVC TempData dictionary is used to share data between
    controller actions.

5. The value of TempData persists until it is read or until the current user’s session times out.

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

7. TempData values are marked for deletion when you read them. At the end of the request,
    any marked values are deleted.

8. The benefit is that if you have a chain of multiple redirections it won’t cause TempData to
     be emptied the values will still be there until you actually use them, then they clear up after
     themselves automatically.

How to use TempData ?

Best Way
There are 2 ways which we can use TempData.

Method 1 :

   We can use it Inside the Redirect Action method like below.

Model

MVC
public class CreditCardInfo
{
    public string CardNumber { get; set; }
    public string Span { get; set; }
    public int ExpiryMonth { get; set; }
 }


Action Methods

    TempData Declared Action Method

        [HttpPost]
        public ActionResult CreateOwnerCreditCardPayments(CreditCard cc, FormCollection frm)
        {
           var providerKey = frm["providerKey"];
           var creditCardInfo = new CreditCardInfo();
            creditCardInfo.CardNumber = cc.Number;
            creditCardInfo.ExpiryMonth = cc.ExpMonth;
            creditCardInfo.Span = cc.Span;

            //persist data for next request
            TempData["CreditCardInfo"] = creditCardInfo;

            return RedirectToAction("CreditCardPayment", new { providerKey = providerKey});
        }

       TempData Used Action Method

        [HttpGet]
        public ActionResult CreditCardPayment(string providerKey)
        {
            if (TempData["CreditCardInfo"] != null)
            {
               var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo;
         
            var payPros =(PayPros)PaymentGateway.GetPayment(Enums.PayPros);
            var creditCardResponse = payPros.Ecommerce(creditCardInfo);
            return View();
           }
          else
           {
                return View("error");
           }
        }

Method 2 :

   You can use TempData Inside a Redirected Action Method's View.
    In our example it is :

    CreditCardPayment.cshtml  - View.

@{
      if (TempData["CreditCardInfo"] != null)
         {
           var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo;
          }
    }

Good Practice :  Always do null check and do necessary action if TempData is null 
                           (either get data again or exit gracefully).

Bad Way of using TempData

  When using with ViewResult Action method.

     [HttpPost]
    public ActionResult CreateOwnerCreditCardPayments(CreditCard cc, FormCollection frm)
        {
           var providerKey = frm["providerKey"];
           var creditCardInfo = new CreditCardInfo();
            creditCardInfo.CardNumber = cc.Number;
            creditCardInfo.ExpiryMonth = cc.ExpMonth;
            creditCardInfo.Span = cc.Span;

            //persist data
            TempData["CreditCardInfo"] = creditCardInfo;

            return View();
        }

View 
  Related View :

CreateOwnerCreditCardPayments.cshtml - View

@{
      if (TempData["CreditCardInfo"] != null)
         {
           var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo;
          }
    }

Why this Method is Bad ?

If your controller action returns a ViewResult, and you are tempted to put data into TempData,
Don’t do That.Use ViewData/ViewBag, instead, in this case.
TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only. Since TempData works this way, you need to know for sure what the next request will be, and Redirecting to another View is the only time you can guarantee this.Therefore, the only scenario where using TempData will Reliably work is when you are Redirecting.So Keep in Mind.

Other Usage of TempData

Usage 1 : If you want to keep TempData values even after reading them call Keep().Then those
                 values will keep for next request also.

                TempData.Keep("CreditCardInfo");

Usage 2 : If you want to remove TempData values then call Remove().Then those values
                will remove from current and next request.

               TempData.Remove("CreditCardInfo");

Conclusion

 TempData, is geared specifically for working with data on HTTP redirects, so remember to be
 cautious when using TempData. Always do null check before use TempData.
 If you set the Session State Mode to Out of Process , then the data (model) you put in it must be
 Serializable. (Use   [Serializable] attribute)

       What is the meaning of 'Session State Mode to Out of Process' ?
       Such as State Server mode, which stores session state in a separate process called the
       ASP.NET state service. This ensures that session state is preserved if the Web
       application is restarted and also  makes session state available to multiple Web servers in a
       Web farm or Windows Azure (Cloud) environment.


I hope this helps to You.Comments and feedback greatly appreciated.


Happy Coding.

May Be Use Full To You :
How to Use Git with Visual Studio 2010 ? - PART 1
How to Improve Performance of Entity Framework Query (over 400 times)?
How to Convert Linq Entity Query into T-SQL ?
How to Disable a Button Using Jquery and CSS ?
How to Enable jQuery Intellisense in VS 2010 ?

Sunday, September 16, 2012

How to Use Git with Visual Studio 2010 ?

What is GIT ?
  • In software development, Git is a distributed revision control and source code management (SCM) system with an emphasis on speed
  • Every Git working directory is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on network access or a central server.
  • Git is free software


GIT


For work with Git and VS 2010 You have to Down load and Install below mentioned Software.
(just click below mentioned hyper links)

1. Git Extensions

2.  Git Source Control Provider
   
    Note: for install Git Source Control Provider use below mentioned Steps :
              * Run Visual Studio.
              * Go to Tools | Extension Manager, Search Online Gallery for Git Source Control
                 Provider and  Install. (If you do above stepsthen you don't need to do any extra
                 configurations for this tool)

How to use GIT with VS 2010 ?

Step 1 :  Create a GIT Repository
   
              Select your Project by right click and then click "Create GIT Repository"

Create a GIT Repository

           

   

 













Then You can see Yellow Plus Symbols to denote that there are New Files.

Yellow Plus Symbols


Step 2 : Since I’m working on a New Project, I’ll Commit the New Files by using the 
             "Git Pending Changes" option as below. (right click your project)

Git Pending Changes

Step 3 : Then you can select files which you want to Commit and give a meaningful Comment and 
             Press  Commit Button as below.

 Press  Commit Button

After that it Shows Added State as below.

Added State

Step 4 : When you set below mentioned Setup (TorticeGit Style) then generated Markers are very 
             easy to understand the status of files. 

Using VS 2010 : Tools --> Options --> Git Source Control Provider Options 

Git Source Control Provider Options
Colors Indicators :

Green   - Up to date
Yellow  - New File
Red      - Modified (not commit) 
Colors Indicators


Step 5 :  How to Modify a file and then Commit to Local Master ?

              Do modification to your file and then right click your project and click
              'Git Pending Changes'. It will show below screen.
              Right side of the below screen shows the changes done for the file.Its very useful 
              for double check the changes before Commit. 

Commit to Local Master

Step 6 :  After Defining a Main Repository here  then Push your work for that Remote Repository 
              by clicking "Git Bash" short cut as below. 

Git Bash

Then you need to Type $ git push Your projects Remote Repository URL like below.
Then Username and Password for Remote Git Repository.

Remote Git Repository

That is it.Now your codes are in Remote Git Repository.How easy it is. 

Other Important Git Functionalities

You can do all other Version Control related tasks such as pull,push,revert,commit,merge,stash etc. by using either Git Extensions or Tortoise Tool as below.

Select your project and then right click will popup below screen.

Important Git Functionalities
Important Note:

With Git Extention's  'Push' option is Not Working so far.So if you need to Push your code then You have to use either Git Bash (Command line utility which I showed early) or Tortoise Utilities.


Conclusion
  • By using above steps you can easily use Git with VS 2010
  • My Next Post about Git will explain how to Resolve Conflicts with Remote Repository by using inbuilt Tools in Git.


Happy Coding.

May Be Use Full To You :

Saturday, September 8, 2012

How to Enable jQuery Intellisense in Visual Studio 2010 ?

How to Do That ?

There are 2 ways to do that.

Method 1 :

When you are working with Local copy of js files,Then you have to set up jquery-1.5.1-vsdoc.js file as below.(This is my js file version.It supports These versions )

Local copy of js files

Then on Master Page Set Script Tags like below.
<head>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>

After that on Child Pages you can have Jquery Intellisense on each level of your code as below.

Jquery Intellisense


Method 2 :

If you are referring js files from CDN (Content Delivery Network) then add vsdoc.js file into your Scripts folder  like below.

CDN (Content Delivery Network)

Your Master Page should looks like below.
                                      with  Microsoft CDN 
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript">
</script>
</head>
                                       with Google CDN

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
</script>
</head>


Note : If you set up vsdoc.js file as above then it works with both CDN.

Conclusion

By using above methods you can use jQuery Intellisense with VS 2010.One Very Important thing you have to remember here is both your .min.js file and .vsdoc.js files Versions Must be the Same.Otherwise some wrong Intellisense information may appear for Jquery functions.

Happy Coding.

May Be Use Full To You :
How to Disable a Button Using Jquery and CSS ?
How to Convert Linq Entity Query into T-SQL ?
How to Improve Performance of Entity Framework Query (over 400 times)?