Tuesday, August 21, 2012

Efficient Paging with WebGrid Web Helper - ASP.NET MVC 3 RC

Efficient Paging with WebGrid Web Helper - ASP.NET MVC 3 RC

 

reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=618 

Abstract: The following article demonstrates one way of performing efficient paging using the WebGrid WebHelper in ASP.NET MVC 3 RC.
Last week I published an article on how to use the WebGrid WebHelper in ASP.NET MVC 3 RC. This was a beginners article on getting started. The one piece of functionality I didn’t touch on was paging. Out of the box, the WebGrid has a built-in Pager object, which handles the rendering of paging links underneath the WebGrid. The biggest downside of using this paging is smart paging isn’t enabled. What I mean by that is if you have a WebGrid fetches it data from 10,000 records from a database, but it only displays 10 records per page, each time you click on a paging link, you’re not retrieving 10 records you want to display, you’re fetching the 10,000 records each time and only displaying 10. This is terribly inefficient when you hit a large scale system. Well this article you’re reading right now will show you one possible way of creating efficient paging and still using the WebGrid.
Before moving on, you need to download ASP.NET MVC 3 RC. Click here to download and install them using the Microsoft Web Platform Installer.
The Microsoft Web Helpers are added as a reference by default now in ASP.NET MVC 3 RC. I’ve left the instructions on how to add them in this article in case you need to do this as a separate exercise.
Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. The new MVC 3 dialog can be seen below:
Empty Template Razor 
Choose Razor as the view engine and click OK.
The next step is to download the Microsoft Web Helpers library through NuGet. Follow these steps to do this:
Step 1. Right click the website and choose Add Package Reference.
Mvc Add Package Reference 
Step 2. The Add Package Reference dialog will open. Search for Microsoft in the search box in the top right corner. Upon completion you'll see microsoft-web-helpers option. Select that option and click Install.
Microsoft Web Helpers
Step 3. Click 'Close' to return to the project

Check the references and you'll see that the library has been added to the project.

System Web Helpers

Now it's time to start coding! For this example I’ve created a model called FavouriteGivenName. This will store 10 records. The model would normally be a database, but I’m using a smaller set of data to illustrate the paging examples.

Default Paging in MVC 3 WebGrid

By default, the WebGrid’s paging functionality will retrieve the entire set of data for each paging request. To see this in action, create a Home controller and add an index action.

Home Controller IndexAction

The code above is setting model for the view as a collection of FavouriteGivenName’s. Add the following code to the view:

MVC CollectionView

The output from the above code is shown below.

MVC Grid Pager

The grid.Pager method sets the paging for the WebGrid. The problem is when you page through the data, all the data is returned. If you try to limit the data being returned, the problem you’ll encounter because you’re only returning a subset of the data is the WebGrid thinks there’s only that amount of data to display, so the paging links will disappear! Not good! So to show you what this looks like, I’m going to only return the first 5 records for the WebGrid, because I only want to display 5 records per page. Here’s my updated action:

MVC ActionResult 
Now because I’m returning only 5 instead of 10 records, the paging has disappeared from the WebGrid!

MVC Grid NoPaging

Efficient Paging in MVC 3 WebGrid Web Helper

The solution I came up with is one possible solution. I’m sure there are many others, but this works well. The issue around the WebGrid’s paging is it needs the total count of data that the grid is supposed to display. If you limit the WebGrid to only the records you want displayed, you limit the total count and the paging doesn’t work. To fix this problem you need to separate the two. One set of data for the grid and a separate piece of data that tells the WebGrid how many paging links to display. Unfortunately the paging object is locked, so I had to make my own.

To incorporate the
DRY (Don’t Repeat Yourself) principal, I’m going to create an action method that returns the WebGrid as one object, and a total record count as another object and wrap both of them in a JSON object. Here’s the action method.

MVC Json Efficient Paging

The JSON being returned stores two object.  
  • Data – this stores the data only needed for the grid. It utilises the Skip and Take methods to limit the data being returned. It is returning the WebGrid as HTML. This ensures this code will replicate what the WebGrid would look like if we were declaring it in the Razor mark-up.
  • Count – this stores the total records. This will be used for creating the paging links.
The view for this is simple. All the hard work is in the JavaScript. Here’s the JavaScript below that calls the EfficientPaging action and displays the returned WebGrid and creates the paging links.

