Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET MVC 3 Hosting - ASPHostPortal :: How to Create a blog with JQuery Mobile and ASP.NET MVC 3 with C#

clock September 12, 2011 08:26 by author Jervis

First, I created a new project and then used the Library Package Manager to add the (Code First) Entity Framework (CTP5) to the project.










I then added a class called Post to the Models folder with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;   

namespace MobileBlog.Models
{
    public class Post
    {
        public int ID { get; set; }
        public string Title { get; set; }
        [DataType(DataType.MultilineText)]
        public string Content { get; set; }
        public DateTime PublishDate { get; set; }
    }   

    public class PostDBContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
    }
}

This re-creates the same scheme I had for the PHP/MySQL Mobile Blog project. I also then created another class to the Models folder called PostInitializer to re-create the database and seed it with data as required. Here is the code for that class:

using System;
using System.Collections.Generic;
using System.Data.Entity.Database;   

namespace MobileBlog.Models
{
    public class PostInitializer : DropCreateDatabaseIfModelChanges<PostDBContext>
    {
        protected override void Seed(PostDBContext context)
        {
            var posts= new List<Post> {    

                 new Post { Title = "My new blog",
                             Content = "This is my first blog post...",
                             PublishDate= DateTime.Now},    

                 new Post { Title = "Second post",
                             Content = "This is my second blog post. Hi!",
                             PublishDate= DateTime.Now}
             };
            posts.ForEach(d => context.Posts.Add(d));
        }
    }
}

That requires a change to the web.config (for the connection string) and the Global.asax.cs file.

To the Application_Start() in the Global.asax.cs file I added the following line:

DbDatabase.SetInitializer<PostDBContext>(new PostInitializer());

…as well as this:

using System.Data.Entity.Database;

using MobileBlog.Models;

The connection string for the web.config file is as follows:


<connectionStrings>
  <add name="PostDBContext"
       connectionString="Server=.\SQLEXPRESS;
       Database=Posts;Trusted_Connection=true"
       providerName="System.Data.SqlClient" />
</connectionStrings>

Going into the Views/Shared folder no I modified the _Layout.cshtml file to be a good template for the project and to be in HTML5 format as well as to use the JQuery CDN to import the JQuery and JQuery Mobile frameworks.

<!DOCTYPE html>
<html lang="en-us" >
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MobileBlog</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
    <script src="http://code.jquery.com/jquery-1.5.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
</head>
<body>
    <div data-role="page">
        <div data-role="header">
            <h1>@ViewBag.HeaderString</h1>
        </div>
        <div data-role="content">
            @RenderBody()
        </div>
        <div data-role="footer"><h1>- MobileBlog -</h1></div>
    </div>
</body>
</html>

I then added a HomeController with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileBlog.Models;   

namespace MobileBlog.Controllers
{
    public class HomeController : Controller
    {
        PostDBContext db = new PostDBContext();   

        public ActionResult Index()
        {
            ViewBag.HeaderString = "Welcome!";
            return View();
        }   

        public ActionResult Create()
        {
            ViewBag.HeaderString = "Create New Post";
            return View();
        }   

        public ActionResult Read()
        {
            ViewBag.HeaderString = "Read Blog";   

            var posts = from p in db.Posts
                         select p;   

            return View(posts.ToList());
        }   

        public ActionResult About()
        {
            ViewBag.HeaderString = "About MobileBlog";
            return View();
        }   

        [AcceptVerbs(HttpVerbs.Post)]
        public string SavePost(string title, string content)
        {
            Post post = new Post();
            post.Title = title;
            post.Content = content;
            post.PublishDate = DateTime.Now;   

            if (ModelState.IsValid)
            {
                db.Posts.Add(post);
                db.SaveChanges();
                return "SUCCESS";
            }
            else
            {
                return "FAILED";
            }
        }
    }
}

From that controller I generated views for the following pages: About, Create, Index, and Read.

File: About.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}   

<div data-role="fieldcontain">
    <p><a href="http://windows2008hosting.asphostportal.com">MobileBlog</a></p>
    <p>Created by: <a href="http://twitter.com/jervis">Jervis</a></p>
    <p>Powered by: <a href="http://jquerymobile.com">JQuery Mobile</a></p>
</div>

File: Index.cshtml

@{

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

<ul data-role="listview">
    <li>
        @Html.ActionLink("Create New Post", "Create")
    </li>
    <li>
        @Html.ActionLink("Read Blog", "Read")
    </li>
    <li>
        @Html.ActionLink("About MobileBlog", "About")
    </li>
</ul>

File: Create.cshtml

@model MobileBlog.Models.Post   


@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}   

<script type="text/javascript">
    function resetTextFields()
    {
        $("#Title").val("");
        $("#Content").val("");
    }   

    function onSuccess(data, status)
    {
        resetTextFields();
        // Notify the user the new post was saved
        $("#notification").fadeIn(2000);
        data = $.trim(data);
        if(data == "SUCCESS")
        {
            $("#notification").css("background-color", "#ffff00");
            $("#notification").text("The post was saved");
        }
        else
        {
            $("#notification").css("background-color", "#ff0000");
            $("#notification").text(data);
        }
        $("#notification").fadeOut(5000);
    }   

    $(document).ready(function() {   

        $("form[action$='SavePost']").submit(function () {
            $.ajax({
                url: $(this).attr("action"),
                type: "post",
                data: $(this).serialize(),
                success: onSuccess
            });
            return false;
        });   

        $("#cancel").click(function(){
            resetTextFields();
        });
    });   

</script>
using (Html.BeginForm("SavePost", "Home", FormMethod.Post))
{
    <div data-role="content">
        <form id="newPostForm">
            <div data-role="fieldcontain">
                @Html.LabelFor(model => model.Title, "Post Title")
                @Html.EditorFor(model => model.Title)   

                @Html.LabelFor(model => model.Content, "Post Content")
                @Html.TextAreaFor(model => model.Content)   

                <fieldset class="ui-grid-a">
                    <div class="ui-block-a">@Html.ActionLink("Cancel", "Index", null, new { @data_role = "button" })</div>
                    <div class="ui-block-b"><button data-theme="b"
id="submit" type="submit">Submit</button></div>

                </fieldset>
                <h3 id="notification"></h3>
            </div>
        </form>
    </div>
}

File: Read.cshtml


@model IEnumerable<MobileBlog.Models.Post>   

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}   

<script type="text/javascript">
    $(document).ready(function() {
        $("#refresh").click(function(){
            location.reload();
        });
    });   

</script>   

<button data-theme="b" data-role="button" data-iconpos="left" id="refresh" type="button" data-icon="refresh">Refresh</button>
<ul data-role="listview" data-theme="d" data-inset="true">   

    @foreach (var post in Model) {
        <li><h2>@post.Title</h2>@post.Content<p class="ui-li-aside"><strong>@post.PublishDate</strong></p></li>
    }
