ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

MVC 3.0 Hosting :: Embedding Microsoft Chart Controls on your Application

clock June 7, 2011 16:50 by author Administrator

Introduction

The Microsoft Chart controls are a series of classes in the System.Web.UI.DataVisualization.Charting namespace that allow web developers to ability to add charts to their ASP.NET applications. The most pertinent charting-related class is the Chart class, which contains information about the chart's appearance, series, charting areas, and so forth. In most of the demos and code samples we've explored thus far, we've used the Chart class as a Web control, adding the <asp:Chart> declarative markup to our ASP.NET page, setting a few properties and, occasionally, writing a few lines of code. When used as a Web control, the Chart class both creates the chart (as an image) and then renders an <img> element that points to the generated chart image.

Using the Chart Web control is a standard practice in a WebForms application, but it is not suggested when building an ASP.NET MVC application. (While it is possible to add Web controls - including the Chat Web control - to the views of an ASP.NET MVC application, it is generally frowned upon.) So, if we can't use the Chart Web control in an ASP.NET MVC application, how do we display a chart? In addition to being used as a Web control, the Chart class can also be used programmatically. It is quite possible to create a new Chart object, set some properties, plot the data points, and then generate the chart image. In fact, we looked at using this technique in an earlier installment, Programmatically Generating Chart Images, in which we saw (among other things) how to generate chart images programmatically and add them as attachments in an email message.

This article explores how to display charts in an ASP.NET MVC application. Read on to learn more!

An Overview of Displaying Charts in an ASP.NET MVC Application

Using the Chart Web control in an ASP.NET WebForms application typically involves adding the Chart control to a page, setting a few properties and, perhaps, writing a few lines of code. When a visitor arrives at such a page, the Microsoft Chart Controls take the data to be plotted, dynamically generates an image, and then stores this image either in memory. The Chart Web control itself doesn't return the binary contents of the image; rather, it renders an <img> element whose src attribute points to a file named ChartImg.axd, which grabs the just-created image file from memory and returns it. (This is a bit of an oversimplification and does not describe all of the possible ways the Chart Web control can generate and serve the chart image; refer to the Rendering the Chart article for a more in-depth examination on this topic.)

In an ASP.NET MVC application we do not have the Chart Web control or the ChartImg.axd file at our disposal. Instead, we are on the hook for:

    1. Defining a URL that, when visited, plots the chart data, generates chart image, and returns its contents, and
    2. Adding the HTML to our views to display the chart image

Consider an ASP.NET MVC application that displays sales data charts from the Northwind database. One chart of interest is the annual sales chart, which displays the total sales for all products in a specified category for a specified year (such as the total sales for all Beverages products in 1997). Our first step to displaying such a chart would be to define a URL that, when visited, would return the corresponding chart image. You have total flexibility in the URL pattern you choose to render a report. I like to create a controller named Charts with actions for each type of chart I offer, using querystring parameters to indicate the input parameters for the chart (if any). In other words, for the annual sales chart I'd use a URL pattern like Charts/SalesByYear?CategoryName=CategoryName&OrderYear=Year. With such a pattern in place, visiting www.yoursite.com/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997 would return the contents of an image file that displays the annual sales data for 1997 for those products in the Beverages category. Bear in mind that this URL returns just the image contents and not any other markup. To display the chart in a view you would add an <img> element to the view, like so:

<img ... src="/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997" />

I've created an ASP.NET MVC 2 application using C#, Visual Studio 2010, and ASP.NET 4, which is available for download at the end of this article. The remainder of this article shows how to display charts in an ASP.NET MVC application by walking through some of the more interesting aspects of this demo application.

Creating the Charts Controller and SalesByYear Action

In ASP.NET MVC, incoming URLs are mapped to actions, which are methods in a controller. Typically, actions return the HTML markup rendered by a view, but actions can actually return any kind of markup, including plain text, JSON, and binary content. In other words, it's quite possible to create an action that returns the binary contents of an image.

To display charts in an ASP.NET MVC application we need to create an action that returns the binary contents of a specific chart image. As I noted earlier in this article, I like to put all of my chart-generating actions in a single controller named Charts. The name of the action determines the URL that will be used to view a chart image. For example, in the demo application I created an action in the Charts controller named SalesByYear. A simplified version of this action is shown below:

public class ChartsController : Controller
{
   public ActionResult SalesByYear(string categoryName, int orderYear = 1995, bool showTitle = true)
   {
      ...
   }
}


Note that this action takes three input parameters: categoryName, orderYear, and showTitle. These input parameters are automatically assigned the values of the querystring parameters with a matching name. If a visitor requests the URL Charts/SalesByYear, without specifying any querystring parameters, the three input parameters will be assigned their default values - null, 1995, and true, respectively. However, if appropriately named querystring fields are present in the request, such as Charts/SalesByYear?CategoryName=Condiments&OrderYear=1996&ShowTitle=false, then the three input fields will be assigned those values - Condiments, 1996, and false, in this example. (The showTitle input parameter is used to indicate whether to display the chart title in the rendered image.)

The job of the SalesByYear action is to:

    1. Generate the annual sales chart for the requested category and year,
    2. Generating the chart image, and
    3. Return the chart image's binary contents

