Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, February 9, 2016

Automated integration testing in ASP.Net MVC & Forms without IIS

Background

I have wrote about testing ASP.Net web forms in one of my previous post. This the era of MVC and I am still writing about web forms. Mainly I am working with web forms only for my web site http://joymononline.in. I have started it before MVC days and still I don't see any reason for converting to MVC. Its serving its purpose using the web forms technology? Why should I change? Another reason I am keep it there in web forms just to realize that technology should not drive our architectural decisions. Every time before I suggest MVC for any project, I think about my own web site and think twice whether we should go to MVC or not? None in my company agree or do in old web forms but its still worth considering and making sure there is specific reason for selecting ASP.Net MVC. According to them we should never do anything in web forms.

Recently I tried to implement Continuous Integration and Continuous Delivery to my web site. Details of doing it via AppVeyor can be found in another post. It was very easy to run unit tests in the integration server.

Problem

But the one of the issue I found during that exercise is on running Integration tests. What I wanted was to make sure all the pages in my site is browsable after each check and and deploy to staging. I was using [HostType("ASP.NET")] attribute to run the tests against IIS. This is mentioned in my earlier post about testing web forms. This works well in development machine as I have created IIS web application from Visual Studio and the project was pointing to that web application(Project Properties->Web->Server->Local IIS in VS 2013). But in build machine, this hosting will not happen automatically. We need to write script to host the application to IIS which is according to me extra task.

Possible approaches

This problem is not new. Many people have solved it in many ways. There are free solutions such as using tools like Selenium or can use hosting libraries such as WatiN, MVCInterationTestFramework etc... Some more options can be seen in the below link.
http://stackoverflow.com/questions/118531/what-is-the-best-way-to-test-webforms-apps-asp-net

My Solution

The requirement is clear. We need to host the site in a web server to run integration tests. So why can't we start a web server before the test begins and the test request site page. This lead to MVCIntergationTestFramework library. This .Net library helps us to host any folder as IIS web application. It also has some features to test results from MVC response.

No need to get confused with MVC prefix. As mentioned earlier, we can host any folder as IIS web application. So web forms also works. The main git project has many clones and one of those provide nuget as well named FakeHost. So its easy to include into VS test project.

Continuous integration

Since it doesn't need upfront IIS web application, it is easy to run tests from CI server provided it has IIS in it. AppVeyor has IIS in it and it runs smoothly there.

Once again this is my solution towards a small problem of integration testing of my personal web site. It may not be applicable always. If anybody wants to take a look at production code how its done, have a look at my personal web site code in Github. Now I am really enjoying the free CI & CD life. I don't know how to write down the joyful feeling of getting our source compiled after each check in, automatically testing the same and publish to staging and production if everything goes well. Everything free.

Happy CI & CD

Tuesday, May 19, 2015

Unit testing ASP.Net Web Forms

Scenario

We have a simple legacy web application created using ASP.Net Web Forms. It works well and doing its duties without fail. Mainly it deals with simple pages not many transactions involving many pages. But rarely there are changes coming in. Even if the changes come frequently, the changes are small changes which are not affecting the core functionality of web site. Being a passionate software engineer, we wanted to bring innovation into the project such as refactoring to patterns and more object orientation.

Problem

We are confident on the refactoring we are doing in the site. But still there is a factor of fear that whether those changes will break the other pages in the site or not? Basically need to make sure all the links are working. Normally after a change we manually click on every link and make sure they are all loading.

That is a repetitive work. No software engineer should be doing repetitive work. We need to solve this in less cost. As usual since its legacy application, there is no budget to buy tools or automated testing service.

Approaches

1.Write a tool to validate links

We can write a tool which will parse the html of default.aspx and make sure all the links are working properly ie returning valid html contents. Can use XMLHttpRequest or WebClient class to accomplish it. Can configure the tool to run as post build action.

Challenges are in validation because there is no guarantee that HTML pages can be easily parsed with XML classes. There is a nuget called HTML Agility pack which we can try here.

2.Write unit tests on existing Web Forms app

Write unit tests for all the pages and at least make sure all the are passing.

After evaluating, I feel the unit tests are the way to do developer testing. But is my legacy application written as testable. Absolutely no. Now what we can do? One way is to rewrite as ASP.Net or use the Url based unit test. Refactoring the business logic and testing those is not applicable as the site doesn't have complex logic and more than that we need to make sure the pages are all working after our change.

3.Convert into ASP.Net MVC and unit test

Though this is the perfect solution most of the time this will not work out because.
  1. There may not be enough budget for maintaining legacy app or convert into ASP.Net MVC because from the business perspective, the site is doing its duty properly
  2. There might be links already bookmarked by users. Those will be invalid unless there is a rerouting mechanism in new MVC application.

Solution - Unit test ASP.Net Web Forms

The concept of unit test is applied to one level above the normal unit testing of classes and methods. Here we test the ASP.Net Pages itself. We can check particular properties of Page is set when rendered for a particular request url. Below are the steps to create unit tests for ASP.Net Web pages