</ul>

So the code is familiar to the PHP code in most regards. Running the project in the Android emulator I get the same results as the PHP project before. BTW, I used the following address (because the Android emulator currently can’t use localhost for this type of thing):









Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Implement Elmah in MVC Application for error log

clock August 30, 2011 05:16 by author Jervis

In this article, I will show you how to configure Elmah in MVC 3.0 Application. Elmah is Open source code so you also download a code also for any modification. Below is the URL for Elmah code and download.

http://code.google.com/p/elmah/

Along with this kind of feature they are providing good UI also to view all log with details along with download functionality. Elmah can be fit in any .net application with below error log mechanism.

1. Log in XML file
2. Log in SQL database
3. Log in Mail (sent an email to provided email address)
4. Log in Oracle database
5. Log in Access database

So, let we start this tutorial.

Select Project > Click on Right Click > Select “Add Library Package Reference”  and search elmah and install that in your application

Now you have to add below xml tag in your web.config file.

Add below ConfigSection (if tag exist then add tag in that existing tag) 

Now Add Elmah tag in below this configSection. Where you can uncomment what ever you want and add your setting.(like database name, log file path etc…)

<elmah> 
    <!-- 
            Use to log errors to Microsoft SQL Server 2000 or 2005 
            using ASP.NET 2.0. Set value of connectionStringName attribute 
            to the name of the connection string settings to use from 
            the <connectionStrings> section.    

        <errorLog type="Elmah.SqlErrorLog, Elmah" 
            connectionStringName="..." /> 
        -->
    <!-- 
            Use to log errors to Microsoft SQL Server 2000 or 2005 
            using ASP.NET 1.x and adjust the value of connectionString 
            attribute to your settings.     

        <errorLog type="Elmah.SqlErrorLog, Elmah" 
            connectionString="Data Source=.;Initial Catalog=ELMAH;Trusted_Connection=True" /> 
        -->
    <!-- 
            Use to log errors to MySQL 5.0+  Set value of connectionStringName attribute 
            to the name of the connection string settings to use from the <connectionStrings> 
            section. 

        <errorLog type="Elmah.MySqlErrorLog, Elmah" 
            connectionString="..." /> 
        -->
    <!-- 
             Use to log errors to a SQL Server Compact 4 database file (requires .NET 3.5 SP1) 
             Set value of connectionStringName attribute to 
             the name of the connection string settings to 
             use from the <connectionStrings> section.    

          <errorLog type="Elmah.SqlServerCompactErrorLog, Elmah" connectionStringName="..." /> 
                 The format of the connection string should be as follows:     

          <connectionStrings> 
            <add name="..." connectionString="data source=[path to the database file]" /> 
          </connectionStrings> 
  
            Replace the content of the brackets with a file name, for example:     

          data source=C:\Elmah.sdf    

             If the database file doesn't exist it is created automatically. 
             You can also place the file in the App_Data folder, by using the |DataDirectory| macro: 

          <connectionStrings> 
             <add name="..." connectionString="data source=|DataDirectory|\Elmah.sdf" /> 
          </connectionStrings> 

      -->
    <!-- 
            Use to log errors to SQLite using ASP.NET 2.0. 
            Set value of connectionStringName attribute to 
            the name of the connection string settings to 
            use from the <connectionStrings> section.     

        <errorLog type="Elmah.SQLiteErrorLog, Elmah" connectionStringName="..." /> 

            The format of the connection string should be as follows: 

        <connectionStrings> 
          <add name="..." connectionString="data source=[path to the database file]" /> 
        </connectionStrings> 
               Replace the content of the brackets with a file name, for example: 

        data source=C:\Elmah.db     

            If the database file doesn't exist it is created automatically.
            To specify a path relative to and below the application root, 
            start with the root operator (~) followed by a forward slash (/), 
            as it is common in ASP.NET applications. For example: 

        data source=~/App_Data/Error.db 
        -->
    <!-- 
            Use to log errors into separate XML files that are stored on 
            disk at the path specified in the logPath attribute. 
-->
    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/ErrorLog" /> 
    <!-- 
            Use to log errors to Oracle 
            using ASP.NET 2.0. Set value of connectionStringName attribute 
            to the name of the connection string settings to use from 
            the <connectionStrings> section. 

            The schemaOwner parameter is *optional*. Use this if the owner of the 
            ELMAH package (pkg_elmah$error) is not the same user that you are 
            using to connect to the database. 

        <errorLog type="Elmah.OracleErrorLog, Elmah" 
            schemaOwner="xxx" /> 
            connectionStringName="..." /> 
        -->
    <!-- 
            Use to log errors to Oracle 
            using ASP.NET 1.1 and adjust the value of connectionString 
            attribute to your settings. 

            The schemaOwner parameter is *optional*. Use this if the owner of the 
            ELMAH package (pkg_elmah$error) is not the same user that you are 
            using to connect to the database.  

        <errorLog type="Elmah.OracleErrorLog, Elmah" 
            schemaOwner="xxx" /> 
            connectionString="Data Source=xxxx;User ID=username;Password=password" /> 
        -->
    <!-- 
            Use to log errors to Microsoft Access 
            using ASP.NET 1.x and adjust the value of connectionString 
            attribute to your settings. 
            Use Elmah.mdb as your database. 

        <errorLog type="Elmah.AccessErrorLog, Elmah" 
            connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Elmah.mdb" /> 
        -->
    <!-- 
            Use to log errors to Microsoft Access 
            using ASP.NET 2.0. Set value of connectionStringName attribute 
            to the name of the connection string settings to use from 
            the <connectionStrings> section. 
            Use Elmah.mdb as your database.    

        <errorLog type="Elmah.AccessErrorLog, Elmah" 
            connectionStringName="..." /> 
        -->
    <!-- 
            Use to log errors to PostgresSQL 
            using ASP.NET 2.0. Set value of connectionString to a 
            valid Npgsql connection string.    

        <errorLog type="Elmah.PgsqlErrorLog, Elmah" 
            connectionString="Server=...;Port=...;Database=...;User Id=...;Password=...;" /> 
        -->
    <!-- 
            Use to send error reports by e-mail and adjust the attributes 
            according to settings desired. Note that only the from and 
            to attributes are required. The rest are optional and may 
            be removed. If the SMTP server does not require authentication, 
            you MUST remove the userName and password attributes or 
            set them to empty values (resulting in zero-length strings). 
            If you are using ELMAH compiled for .NET Framework 1.x, then 
            the to attribute may contain multiple recipient addresses,  \
            each of which must be delimited by a semi-colon(;). If you are 
            using ELMAH compiled for .NET Framework 2.0 or later, then the 
            to attribute may contain multiple recipient addresses, 
            each of which must be delimited by a comma (,).
        <errorMail 
            from="[email protected]" 
            to="[email protected]" 
            subject="..." 
            priority="Low|Normal|High" 
            async="true|false" 
            smtpPort="25" 
            smtpServer="smtp.example.com" 
            useSsl="true|false" 
            userName="johndoe" 
            password="secret" 
            noYsod="true|false" /> 
        -->
    <!-- 
            Use to send short error messages to a twitter account. 
        <errorTweet 
            userName="johndoe" 
            password="secret" /> 
        -->
    <!-- 
            Use to prevent errors from being mailed or logged based on 
            assertions. An assertion evaluates the current context, resulting 
            in a Boolean outcome. An error is filtered if the assertion results 
            in true. For a more detailed explanation, see: 