Back in the Programmatically Generating Chart Images article, we looked at how to work with charts in lieu of the Chart Web control by programmatically creating the Chart object, setting its properties, specifying its data points, and generating the chart image. To start, we need to create an instance of the Chart object and set properties like the Width and Height:

public ActionResult SalesByYear(string categoryName, int orderYear = 1995, bool showTitle = true)
{
   // Create the Chart object and set some properties
   var salesChart = new Chart() {
      Width = 600,
      Height = 400
   };
   ...

Next, we need to plot the chart's data points. There are a variety of ways to do this programmatically, as covered in the Plotting Chart Data installment. If you are going to be frequently creating charts through programmatic means, I recommend that you familiarize yourself with K. Scott Allen's ChartBuilder class, which provides a simple API for plotting the points in a Chart object. (Scott introduced his ChartBuilder class in Charting With ASP.NET And LINQ.)

The following four lines of code uses Scott's ChartBuilder class to create a Sales By Category chart. All of the heavy lifting is handled by the SalesByCategoryChartBuilder class, which we examined in a demo in Plotting Chart Data. (The SalesByCategoryChartBuilder class extends Scott's ChartBuilder class.) In a nutshell, the SalesByCategoryChartBuilder class takes two inputs - the category name and order year - and plots the gross sales for the specified year for all products in the specified category.

  
var builder = new SalesByCategoryChartBuilder(salesChart);
   builder.CategoryName = categoryName;
   builder.OrderYear = orderYear;
   builder.BuildChart();


After the BuildChart method has completed, the Chart object contains information about its chart areas, series, and, most importantly, its data points, which are the sales figures for each of the products in the specified category. At this point the title has been added to the chart, so we can hide it, if needed.

   if (!showTitle)
      salesChart.Titles[0].Visible = false;


We are now ready to generate the chart image! The Chart object has a SaveImage method that can save the chart image to a file or a stream. In this case we want to save the image to a stream so that we can send back the binary contents directly to the client without having to first save the image to disk on the web server. To accomplish this, we: create a new MemoryStream object; save the image as a PNG, sending the image contents to the just-created MemoryStream; return to the beginning of the stream; and then return the binary contents of the stream to the client, specifying a content-type of "image/png", which tells the browser that the binary data it is receiving the binary contents of a PNG image.

   // Save the chart to a MemoryStream
   var imgStream = new MemoryStream();
   salesChart.SaveImage(imgStream, ChartImageFormat.Png);
   imgStream.Seek(0, SeekOrigin.Begin);
   // Return the contents of the Stream to the client
   return File(imgStream, "image/png");
}

That's all there is to it! With this code in place, visiting www.yoursite.com/Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998 returns the following image:

The sales for Condiments in 1998 chart.



Displaying the Chart in a View

At this point we have a URL that, when visited, generates the chart image and returns it. The next question is, how do we display this chart in a view? Because we have a URL that, when requested, returns an image, we can display this image in a web page by using the <img> element. For example, in the demo application's Home controller's Index view you'll find the following <img> element, which displays the annual sales chart for the Beverages category for 1997:

<div style="text-align: center">
   <img ... src="/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997" />
</div>


To facilitate displaying charts, I added a number of extension methods to the HtmlHelper class - see the MyHtmlHelpers.cs class in the demo. This adds a Chart extension method to HtmlHelper, allowing you to use syntax in your view like <%: Html.Chart(actionName, controllerName, routeValues) %>. This renders an <img> element with the appropriate src attribute. (For more information on creating your own custom HTML helpers, refer to Creating Custom HTML Helpers.) For example, the following syntax renders the same <img> element from the code snipped above:

<div style="text-align: center">
   <%: Html.Chart("SalesByYear", "Charts", new { CategoryName="Beverages", OrderYear = 1996 }) %>
</div>


What's more, the Chart extension method also can accept a collection of HTML attributes. For example, the following syntax generates an <img> element whose src attribute references the Charts/SalesByYear?CategoryName=Beverages&OrderYear=1996 URL and whose alt attribute is set to "Beverage sales for 1996."

<div style="text-align: center">
   <%: Html.Chart("SalesByYear", "Charts", new { CategoryName="Beverages", OrderYear = 1996 }, new { alt = "Beverage Sales for 1996" }) %>
</div>


The demo includes two views for displaying the annual sales data. The first one is Home/SalesData, which contains a form with two drop-down lists, one for the set of categories and another for the available years. The screen shot below shows this view in action.

The sales for the Meat/Poultry products in 1997.


The second view, Home/SalesDataFancy, hides the title in the chart and instead replaces it with text so that the category name and year can be displayed as drop-down lists. In this example, I use JavaScript and jQuery to change the URL of the <img> element whenever the drop-down list selection changes. For example, imagine the user is viewing the sales for the Condiments category for 1998. In that case, the <img> element on the page will have its src attribute referencing Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998. If the user then changes the categories drop-down list to Seafood, rather than doing a postback or requiring the user to click a button, I execute JavaScript code that changes the src of the <img> tag from Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998 to Charts/SalesByYear?CategoryName=Seafood&OrderYear=1998. This has the effect of instantaneously changing the chart and does not require an extra click from the user or the entire page to be reloaded.

