Tuesday, July 30, 2013

Nested Layout pages in ASP.NET MVC

Like nested master page in ASP.NET, we can use nested layout pages in ASP.NET MVC. A layout page is a typical HTML page with a special @RenderBody() section. Here is a simple example of layout page:

<!DOCTYPE html>

<html >

<head>

    @RenderSection("styles", required: false)

</head>

<body>

    @RenderBody()

    @RenderSection("scripts", required: false)

</body>

</html> 

We can optionally define “name sections”. In the above layout page, we have define two optional name sections. Now let’s define a inner layout page:

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

@section styles {

<link href="~/Areas/Second/Content/aStyle.css" rel="stylesheet" />

}

@RenderBody()

In the above layout page, we are referring parent layout page. This inner layout page has to have a render body section. The name section is optional. You can use any of the parent name sections.

Now, we can use this nested layout page into any view.

Hope this helps!

Monday, July 29, 2013

Non-interactive Authentication to ASP.NET Web API using HTTPClient

HttpClient is a new HTTP library in .NET for accessing HTTP request. It is powerful library to utilize and get benefit of HTTP protocol. You can download it using NuGet.

In order to call authenticate service, the HTTPClient has to be authenticated with non-interactive way. On the other hand, the service has to have a login option for non-interactive client.


The following code snippet shows how we can allow non-interactive user to login:

public HttpResponseMessage PostJsonLogin(LoginModel model)
{
   if (ModelState.IsValid)
      {
       if (true)//Validate User
          {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return Request.CreateResponse(HttpStatusCode.OK, true);
           }
       }
    return Request.CreateResponse(HttpStatusCode. Unauthorized, false);
}


Here, if the user is valid, it will pass the authentication cookie and set the HTTP status code OK.

To call any authenticate service, the HTTPClient itself has to be authenticated by calling the PosrJsonLogin action. The following pseudo code shows how we can call an authenticate action:

var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;

var client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9712/baseurl ");
          

var model = new { UserName = "Gizmo", Password = "123", RememberMe = true };
HttpResponseMessage response = client.PostAsJsonAsync("api/Account/JsonLogin", model).Result;

if(response.IsSuccessStatusCode)
{
   var result = client.GetStringAsync("api/ContentManagement").Result;
}

In the above code snippet, it’s calling JsonLogin which will reply authentication cookie. If the HTTP status code is 200/OK, it can call any authenticate action.

You can download the source code from here.

Hope this helps!  

Wednesday, July 24, 2013

Automatic sign out problem in ASP.NET

Have you ever worked with two ASP.NET sites under “Default Web Site” and signing in into two sites? One of the sites gets automatically sign out. This is a silly problem I was having while showing two sites from my development machine. The problem was happening because I was using same name for “forms” tag in web.config file. Here is how we define forms authentication in web.config file:

<forms loginUrl="~/" timeout="2880" name="SameName" />

If you have two sites where name of forms tag is same, you will be sign out from one site as soon as you sign in into other site.

The solution is use different name for forms tag as long as the parent site is same.

Hope it saves your time!

Tuesday, July 23, 2013

Rich Interactive CRUD Operation In ASP.NET MVC

CRUD is fundamental operation in any application. There are many ways we can implement CRUD operation in ASP.NET MVC. If you google with bing(scott’s dialog), you will find thousands of example. However, this write-up is simple way to perform CRUD using AJAX in ASP.NET MVC. I have used the following library alone with ASP.NET MVC:

1> JQuery
2> JQuery UI
3> Bootstrapper(Not mandatory)

 You will find the source code here.

CRUD

In order to implement ajax post, I have used Ajax.BeginForm of ASP.NET MVC. The main advantage of  Ajax.BeginForm is you don’t need to do anything to submit the form as a ajax request. Moreover, it has all the default behavior of submit such as it validates the form in client side. You can use your regular form design of asp.net mvc and replace Html.BeginForm with Ajax.BeginForm.  To open the dialog, I used JQuery modal dialog.