http://code.google.com/p/elmah/wiki/ErrorFiltering 

            The example below will filter errors when any of the 
            following conditions occur: 

            - The status code is set to 404 
            - The root/base cause is System.IO.FileNotFoundException 
            - The root/base cause is System.Web.HttpRequestValidationException 
            - The user agent making the request identifies itself as "crawler" 
            - The request is from the local machine 

            The assertion below is expressed as a JScript expression and is the 
            most generic and simplest of the assertions to use if you are 
            familiar with the JavaScript language. It can work in Medium and 
            Full trust environments. 

        <errorFilter> 
            <test> 
                <jscript> 
                    <expression> 
                    <![CDATA[ 
                    // @assembly mscorlib 
                    // @assembly System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 
                    // @import System.IO 
                    // @import System.Web 

                    HttpStatusCode == 404 
                    || BaseException instanceof FileNotFoundException 
                    || BaseException instanceof HttpRequestValidationException 
                    /* Using RegExp below (see http://msdn.microsoft.com/en-us/library/h6e2eb7w.aspx) */ 
                    || Context.Request.UserAgent.match(/crawler/i) 
                    || Context.Request.ServerVariables['REMOTE_ADDR'] == '127.0.0.1' // IPv4 only 
                    ]]> 
                    </expression> 
                </jscript> 
            </test> 
        </errorFilter> 
        -->



ASP.NET MVC 3 Hosting - ASPHostPortal :: How to Build a RESTful API Architecture in ASP.NET MVC 3

clock August 26, 2011 06:59 by author Jervis

ASP.NET MVC 3, with its glorious URL structures and ease of working with and controlling HTTP request/response data is primed to build REST type API services. But how does one accomplish that and what does the whole RESTful thing really mean?

Building a full blown API (of any type) involves a lot of architecture components, from data validation to security and beyond. This post does not attempt to address all of that. It focuses on the initial structure of a RESTful service within an ASP.NET MVC 3 application that works with JSON data in and out. We will look at how we can use the route engine, the HTTP verb attributes and a lean controller design to provide a starting point for a REST API.

We start by making use of Areas in MVC to create an API Area within an application. This will allow us to isolate the API and use another Area or even the top level to add documentation and other API support tools like a web interface for testing the API (outside the scope of this post).



Our sample API will handle Comment data. The class for a comment:

namespace Website.Areas.Api.Models
{
    public class Comment
    {
        public int Id { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AuthorName { get; set; }
    }
}

The API will support sending and receiving JSON structured data. We will be able to send in a Comment object in JSON like so:

{
    "Subject": "A Subject",
    "Body": "The Body",
    "AuthorName": "Jervis"
}

or a batch of Comments:

{
    items: [{
        "Subject": "A Subject",
        "Body": "The Body",
        "AuthorName": "Jervis"
    }, {
        "Subject": "A Second Subject",
        "Body": "The Other Body",
        "AuthorName": "Kevin"
    }]
}

Returned JSON for a single Comment will look like:

{
    "Id": 3,
    "Subject": "A Subject",
    "Body": "The Body",
    "AuthorName": "Jervis"
}

A set of Comments returned like so:

[{

    "Id": 1,
    "Subject": "A Subject",
    "Body": "The Body",
    "AuthorName": "Jervis"
}, {
    "Id": 2,
    "Subject": "A Second Subject",
    "Body": "The Other Body",
    "AuthorName": "Kevin"
}]

A brief REST before we route and control

To craft a RESTful solution there are a couple of targets that we want to hit. The first is the use of HTTP verbs to handle relative actions.

- GET Used to request data
- POST Used to create a new data record or a set of new data records
- PUT Used to update an existing data record
- DELETE Used to delete an existing data record

The second is to use a url structure that embodies a human readable request for data.

- GET
/Api/Comments
/Api/Comments/2/10
/Api/Comments/Comment/3
-
POST
/Api/Comments/Comment
-
PUT
/Api/Comments/Comment/3
-
DELETE
/Api/Comments/Comment/3

Routing


Within the area registration code (ApiAreaRegistration.cs) we can add routes for our RESTful url patterns. Let’s take a look at the code for the routes and then go over their purpose.

using System.Web.Mvc;

namespace Website.Areas.Api
{
    public class ApiAreaRegistration : AreaRegistration
    {
        public override string AreaName { get { return "Api"; } }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "SingleComment",
                "Api/Comments/Comment/{id}",
                new { controller = "Comments", action = "Comment",
                    id = UrlParameter.Optional }
            );
            context.MapRoute(
                "ListComments",
                "Api/Comments/{page}/{count}",
                new { controller = "Comments", action = "CommentList",
                    page = UrlParameter.Optional, count = UrlParameter.Optional }
            );
            context.MapRoute(
                "ListCommentsAll",
                "Api/Comments",
                new { controller = "Comments", action = "CommentList",
                    page = UrlParameter.Optional, count = UrlParameter.Optional }
            );

            context.MapRoute(
                "Api_default",
                "Api/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Routes do not have any knowledge of the HTTP verbs, so the ones that we add are going to support multiple scenarios to get to our controller actions. The SingleComment route supports our GET, PUT and DELETE requests when an id is included in the url string, and the POST when the id is left off. The ListComments route supports a GET request for paging Comments in which a page number and a count per page is included in the url string. The ListCommentsAll route handles a GET request for all Comments (no paging). It will also support a POST request of a list of Comments where the url string does not include anything after the /Api/Comments.

Before we take a look at the
CommentsController
code, let’s check out a custom ActionFilterAttribute that we can craft to help us handle multiple verbs through a single controller action.

using System.Web.Mvc;

namespace Website.Models
{
    public class RestHttpVerbFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var httpMethod = filterContext.HttpContext.Request.HttpMethod;
            filterContext.ActionParameters["httpVerb"] = httpMethod;
            base.OnActionExecuting(filterContext);
        }
    }
}

This code will capture the HTTP verb of the request and store it in the ActionParameters collection. By applying this attribute to a controller action we can add a method parameter named httpVerb and the RestHttpVerbFilter will handle binding the HTTP request verb value to it. Our controller needs to support an action method with a common signature (the same parameters) but take different actions based on the HTTP verb. It is not possible to override a method with the same parameter signature but a different HTTP verb attribute. This custom attribute will allow us to have a single controller action method that can take action based on the HTTP verb without having to contain the logic to determine the verb. With a single controller this is not that big of a deal, but I’d imagine that our API is going to embody more than just Comment management, and thus a need to repeat the verb capture code in multiple controllers for the API.

Let’s take a look at the
CommentsController
code and see how this all unfolds:

using System.Collections.Generic;
using System.Web.Mvc;
using Website.Areas.Api.Models;
using Website.Models;

namespace Website.Areas.Api.Controllers
{
    public class CommentsController : Controller
    {
        ICommentManager commentManager;