The sales for the Condiments products in 1998.


Conclusion

The Microsoft Chart controls include a Chart Web control that simplifies adding charts to an ASP.NET WebForms application. While this Web control can be used in an ASP.NET MVC view, mixing Web controls in MVC views is generally frowned upon. Fortunately, a chart's image can be generated programmatically and its binary contents returned from an action. In this way, it is possible to associate a URL - like Charts/SalesByYear?CategoryName=CategoryName&OrderYear=Year with the image contents of a particular type. Once such a URL has been defined and the action implemented, displaying the chart in a view is as simple as adding an <img> element whose src attribute points to the URL. To simplify this process, I created an extension method for the HtmlHelper class named Chart, which you can find in the demo available for download at the end of this article.

Happy Programming!

 

Currently rated 1.6 by 39 people

  • Currently 1.589743/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: Working with Razor Syntax RenderSection, RenderBody and RenderPage

clock May 8, 2011 17:23 by author Administrator

Everybody knows Razor is the new view engine ASP.NET Web Pages, so we thought we could write about some Razor syntax you may not be aware of. The three methods we’ll be focusing on today are RenderBody, RenderPage and RenderSection. You’ll need to understand how each of these work if you want to get know the Razor syntax intimately. This code also works in WebMatrix if you're using it.

Before moving on, you need to download ASP.NET MVC 3.
Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. Now it's time to start coding! we’ll begin with the RenderBody method.

RenderBody

The RenderBody method resides in the master page, or in Razor this is commonly referred to as the Layout page. There can only be one RenderBody method per Layout page. If you’re from Web Forms world, the easiest way to think of RenderBody is it’s like the ContentPlaceHolder server control. The RenderBody method indicates where view templates that are based on this master layout file should “fill in” the body content.



RenderPage

Layout pages can also contain content that can be filled by other pages on disk. This is achieved by using the RenderPage method. This method takes either one or two parameters. The first is the physical location of the file, the second is an optional array of objects that can be passed into the page. Add a new cshtml file to the Shared folder and call it _Header.cshtml. We've prefixed this file with an underscore because we don't want this file to be called outside of RenderPage. By default, ASP.NET will not serve pages beginning with an underscore. Here's the code we’re adding to the _Header.cshtml page.

<h1>Header Here</h1>

And to use this in the layout, it's as easy as this.



RenderSection

Layout pages also have the concept of sections. A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file, whereas RenderSection runs code blocks you define in your content pages. The following code illustrates how to render a footer section.


RenderSection expects one parameter and that is the name of the section. If you don’t provide that, an exception will be thrown. Views can add data to sections by using the following code.


If you ran the website now it’ll run without error. If on the other hand you don’t include the section footer in the view, you’ll get an error.


That’s because by default, sections are mandatory. To make sections optional, just add the second parameter, which is a Boolean value.


Now things will run just fine.

These three methods you will use time and time again when you're using the Razor view engine. This code works both for ASP.NET MVC 3 and also WebMatrix. Have fun!

      

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: Analyzing AllowHtml Attribute in ASP.NET MVC 3.0

clock March 31, 2011 15:10 by author Administrator

Let's say we are creating a simple form in our ASP.NET MVC 3 web application and there is a Body field on the form where we want to allow HTML Tags.

If we do not disable request validation in some manner for this Body field, we will get the dreaded error - A potentially dangerous Request.Form value was detected from the client (Body = "<br>").


Request validation is a good thing since it keeps people from injecting script tags in our application for Cross-Site Scripting ( XSS ) attacks. However, in this case we want to disable request validation on the Body Field so we can put HTML in the body of our blog posts.

ValidateInput Attribute

In ASP.NET MVC 2 we used the ValidateInput Attribute on the action to disable request validation for the entire request

The downfall of this approach is that the ValidateInputAttribute disables request validation on all model properties, and we just want to disable request validation on a single property, called Body.

AllowHtmlAttribute in ASP.NET MVC 3

In ASP.NET MVC 3 we now have a property attribute that we can include on model properties to disable request validation on a property by property basis, called AllowHtmlAttribute. Instead of using the ValidateInputAttribute on the action, we turn off request validation just on Body by adding the [AllowHtml] Attribute to it:


This allows HTML for the Body Property, but does not allow HTML for the Title Property, which is what we want.

[Note: Briefly in ASP.NET MVC 3, before it was released, there existed a SkipRequestValidationAttribute. It no longer exists and has been renamed to AllowHtmlAttribute.]

   

Currently rated 1.5 by 4 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: Working with Custom Authorisation in ASP.NET MVC Framework

clock March 30, 2011 16:20 by author Administrator

The whole advantage with MVC over webforms is extensibility at every point. Extensibility, Extensibility, Extensibility.

Authorization is a very important and every web project has there own needs and requirements. Full customisation is paramount.

Here I will show you a simple way to customise your authorization.

In MVC attributes are used to protect a controller method, so we to get started all we need to do is inherit from the AuthorizeAttribute class.

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string[] users = Users.Split(',');
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            if (users.Length > 0 &&
                !users.Contains(httpContext.User.Identity.Name,
                    StringComparer.OrdinalIgnoreCase))
                return false;
            return true;
        }
    }