1.Create UnitTest Project

Create normal unit test project from VisualStudio->New->Project dialog which we used to create for other scenarios such as class libraries or MVC.

2.Refer System.Web

Reference to Syste.Web.dll in UnitTest project is required if we want to hold the Page variable for assert.

3.Write test method with special attributes

Now comes the testmethod same as in normal test project. Here additions are 2 attributes HostType and UrlToTest. They specifies where the web page is hosted and what page corresponding test method is going to test. Below is one scenario where test method is testing a page hosted in Local IIS server.

string url = "http://localhost/joymononline/"
[TestMethod]
[HostType("ASP.NET")]
[UrlToTest(baseUrl+"links.aspx")]
public void WhenLinksPageIsRequested_ShouldReturn200AndContent()
{
    Page page = TestContext.RequestedPage;
    string url = Path.Combine(baseUrl, "links.aspx");
    //Assert.IsTrue(UrlIsValid(url));
    Assert.IsTrue(page.Title.Equals("Joymon Online | Links"));
}

If you are looking for how to test a web application running from development server, please have a look at the below links.


I strongly recommend developing by pointing to local IIS server, because IIS is the way your application is going to be served to end users. Otherwise there will be scenarios of  "works on my machine" which is really tough to deal with.

Debugging IIS hosted Web Forms Unit test

By default if we put a break point in ASP.Net Web Forms unit test where the site is hosted in IIS, it wont get hit. We need to attach to IIS process w3wp.exe.

So put a Debugger.Break or Debugger.Launch. This will open up an error dialog and from there we can attach to W3WP.exe.1

Also need to make sure that the dlls are compiled in debug mode.

Issues

Sometime there may be issues when running the unit tests. One error what I faced was below.

The URL specified ('http://localhost/joymononline') does not correspond to a valid directory. Tests configured to run in ASP.NET in IIS require a valid directory to exist for the URL. The URL may be invalid or may not point to a valid Web application

There are multiple reasons for this.

First we need to run Visual Studio in admin privilege. 

Second we need check whether the below entry is logged into event log viewer -> application  node

(QTAgent32_40.exe, PID 12920, Thread 14) WebSites.GetWebServer: failed to create AspNetHelper: Microsoft.VisualStudio.Enterprise.Common.AspNetHelperException: The website metabase contains unexpected information or you do not have permission to access the metabase.  You must be a member of the Administrators group on the local computer to access the IIS metabase. Therefore, you cannot create or open a local IIS Web site.  If you have Read, Write, and Modify Permissions for the folder where the files are located, you can create a file system web site that points to the folder in order to proceed. ---> System.Runtime.InteropServices.COMException: Unknown error (0x80005000)
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_IsContainer()
   at System.DirectoryServices.DirectoryEntries.ChildEnumerator..ctor(DirectoryEntry container)
   at System.DirectoryServices.DirectoryEntries.GetEnumerator()
   at Microsoft.VisualStudio.Enterprise.Common.IISHelper.GetWebServerOrdinal(Uri site)
   --- End of inner exception stack trace ---
   at Microsoft.VisualStudio.Enterprise.Common.IISHelper.GetWebServerOrdinal(Uri site)
   at Microsoft.VisualStudio.Enterprise.Common.IISHelper.get_WebServerOrdinal()
   at Microsoft.VisualStudio.Enterprise.Common.IISHelper.get_RootPath()
   at Microsoft.VisualStudio.Enterprise.Common.IISHelper.get_PhysicalPath()
   at Microsoft.VisualStudio.Enterprise.Common.AspNetHelperMan..ctor(Uri uri, BasicAuthCredential credential, Int32 frameworkMajorVersion)
   at Microsoft.VisualStudio.Enterprise.Common.AspNetHelperMan..ctor(Uri uri, BasicAuthCredential credential)
   at Microsoft.VisualStudio.Enterprise.Common.AspNetHelper.Create(Uri uri, BasicAuthCredential credential)
   at Microsoft.VisualStudio.TestTools.HostAdapters.WebSites.GetWebServer(String webServerName, WebServerType webServerType, String urlToTest, String pathToWeb, String webAppRoot, BasicAuthCredential credential, Context context, WebSiteConfigurationType webSiteConfigType, Origin origin)

If we can see the above, we can try enabling IIS 6 compatibility. This is applicable if we are running on Windows 7 with IIS 7 or above.

Go to Control Panel->Programs and Features->Turn Windows Featuers On or Off
Then
Internet Information Services->Web Management Tools->IIS 6 Management Compatibility Tick the "IIS Metabase and IIS 6 configuration compatibility" option and install it.

Some users says that we need to enable everything in IIS 6 Management Compatibility.2

References

1http://forums.asp.net/t/1246417.aspx?How+to+Debug+unit+tests+for+ASP+NET+web+application
2http://stackoverflow.com/questions/9065937/asp-net-unit-testing-windows7-iis7

Tuesday, April 28, 2015

Change Areas folder convention to Plugins in ASP.Net MVC