        public CommentsController()
        {
            this.commentManager = new CommentManager();
        }

        [HttpGet]
        public JsonResult CommentList(int? page, int? count)
        {
            var model = this.commentManager.GetComments(page, count);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult CommentList(List<Comment> items)
        {
            var model = this.commentManager.CreateComments(items);
            return Json(model);
        }

        [RestHttpVerbFilter]
        public JsonResult Comment(int? id, Comment item, string httpVerb)
        {
            switch(httpVerb)
            {
                case "POST":
                    return Json(this.commentManager.Create(item));
                case "PUT":
                    return Json(this.commentManager.Update(item));
                case "GET":
                    return Json(this.commentManager.GetById(id.GetValueOrDefault()),
                        JsonRequestBehavior.AllowGet);
                case "DELETE":
                    return Json(this.commentManager.Delete(id.GetValueOrDefault()));
            }
            return Json(new { Error = true, Message = "Unknown HTTP verb" });
        }
    }
}

The controller has a private member of type ICommentManager and the controller constructor instantiates an object of type CommentManager
that will implement the interface. The contract for the interface looks like so:

using System.Collections.Generic;

namespace Website.Areas.Api.Models
{
    public interface ICommentManager
    {
        Comment Create(Comment item);
        List<int> CreateComments(List<Comment> items);
        Comment Update(Comment item);
        Comment GetById(int id);
        List<Comment> GetComments(int? page, int? count);
        bool Delete(int id);
    }
}

The first controller action, CommentList(int? page, int? count), supports the HTTP GET verb only and handles querying comments. The logic to determine if the list of comments is paged or not will be brokered off to the CommentManager. The returned List<Comment>
data is sent to the JsonResult which will handle serializing it to JSON and providing the correct response headers to the client consuming the API. This method is hit whenever a GET request is made with the following url string structures:

/Api/Comments
/Api/Comments/2/10

The next controller action, CommentList(List<Comment> items)
, supports the HTTP POST verb only and is used to support adding multiple Comment objects in a single request. This method is hit whenever a POST request is made with the following url string structure:

/Api/Comments

The final controller action, Comment(int? id, Comment item, string httpVerb)
, is where most of the magic happens. This method supports all four verbs when a request is made with the following url string structures:

/Api/Comments/Comment
/Api/Comments/Comment/3

The Comment method brokers all logic to work with a single comment to the appropriate CommentManager method and returns the result of those methods directly through the JsonResult
. If, for some insane reason (HTML 6 arrives with new verbs), we receive an unsupported HTTP verb we return a custom JSON error object.

Testing the API with Fiddler

We can make use of
Fiddler to test the API. First we need to create the CommentManager class and give it some sample logic to return some test data.

using System.Collections.Generic;

namespace Website.Areas.Api.Models
{
    public class CommentManager : ICommentManager
    {
        public Comment Create(Comment item)
        {
            item.Id = 1;
            return item;
        }

        public List<int> CreateComments(List<Comment> items)
        {
            return new List<int> { 1, 2, 3 };
        }

        public Comment Update(Comment item) { return item; }

        public Comment GetById(int id)
        {
            return new Comment
            {
                Id = id,
                Subject = "Loaded Subject",
                Body = "Loaded Body",
                AuthorName = "Loaded Author"
            };
        }

        public List<Comment> GetComments(int? page, int? count)
        {
            var comment1 = new Comment
            {
                Id = 1,
                Subject = "First Subject",
                Body = "First Body",
                AuthorName = "First Author"
            };
            var comment2 = new Comment
            {
                Id = 2,
                Subject = "Second Subject",
                Body = "Second Body",
                AuthorName = "Second Author"
            };
            var items = new List<Comment> { comment1, comment2 };
            return items;
        }

        public bool Delete(int id) { return true; }
    }
}

Then we can F5 the project to have the API running, copy the localhost with port url and use that in Fiddler to send in HTTP requests. The url for my instance:

http://localhost:24771/

Creating a new request in Fiddler is done by clicking on the Request Builder tab. Leaving the drop down for the verb to GET and setting the url to http://localhost:24771/Api/Comments, we can execute it and see that application is hit (by the result in the Web Sessions panel on the left).



Selecting the session result, clicking on the Inspectors tab and then on the Raw view button allows us to view the response data.



The other GET requests are done the same, but with different urls. The POST, PUT and DELETE actions involve changing the HTTP verb drop down, using either the http://localhost:24771/Api/Comments url for a POST of multiple comments or the http://localhost:24771/Api/Comments/Comment/{id} url for working with a single comment. Within the Request Body text area we can add the JSON object that we want to send to the API. The only other piece that we need to handle is telling the API via the HTTP header that the content type is JSON. In the Request Headers text area we need to add the following line:

Content-Type: application/json

MVC will identify this header and use the JSON model binding to map the request body data to a Comment object in our controller actions (or the List<Comment> item
object if we are doing a POST of multiple Comments at once). Posting a new comment to the API with Fiddler looks like so:



If we set breakpoints throughout the
CommentsController
we can go through the various requests with Fiddler and validate that our routing is working as planned and that we are reaching the correct action methods for each type of request.

Can I hand out my API url now?

Remember, this is just a starting point for creating REST type functionality in an MVC 3 application. There is a long way to go to craft out a true API solution. The next step would be to fill out the logic for the
CommentManager to work with a data storage layer for persisting the Comment data. After that, adding some logic in the CommentsController.Comment
method to support clients that don’t support the PUT or DELETE verbs. From there the fun begins. Thinking about security, data validation, standard error response support, cross domain support, and on and on.

If you are in need of a way to write a RESTful service within MVC 3 hopefully this can help get you rolling.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: ASP.NET MVC 3 Partial View

clock August 17, 2011 07:01 by author Jervis

Partial views in ASP.NET MVC 3 allow the developer to create reusable content with the very precise and clean Razor syntax (or ASPX). The syntax that renders the partial view is implemented as an Html helper. The Html.Partial helper renders the partial view named "_FeaturedProduct" inline. The first argument of all overloaded methods in the call the @Html.Partial expect the view/partial's file name, without the file extension. Adhering to convention, the @Html.Partial helper assumes the view resides in the \Views\Shared\ folder. Additional overloads in the @Html.Partial method allow you to pass ViewData/ViewBag objects between views/partials (see below under Sharing data...).

The code below demonstrates the call to render the featured product partial view.

<
div>
  @Html.Partial(
"_FeaturedProduct")
</div>


Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.

There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.

<
div>
  @Html.RenderPartial(
"_FeaturedProduct"
)
</div>


How to Create a Partial View

Both partial views and regular views are .cshtml files, with the difference being the folder where the partial views reside: \Views\Shared\. Use the Add New View dialog by accessing the context menu from the \Views\Shared node in Solution Explorer. The Add New View template dialog offers choices for creating your partial views, including the option for strongly typing views. Don't forget to check off  "Create as a partial view" or you'll end up with a lot of code to delete.



Once you've created the view you can get started customizing it by simply editing the file. There's no problem in deleting or modifying the view's code, as there's no designer tied to it. The code shown below (_FeaturedProduct.cshtml) is the same code the default view template creates, but modified to display the featured product differently:

<style type="text/css">
   
.featuredProduct {border: solid 1px #000
}
</style>
<div>

   
<div>

       
<h2>