JavaScript Efficient Paging

The result of this is below.

MVC Grid Paging

It looks the same as the previous example, but now if you page through the data, the page you’re requesting will be sent as a parameter to the action method, and only that data will be fetched from the server.

MVC Json Debug

Now you have efficient paging and are still using the WebGrid WebHelper! The only difference is you’re creating your own paging links.

Like I mentioned earlier, this is only one possible solution, but for me this works well because I’m still creating only one WebGrid. If you think of other ways to do this, please let me know.

Wednesday, August 8, 2012

Asp.net 4.0 features

ASP.NET 4.0 Features

 ASP.NET v4 is released with Visual studio 2010. Web developers are presented with a bewildering range of new features and so vamshi has described what he considers to be the most important new features in ASP.NET V4
The focus of Microsoft’s latest ASP.NET 4has mainly been on improving the performance and Search-engine Optimization (SEO). In this article, I'll be taking a look at what I think are the most important new features in ASP.NET 4.
  • Output cache extensibility
  • Session state compression
  • View state mode for individual control
  • Page.MetaKeyword and Page.MetaDescription properties
  • Response.RedirectPermanent method
  • Routing in ASP.NET
  • Increase the URL character length
  • New syntax for Html Encode
  • Predictable Client IDs
  • Web.config file refactoring
  • Auto-Start ASP.NET applications
  • Improvements on Microsoft Ajax Library
I’ll describe the details of each of these features in the following sections.

Output Cache extensibility

Output caching, or Page-Level Caching, caches the entire rendered markup of an ASP.NET web page for a specific time-period. This has always been one of the essential features for ASP.NET that is used extensively to increase application performance. However there have been some limitations on the feasible extent of caching, because cached content always had to be stored in-memory.
But with ASP.NET 4.0 developers can extend their caching by using Output-cache providers. Developers can now create ‘output-cache providers’ that store the cache contents to any persistence mechanism such as databases, disks, cloud storage and distributed cache engines.
To create a custom output-cache provider, a class which derived from System.Web.Caching.OutputCacheProvider has to be created in ASP.NET 4.0. There are four public methods which you have to override in order to provide your own implementation for add, remove, retrieve and update functionality. Also, the output-cache provider has to be registered in the web.config file as shown in the following screen capture.
You can also set this custom output-cache provider as your default cache mechanism. So once you add the page cache directives all of your contents will be stored using the custom output-cache provider.
Moreover, developers can also dynamically configure which output-cache Provider is used. For example you might want to cache the frequently access pages in the memory for faster access and less frequent pages on disk. By overriding the GetOutputCacheProviderName() method you can configure which output cache provider to use for different requests. These additions to the output-cache can enable developers to write extensible and more efficient cache mechanisms to their web application and thereby improve its responsiveness.

Session State compression

The ASP.NET session state is a mechanism to maintain session-specific data through subsequent requests. In some instances, you may wish to store your session state data in a session-state server or in Microsoft SQL server. However, these two options require you to store data out of the web application’s worker process. To send across to the relevant sources, (State server or Microsoft SQL Server), session-state data has to be serialized. This can take a significant time if the size of the data to be serialized grows significantly. This will increase the latency of the application.
This latency can be reduced if the size of the data is lessened by compression. ASP.NET 4.0 introduces a new mechanism to compress your session state data for both Session-state server and Microsoft SQL server.  Compression can be enabled by setting the compressionEnable to true in the web.config file. In this example, the session-state data will be serialized/desterilized using System.IO.Compression.GZipStream.
<sessionState  mode="SqlServer"  sqlConnectionString="data source=DB;Initial Catalog=LudmalDB"  allowCustomSqlDatabase="true"  compressionEnabled="true"/>
With this compression feature, developers can often reduce the time it takes for a web application to respond by reducing the size of session data.

View State mode for Individual Controls

View state is a mechanism to maintain page controls’ state on subsequent post backs. ASP.NET stores the view state data for controls that are in the page, even if it’s not necessary. Since the view state data is stored in the pages’ html, the size of the request object will be increased, and make performance worse.
In ASP.NET 4.0, each web control will include a ViewStateMode property which lets developers disable view-state by default, and enable it just for the controls for which a persistence of state is required. ViewStateMode has the following three values;
  • Enabled – enables the view state for this control and any child control.
  • Disabled – disable the view state.
  • Inherits – this specify the control uses the settings from its parent control.