ASP.Net MVC is mostly about convention. The controllers are inside Controller folder, cshtml files needs to be under views folder, the views are looked up from ActionResult by the action name etc...But whatever conventions are there, all those can be overridden. That is the beauty of MVC framework.

Recently we faced one scenario of overriding convention in one of the MVC projects. It uses MVC Areas to achieve plugin model. We deploy new plugins into the areas folder without recompiling the original framework web application. During one of the demo, there was a suggestion to rename the 'Areas' folder to 'Plugins' for better naming convention and readability. We tried to resist it as it adds unwanted code. But due to the pressure from leadership we decided to change it. It is good in one way that, we gets more chances to look inside the MVC framework.

Initially thought of having custom controller or ViewEngine. But after playing with MVC for some time, it became very easy as adding some lookup folder paths into RazorViewEngine. Files and folder hierarchy under the Plugins folder needs to be done manually. Right click and add area will not put new files into Plugins folder. Code below. The sub folder structure and files can be organized in side the Plugins folder in the same way how its seen in Area's folder.


        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AddPluginsFolderToAreaLocationFormatsOfRazorViewEngine();
        }

        private static void AddPluginsFolderToAreaLocationFormatsOfRazorViewEngine()
        {
            string[] PluginsLocationFormats = new string
                [] { "~/Plugins/{2}/Views/{1}/{0}.cshtml" };
            var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
            razorEngine.AreaMasterLocationFormats = 
                razorEngine.AreaMasterLocationFormats.Concat(PluginsLocationFormats).ToArray();
            razorEngine.AreaViewLocationFormats = 
                razorEngine.AreaViewLocationFormats.Concat(PluginsLocationFormats).ToArray();
        }


If anybody faces issues in getting this run, comment here. I can upload a sample MVC5 project.

http://theshravan.net/blog/configure-the-views-search-locations-in-asp-net-mvc/
http://stackoverflow.com/questions/632964/can-i-specify-a-custom-location-to-search-for-views-in-asp-net-mvc

Monday, July 14, 2014

Hosting ASP.Net MVC app in Windows 8 IIS 8 - HTTP Error 403.14 - Forbidden

Recently I was trying to run an ASP.Net MVC application in my new Windows 8 environment. When I run the application from visual studio, I got the below error.

HTTP Error 403.14 - Forbidden

The Web server is configured to not list the contents of this directory.


It was silly as the Windows 8 by default don't support pre .Net 4.0 versions also we need enable programming support explicitly.

First We need to enable it in
Control panel -> Turn windows features -> .Net framework 3.5(includes .Net 2.0 and 3.0) in case the project is targeting older version.

Also we need to enable ASP.Net development support too. Go to  Control panel -> Turn windows features -> Internet Information Services-> World wide web services -> Application development features and enable ASP.Net 3.5 and 4.5 based on the project target.

http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-using-aspnet-35-and-aspnet-45

Monday, May 26, 2014

Why the __RequestVerificationToken sent from @Html.AntiForgeryToken() is not changing

Recently we got an issue during the security review conducted by the client on an ASP.Net MVC 4 web application. It was related to the CSRF attacks. We have used the anti forgery token throughout our application. But the reviewer said that the token value generated by HTML helper is constant always. Ideally the "__RequestVerificationToken" value should not be same for the subsequent requests. But in our case the token value returned is always the same.

We were able to reproduce the issue easily using a sample application in our QA environment. But the same sample worked well in development servers. This helped us to narrow down the issue to the server configuration.

There were no forum questions about such an issue when we googled except one question in SO but there is no answer. Then the search turned towards relations between windows updates and anti forgery token. It lead to one SO link where it mentioned about a KB. Immediately installed the same in the QA test server and could see it worked. 

Below is the link to KB which solve the repetition of anti-forgery token issue across multiple page loads

http://support.microsoft.com/kb/2656351

Tuesday, April 29, 2014

XSS attack into ASP.Net MVC 4 site via Javascript comment

Introduction

Till this moment I strongly believe that, software security can not be achieved. I am telling this within my 6 academic + 8 professional years of experience with computer systems. I did building computer systems as well as hacking the same. Whenever I architect a system most of the time I was able to forecast the holes too. But since timely release of the application takes more priority in most of the cases, I have no way except building the systems with security holes. 
"Computer software security is always a concept like perfection"
Hacking a desktop based software is more easy because we can always see the source code which helps to understand how its being executed. Sorry to the new generation developers who born into the managed world. When the old generation says source code its always assembly language which cannot be obfuscated or protected. Assembly language is enough to understand how the system works.

Web systems are easy to build as it requires primary knowledge of HTML and one scripting language. Now a days with the penetration of Node.JS, one can create web sites with only HTML & Javascript knowledge without even knowing how the web works on request-response mechanism. If a hacker finds out a security hole in a desktop system and make use of it, the impact will be normally less. For example if somebody hacks the serial key mechanism, only some people are going to use it, unless he puts that in internet. But think about a web system, if attacker succeeds in hacking a bank web site, the impact will be huge.