            Our Featured product:
<br />

            @ViewBag.FeaturedProduct.Name
       
</h2>

   
</div>    <div>

       
<h3>

            Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100)
       
</h3>

   
</div>
  
   
<div>

        @Html.ActionLink("Featured Product Details", "Details", new { id = ViewBag.FeaturedProduct.ProductId })
   
</div>
 
   
<div>

       
<img class="featuredProduct" src="@Href("~/Content/Images")/@ViewBag.FeaturedProduct.ImageName" alt="Featured Product"/>

   
</div>
</div>


As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.

It should be clear when reading through the above code that the syntax of partial view looks the same as a regular view. The important take-away is not about the syntax but how the partial view is used. However, a syntactic benefit to developers is the consistency between both partial and full views, particularly when we need to share data between them.

Views and Partial Views Sharing Data

It's a common occurrence to pass data between components of an application, and in this case those components are MVC partials, views & controllers. As previously noted, you should use the ViewBag or ViewData classes to share data across views and controllers. First, a few notes on ViewBag and ViewData:

- ViewData was available in previous versions; ViewBag was released with MVC 3.
- ViewData can contain any type of data in a name-value pair format. I.e., ViewData["Message"] = "Welcome";
- ViewBag objects are just wrappers around ViewData objects, and allow developers to code to them using strongly typed syntax.
- ViewBag objects can be extended by simply setting properties in a more fluent syntax. I.e.,  ViewBag.Customer = new Customer(1,"Smith");

If code in a controller uses either the ViewBag or ViewData classes, those classes will be available throughout the view's lifecycle, and that includes its partial views. 

The preferable object is the ViewBag. Because of its more fluent and dynamic syntax, there's more complex objects that can be shared quite easily between components. The sample below demonstrates setting up the ViewBag object in the controller so it will be available to all necessary components:

ProductModel
productModel = new ProductModel();       
public ActionResult Index()
{
    ViewBag.FeaturedProduct = new FeaturedProduct(105, "The Most Awesome Bike Ever!", 1000.00M, "bike4.png");          
    return View(productModel.Products);           
}

The ViewBag is accessed inside the view or partial using the follows syntax:

@ViewBag.FeaturedProduct.Name

Summary

Partial views are a great way to reuse fragments of HTML and Razor syntax together, with the ability to easily share data.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: How to Integrate Twitter to your ASP.NET MVC 3 Application

clock August 10, 2011 07:20 by author Jervis

Here are the steps:

1. Visual Studio 2010 Service Pack 1.  You can install it from
Download details- Microsoft Visual Studio 2010 Service Pack 1.

2. ASP.NET MVC 3 and the Tools Update that you can download it from
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=82cbd599-d29a-43e3-b78b-0f863d22811a&displaylang=en.

3. Then, create a file New and rename it “TwitterHelperDemo”



4. Allow the default “Razor” as the View engine and click OK.



For the purpose of this sample, we will just use the Index.cshtml View which is under the Home folder under Views.

5. In the Visual Solution Explorer, right click the Project and select “Add Library Package Reference”.



6. Click “Online” Tab and type “Twitter” in the search box on top right. Choose Twitter.Helper and Intall it.



7. Done. In the root director, you will find packages.config file.  Open the file to verify if the package is installed.  If it is installed, it would list as

<package id="Twitter.Helper" version="1.0" />

Next, open the Index.chstml file and remove the default “To Learn ASP.NET MVC” message within the paragraph. 

Start typing @Twitt and you should see intellisense for TwitterGoodies.

Add @TwitterGoodies.Profile(“TWITTER HANDLE”)

When you run the solution, you can see the Twitter Profile loading and the latest tweets showing up.

You can try more options like @TwitterGoodies.Search("#webcamps") and @TwitterGoodies.TweetButton()

The complete code for this page is

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
   @TwitterGoodies.Profile("asphostportal")
</p>
<p>
@TwitterGoodies.Search("#webcamps")
</p>
<p>
@TwitterGoodies.TweetButton()
</p>

Easy, right? Now, you can integrate Twitter into your ASP.NET MVC 3 Application.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Razor View And HTML Helpers in ASP.NET MVC 3

clock August 8, 2011 06:29 by author Jervis

In this tutorial,  I will show you:

1. How to use inline HTML helper inside the view itself
2. How to use HTML helper with an extension method and call the method in side view.

OK, here we go:

Create your MVC project first





Use HTML helpers as a declarative incline content

In this simple example I am creating a radio button using HTML helper by declaring the logic inside the view file itself. Open the index.cshtml file. The Cshtml file is meant to handle HTML related functionality in a razor view implementation



The code inside is:

@helper CustomRadioButton()
    {   

    @Html.RadioButton("Custom", "Y", true)
    @Html.RadioButton("Custom", "N", false)
                                      
}
<h2
>
   Radiobutton from inline MVC HTML helper @CustomRadioButton()</h2>

@helper is the key and you should use the same name. Then comes your method name and it's your own choice. I chose CustomRadioButton() even though it's returning normal radio buttons. Now the method body; @Html will give you a Ref. to HTML helper and you can access built-in control classes. Here I used RadioButton. Our logic is finished and now we need to call the method named CustomRadioButton(). You call it from anywhere using @<<method name>> i.e. @CustomRadioButton(). Now run the application and its output will be as below.



Use HTML helpers using extension methods

Create a new class named Helpers (like the following) in a new folder:



The inner code is like below and you may already be aware that extension methods are not new and it needs a static class. I will not explain in depth about extension methods, but here we are adding one extension method to the built-in HtmlHelper class.

namespace MvcApplication1.Utilities

{
    public static class
HtmlHelpers
    {
        public static  DateTime GetTodayDate(this HtmlHelper helper)
        {
            return DateTime.Now;
        }

    }
}


The method merely returns the current date time.

The "this" keyword is determining which class is being extended. Here it's HtmlHelper like GetTodayDate(this HtmlHelper helper).

Now need to build the solution and use this new extension method inside the view file. Again open the same index.cshtml and the code will be like below:

@using
MvcApplication1.Utilities;
Date from MVC html helper extension method  @Html.GetTodayDate()</h2>

The 1st statement is understandable as it's importing the required namespace. Once you imported the namespace, now you can use the extension method declared inside that namespace like @Html.GetTodayDate(). Just look at the method you defined can access with the built-in class, @Html i.e. HtmlHelper. This is the basic behavior of extension methods. Now run the application and see the output like below.



Last one more point. The configuration settings here are more flexible. Using this you can avoid the using statement of @using MvcApplication1.Utilities. This can be achieved by putting the same namespace inside config file under the views folder. See the following screen shot.



Note that it's not application web.config, but specific to views. The section will be like this.

<system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Routing" />
                <add namespace="MvcApplication1.Utilities"/>
            </namespaces>
        </pages>
</system.web.webPages.razor>

Enjoy the post…

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Using Fluent Nhibernate, LINQ and SQLite in ASP.NET MVC 3 Project

clock August 2, 2011 08:36 by author Jervis

Here are the steps that you can follow:

1. Create a new MVC 3 project

First download and install MVC3 RC
[ASP.NET MVC 3 RC]. ASP.NET MVC 3 can be installed side by side with ASP.NET MVC2 so MVC 2 doesn’t need to be uninstalled for v3 to run. After installing v 3.0 create a new ASP.NET MVC 3 project. For this tutorial I will be using the Razor View Engine.

2. Download Nhibernate 3.0

3. Setup Fluent Nhibernate to Use LINQ

- Run the following command to get the latest Fluent Nhibernate source – assuming git is in your PATH.
git clone git://github.com/jagregory/fluent-nhibernate.git fluent-nhibernate
Add the Fluent Nhibernate VS.NET project located in [Path]\fluent-nhibernate\src\FluentNHibernate\ to your ASP.NET MVC 3 project.
- Convert the Fluent Nhibernate project to target

- Remove all Nhibernate 2.0 library references from Fluent NHibernate project. In particular you might be interested in the follwoing libraries – NHibernate, Iesi.Collections, Antlr3.Runtime.
- Add the NHibernate v3 libraries – all libraries removed in earlier step – to the project and build it.

4. Use NHibernate 3 LINQ

NHibernate defines the LINQ specific functionalities in
NHibernate.Linq. Here is a sample code that shows how to use LINQ in NHibernate.


using NHibernate;
using NHibernate.Linq;

......

[HttpPost]
public ActionResult Edit(Post updatedPost)
{
      ISession session = SQLiteUtil.SessionFactory.OpenSession();
      IQueryable<Post> postRepository = session.Query<Post>();
      Post oldPost = postRepository.Single(post => post.Id == updatedPost.Id);

      if (ModelState.IsValid)
      {
            oldPost.Title = updatedPost.Title;
            oldPost.Body = updatedPost.Body;
            oldPost.CreatedBy = updatedPost.CreatedBy;
            session.SaveOrUpdate(oldPost);

            return RedirectToAction("Index");
      }
      return View(updatedPost);
}

5. Use SQLite

In order to use SQLite in our project, download the .NET driver from
here. Reference the Dlls from your ASP.NET MVC 3 project.

Hope you enjoy the post. Happy coding!!

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: ASP.NET MVC3 Razor Script Loading Tips

clock July 18, 2011 06:30 by author Jervis

Lately, I have been playing with few JavaScript frameworks and in today’s modern web applications it is very common that we are including tons of JavaScript files in our application. One of the thing that plays important role in application performance is how fast these script files are delivered into the browsers. I have extensively blogged on combining, compression and caching of JavaScript files in my old blog, in this post I will show you, how you can achieve parallelism in delivering the scripts in the browser with the Head JS library. If you do not know what parallel script downloading is and how does it impact on page speed, then I would suggest to read this article of the YSlow creator. In short, when a browser encounters a script tag in a page it halts its rending until it downloads the script file, the parallelism is actually archived by adding the script dynamically or by XHR depending upon the browser it is running.

Though there are several libraries like HeadJS which support parallelism in script downloading like
LABjs, ControlJS but I am bit partial to it due to jQuery like syntax. Other than script parallelism HeadJS also has few more features as like Modernizr but I will only show the script loading part in this post.

Now, in a typical ASP.NET MVC Application we usually load our shared scripts in the master page and specific scripts in content page, beside that we also want our content page script runs after the master page scripts. So we do have two tasks in hand first serialize the script files so that independent script files download first then dependent files and then serialize the script statements in document.ready.

So, the first thing we will do is add the HeadJS script loader in the head of the master layout file, like the following:

<head>
    <title>@ViewBag.Title</title>
    <script src="@Url.Script("head.load")"></script>
</head>


The Script is just an extension method of UrlHelper which just returns the regular or minified version of the script depending the debug compilation. But in your real application you should group, compress, cache and if possible create a different domain(e.g. static.yoursite.com or assets.yoursite.com) to host the scripts. Here is the code of the Script
method:

public static string Script(this UrlHelper instance, string scriptFileName)

{                  const string Path = "~/Scripts/";              
    return instance.Content(Path + scriptFileName +
(instance.RequestContext.HttpContext.IsDebuggingEnabled ? ".js" :
".min.js"));

}

Now, at the bottom of the master layout, I have added the following snippet:

<script>
        head.js("@Url.Script("jquery-1.4.4")", function() {
            head.js("@Url.Script("jquery-ui")")
                .js("@Url.Script("jquery.unobtrusive-ajax")")
                .js("@Url.Script("jquery.validate")",
"@Url.Script("jquery.validate.unobtrusive")")

                .js("@Url.Script("jquery.customSharedPlugin")");
            @RenderSection("scriptFiles", false)
        });                      head.ready(function() {
            $('#main').customSharedPlugin();
            @RenderSection("scriptOnReady", false)
        });                  </script>
</body>              </html>

For the shake of simplicity I am mostly using the scripts which comes with the default ASP.NET MVC project, in your real application it may vary. Now, in the above example I am first loading the jQuery as my other scripts depends upon it and in the callback which fires when the script is loaded I am loading the other depend scripts and these are the script files that are loaded simultaneously without blocking each other. Now when I am done with layout file script loading, I am using the new Razor RenderSction to include the content page scripts. But as I am marking the section as optional by passing false in the second argument, it is perfectly okay if the content page does not has its own script files. But if the content page has scripts then it is included in the following way:


@section scriptFiles {
    head.js("@Url.Script("jquery.customPlugin1")");              }

Next, the head.ready, it is executed when all of the scripts are loaded and like the script loading we are first calling the layout page specific code then using the RenderSection(also making it as optional) so that the content page can inject its script. Now, in the Content page:

@section scriptOnReady {
    $('#main > h2').customPlugin1();              }

So when the page renders it will render the following:

<script>
  head.js("/Scripts/jquery-1.4.4.js", function() {
      head.js("/Scripts/jquery-ui.js")
               .js("/Scripts/jquery.unobtrusive-ajax.js")
               .js("/Scripts/jquery.validate.js", "/Scripts/jquery.validate.unobtrusive.js")
               .js("/Scripts/jquery.customSharedPlugin.js");
                      head.js("/Scripts/jquery.customPlugin1.js");
     });                              head.ready(function() {
      $('#main').customSharedPlugin();
      $('#main > h2').customPlugin1();                 });
</script>

Happy reading.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Introducing MVC Development with the Razor View Engine for Visual Studio Developers

clock July 12, 2011 05:23 by author Jervis

The Razor View Engine is a precise, useful, light language that enables you to create views for MVC projects in ASP.NET still while keeping a separation of concerns, ability to test, and pattern based development.  ASP.NET MVC developers looking for a more concise syntax now have another option that's built-in (of course, there are many 3rd party view engines out there) with the language being a familiar light version of C#. 

The Razor View engine is used to create WebMatrix sites or Visual Studio MVC applications.  When using ASP.NET MVC with either engine, you'll stick to a style of development called "convention over configuration", meaning that you'll use certain naming conventions to name files, models, views, controllers, and other key application elements rather than storing lots of metadata about these same elements in a configuration file.  When using MVC in Visual Studio 2010, it's is setup so that you'll be guided to use convention over configuration, which becomes evident when exploring an ASP.NET MVC project.

Getting Started

Before you start, go and download these two things (as of this post; things are subject to change - these could end up in VS at some point):

- ASP.NET
MVC 3
-
Razor Syntax Highlighter Extension (not mandatory, but a huge help)

You can also find the Razor Syntax Highlighter by choosing Extensions Manager from the Visual Studio Tools menu.  Once installed, MVC 3 project templates are available from Visual Studio.  The MVC 3 Web Application template allows you to use either the Web Forms View Engine or the Razor View Engine, while MVC 2 Applications contain only the WF View Engine.



When creating a new MVC 3 project a new dialog box appears asking which application type, view engine, and testing framework you'd like to use.  You can and should add a test project so you can test your code, then actually write some tests in it.   The image below demonstrates selecting the internet application project template using Razor as the view engine, as well as the test framework.  The internet application MVC template adds in ASP.NET membership & security features to the project by creating the necessary model, view and controller for logging on and registering as a site user.



Verify that the project is created with three folders, one each for Models, Views, and Controllers which is the same folder structure as a MVC 2 site.  The project also contains auxiliary folders and files needed for the application such as the Content & App_Data folders.   Since this is an MVC application using the Razor View Engine, you will see a different file extension - .cshtml.  The .cshtml files are Razor View Pages written using the Razor View Engine.  If you're not familiar with Razor syntax, I've blogged about it
here, and the online documentation has more information as well. 



The application template sets up some models, views and controllers to start with, and is now ready for new models, views, and controllers.  I've found the easiest way to work with MVC in VS is to start with the model, move to the controller, then create the view, so we'll look at models first.

Models

A model is a representation of an underlying data store.  Models can be almost anything from any data source; EF or Linq2Sql Models, or a simple class.  The code the builds the model below consists of two classes, a ProductModel class and a Product class.  The ProductModel class returns a List<t> of Product objects in a property aptly named Products that represents one or more products in the data store .  Product objects contain ProductNumber, Name and Price properties and represent an individual product in the data store.  The model code representing these product objects is below:


using System.Collections.Generic;
namespace AdventureWorks.Models
{
    public class ProductModel
    {
        public List<Product> Products { get; set; }
        public ProductModel()
        {
            Products = new List<Product>();
            this.Products.Add(new Product("AB-00-J1" ,"Super Fast Bike" ,1000M));
            this.Products.Add(new Product("EE-9-OL"  ,"Durable Helmet"  ,123.45M));
            this.Products.Add(new Product("MMM99-54" ,"Soft Bike Seat"  ,34.99M));
        }
    }
 