By setting these values in page controls accordingly, a significant performance improvement can be gained in response-time.

Page.MetaKeywords and Page.MetaDescription properties

To increase the relevance of pages in searches, developers should  include relevant “keyword” and “description” meta tags in the html <head> section.     Unfortunately, it takes some time to add these tags for each and every page, and the alternative of adding these tags programmatically was difficult.
But with ASP.NET 4.0, there are two new properties in the code behind file;
  • Page.MetaDescription – equivalent to meta name “description”
  • Page.MetaKeywords – equivalent to meta name “keywords”
This will enable developers to easily and programmatically add the relevant keywords and description.
This will even be useful for Master pages—where you only have to add these properties in the master page. In addition to “keywords” and “description” settings in the code behind, developers can also set these values within the @Page directive.

Response.RedirectPermanent Method

ASP.NET 4.0 has improved SEO (Search-engine Optimization) facilities. Typically developers use Response.Redirect(string url) to handle requests for old URLs. However, this leads to an extra round trip to access the old URLs and so will negatively affect your page-ranking  in search-engines.
ASP.NET 4.0 introduces a new Response.RedirectPermanent(string url) helper method to be used as HTTP 301 (Moved permanently) to handle requests. This will enable search-engines to index URLs and content efficiently and thus improve the page rankings. 

Routing in ASP.NET

Routing will let developers serve meaningful URLs to users and map them with the actual physical files. This URL-rewriting mechanism enables developers to write high ranking, search-engine optimized web applications. For example, URL for a page which displays an actual product might look like the following;
http://www.ludmal.net/showproducts.aspx?prodId=24
By using routing the URL will look like the following
http://www.ludmal.net/products/ipod
In this way, the URLs will be more easily remembered by users.  It will also significantly improve the search-engine page rankings of the web site.
The following example shows how to implement routing behavior in ASP.NET 4 using new MapPageRoute in Route class.
public class Global : System.Web.HttpApplication {   void Application_Start(object sender, EventArgs e)   {     RouteTable.Routes.MapPageRoute("ProductsRoute",       "product/{prodId}", "~/products.aspx");       } }

Increase the URL character length

In previous versions of ASP.NET,  URLs were limited to 260 characters in length. But in ASP.NET 4.0 developers have the option of increasing or decreasing  the length of URLs by using  the new maxRequestPathLength and maxQueryStringLength. I’ll illustrate this in an example.
<httpRuntime maxRequestPathLength="360" maxQueryStringLength="1024" />
In previous versions of ASP.NET you were limited to a fixed set of characters but in v4, developers can also validate the invalid characters by specifying values in the requestPathInvalidChars attribute.

New syntax for Html Encode

Html Encode method encodes a particular string to be displayed in a browser. It is important to encode strings prior it’s rendering in the page, mainly to avoid cross-site script injection (XSS) and HTML injection attacks. However, developers so often forget to call the encode function.
In previous .NET versions, Server.HtmlEncode() or HttpUtility.Encode() methods has been used for string encoding as shown in the following example.
ASP.NET 4.0 introduced new code expression syntax for encoding a particular string.  While the syntax will render the output it also encodes the relevant string as shown below. Note “:” character after opening tag (“<%”).
The new encoding syntax provides an easy and concise way of encoding a particular string.

Predictable Client IDs

ASP.NET 4 now supports a new ClientIDMode property for server control. This property indicates how the Client ID should be generated to a particular control when they render. Client ID has been an important property of the server controls recently—especially with the success of jQuery and other Ajax scripting technologies.  The ClientIDMode property has four values;
  • AutoID – This renders the output as it was before (example: ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1)
  • Predictable (Default)– Trims all “ctl00” strings in the Client Id property.
  • Static – Full control over the Client ID (developer can set the Client Id and it will not be changed after the control renders)
  • Inherit – Allow control to inherit the behavior from its parent control
Client ID property can be set in three different ways;
  • Directly on individual control
  • On the container control. (All the child controls will inherit the settings from parent/container control)
  • Page or User Control level using <%@ Page%>  or <%@ Control %> directives.
  • Directly in the web.config file. All the controls within the web application will inherit the settings.