XSS is one type of the web attack.In short we can define that as below

"Injecting script into the system as if, it is input data and getting the same script executed on other user's browser"

I know this is not easy to digest at the first glance. If you need more details, visit the below links.
Below is one sort of XSS attack which uses the query string to inject script and makes it available inside a script block.
http://buffered.io/posts/xss-flaws-via-mvc-model-binding-and-request.querystring-inconsistencies/

One more special case is to exploit the javascript encoding and passes the javascript via innerHTML property of html elements.
http://weblogs.asp.net/jgalloway/archive/2011/04/28/preventing-javascript-encoding-xss-attacks-in-asp-net-mvc.aspx

XSS via commented JS which has ASP.Net MVC RAZOR token

Normally in MVC people may not use the old query string technique.Also the sites will be having the ASP.Net request validation enabled. The ASP.Net request validation scans all the requests for any possible script tags and throws exception on the same.

What if the script came through an Action method without script tag and renders with the help of a commented line and get executed without even an HTML event? Again, the Action method can be invoked both by get requests and post requests.

We are going to discuss how such a situation can occur.

The victim Web application / ASP.Net site

In most of the cases the security holes are opened by the programmers unknowingly. Lets take an example of a simple web site. Here the programmer wants to implement a contact page where the contact person's name comes via an action method.

@model MvcExceptionHandlingDemo.Models.Contact
@{
    ViewBag.Title = "Contact";
}
 
<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
    @using (Html.BeginForm())
    {
        @Html.LabelFor(s => s.Name)    @Html.TextBoxFor(s => s.Name)
        <input type="submit" value="Change" />
    }
</hgroup>

        public ActionResult Contact(string name)
        {
            ViewBag.Message = name;
            if (ViewData.Model == null)
            {
                ViewData.Model=new Contact(){Name=name};
            }
            return View();
        }
        [HttpPost]
        public ActionResult Contact(Contact c)
        {
            ViewBag.Message = c.Name;
            if (ViewData.Model == null) ViewData.Model = c;
            return View();
        }

One of his intention was to show the social profile of that person by using some web services which accepts name. So wrote a javascript function. But later he commented the js code because he was not able to find suitable web API which gives the social profiles.

<script type="text/javascript">
    function dispProfile() {
        //var s = '@ViewBag.Message';
    }
</script>

How to conduct attack

The base for this attack is the option of rendering text into javascript which is commented. The MVC framework doesn't know about the javascript comment. So it will do its duty which is nothing but rendering the value in @ViewBag.Message property.

What string we should inject as script in this scenario is little tricky.
  1. We need to close the existing js function. 
  2. Then we can have our script. Since it is outside of the function it will get executed when page loads.
  3. Finally we need to have a dummy function with only starting '{' to make sure the script is in correct syntax
Below is one sample javascript which we can inject