    public class Product
    {
        public Product(string productNumber, string name, decimal price)
        {
            Name = name;
            Price = price;       
            ProductNumber=productNumber;
        }
        public string ProductNumber { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
       
    }
}


Models are handed over to views by controllers so the views can render the data from the model.  The model will extend business logic (of course, this is a simple example, business logic will likely be spread out into other applications & tiers). Models also provide validation information to the view via metadata & code.  You can add the model to the \Models folder or you can reference an external data model library.  In this case, the model's been added to the \Models folder.

Controllers

Controllers are objects that inherit from the System.Web.Mvc.Controller class that match models with views.  During incoming requests, MVC's routing system kicks in and determines which controller method to use based on routing code set in the global.asax.cs file.  A default route is set in the global.asax.cs file that works for most of the routes you'll need, however, if need be then you can modify/add/delete your own routes.

Staying within convention, controller code files should go in the \Controllers folder. The controller class must follow the naming convention of YourNameController, i.e., ProductsController.  The controller's Index method, again following convention, must be named the same name as its view but without the file extension.  By following this pattern, the controller can have multiple actions that deliver data to multiple views, making code easier to write, maintain, and test.

namespace
AdventureWorks.Controllers
{
    public class ProductsController : Controller
    {
        public ActionResult Index()
        {
            ProductModel p = new ProductModel();           
            return View(p.Products);
        }
    }
}


By observing the previous code sample and the conventions that it follows, it's clear that the Index method maps to the \Views\Products\Index.cshtml view.  The Index() method's return type is an
ActionResult from the System.Web.Mvc namespace.  There's many different results that you can use for different scenarios such as ContentResult, FileResult, RedirectResult, ViewResult and others depending on your view's needs

Views

Views are a mechanism to format and render data in a browser from the model, as specified by the @model attribute (or @inherits) at the top of the view.  Views in ASP.NET MVC with either the ASPX or Razor View engines use a code-based way to render the page rather than relying on declarative controls, which create tight coupling and are hard to test.  Using the MVC approach creates cleaner output in the browser as well as cleaner and more terse syntax in the views as well.  Views are meant to only render the markup, code and data; they're not meant as a place to store business logic. The model and tiers accessed by the model, are the appropriate places to host business logic.  The view can have a small amount of UI validation logic,as a first line of defense for input sanitation, e.g., required, regex and range validators.

To add a view to your project, right click on the controller and select Add View. 



Visual Studio will need some information about the view, which is supplied in the Add View dialog box:

1. Specify whether you want a strongly-typed view or not.  Creating a strongly-typed view allows you to refer to the underlying data structures in the classic object.property syntax.
2. Specify the view data class.  The dropdown list displays classes in your project that are part of the data model.
3. Specify the view engine.  ASPX and Razor are the options.
4. Specify the view content.  Choices are list, details, edit. etc...  Choosing this option creates .cshtml or .aspx view pages that do page rendering for you.



Here's what choosing these options will produce in a Razor view page named \Views\Products\Index.cshtml:

@model
List<AdventureWorks.Models.Product>
@{
    View
.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>Index</h2
>
<
p>
@Html.ActionLink("Create New", "Create")
</p
>
<
table>
  <tr>
    <th>Edit/Details/Del</th>
    <th>Product Number</th>
    <th>Name</th>
    <th>Price</th>
  </tr>
 
@foreach (var item in Model) {
  <tr>
    <td>
      @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ })
      @Html
.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */
})
|
      @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
    </td>
    <td>
      @item.ProductNumber
    </td>
    <td>
      @item.Name
    </td>
    <td>
      @String.Format("{0:F}", item.Price)
    </td>