After inserting or updating any item, we do refresh the tabular view. In my implementation, I have written a reusable javascript code to update the table. To use the reusable function, the property name has to be with table header(th) in form of  data-source="Title". Once we have property name of any particular cell, we can retrieve cell value from model. The beauty of javascript is we can get the value of any property using dot(.) operator or using key index.
Download the source code and have a look into it. It’s very simple but  powerful way to implement rich interactive CRUD operation in ASP.NET MVC. .

Hope it helps!

Monday, July 8, 2013

Show error message as tooltip in ASP.NET MVC

There are many ways form validation messages can be shown in web application. One of the typical error message is to show star(*) character beside the input box and show the actual message as a tooltip. I have been developing a web application using asp.net mvc where my clients wants to display error message as a tooltip.

In my asp.net mvc application, I am using data annotation with JQuery validation for validating my model. I will not go into the details of data annotation and JQuery validation since it is not scope of this post.

JQuery validation shows the full error message beside the input box like the following screenshot:


I didn't find any straight forward way to show error message as star(*) character. In order to achieve this, we need to write following javascript code:

$(document).ready(function () {
        var settngs = $.data($('form'), 'validator').settings;
        var oldErrorPlacement = settngs.errorPlacement;
        settngs.errorPlacement = function (error, inputElement) {
            var message = error.html();
            error.html("*");
            error.attr("title", message);
            oldErrorPlacement(error, inputElement);
        };
    });

The above code snippet overrides the errorPlacement event of JQuery validator. Inside the event, the code is self explanatory.

Now, the error message will look like following screenshot:


Hope this helps!


Tuesday, May 28, 2013

Response version '2.0' is not supported. The highest version supported is '1.0'


If you get an exception "Response version '2.0' is not supported. The highest version supported is '1.0'" after calling an OData service from .NET framework 3.5, it means that your .NET framework is not updated for calling OData service. You need to install an update to call OData service. You will find the update in following link:

Install the update, you will be able to call OData service. It took me one complete day to figure the problem out.

Hope this helps!

Sunday, March 20, 2011

Ext JS TreeGrid with WCF Restful Service

The TreeGrid of Ext JS is one of the most powerful controls of ext js control library. It has been added to the library recently. Most of the features and flexibilities of Tree and Grid are in TreeGrid.

image

Let’s see how we can use treegrid with WCF restful service.

1> Treegrid is not included in the default ext js’s script library. It has separate script and css files. To use this control we have to download the script files and add it into our project. You will get everything in the demo project.

2> We can create a new treeGrid by using the following code snippet:

var treeGrid = new Ext.ux.tree.TreeGrid({
            width: 900,
            root: localallTagsNode,
            renderTo: 'treeRegion',
            autoHeight: true,
            columns: colModel,
            loader: treeGridLoaderlocal
        });

You have to set the root node. 'treeRegion' is div where the control will be rendered. colModel is collection of columns defined as:

var colModel = [{
            header: 'Team Name',
            dataIndex: 'Name',
            id:"Id",
            width: 230
        },
        {
            header: 'Total Match',
            dataIndex: 'TotalMatch',
            id: "Id",
            width: 150
        },
        {
            header: 'Win',
            dataIndex: 'Win',
            width: 150
        },
        {
            header: 'Loss',
            dataIndex: 'Loss',
            width: 150
        }];

‘dataIndex’ is property name of JSON object.

3> There is no default json tree loader for treeview. However, you will find an extended version of the Treeloader for json object. You will find this inside ExtWrapper.js file.

4> In order to create a JSONTreeLoader, use the following code snippet:

var  treeGridLoaderlocal = new JsonTreeLoader({
        dataUrl: ServiceHelper.getServiceUrl('GetTeam'),
        requestMethod: 'post',
        responseRoot: 'GetTeamResult'
    });