This is the basics. We can put any logic we like in here and all we have to do is return false if for whatever reason the user should not be authorized. Then all you need to do is decorate the controller method with the new attribute as below.

    [CustomAuthorize]
    public ActionResult Index()
    {
        return View();
    }

From this simple example we can expand it with custom Roles.

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        // the "new" must be used here because we are hiding
        // the Roles property on the underlying class
        public new SiteRoles Roles;
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            string[] users = Users.Split(',');
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            SiteRoles role = (SiteRoles)httpContext.Session["role"];

            if (Roles != 0 && ((Roles & role) != role))
                return false;
            return true;
        }
    }

Where the SiteRoles class is defined as below.

    [Serializable]
    [Flags]
    public enum SiteRoles
    {
        User = 1 << 0,
        Admin = 1 << 1,
        Helpdesk = 1 << 2
    }

This can then be used be used as follows.
    [CustomAuthorize(Roles=SiteRoles.Admin|SiteRoles.HelpDesk)]
    public ActionResult Index()
    {
        return View();
    }

This will only allow the Admin and the Helpdesk Role access to the Index controller. If you don’t belong to one of these roles then you will be sent to the Login page.

The possibilities are really endless.

Happy coding.

Currently rated 2.1 by 12 people

  • Currently 2.083333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3.0 Hosting :: ASP.NET MVC 3.0 Validation and IValidatableObject

clock March 27, 2011 19:04 by author Administrator

I was working with ASP.NET MVC 3 validation today and was tickled to learn of the support for IValidatableObject. I mainly like to use the Enterprise Library Validation Application Block in my projects, but System.ComponentModel.DataAnnotations has come a long way in .NET Framework 4.

[Aside: Note in the following post I interchange “object“, “model“, and “self” validation.] IValidatableObject for Self Validation

For those of you who are familiar with Enterprise Library, you know it has two attributes that can be used for self validation of an object: HasSelfValidation and SelfValidation. The idea here is that there is model validation that may need to happen as a whole in addition to just property validation. Or, maybe validation is so complex that you don't want to use validation attributes and just want to do all validation “manually“ in a method. Self validation in Enterprise Library gives you opportunity to do this.

In the DataAnnotations world, you get this same kind of model or object validation by implementing IValidatableObject. ASP.NET MVC 3 has built-in support for IValidatableObject, so after propery validation it will fire off object validation if your object implements IValidatableObject. An example is shown below:

  

In this trivial example, I test to see if ConfirmPassword equals Password during registration using IValidatableObject. If they don't match, this is a validation error and I return a ValidationResult with the error. Pretty simple stuff.

IValidatableObject Doesn't Always Fire

There is a gotcha here that may not be obvious. IValidatableObject in ASP.NET MVC 3 will not fire if there are property-level errors. As I mentioned, ASP.NET MVC 3 property validation occurs before object validation. If there are property errors, ASP.NET MVC 3 by design will not fire IValidatableObject so as not to return false positives ( thanks to Brad Wilson of Microsoft for confirming this today ). For those of you who use EnterpriseLibrary and Self Validation where Enterprise Library combines the results, this might not seem obvious and could trip you up. ASP.NET MVC 3 does not combine the results.

In the case above, if the username is not provided ( yet as shown is required ), but both password and confirm password are provided, IValidatableObject will not fire and confirm the passwords match. IValidatableObject will not fire until all property-level validators validate, regardless if the properties play a part in the self-validation or not.

Personally I don't find this an issue, but just wasn't expecting it with all my years of Enterprise Library Validation Application Block experience.

A Note About ValidationAttribute in .NET Framework 4

Just a quick note about ValidationAttribute in System.ComponentModel.DataAnnotations. The ValidationAttribute in .NET 4 has been beefed up with a ValidationContext Class being passed in the validate method. ValidationContext contains the entire object being validated during property validation. You could create a custom validation attribute and place it on Password or ConfirmPassword for property comparison. That is certainly a workaround if you want to return the password comparison error regardless if other non-involved properties do not validate.

 

Currently rated 3.0 by 4 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: Working with ASP.NET MVC 3 RedirectPermanent syntax

clock March 23, 2011 16:42 by author Administrator

I am converting an ASP.NET WebForms website to ASP.NET MVC 3 for a client and by choice we are changing the URL structure as well. Because this may be a common situation, Microsoft introduced a new RedirectPermanent method on Response in ASP.NET 4.0.

If you take a peek at ASP.NET MVC 3, you will see new ActionResult Classes that do the same thing. You are probably familiar with Redirect, RedirectToAction, and RedirectToRoute, but now there are versions of these ActionResult Classes for permanent redirects: RedirectPermanent, RedirectToActionPermanent, and RedirectToRoutePermanent:  


Although out of the scope of this post, for search engine optimization benefits you will want to permanently redirect to the new location of a resource that has permanently moved by issuing an HTTP 301. The previous results only issue an HTTP 302, which means the resource has only temporarily moved.
  

Hope this helps.