';
}
alert(2024);
function dummy(){
//

This will make sure dispProfile() function closed properly. and write the attack script (Here it is alert(2024);) and starts a new dummy function to make the syntax proper.Otherwise the dispProfile() function will be in open state. So after the injection the rendered script will be as follows.

 <script>
    function dispProfile() {
        //var s = '&#39;;
}
alert(2024);
function dummy(){
//';
    }
</script>

One more thing to remember is how to inject this script .One of the option is to exploit the Contact action method with msg parameter. If we normally inject any script tag the ASP.Net request validation system will throw error. But here we are not injecting the script tag as it is. Instead some fragments of script. The script as its cannot be added to URL. For that we need to use the URLEncoded string of the script. Encoded URL can be

http://localhost:50471/Home/Contact?msg=%27%3B%0A%7D%0Aalert(2024)%3B%0Afunction%20dummy()%7B%0A%2F%2F

There are so many online URL encoding and decoding sites. Those can be used to do the encoding.

How to prevent

In this case the problem is commented code. The intention of the programmer is to stop the functionality of dispProfile() but he forgot the fact that its containing RAZOR token. He should have commented RAZOR code as well. In other words here same program is handled by 2 execution engines. RAZOR & Javascript. So when commented it should be commented for both the engines.

Sample application can be downloaded from the below link.

Monday, April 21, 2014

How to remove Antlr3.Runtime & WebGrease from your ASP.Net MVC web application

What is Antlr3.Runtime & WebGrease

As of a new programmer those are the dll which increase the size of their project. Before we remove these dlls we should know what are those dlls and their duties? Those are the dlls used for Bundling and Minification. By default the Visual Studio adds those nuget packages in the newly created MVC web application.

http://westdiscgolf.blogspot.in/2012/06/aspnet-mvc-4-webapi-rc-what-on-earth-is.html
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

When should we remove Antlr3.Runtime & WebGrease

Next thing we need to understand when we should remove those and why we need to remove? If you are creating a production application, never remove as those libraries will increase the performance of our application. We may not require if we are doing any of the following.
  • Creating a PoC and mailing the same which don't deal with minification and bundling.
  • Creating a sample for blogging.

Removing Antlr3.Runtime.dll & WebGrease.dll packages

Method 1 - nuget uninstallation

Below are the steps proper steps if we have the solutions in proper condiction
  • Open nuget package manager console or UI.
  • Execute the command Uninstall-package 'package name'.The order of removal is as follows
    • Microsoft.AspNet.Web.Optimization
    • WebGrease
    • Antlr
  • Follow the common steps for method 1 & 2

Method 2 - Manual removal

Use these steps if you are not able to make it via nuget.
  • Manually remove the reference to the Antlr3.Runtime.dll, WebGrease.dll & Microsoft.AspNet.Web.Optimization from solution explorer
  • Follow the common steps for method 1 & 2

Common steps for Method 1& 2

  • Remove or exclude the App_Start\BundleConfig.cs file.
  • Remove the method call BundleConfig.RegisterBundles(BundleTable.Bundles); from Global.asax.cs
  • Remove the import using System.Web.Optimization; from all code files.
  • Remove the @Scripts.Render() and @Styles.Render method calls from your view files
  • It will make the application fail, if we are using scripts and styles. You need to explicitly add the styles and scripts to the application For example to render styles add the below line.
  • <link rel="stylesheet" href="@Url.Content("~/Content/site.css")">
  • Remove the "System.Web.Optimization" entry from views\web.config file->
    <system.web.webPages.razor> -> <namespaces>
    
  • Clean the solution and delete everything in \bin folder

Method 3 - Remove the packages folder and bin folder and ask the user to sync nuget packages

As you see the problem its about sending the sample code to other user and his easiness to run the same. If the target developer knows about nuget, let him install the nuget packages before running the sample. This is the actual solution provided the target developer have enough internet connectivity to sync nuget packages.

I have tried this in MVC 4 & 5 from VS2010 & VS 2013 without any issues.
Happy coding.

Monday, April 7, 2014

Showing different RAZOR Views based on the Model type in ASP.Net MVC

Problem

In real time, there will be scenarios where we need to display different model classes differently in the Views. Normally, if the controller is aware of the Model type and knows the corresponding View, it can return the proper ViewResult object via its Action() methods. But what should we do, if we have an GenericBusinessObject ie an Entity which have its properties in a dictionary or enclosed in XElement and we need to switch the View based on the type of Generic Entity?

My current project have an offline processing feature which is controlled via queues. When somebody needs to process a long running task they put their request into the queue and the queue monitor mechanism dequeue the requests whenever there is space to process that request. This is a general framework where the track developer needs to write code for queuing the request which accepts the parameter in the form of xml. The parameter decide how the processing server process that particular request. The track developer also needs to write code for the actual processing by implementing certain interfaces. Simply saying the queuing system just makes the processing delayed until the processing servers have enough capacity to process the request and the details about how to process and related logic is decoupled from the queue framework as the operation detail is passed as xml.

This system also has monitoring web application as well where the production engineers can see how many queue items are waiting in the queue, how many failed etc...The web site also have provision to see the queue request parameter xml which is viewable only to the application support engineers. A trained application support engineer can identify, what a particular queue request is intended for, by analysing the queue requests parameter. This monitoring site is implemented using ASP.Net MVC 4 with a page to see all queue requests. Things were easy until we get a requirement to display different pages based on the queue request type, so that the application support engineers don't need to analyse the xml to know what is the intention of the queue request.

To understand the issue in a simple scenario, lets take Person object with 2 properties. PersonType and Properties. Definition is given below.

    public class Person
    {
        [Display(Name = "First Name")]
        public string PersonType { get; set; }
        public XElement Properties { get; set; }
    }

The Properties is kept as xml as it is having dynamic schema or in simple words variable number of properties. If the PersonType is Employee the Properties can include FirstName & Company.For Student type it can have FirstName,School & Marks. 
The MVC site is supposed to call a web service to get person  object list and display all the unique person types from the obtained person list. When the user clicks on the PersonType link it should display Person objects corresponding to the person type. If the type is known such as Student display 3 columns and if its unknown just show the Person type. The URL might look like as below
site.com/Person/List?personType=Employee
or
site.com/Person/List?personType=Student

Challenges

  • If we just return the model from Action method, it cannot render as it don't know the View corresponding to the Model.
  • If we put if/switch condition based on the PersonType in the List.cshtml and render the <Table> accordingly the List.cshtml will grow to large size.
  • We can have same if/switch based on PersonType and render partial views which will limit the size of the List.cshtml. But again the partial view need to have logic for parsing the XML and display accordingly.

Solution

The better solution, I could think of is "having an abstraction for parsing the xml to create concrete model classes and give to View for just display" instead of view working on Model to find out what is relevant. So the logic of parsing xml is done in the Action and it returns typed model class object to the corresponding views. When we say abstraction, its just and interface which returns the typed objects and the corresponding view name. The implemented classes will have the logic of parsing the xml to convert to typed objects. Only consideration is about having a base class for view model classes which are returned from the interface methods or properties.

It is not the perfect solution. We can argue on merits of having partial views v/s this provider mechanism. But its worth looking at this provider mechanism as well. Below is the relevant code for this approach.

    public class ViewModelBase
    {
    }
//Typed class for student.It will differ for employee
    public class StudentViewModel:ViewModelBase
    {
        public IEnumerable<StudentModel> Students { get; set; }
    }
    public class StudentModel
    {
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Display(Name = "School")]
        public string School { get; set; }
        [Display(Name = "Marks")]
        public string Marks { get; set; }
    }
    public class DefaultViewModel : ViewModelBase
    {
        //Reuse the Person itself instead of DefaultModel
        public IEnumerable<Person> Persons { get; set; }
    }