</tr>
}
</table>


Since the view is strongly typed, the data structure can be accessed as it is - an object with properties.  The code above loops through the model and renders a <TR> for each entity that the model holds along with <TD> tags and the actual data in them (ProductNumber, name and Price).  The result is a simple list of the three products in model with accompanying action links.



The HTML source shows a clean, precise table rendered to the browser



Summary

Rendering a list of products is very easy using MVC and the Razor View Engine, as is
updating/manipulating the data (logically what you'd do next if following this example).   If you're digging deeper into learning MVC w/Razor the next topics you'll want to get into are jQuery and HTML validation helpers for client side validation, and decorating the model with data annotations (also for validation).  The MVC web site has a ton of great examples and tutorials.

Although many ASP.NET MVC samples use the ASPX/Web Forms view engine they're easily compared & converted to razor pages - so don't avoid them, it's still a great way to learn both MVC w/Razor and the ASPX engine.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Model binding XML in ASP.NET MVC 3

clock July 8, 2011 07:01 by author Jervis

ASP.NET MVC 3 introduced the concepts of service location to conditionally build providers and factories for various extension points, such as Value Providers, Model Metadata Providers, and notably, Model Binders. Model binders in ASP.NET MVC are responsible for binding contextual HTTP request data (and any other context information) into the action method parameters.

Most of the time, these values are served up through the DefaultModelBinder class, which in turn leans on a collection of Value Providers to, well, provide values to the Model Binder. Value providers are great for centrally modeling dictionary-centric information, such as HTTP request variables (form POST, query string, cookie values etc.)

Model binders operate at one level of abstraction up from value providers, where we take control of the entire object deserialization/resolution/composition step ourselves. XML is one area where we can easily provide deserialization seamlessly from our controller action knowing about it. Let’s look at a simple example of a controller action accepting XML and responding with XML:

public class MathController : Controller
{
    public ActionResult Square(Payload payload)
    {
        var result = new Result
        {
            Value = payload.Value * payload.Value
        };

        return new XmlResult(result);
    }
}

Our input and output models are items easily serializable/deserializable:

public class Payload
{
    public int Value { get; set; }
}

public class Result
{
    public int Value { get; set; }
}

The XmlResult is from
MvcContrib, and encapsulates the serialization for us. However, we don’t have anything to accept XML as an input. We could just accept a string value and do the manual deserialization ourselves, but what’s the fun in that?

We’d also like to have the binding done according to the content type of the request payload, so that “text/xml” is recognized and automatically deserialized, just as “application/json” is currently done out of the box. Using
RestSharp, we want to get this test to pass:

[Test]
public void RestSharp_Tester()
{
    var client = new RestClient("http://127.0.0.1.:33443");

    var req = new RestRequest("Math/Square", Method.POST);

    var body = new Payload
    {
        Value = 5
    };

    req.AddBody(body);

   
var resp = client.Execute<Result>(req);

    var value = resp.Data.Value;

    Assert.AreEqual(25, value);
}

Just to make sure we’re not pulling any punches, here’s the actual HTTP request from Fiddler:

POST http://127.0.0.1.:33443/Math/Square HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp 101.3.0.0
Content-Type: text/xml
Host: 127.0.0.1.:33443
Content-Length: 41
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

<Payload>
  <Value>5</Value>
</Payload>

Not that exciting, I know, but you can see from the request that the content type indicated is “text/xml”. Our model binder should detect this and provide a deserialized object from that XML.

To do this, we’ll first need to build a model binder provider. Model binder providers decide on whether or not for the given type that they can provide a model binder. Instead of looking at the type metadata, let’s look at the content type of the incoming request:

public class XmlModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
        var contentType = HttpContext.Current.Request.ContentType;

        if (string.Compare(contentType, @"text/xml",
            StringComparison.OrdinalIgnoreCase) != 0)
        {
            return null;
        }

        return new XmlModelBinder();
    }
}