dataUrl is the url of the restful service. In the above example ‘GetTeam’ is the operation name of the service. Another important thing to notice is ‘respoonseRoot’. 'GetTeamResult' is the root element of returned JSON object. This is how WCF restful service returns data. The syntax is operationName + ‘Result’.

That’s all you need to create TreeGrid in Ext JS with WCF restful service.

You can download the source code from here.

Hope this helps!

Tuesday, March 8, 2011

Could not open key: Software\Microsoft\ASP.NET\x.x.x.x : ASP.NET Application Installation issue

The problem is related to ASP.NET application installation. I had an ASP.NET 4.0 application. I created a setup for that application. I tried to install it in a machine where .Net framework 4.0 was installed. I got the following error:

clip_image002

I was unable to infer the problem from the above error. After googling a bit, I figured the problem out. My machine had .net framework 4.0 Beta installed and my web application was developed in released version of .Net framework 4.0. The version of the web application and .net runtime of deployed machine didn’t match. In order to install asp.net application, the ASP.NET version of install application and .net runtime version of the web server’s machine has to be same. You can check the version from the property of Setup project.

clip_image004

This requirement is true for any version of ASP.NET application to be installed.

Monday, March 7, 2011

Never define blank div as <div id=”dv”/>

Today, I came across an interesting behavior of div. It may be well-known to everyone but new to me. I needed a blank div. I wanted to set the InnerHTML of the div from javascript. Instead of end tag, I declared the div as <div id=”dv”/>

No wonder, I can access the div from Javascript. When I assign anything (say “Test”) into innerHtml of the div, the html below the div is replaced by the “Test”. However, if you declare the div as <div id=”dv”></div>, it will work as expected. 

Therefore, we should always use end tag of div.

Hope this helps to someone!

Sunday, March 6, 2011

The page cannot be found: Install .Net framework 4.0 and deploy ASP.Net 4.0 application in IIS 6.0

You have an IIS 6.0 web server with .net framework 2.0 installed. You want to deploy ASP.Net 4.0 application in this web server. In order to this, you will install .net framework 4.0 and deploy your asp.net 4.0 application. When you access your newly deployed application, you will get “The page cannot be found”.

A lot of headless running around ensued after this, trying to figure out why 404 is occurring. It is difficult to trace this error. Since the web application is deployed accurately, there is no reason of this error.

The problem is in the following image:

clip_image002

When you install the .net framework 4.0, by default it’s not allowed. You have to allow it to run the asp.net 4.0 application.

Hope this helps!

Tuesday, March 1, 2011

Use jsTree with WCF Restful Service

If you try to use jsTree with WCF Restful service, you will find some difficulty. It is not as simple as drag a control from toolbox, drop it onto aspx page and bind the data source. You need to tweak the jsTree source code to use it with WCF Restful Service. Below is the snapshot of Demo application.

The demo application uses WCF restful service. The service contains a GetTreeData operation which returns a list of TreeData as a JSON. The property name of the TreeData class has to be same as declared in the demo application. jsTree uses these property name to construct the tree. I have added an additional property for custom css which is not available in the default jsTree source code. You can add a custom css for each node now.

When WCF restful service returns JSON, it adds a root property under which the actual returned object remains. So you have to tell the jsTree to use the actual JSON object. To make this happen, I have added a “dataPath” property to jsTree and changed the source a bit.

If you click on the node, it will not be expanded by default. The jsTree doesn’t support this. I have changed jsTree source to make this happen. Therefore, use the source code of JsTree included in the demo application rather than original jsTree source code.

You can download the demo application from here.

Hope this helps!

Friday, January 7, 2011

A step by step guide to use Asp.Net 4.0 Chart control with IIS 7

Asp.Net 4.0 has built-in chart control. You can drag it from the ToolBox and drop it onto any markup page. It is supposed to work if you bind data with the chart control’s data source. However, it doesn’t work. Let’s see the steps which are required to use chart control properly.