/////////////////Classes related to provider model.
    public interface IViewModelProvider
    {
        ViewModelBase GetViewModel(IList<Person> persons);
        string ViewName { get; }
    }
    internal partial class StudentViewModelProvider : IViewModelProvider
    {
        ViewModelBase IViewModelProvider.GetViewModel(IList<Models.Person> persons)
        {
            StudentViewModel studVMList = new StudentViewModel() { };
            studVMList.Students = persons.Select(p=>new StudentModel(){
                FirstName = p.Properties.Attribute("FirstName").Value,
                School = p.Properties.Attribute("School").Value,
                Marks = p.Properties.Attribute("Marks").Value
            });
            return studVMList;
        }
        string IViewModelProvider.ViewName
        {
            get { return "Student"; }
        }
    }
    public class DefaultViewModelProvider : IViewModelProvider
    {
        ViewModelBase IViewModelProvider.GetViewModel(IList<Models.Person> persons)
        {
            DefaultViewModel personVMList = new DefaultViewModel() { };
            personVMList.Persons = persons;
            return personVMList;
        }
        string IViewModelProvider.ViewName
        {
            get { return "Index"; }
        }
    }
/////////////MVC Specific
    public class PersonController : Controller
    {
        public ActionResult List(string personType)
        {
            IEnumerable<Person> persons = DataRepository.GetPersonsByType(personType);
            IViewModelProvider provider = ViewModelProviderFactory.GetProvider(personType);
            ViewModelBase viewModel = provider.GetViewModel(persons.ToList());
            return View(provider.ViewName, viewModel);
        }
    }

Hope this is clear. Sample can be downloaded from the below location.

Tuesday, November 19, 2013

ASP.Net MVC AJAX requests are not running in parallel when the Session is enabled

Recently I was into a mission of increasing the speed of an ASP.Net MVC web site which was continuously throwing exceptions (time outs) when the data increased to 10,000 records in one table.

Initially the site was taken care as stepchild which got less developers to work on and less allocation of design time as it is targeted to admin people who are less in number. Now the things changed suddenly and it needs to be a competitor for Facebook in terms of performance.

The main issue was due to lack of join support in OData. We fixed so many coding issues which are related to usage of WCF Data services which uses OData protocols internally. Then made most of the pages AJAX friendly. Implemented real lazy paging in grids. Earlier, the app was pulling all data to the client side and was doing paging in javascript.

The site became responsive in 5 seconds. Now a special issue got our attention. Multiple AJAX calls, we issued from javascript are not getting executed in parallel in the server side. In particular page, there are 2 AJAX requests made from jQuery. Based on the server logs, each takes 2 seconds to process. But when we looked in F12 tools, the second call ends only after 4 seconds. The search ended up in usage of session variables. By default 'only one thread can access particular Session'. In our case both the AJAX requests are executed from same page which means the execution of action methods will be serial.

Initially we though of getting rid of session usage in the whole application. But after sometime, we started thinging differently. We are not the ones who are facing this issue. Somebody might also faced it and resolved it. What they did to resolve this?

It simply ended in SessionState attribute where we can control the behaviour of session usage per Controller. Thanks to the authors of below blogs.

http://www.stefanprodan.eu/2012/02/parallel-processing-of-concurrent-ajax-requests-in-asp-net-mvc/
http://johnculviner.com/asp-net-concurrent-ajax-requests-and-session-state-blocking/

How to apply SessionState to action method level

http://sapoval.org/per-action-custom-sessionstateattribute

Monday, October 21, 2013

ASP.Net MVC 4 Error handling in real time applications

Whenever we google for ASP.Net MVC exception handling techniques, we get a bunch of links but most of those explains about different techniques and finally ask us to decide one method based on our requirement. Sometimes we will end up in a more confused state. This article is to help a real time ASP.Net MVC developer to decide his logging mechanism.

Aim of error handling

Below are the things we should aim when we develop a error handling framework.

Never expose the exception details

We should never return the details of exception such as call stack to the end user. If we expose, it is considered as a security hole for hackers to understand the working of our system.

Log all the exception details

No system in this world is perfect. We need to accept the fact that, there may be exceptions. How we are dealing with those exceptions is important. To fix bugs and improve our system, it is required to log all the exceptions occurred in the system. The developers can therefore analyse the logs and fix.