We check the incoming request’s content type, and if it matches our “text/xml” type, we return our XmlModelBinder. The XmlModelBinder is rather simple now, shown below.

public class XmlModelBinder : IModelBinder
{
    public object BindModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var modelType = bindingContext.ModelType;
        var serializer = new XmlSerializer(modelType);

        var inputStream = controllerContext.HttpContext.Request.InputStream;

        return serializer.Deserialize(inputStream);
    }
}

We simply build up the built-in XML serializer based on the model type we’re binding to, feeding in the raw Stream from the request. Finally, we need to make sure we add our model binder provider to the global providers collection at application startup (Application_Start):

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    ModelBinderProviders.BinderProviders
        .Add(new XmlModelBinderProvider());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

This model binder provider could have been provided through the service location option instead of registered manually. With this model binder provider added, our model is correctly bound, and the response returned matches our expectation:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Fri, 24 Jun 2011 01:15:55 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Content-Length: 178
Connection: Close

<?xml version="1.0" encoding="utf-8"?>
<Result>
  <Value>25</Value>
</Result>

The value coming out is just what was returned from the XmlResult, but what’s neat is that our input model is just a POCO that looks like it could have come from a POST from form encoded values, JSON or XML. In fact, they all work!

With just a few lines of code, we were able to effectively add XML support to our HTTP endpoints. It’s certainly not a full REST framework, but it can serve in a pinch in cases we just need to expose simple endpoints for consumers that want to do RPC but don’t want to go the full SOAP route.

We also leave open the option of supporting alternative content types, all seamless to our controller action (except for content negotiation). All without mucking around with the complications of WCF, using the same deployment, development and configuration model of our normal ASP.NET MVC sites.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in