1> You will find the Chart control inside the Data section of the toolbox. Do drag and drop the control in any markup page.

2> Set the XValueMember and YValueMembers property of “Series” element with the properties of your object you want to bind with the chart control.

3> Set the Datasource of the chart control.

4> Open the web.config file.

5> Add the following element inside the handlers section.

<add name="ChartImageHandler" preCondition="integratedMode" path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

6> Add the following element inside the appSettings section:

<add key="ChartImageHandler" value="storage=file;timeout=20;Url=~/tempImages/;" />

Point out the Url of the value. Instead of Url, you can set absolute path.

7> Create a folder named “tempImages” in your root virtual folder.

8> Let the write privilege of “tempImages” folder to the IIS user (IIS_IUSRS).

Now, if you run you web application, you will see the chart control. You can download a small demo  from here.

Hope this help!

Thursday, October 28, 2010

A cool tool to rename your .Net project

Have you ever tried to rename your solution, project, namespace? If you have ten projects in your solution and you try to rename all projects and solutions, it will be nightmare for you. It’s a totally boring work. Once, I faced this scenario. My solution had 21 projects. Instead of renaming the projects , namespaces manually, I built a tool which did the work for me.

clip_image002

This tool is easy to use. Say, you have projects named; MyProject.DAL, MyProject.Buiness, MyProject.Common, MyProject.Model etc. You want to rename MyProject into HelloProject. In order to do this, write “HelloProject” onto new solution Name text box, “MyProject” onto Old Solution Name text box and locate the folder of your project.

Consider the following things while using this tool:

  • · Keep a backup project.
  • · You might get an error if you don’t have permission to rename each file and folder. In spite of getting error, you can open the rename solution. The tool should change the necessary files and folders.
  • · After opening the solution, clean it and rebuild it.

You can download the source code from here.

Happy Programming!

Wednesday, October 6, 2010

A generic Data Access Layer using ADO.Net entity framework for N-Tier application

If you work with ADO.Net, you know object context is mainly responsible to track changes of entity in an object graph. So, ADO.Net entity framework works fine as long as your entity is connected to object context. However, in N-Tier application/web application, the entity has to be disconnected from object context. In order to work with disconnected entity, entity framework doesn’t have any straight forward way before the entity framework team introduces self-tracking entities.

I have created a simple data access layer for disconnected entities using the self-tracking feature of Entity framework. The following code snippet shows generic implementation for CRUD operations:

public class MallInteractiveMapEntities2 : MallInteractiveMapEntities
    {
        private static Dictionary<string, Action<MallInteractiveMapEntities2, object>>
            _AddToMethodCache =
                new Dictionary<string, Action<MallInteractiveMapEntities2, object>>();

        public MallInteractiveMapEntities2():base()
        {
            if(_AddToMethodCache.Count == 0)
            {
                lock(_AddToMethodCache)
                {
                    _AddToMethodCache.Add(typeof (Mall).Name,
                                          (context, entity) => context.Malls.ApplyChanges(entity as Mall));
                    _AddToMethodCache.Add(typeof(Floor).Name,
                                          (context, entity) => context.Floors.ApplyChanges(entity as Floor));
                }
            }
        }

        public void AddTo<TEntity>(TEntity entity)
        {
            _AddToMethodCache[typeof(TEntity).Name](this, entity);
        }

        public bool ApplyChangesToEntity<TEntity>(TEntity entity) where TEntity : IObjectWithChangeTracker
        {
            try
            {
                AddTo<TEntity>(entity);
                SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }

public bool ApplyChangesToEntityList<TEntity>(IEnumerable<TEntity> entities) where TEntity : IObjectWithChangeTracker
        {
            try
            {
                entities.AsParallel().ForAll(AddTo);
                SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }
      
    }

MallInteractiveMapEntities class is generated from Entity framework designer for a specific database. MallInteractiveMapEntities2 class which is inherited from MallInteractiveMapEntities has some methods to perform the CRUD operations.

To illustrate the use of the above class, consider we have two entities named “Map” and “Floor”. “Floor” is the child of “Map” and the relation is one to many. In order to create(C) Map and Floor, use the following pseudo code.

  Mall mall = new Mall();
  mall.Name = "American Shopping Mall";

            Floor floor1 = new Floor();
            floor1.Name = "Ground Floor";
            mall.Floors.Add(floor1);

            Floor floor2 = new Floor();
            floor2.Name = "First Floor";
            mall.Floors.Add(floor2);


            using (MallInteractiveMapEntities2 context = new MallInteractiveMapEntities2())
            {
                context.ApplyChangesToEntity<Mall>(mall);
            }

When you instantiate an entity, it will be marked as an added state.

To update an entity with child entities, use the following pseudo code:

      Mall mall = new Mall();
      mall.Id = 1;
      mall.Name = "American Shopping Mall";
      mall.MarkAsModified();
 
      Floor floor1 = new Floor();
      floor1.Name = "Ground Floor";
      floor1.MallId = mall.Id;
      floor1.MarkAsModified();
      mall.Floors.Add(floor1);

      Floor floor2 = new Floor();
      Floor2.MallId = mall.Id;
      Floor2.MarkAsModified();
      floor2.Name = "First Floor";
      mall.Floors.Add(floor2);


      using (MallInteractiveMapEntities2 context = new MallInteractiveMapEntities2())
            {
                context.ApplyChangesToEntity<Mall>(mall);
            }


Here, you have to mark the entity as a modified state. You also have to set the parent id to a child entity.

To delete (D) an entity, simply mark each entity as a deleted by using the “MarkAsDeleted()” method.

Self tracking is a promising feature of Entity framework. By using this feature, you can create a data access layer for disconnected entity of ADO.Net entity framework.

Hope this help!

Be careful about using Session state of ASP.NET

As an ASP.NET developer, we always use session state whenever we need to keep something related to user. Usually, session’s data stays in memory. Now a day, memory is not very expensive. Since memory is not expensive, we like to keep something into session without thinking much about it. This thinking leads to a dangerous state of an asp.net project.

Recently, our team was profiling one of our asp.net applications. At the time of profiling, we figured out some CPU intensive operations. Among the CPU intensive operations, session serialization was very costly.

We are using ASP.NET state server for our session state. In order to keep an object into state server, the object has to be serialized. As mentioned before, serialization is very costly operation. The following are the thumb rules for me while using state server:

  • Always run and use state server at the time of development. In other words, never use InProc.
  • Until or unless you need anything to keep in session, don’t keep it.
  • If you need any user specific data which is costly to get and doesn’t change during the session time, keep that data in the static field. Keep in mind that for a web farm environment, each process has to initialize the static field.
  • Never use default serialization of .Net for large and heavy object. .Net default serialization uses reflection which is expensive. Implement custom serialization for such a scenario.
  • Don’t keep large object using a single key. If you don’t need the entire object at a time, splits the object. It will reduce the size of the object and reduce the de-serialization cost.

Happy Programming!

Tuesday, August 17, 2010

WPF calendar control for touch screen application

If you are looking for WPF calendar control, you will get many over the internet. However, none of the calendar control is friendly for touch screen application. If you use any third party touch application framework such as “breezmultitouch”, you will not be able to get all the complex event of WPF built-in controls. For this reason, WPF built-in calendar control is not suitable for touch screen application.

The following screen shot shows a calendar control which is totally touches friendly. Its basic behavior is similar to Windows OS’s calendar control. All features of calendar control are managed by Button and RadionButton control. Both of these controls are very friendly for touch screen application.


There is nothing complicated in the implementation of the calendar control. Most of the implementation is easy to read. You can easily use this control by just referencing the WpfCustomControlCalendar project or you can copy the source of the control to any of your own project.

You can download the complete source code from here.

Hope this Help!