Currently rated 1.9 by 40 people

  • Currently 1.85/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3.0 Hosting :: How to Create and Maintain SessionLess Controllers in ASP.NET MVC 3

clock March 22, 2011 17:43 by author Administrator

One of the new features in ASP.NET MVC 3 is the [SessionState] Attribute that can be decorated on controllers. Using the attribute, you can completely turn on or off session state, adjust it to readonly, or make it required using a SessionStateBehavior Enum with the following choices:

- Default - The default ASP.NET logic is used to determine the session state behavior for the request. The default logic looks for the existence of marker session state interfaces on the IHttpHandler.
- Required - Full read-write session state behavior is enabled for the request. This setting overrides whatever session behavior would have been determined by inspecting the handler for the request.
- ReadOnly - Read-only session state is enabled for the request. This means that session state cannot be updated. This setting overrides whatever session state behavior would have been determined by inspecting the handler for the request.
- Disabled - Session state is not enabled for processing the request. This setting overrides whatever session behavior would have been determined by inspecting the handler for the request.

Turning off session state using the new SessionState Attribute in ASP.NET MVC 3 would look like this:



Obviously if session state is disabled we should no longer try to use the Session Property on the Controller as it will be null. Turning off session state and using the Session Property will give you the dreaded “object reference not set to an instance of object” error:




TempData and Session State

One thing that might not be so obvious is that the default provider for TempData uses session state ( SessionStateTempDataProvider ). Therefore if you turn off session state for the request but then try to access TempData you will get an error. Here is the use of TempData and the default SessionStateTempDataProvider:



and here is “The SessionStateTempDataProvider class requires session state to be enabled” exception you will receive:



If you still want to disable session state but use TempData, create a different provider for it that uses browser cookies for example. As it so happens, you can find a CookieTempDataProvider in ASP.NET MVC 3 Futures

Session State and Child Actions

The TempData scenario may be obvious, but this child action scenario may not be so obvious. Let's say we turned off session state in the parent controller and then we call a child action in a different controller using Html.RenderAction or Html.Action from within the view.



Does the child action have access to TempData and Session? The Child Controller looks like this:



Even though we did not disable session state on this controller, we won't have access to Session State or TempData in the child action because session state was disabled in the parent controller. The same errors mentioned above will occur.

Child Actions vs. Ajax Requests

Don't confuse ajax requests with child actions. I don't suspect you would, but the question has come up before. A child action is kicked off using Html.RenderAction or Html.Action in a view. Ajax requests coming from the browser are not child actions, but completely separate requests into the application. If you use jQuery within a view to grab data from the same action used above, called ChildAction, the action will have full access to session state since the request is no longer a child action but a normal request coming into the application.



I changed the controller to just grab the SessionId which will work fine:



Of course, this is true of any direct request to the action (e.g. http://.../child/childaction ). That request would no longer be a child action, but a regular ol' request. Since it is a regular request through this controller and session state has not been disabled using the [SessionState] Attribute or other means, session state is enabled and fully accessible.

Why Bother With SessionLess Controllers

The big question becomes why bother with SessionLess Controllers in ASP.NET MVC 3 if we have to tip-toe around TempData, ChildActions, etc?

Well, the use of session state has mainly been an issue of scalability, but things are changing a bit with heavy use of Ajax in the browser. One big drawback of using Session State is that concurrent requests to session state within the same session must be done one at a time when done with full read-write access. You cannot access session state in parallel with full read-write privileges as data corruption can occur. Therefore if you have multiple, concurrent requests from the same session they will need to be performed one at a time rather than in parallel.

When does this become a big deal? Mainly when concurrent ajax requests from the browser are firing off in the background in the same user session. If session state is enabled with full read-write privileges, those scripts cannot be run in parallel as they could corrupt session state. They will be executed one-at-a-time and possibly deteriorate the responsiveness of the UI.

A way to get multiple, concurrent requests in the same session to perform in parallel would be to completely disable session state or make it read only when it is indeed read only.

Conclusion

A new feature in ASP.NET MVC 3 is the ability to specify session state behavior on controllers using the new [SessionState] Attribute. Although there are some challenges, they can easily be managed if you need to squeeze out every ounce of scalability and responsiveness from your application.

Hope this helps.

Currently rated 1.8 by 41 people

  • Currently 1.780487/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: Things to know on MVC3's GlobalFilters and HandleErrorAttribute

clock March 21, 2011 18:20 by author Administrator

In MVC3 a GlobalFilterCollection has been added to the Application_Start. This allows you to register filters that will be applied to all controller actions in a single location. Also, MVC3 web applications now add an instance of HandleErrorAttribute to these GlobalFilters by default. This means that errors in the MVC pipeline will now be automatically handled by these attributes and never fire the HttpApplication's OnError event.

This is nice because it is another step away from the old ASP.NET way of doing things, and a step toward the newer cleaner MVC way of doing things.

Out With the Old

Our old HttpModule wired up to the HttpApplication's OnError event and used that to log unhandled exceptions in web applications. It didn't care if the error happened in or out of the MVC pipeline, either way it was going to bubble up and get caught in the module.

public virtual void Init(HttpApplication context)
{
   InsightManager.Current.Register();
   InsightManager.Current.Configuration.IncludePrivateInformation = true;
   context.Error += OnError;
}

private void OnError(object sender, EventArgs e)
{
   var context = HttpContext.Current;
   if (context == null)
       return;
   Exception exception = context.Server.GetLastError();
   if (exception == null)
       return;

   var abstractContext = new HttpContextWrapper(context);   InsightManager.Current.SubmitUnhandledException(exception, abstractContext);
}

However, now the MVC HandleErrorAttribute may handle exceptions right inside of the MVC pipeline, meaning that they will never reach the HttpApplication and the OnError will never be fired. What to do, what to do...

In With the New

Now we need to work with both the attributes and the HttpApplication, ensuring that we will catch errors from both inside and outside of the MVC pipeline. This means that we need to find and wrap any instances of HandleErrorAttribute in the GlobalFilters, and still register our model to receive notifications from the HttpApplications OnError event.

The first thing we had to do was create a new HandleErrorAttribute. Please note that this example is simplified and only overrides the OnException method. If you want to do this "right", you'll have to override and wrap all of the virtual methods in HandleErrorAttribute.

public class HandleErrorAndReportToInsightAttribute : HandleErrorAttribute
{
   public bool HasWrappedHandler
   {
       get { return WrappedHandler != null; }
   }

   public HandleErrorAttribute WrappedHandler { get; set; }
   public override void OnException(ExceptionContext filterContext)
   {
       if (HasWrappedHandler)
           WrappedHandler.OnException(filterContext);
       else
           base.OnException(filterContext);
       if (filterContext.ExceptionHandled)           InsightManager.Current.SubmitUnhandledException(filterContext.Exception, filterContext.HttpContext);   }
}

Next we needed to update our HttpModule to find, wrap, and replace any instances of HandleErrorAttribute in the GlobalFilters.

public virtual void Init(HttpApplication context)
{
   InsightManager.Current.Register();
   InsightManager.Current.Configuration.IncludePrivateInformation = true;
   context.Error += OnError;
   ReplaceErrorHandler();
}

private void ReplaceErrorHandler()
{
   var filter = GlobalFilters.Filters.FirstOrDefault(f => f.Instance is HandleErrorAttribute);
   var handler = new HandleErrorAndReportToInsightAttribute();
   if (filter != null)
   {
       GlobalFilters.Filters.Remove(filter.Instance);
       handler.WrappedHandler = (HandleErrorAttribute) filter.Instance;
   }
   GlobalFilters.Filters.Add(handler);
}

In Conclusion
Now when we register the InsightModule in our web.config, we will start capturing all unhandled exceptions again.

<configuration>
 <configSections>
   <section name="codesmith.insight" type="CodeSmith.Insight.Client.Configuration.InsightSection, CodeSmith.Insight.Client.Mvc3" />
 </configSections>
 <codesmith.insight apiKey="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" serverUrl="http://app.codesmithinsight.com/" />
 <system.web>
   <customErrors mode="On" />
   <httpModules>
     <add name="InsightModule" type="CodeSmith.Insight.Client.Web.InsightModule, CodeSmith.Insight.Client.Mvc3"/>
   </httpModules>
 </system.web>
</configuration>

Currently rated 2.6 by 14 people

  • Currently 2.642857/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: 13 ASP.NET MVC Extensibility Points You Must to Know

clock April 29, 2010 14:37 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

One of the main design principles ASP.NET MVC has been designed with is extensibility. Everything (or most of) in the processing pipeline is replaceable so, if you don’t like the conventions (or lack of them) that ASP.NET MVC uses, you can create your own services to support your conventions and inject them into the main pipeline.

In this post we are going to show 13 extensibility points that every ASP.NET MVC developer should know, starting from the beginning of the pipeline and going forward till the rendering of the view.

1. RouteConstraint

Usually you could put some constrains on url parameters using regular expressions, but if your constrains depend on something that is not only about the single parameter, you can implement the
IRouteConstrains’s method and put your validation logic in it.

One example of this is the validation of a date: imagine an url that has year, month and date on different url tokens, and you want to be able to validate that the three parts make a valid date.

2. RouteHandler

Not really specific to ASP.NET MVC, the
RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm.

3. ControllerFactory

The controller factory is the component that, based on the route, chooses which controller to instantiate and instantiate it. The default factory looks for anything that implements
IController and whose name ends with Controller, and than create an instance of it through reflection, using the parameter-less constructor.

But if you want to use Dependency Injection you cannot use it, and you have to use a IoC aware controller factory: there are already controller factory for most of the IoC containers. You can find them in MvcContrib or having a look at the Ninject Controller Factory.

4. ActionInvoker

ActionInvoker is responsible for invoking the action based on it’s name. The default action invoker looks for the action based on the method name, the action name and possibly other selector attributes. Then it invokes the action method together with any filter defined  and finally it executes the action result.

If you read carefully you probably understood that most of the execution pipeline is inside the logic of the default
ControllerActionInvoker class. So if you want to change any of these conventions, from the action method’s selection logic, to the way http parameters are mapped to action parameters, to the way filters are chosen and executed, you have to extend that class and override the method you want to change.

5. ActionMethodSelectorAttribute

Actions, with the default action invoker, are selected based on their name, but you can finer tune the selection of actions implementing your own Method Selector. The framework already comes with the
AcceptVerbs attribute that allows you to specify to which HTTP Verb an action has to respond to.

A possible scenario for a custom selector attribute is if you want to choose one action or another based on languages supported by the browser or based on the type of browser, for example whether it is a mobile browser or a desktop browser.

6. AuthorizationFilter

These kind of filters are executed before the action is executed, and their role is to make sure the request is “valid”.

There are already a few Authorization filters inside the framework, the most “famous” of which is the
Authorize attribute that checks whether the current user is allowed to execute the action. Another is the the ValidateAntiForgeryToken that prevents CSRF attacks. If you want to implement your own authorization schema, the interface you have to implement is IAuthorizationFilter. An example could be the hour of the day.

7. ActionFilter

Action Filters are executed before and after an action is executed. One of the core filters is the
OutputCache filter, but you can find many other usages for this filter. This is the most likely extension point you are going to use, as, IMHO, it’s critical to a good componentization of views: the controller only has to do its main stuff, and all the other data needed by the view must be retrieved from inside action filters.

8. ModelBinder

The default model binder maps HTTP parameters to action method parameters using their names: a http parameter named user.address.city will be mapped to the City property of the Address object that itself is a property of the method parameter named user. The
DefaultModelBinder works also with arrays, and other list types.

But it can be pushed even further: for example you might use it to convert the id of the person directly to the Person object looking up on the database. This approach is explained better in the following post Timothy Khouri (aka SingingEels): Model Binders in ASP.NET MVC. The code is based on the preview 5, but the concept remains the same.

9. ControllerBase

All controllers inherit from the base class
Controller. A good way to encapsulate logic or conventions inside your actions is to create you own layer supertype and have all your controllers to inherit from it.

10. ResultFilter

Like the ActionFiters, the ResultFilters are execute before and after the ActionResult is executed. Again, the OutputCache filter is an example of a ResultFilter. The usual example that is done to explain this filter is logging. If you want to log that a page has been returned to the user, you can write a custom RenderFilter that logs after the ActionResult has been executed.

11. ActionResult

ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions. But if you need some different kind of result you can write your own
ActionResult and implement the ExecuteResult method. For example, if you want to send a PDF file as result you could write your own ActionResult that use a PDF library to generate the PDF. Another possible scenario is the RSS feed: read more about how to write a RssResult in this post.

Look at implementing a custom action result when the only peculiarity is how the result is returned to the user.

12. ViewEngine

Probably you are not going to write your own view engine, but there are a few that you might consider using instead of the default WebForm view engine.

13. HtmlHelper

Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. There should be no code inside the views, so helpers come very handy for extracting the code from the view and putting it into something that is testable.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 1.9 by 34 people

  • Currently 1.882353/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: An Architectural View of the ASP.NET MVC Framework

clock April 27, 2010 19:35 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

Introduction

At DevConnections Fall and TechEd Europe, Microsoft recently unveiled the ASP.NET MVC Framework. MVC stands for Model-View-Controller and is one of the most popular design patterns for decoupling data access and business logic from data presentation and user interaction. At the time of this writing, the framework is not available yet, not even as a CTP. However, the first CTP is expected to ship in just a few weeks.

In any case, the ASP.NET MVC Framework is definitely worth a look since it addresses aspects of programming that are extremely important for developers and their productivity such as code reusability, testing, and separation of presentation and business logic concerns. At the same time, an early look at the MVC Framework may generate good feedback to Microsoft and help them to deliver a better and richer product in full accordance with the community expectations and needs.

Motivating the Hype on MVC

Most applications, and especially Web applications, have their presentation layer mixed up with some business logic and data access code. As an example, think of a classic ASP.NET page. You define the user interface by composing and configuring server controls until you obtain the desired markup. Next, you use a code-behind class to add some handlers for the various events fired by controls and provide any required glue code. In such pages, more often than not, data access code is interspersed with presentation logic. In ASP.NET 2.0, the introduction of data source controls certainly didn't make this mixture more unlikely. Some data source controls, such as the SqlDataSource control, are a sinful temptation for developers as they see in it the way to go down to SQL queries and stored procedures - the raw data - very quickly. Without beating the bush around, such ASP.NET pages whose code-behind classes contain a mixture of presentation, business and data access code, are quite difficult to maintain. And they are definitely challenging to test appropriately.

User interface facilities (i.e., wizards and tools in Visual Studio) tend to encourage developers to put in the presentation layer more than it should. The presentation layer acts as a catch-all for logic that reasonably belongs to other layers. At the end of the day, you can still have the application working and perform well. Behind the scene, though, you get a too high level of coupling and subsequently high costs of maintenance. What if, in fact, at some point you need to add a new feature or re-implement an existing one? Not having a well designed structure of classes and lacking a clean separation of presentation, business and data layers, most that you can do is cutting and pasting code and run pages over and over again to test results against expectations.

There's not much of reusability too, but quite the reverse we'd say. Code duplication is not unlikely and the need of changing the view for the same data may often result in serious trouble.

Sure, there are architectural design patterns to give you guidance on the best way to design Web applications with cleanly separated layers. However, these patterns require a lot of coding, sometimes repetitive code, which doesn't always sit well with the rush of delivering applications that just work. While the startup costs of implementing recognized patterns manually will certainly pay you off in the context of complex enterprise applications, it seems to be an unnecessary complication in simpler, but still realistic, scenarios.

The classic code-behind model of ASP.NET provides the tools for building great and well-designed applications, but it leaves most of it up to the individual developer or team. As a result, too many applications out there work well, but are not well designed. Over the years, this fact raised the need of a radically different approach to Web programming. The MVC pattern was soon identified as an excellent approach to Web development. MVC ensures a clean separation between the data model and the user interface in such a way that changes to the user interface don't affect data handling. At the same time, the data model and related access code can be refactored without the need of changing the user interface accordingly.

Where Did We See This Already?

Tools like Castle MonoRail have been created to simplify Web development by leveraging the MVC pattern. Where's the difference between MonoRail and ASP.NET? It mostly lies in an extremely simplified form of the code that backs a page up. It's like breaking the code you have in, and reference from, the code-behind class into distinct elements. The controller handles application flow; the model represents the data; the view takes care of presentation. The underlying engine automates some tasks for you (i.e., binding data to form elements) and exposes just plugs for you to connect and customize the engine. As a result, you write less code and have highly specialized components that are easier to test and maintain.  

At the same time, MonoRail is not necessarily better than Web Forms and may not be the right choice for just everybody. Because it propounds a different paradigm, it may not be the ideal environment for those who have strong ASP.NET skills and find it difficult (or just not affordable) to convert large applications.

By the way, regardless of the Mono prefix in the name there's no necessary connection between this project and the Mono project aimed at providing the code to run .NET applications on multiple platforms.

Comparing the MVC Framework to Classic ASP. Net

The ASP.NET MVC Framework is essentially the Microsoft's attempt to create an ASP.NET programming environment centered around the MVC pattern. For the time being (nobody can reasonably foresee future evolutions), the MVC Framework should be considered an alternative to Web Forms. To some extent, the MVC Framework and Web Forms have in common more or less what cars and motorcycles share. Both can take you somewhere else, but with different speed, comfort, sense of freedom, size of the trunk.

The MVC Framework doesn't support classic postbacks and viewstate and doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class. In ASP.NET, you have a 1:1 correspondence between a URL and a resource. The only exception to this rule is when you use completely custom HTTP handlers bound to a particular path.

In the MVC Framework, a URL is seen as the mean to address a logical server resource, but not necessarily an ASPX file to parse. So the URLs employed by the pages of an MVC Framework application have a custom format that the application itself mandates. In the end, the MVC Framework employs a centralized HTTP handler that recognizes an application-specific syntax for links. In addition, each addressable resource exposes a well-known set of operations and a uniform interface for executing operations.

Have you ever heard about Representational State Transfer, or REST for short?

Well, REST is an architectural pattern that defines how network resources should be defined and addressed in order to gain shorter response times, clear separation of concerns between the front-end and back-end of a networked system. REST is based on three following principles:

1. An application expresses its state and implements its functionality by acting on logical resources
2. Each resource is addressed using a specific URL syntax
3. All addressable resources feature a contracted set of operations

As you can see, the MVC Framework fulfills it entirely.

So here's an alternate way of looking at the MVC Framework. It is an ASP.NET framework that performs data exchange by using a REST model versus the postback model of classic ASP.NET. Each page is split into two distinct components -controller and view - that operate over the same model of data. This is opposed to the classic code-behind model where no barrier is set that forces you to think in terms of separation of concerns and controllers and views. However, by keeping the code-behind class as thin as possible, and designing the business layer appropriately, a good developer could achieve separation of concerns even without adopting MVC and its overhead. MVC, however, is a model superior to a properly-done code-behind for its inherent support for test-driven development.

While MVC is definitely a key part of the framework, we wouldn't consider it is the most compelling part. REST is a possible alternative to the postback model, whereas MVC is an alternative to code-behind.

Explaining the MVC Framework to ASP. Net Developers

We wonder what's the quickest and most effective way to explain the MVC Framework to seasoned ASP.NET developers. It's like having a central HTTP handler that captures all requests to resources identified with a new extension. This HTTP handler analyzes the syntax of the URL and maps it to a special server component known as the controller. The controller supports a number of predefined actions. The requested action is somehow codified in the URL according to an application-specific syntax. The central HTTP handler invokes the action on the controller and the controller will process the request up to generating the response in whatever response format you need. The response is generated through a view component.

What here we called the "central HTTP handler" plays the same role that was of the System.Web.UI.Page class in classic ASP.NET. The Page is the handler responsible for any .aspx request
and generates the markup using the code-behind class and serves it back using postbacks. In the MVC Framework, this pattern - hard-coded in the ASP.NET runtime and not subject to change until the whole ASP.NET platform is rewritten - is simply implemented using an alternative HTTP handler and an alternative model based on REST and MVC.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 2.3 by 8 people

  • Currently 2.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in