Types of errors

Below are the different types of error conditions, we can expect in our ASP.Net MVC application.

Exceptions in ASP.Net MVC pages

This is the most common type of exceptions we need to handle. There may be exceptions when we execute the controller code which needs to be handled properly.

How to handle MVC page exceptions

There are 2 methods to handle this. Either we need to handle the exception at MVC framework level using the HandleError attribute on the controller classes or handle the exception at application level by global.asax :Application_Error(). 

I would suggest going for the error handling at the application level. It will capture all the error including routing issues. How that is useful in case of wrong URLs can be seen in next section.

One challenge in handling the exceptions at application level is that we cannot show the MVC Error page directly as we are out of MVC framework. For that we need to follow the below technique in the Application_Error method.

        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;
            new MVCApplicationExceptionHandler().Handle(httpContext,Server);
        }

    public class MVCApplicationExceptionHandler
    {
        internal  void Handle(HttpContext httpContext, HttpServerUtility server)
        {
            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            string currentControllerName = GetCurrentControllerName(currentRouteData);
            string currentActionName = GetCurrentActionName(currentRouteData);
 
            var ex = server.GetLastError();
            new ExceptionLogger().Log(ex);
            RedirectToErrorPage(httpContext, ex,currentControllerName,currentActionName);
        }
        private void RedirectToErrorPage(HttpContext httpContext,Exception ex, string currentControllerName, string currentActionName)
        {
            //Clearing httpContext
            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;
 
            //Setting values for new route
            string errorAction = GetErrorActionNameFrom(ex);
            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = errorAction;
            
            //Fire the ErrorController
            var controller = new ErrorController();
            controller.ViewData.Model = new HandleErrorInfo(ex, currentControllerName, currentActionName);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
        private string GetErrorActionNameFrom(Exception ex)
        {
            var action = "Index";
            var httpEx = ex as HttpException;
            if (httpEx !=null)
            {
                switch (httpEx.GetHttpCode())
                {
                    case 404:
                        action = "NotFound";
                        break;
                    default:
                        action = "Index";
                        break;
                }
            }
            return action;
        }
        private string GetCurrentActionName(RouteData currentRouteData)
        {
            string actionName = string.Empty;
            if (currentRouteData != null &&
                currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    actionName = currentRouteData.Values["action"].ToString();
                }
            return actionName;
        }
        private string GetCurrentControllerName(RouteData currentRouteData)
        {
            string controllerName = string.Empty;
            if (currentRouteData != null &&
                currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    controllerName = currentRouteData.Values["controller"].ToString();
                }
            return controllerName;
        }
    }

The ErrorController and it's View can be simple. ErrorController.Index() action which will be invoked when an exception occurs inside the controller.

Requests to wrong ASP.Net MVC page URLs which cannot be routed

Sometimes there will be requests to wrong URLs. We need to respond with proper message instead of showing the white screen or ASP.Net generated error page.

eg: www.mycompany.com/Emplyee/1 - The spelling mistake in the word 'employee' should be handled by our application.

How to handle wrong MVC URL requests

The above solution will work for wrong URLs as well. In this case the NotFound action will be invoked.See the attached sample for more details.

Exceptions in AJAX calls

AJAX calls may also raise exception in the controller. Those needs to be handled and the required information needs to be passed to the client side to inform the user about his request.

How to handle AJAX exceptions

Instead of error page we should return a JSON response which tells that there is an error happened. Lets see one example below

<script type="text/javascript">
    function divide() {
        var n1 = $("#n1").val();
        var n2 = $("#n2").val();
        //Lets not bother about the data which is available in n1 and n2. Assume that those are numbers
        $.ajax({
            type: "GET",
            cache: false,
            url: "../Calculator/Divide",
            data: { "n1": n1, "n2": n2 },    // multiple data sent using ajax
            success: function (html) {
                if (html.IsSuccess) {
                    $("#res").val(html.Result);
                }
                else {
                    alert(html.Result);
                }
            },
            error: function (a, b, c) {
                alert("Some unexpected error happened");
            }
        });
    }
</script>

    public class CalculatorController : Controller
    {
        public ActionResult Divide(int n1,int n2)
        {
            try
            {
                return new JsonResult() {JsonRequestBehavior = JsonRequestBehavior.AllowGet,Data = new  { IsSuccess = true, Result = n1 / n2 } };
            }
            catch (DivideByZeroException ex )
            {
                return new JsonResult() {JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { IsSuccess = false, Result = "You cannot divide by Zero" } };
            }
        }
    }

I don't think it needs any explanation. Even in case of exception its returning the JSON response. But before processing at the client side, it should check for IsSuccess property. If any other exception occurs the control goes to application level which we can see in next section.

The catch blocks should not be exception eating blocks. Use the catch blocks which we are sure that we can handle.

AJAX Request to wrong URLs which cannot be routed

In case of an AJAX request to wrong url either, we should return JSON response with error details or return "Not found status". Here we are redirecting to  ErrorController.APINotFound() action from there we are returning JSON result. The response http code will still be error. Only advantage here is that the clients will get details of the error or what went wrong in a secure manner. This is the better method which I could see instead of throwing http errors alone.

How to handle wrong AJAX requests

For this we had to modify one of the method in earlier code which is used to retrieve the Error action name. Now we need to look into the request header for the origin. If its originated from AJAX the value will be "XMLHttpRequest".

        private string GetErrorActionNameFrom(Exception ex, HttpContext context)
        {
            var action = "Index";
            if (!string.IsNullOrWhiteSpace( context.Request.Headers["X-Requested-With"]) &&
                context.Request.Headers["X-Requested-With"].Equals("XMLHttpRequest"))
            {
                action = "APINotFound";
            }
            else
            {
                var httpEx = ex as HttpException;
                if (httpEx != null)
                {
                    switch (httpEx.GetHttpCode())
                    {
                        case 404:
                            action = "NotFound";
                            break;
                        default:
                            action = "Index";
                            break;
                    }
                }
            }
            return action;
        }


        public ActionResult APINotFound()
        {
            return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
                Data = new { IsSuccess=false,Result="Not able to process your API request due to wrong url or unexpected errors"} };
        }

    function divide() {
        var n1 = $("#n1").val();
        var n2 = $("#n2").val();
        //Lets not bother about the data which is available in n1 and n2. Assume that those are numbers
        $.ajax({
            type: "GET",
            cache: false,
            url: "../Calculator/ivide",
            data: { "n1": n1, "n2": n2 },    // multiple data sent using ajax
            success: function (html) {
                if (html.IsSuccess) {
                    $("#res").val(html.Result);
                }
                else {
                    alert(html.Result);
                }
            },
            error: function (a, b, c) {
                alert(JSON.parse(a.responseText).Result);
            }
        });
    }
