Month: February 2014

Exporting in Kendo Grid

Grid came into existence to fulfill the need of data presentation in applications. Since it’s creation it has been an undisputed choice for data presentation.

Exporting is an integral component of the grids. In most of the third party tools we have the exporting feature as an inbuilt component. In kendo grid yet we don’t have it so today I will be throwing some light on how to achieve it.

We will be exporting the data of a kendo grid into two different formats i.e Excel(XLS) and Word(doc).

Have a video for the functionality as well.

We need a button on click of which we will be initiating the Exporting into different above mentioned formats.

We can place these buttons either outside or at the toolbar of the Kendo Grid. For my demonstration I will be using the toolbar but the implementation will remain the same even if the buttons are placed outside the grid area.

Kendo Grid:

Untitled

So in the above code a kendo grid is created in the Jquery, this grid has a toolbar in which there are two Image buttons for exporting the data in Excel and word format.

On click of these buttons we are calling a method ExportData with are parameter that will differentiate that wheather the word or excel button is pressed.

Export Function:

In the ExportData method we will be exporting the data of the grid.

Key Steps:

1> Get the DataSource : Retrieve the datasource of the kendo grid. If we want to take              filtering also into account then we have to find the filtered datasource.

2> Declare the extension (Type of file in which the data should be exported).

3> Declare the Table header ( List of the Coulumns Header )

4> Fill the data into rows corresponding to the headers.

5> Create a link button dynamically click of which will initiate the downloading of the               exported files.

Untitled1

This is how we can achieve the Exporting feature in the Kendo grid at the client side.

Keep Learning Keep Exploring 🙂

State Management In Kendo UI Grid

Kendo Grid provides a vast set of  inbuilt settings which makes kendo preferable over other competitors grids present in the market.

Some of these settings are Grouping , Sorting , Filtering , Reordering , Paging , Re sizing and many more .
Sometimes we need to see the grid in the exact state as it was when we left it last time so that we don’t have to make our preferable settings again in the grid when we re-visit the page .
There are two possible solutions for this problem :
1> Either store the complete state into the browser cache.
2> Save the state in the database and retrieve and apply it back to the grid when we come again to the page.
I will be showing you the second way of doing the desired.

Solution :

When you are leaving the page find the grid state and and save it to the DataBase and while coming back Retrieve the settings and apply them back to the grid.

While Leaving the page :
Below explained steps will lead to the saving of grid state to the DataBase.
Step One : Get the Grid’s Datasource:
Untitled
Step Two :Retrieving the current state of Filtering, Paging ( PageSize and Current Page), Sorting, Grouping.
Untitled1
Step Three : Retrieving the order of columns (It Take account of Re ordering of column’s).
Untitled2
Step Four : Retrieving the list of hidden columns if any.
Untitled3
Step Five : Forming a GridSetting string and Saving it to the Database.
Untitled4
Inside the beforeunload event of windows we can save the grid state to the DataBase through a Ajax call.
Untitled5
While coming back to the page :
Following steps will help to achieve the desired.
Step One : Retrieve the Saved KendoSettings
In the page just before creating the grid we have to Retrieve these settings from the Database and have to apply them back on the kendo grid.
Get the data stored in a global variable i.e defaultKendogridSettings
Untitled
Step Two : Restoring the grid state (paging, grouping , sorting and filtering)
Untitled7
Step Three : Restoring Visibility of grid columns.
Untitled8
Step Four : Restoring column’s order.
Untitled9
So this is how one can store the Kendo grid settings in the database and apply it back again.

One important feature of web designing is the depth of configurability in it. A highly configurable design caters large aspect of flexibility but at the same time it brings complexity for the end users too and in such situations state management is helpful in breaking the ice.
Hope this one more way of state management helps 🙂

 

Tuples In MVC

Tuples (Magic In Views)

Many times we come across a situation in MVC when we require two different Models in a strongly typed View. This need usually arise when we have a requirement to use the properties of two different models in our view.



Problem : Can we really have Two or more models in a strongly typed View???



And the solutions that you will found in most of the places is that we can create a View Model (Basically a combination of two models with required properties from both the Models). View Models have lot of benefits as they save the network data by including only the required properties.



But in case if someone want to use two or more Models in a single View so is it possible?

Yes it is possible through Tuples:

By Using Tuples we can include two or more then two models in a single view.Theoretically the view will be strongly typed to a single entity but practically that entity will be a combination of two or more models.

Code Analysis :


View :

Declaration of tuple:

     @model Tuple<ModelFirst, ModelSecond>


Here ModelFirst and ModelSecond are two different models with whom our view is strongly typed.

Usage in the Razor View Engine:

@Html.TextBoxFor(m => m.Item1.StoreId, new { id = “last” })