New ClientIDRowSuffix property on databound controls also gives a similar functionality when rendering an each data item. Once you set the relevant databound property to ClientIDRowSuffix, the value will be added as a suffix to individual row elements.
After the control renders the “State” value will be added as a suffix to each data row element.

Web.config refactoring

Over the past few years web.config file has grown significantly as ASP.NET has used it for more and more features such as routing, Ajax, IIS 7 and version compatibility. This has made it trickier to maintain even with the Visual Studio environment.
With ASP.NET 4, most of the major elements have been moved to the machine.config file. This has enabled developers to maintain a cleaner, less cluttered, web.config file. The new web.config file is either empty, or includes just the .NET framework version details as shown in the following example.
<?xml version="1.0"?>  <configuration>   <system.web>    <compilation targetFramework="4.0" />    </system.web>  </configuration>

Auto-Start ASP.NET Applications

Most application requires initial data load or caching operations to be done before serving the client requests. Typical this happens only when the first user request a page. However, often developers and web administrators write fake requests to keep the application alive to increase the response time. To overcome this issue, ASP.NET 4 introduce new Auto-Start feature. Auto-start feature available with IIS 7.5 and it initialize the ASP.NET application to accept requests.
To configure the Auto-start, you need to configure the “Application pool” worker process by setting the startMode attribute to “AlwaysRunning” in the applicationHost.config file. (C:\Windows\System32\inetsrv\config\applicationHost.config)
As soon you save the applicationHost.config file the worker process will start and initialize the required application operations before the first user has been served.

Improvements on Microsoft Ajax Library

Microsoft Ajax library is client side library which includes high performance server –based user controls and asynchronous page rendering controls. Ajax Library enables developers to easily and quickly write responsive database-driven applications.
There are some significant improvements in the Ajax Library in the ASP.NET 4. of which the most important seem to be...
  • Scrip Loader – the new script loader control enable developers to load all the required scripts only once, thereby eliminating the unnecessary subsequent requests to the server. It supports the ‘lazy load’ pattern which loads scripts only when necessary, and loads scripts in combination, in order to increase the performance of loading a page. It also supports the jQuery script and custom scripts.
  • JQuery IntegrationJQuery is very popular third party javascript library. ASP.NET 4 extensively supports the integration for jQuery by mixing the jQuery and Ajax plug-ins seamlessly.
  • Client Data Access – by using pre-defined client controls inside the Ajax Library, developers can easily build asynchronous data-driven applications. For example client DataView control will display one or more records by consuming a WCF service. All the relevant time-consuming operations will be handled by the Ajax library asynchronously.

Conclusion

ASP.NET 4 includes plethora of new features which will enable developers to write high performance, search-engine friendly web application quickly. The features I’ve mentioned seem to be the most important of all the new features in ASP.NET 4. By upgrading your existing web applications to up-coming ASP.NET 4, you are likely to see an improvement in performance and search-engine optimization.

More readings:

http://www.asp.net/
http://www.asp.net/learn/aspnet-4-quick-hit-videos/
http://weblogs.asp.net/scottgu/archive/2009/08/25/vs-2010-and-net-4-series.aspx
http://www.hanselman.com/blog/ASP4WhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx


This article has been viewed 58698 times.

Monday, August 6, 2012

Parsing Multidimensional Json array with jquery

How to parse following multidimensional json array with jquery 

{
   "data":{
     "item":[
         {
            "val1":58539,
            "val2":450000.0000,
            "Pictures":[
               {
   "Description":"",
                                    "Url":"http:\/\/demo1\/\/Pictures\/640\/58539_7f3a07a1dfe644228bed3378341c1e04.jpg"
               },
               {
                                    "Description":"",
                        "Url":"http:\/\/demo1\/\/Pictures\/640\/7730c8a5b65d4b75ba66dfafbde79a17.jpg"
               }
            ]
         },
         {
            "val1":58540,
            "val2":270000.0000,
            "Pictures":[
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035401.jpg"
               },
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035402.jpg"
               },
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035403.jpg"
               }             
            ],
         }
      ]
   }
}


Solution:


$.getJSON('url', function(data) {
      $.each(data.data.item, function() {
            var val1 = this.val1;
            var val2 = this.val2;
            $.each(this.Pictures, function() {
                  var desc = this.Description;
                  var url = this.Url;                
            });
      });
});