</script>

Sample can be download from sky drive. Now we can say out ASP.Net MVC application has an exception handling framework.

Monday, September 23, 2013

Not able to debug ASP.Net MVC application after windows password change

Some days back, I got a request from one of the team members to solve one issue in his machine. It was simple. He changed his windows login password. After that he is not able to debug ASP.Net MVC application. If he really understands about how his development environment is set up or he know how to google, this would not happen. As of him he gets the below error message when he try to debug MVC 4 application from Visual Studio. Immediately he shared his screen to me.
"Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging."
I had to start from the beginning such as how its running ? Is it from Visual Studio development server or IIS ? Its in IIS. So which app pool is been used? What is the identity of the application pool? We could see that its his windows login. Not the Network Service, ApplicationPool Identity or any other system accounts.

This gives the hint. He changed the windows password but he didn't updated the app pool identity. Updated the application pool identity with new password and things started working.

Happy debugging.

Tuesday, August 20, 2013

Dynamic rows with multiple file uploads in ASP.Net MVC

Scenario / Requirement

There is a dynamic grid with plus (+) button to add new rows. Each row has around 3 normal text columns and one column to upload file.

Solutions

Single post back

  • Render your model which is list / collection type using simple table layout
  • Make sure there is at least one item in the collection. That can be the empty item.
  • Use javascript / jQuery to clone a table row and append at the end.
  • Rename the id and name of the elements in new row to match the naming convention.
  • Use a submit button to post back the rows. You will get added rows in the model list.
For the above we had used the tutorial given in the below link. Thanks to Zorgo for the tutorial.

Now the multiple file upload part comes. To tackle that follow the below method.
  • Have one file input type in the rows which are rendered. Use the naming as follows
    • <input type="file" id='Skills_0__File' name='Skills_0__File' />
      
  • In the postback action method iterate through the Request.Files collection and get the streams
  • If the Request.Files[i].ContentLength = 0 avoid that file because the user had not selected file.

Pros

  • Easy to implement.

Cons

Anyway I had modified the sample I got from the above link and uploaded. It can be downloaded from my sky drive by clicking on the below icon.

Multiple post back

This approach works as follows
  • There will be 1 post back for each file and one posting for the entities.If there are 8 records, there will be separate 8 post backs for files and one posting for the entities.
  • Each file will be posted separately. It returns the file id ie an reference to the server side where its saved. (If its saved in SQL Server or other database the primary key)
  • Associate that id to the row to be saved using jQuery / javascript
  • Post back the rows (entities) and when its saved in the server side, the row can be linked to the uploaded file. (If its in database use the foreign key relation)
  • Need to use iFrame to do posting of file input.

Pros

  • Data size limitation in http post back is resolved.

Cons

  • There are chances that the file upload succeeds and the subsequent record saving didn't success. This will result in orphan files which needs to be cleared as maintenance task.

Chunking

This involves separate reading mechanism or ActiveX controls to send files in chunks. This is useful if you need to transfer really big files. After completing each file the server side id needs to be updated to the new records and save after all file uploads.

We are planning to go with the second approach because we are not sure about the size of the files we need to upload. If the size of the expected files is small we can go with the first approach. So decide yourselves based on your scenario.