@Html.TextBoxFor(m => m.Item2.PromotionLocation)

The models will be accessed as Item1 and Item2 . If there are more then two models the usage will go on as Item3 , Item4 …

So here in the two Textboxes we are using two different properties (StoreId and PromotionLocation )which are present in two different models.


Global.asax entry:

We have to create a Constructor class for tuple model as it doesn’t have any default constructor creation and we have to register the Constructor as a default binder in Global.asax.

    ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();

Defining constructor class:

This class must be inheriting the DefaultBinder

   public class MyDefaultModelBinder:DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
if (modelType == typeof(Tuple<Models.ModelFirst, Models.ModelSecond>))
return new Tuple<ModelFirst, ModelSecond>(new ModelFirst(), new ModelSecond());
return CreateModel(controllerContext, bindingContext, modelType);
}
}

Controller actions:

Initializing the View:

[HttpGet]
public ActionResult TupleMode()
{
var tuple = new Tuple<ModelFirst, ModelSecond> (new ModelFirst()
{StoreId=1,promotionStartDate=5 }, new ModelSecond()
{ promotionId = 1, promotionName = “First”, PromotionLocation = “Bang” });
return View(tuple);
}
      
For performing operations on Form Submit:

[HttpPost]
public JsonResult CreateContact(Tuple<ModelFirst, ModelSecond> tuple)
{
return Json(tuple.Item1.StoreId +”–“+tuple.Item2.PromotionLocation);
}

As a readability point of view off-course this approach sucks as the models will be accessed by Item+Corresponding Number in the View or controller but then it provides you the unique way
of using multiple models in a view without creating ViewModels.

This is how we can practically have two or more models in a strongly typed view of MVCSo the next time if someone ask you that in MVC can we have Two or more 
models in a strongly typed view, I guess you have the answer 😉


In my next blog I will be coming up with a new magic in MVC.

What’s New In .Net4.5

Though 4.5 version is released One year back but still there are many questions like what is new in DotNet 4.5

Let’s Explore some of the most useful features of this version.

1> ASYNC AND AWAIT

Async and await are markers which mark code positions from where control should resume after a task(thread) completes. Thus we can specify that what after and from where the control will be resumed after a long task.

 

2> REGEX TIMEOUT

We usually use regex for putting a regular expression validation for the various controls in a page. Sometimes if the input string is long then it takes time resulting in the late responses of the requests. This version of DotNet regulates a regex timeout period for a validation process.

3> GARBAGE COLLECTOR

Garbage collector is responsible for releasing the unused managed objects in the memory thus improving the performance and reclaiming of the memory space.Objects which are passed to the second generation of the garbage collector cycle are least frequently visited by the garbage collector for memory clearance so they keep wasting the memory. Current architecture runs a separate background thread which targets the second generation objects only , thus improving the garbage collector process.

4> SET DEFAULT CULTURE TO APP DOMAIN

 

In the previous versions of Dotnet we used to set the culture for individual threads but in multi-threaded applications this caused a ample of work for setting culture for all the threads.
In Dotnet 4.5 we can set the culture at the app domain level and all the child threads of app domain will inherit the culture.

 

For Example: 

CultureInfo GlobalCulture=CultureInfo.CreateSpecificCulture("En-US");
CultureInfo.DefaultThreadCurrentCulture=GlobalCulture;

There are many other interesting features . Keep Learning Keep Exploring.

 

Zen Coding

 

We can use zen coding to write large and tedious html markups in a faster yet very effective way.

Steps to use:

Step One: Download Zen Coding(From Microsoft) Extention from http://visualstudiogallery.msdn.microsoft.com/abd79254-b4f7-492d-95ae-d9fa38e0af48

Step Two: After the installation of the extension you will get a zen coding tab in your visual studio menu from where u can see the Expand Abbreviation.
Step Three: Start using zen coding:

Example 1=>
             Write div#myDiv>div.content+ul#navigation>li*5>a
             Press alt+z  (Expand Abbreviation) and the above  expression will be expanded into the following HTML markup:
             <div id=”myDiv”>
                  <div></div>
                  <ul id=”navigation”>
                        <li><a href=””></a></li>
                        <li><a href=””></a></li>
                        <li><a href=””></a></li>
                        <li><a href=””></a></li>
                        <li><a href=””></a></li>
                  </ul>
             </div>
            In the zen coding expression
            # stands for id
            . stands for class
            > stands for adding a child element
            + for adding a adjacent html element
            *5 makes 5 li inside the ul
Example 2=>div>p{Is this a useful tip} expression will result into following markup:
               <div>
            <p>Is this a useful tip</p>
               </div>
               {} is used to give the text to a element like paragraph or span


Benefits: Zen coding is an optimal solution for high speed coding.
                   Easy to learn.