Example Reading from a JSON file 


create a file called test.json and use the below method 

 $.getJSON('test.json', function(data) {
            $.each(data.data, function() {
                var id = this.id;
                var headLine = this.headline
                var URL = this.originalURL;
                var Desc = this.extract;
                var country = this.article.country;
            });
        });

LINQ to XML -


LINQ to XML - How to create and save an XML document
CreateXMLDocument.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" %>  
  2. <%@ Import Namespace="System.Linq" %>  
  3. <%@ Import Namespace="System.Xml.Linq" %>  
  4.   
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  6. <script runat="server">  
  7.     protected void Button1_Click(object sender, System.EventArgs e)  
  8.     {  
  9.         XDocument xDoc = new XDocument  
  10.         (  
  11.             new XDeclaration("1.0","utf-8","yes"),  
  12.             new XComment("This is an Xml Document which programmatically created by LINQ to XML"),  
  13.             new XElement("employees",  
  14.                 new XElement("employee",  
  15.                     new XAttribute("id","101"),  
  16.                     new XElement("name","jenny jones"),  
  17.                     new XElement("city", "rome")  
  18.                              )  
  19.                          )  
  20.         );  
  21.   
  22.         String xmlFile = Server.MapPath("~/App_Data/Employee.xml");  
  23.         xDoc.Save(xmlFile);  
  24.   
  25.         XElement xFile = XElement.Load(xmlFile);  
  26.         TextBox1.Text = xFile.ToString();  
  27.     }  
  28. </script>  
  29.   
  30. <html xmlns="http://www.w3.org/1999/xhtml">  
  31. <head id="Head1" runat="server">  
  32.     <title>LINQ to XML - How to create and save an XML document</title>  
  33. </head>  
  34. <body>  
  35.     <form id="form1" runat="server">  
  36.     <div>  
  37.         <h2 style="color:DarkBlue; font-style:italic;">  
  38.             LINQ to XML - How to create and save an XML document  
  39.         </h2>  
  40.         <hr width="600" align="left" color="CornFlowerBlue" />  
  41.         <asp:TextBox  
  42.              ID="TextBox1"   
  43.              runat="server"   
  44.              TextMode="MultiLine"  
  45.              Columns="75"  
  46.              Rows="15"  
  47.              Enabled="false"  
  48.              >  
  49.         </asp:TextBox>  
  50.         <br />  
  51.         <asp:Button   
  52.             ID="Button1"  
  53.             runat="server"  
  54.             OnClick="Button1_Click"  
  55.             Text="Create and Save an XML Document"  
  56.             Height="45"  
  57.             Font-Bold="true"  
  58.             ForeColor="DodgerBlue"  
  59.             />  
  60.     </div>  
  61.     </form>  
  62. </body>  
  63. </html>  


 

 

 






LINQ to XML - How to generate XML from a current DataSource

Code:
XElement xml = new XElement("contacts",
                    from c in db.Contacts
                    orderby c.ContactId
                    select new XElement("contact",
                              new XAttribute("contactId", c.ContactId),
                              new XElement("firstName", c.FirstName),
                              new XElement("lastName", c.LastName))
                    );


Output:
<contacts>
  <contact contactId="2">
    <firstName>Barney</firstName>
    <lastName>Gottshall</lastName>
  </contact>
  <contact contactId="3">
    <firstName>Armando</firstName>
    <lastName>Valdes</lastName>
  </contact>
  <contact contactId="4">
    <firstName>Adam</firstName>
    <lastName>Gauwain</lastName>
  </contact>
  ...
</contacts>

here db is the datatable




Reading xml using linq


Once these files are loaded into the LINQ to XML API, you can write queries over that tree. The query syntax is easier than XPath or XQuery for developers who do not use XPath or XQuery on a daily basis.

Code:
// Loading from a file, you can also load from a stream
XDocument loaded = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var q = from c in loaded.Descendants("contact")
        where (int)c.Attribute("contactId") < 4
        select (string)c.Element("firstName") + “ “ +
      (string)c.Element("lastName");


foreach (string name in q)
    Console.WriteLine("Customer name = {0}", name);


Output:
Customer name = Barney Gottshall
Customer name = Armando Valdes