European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, EntityFramework 5 CodeFirst, and Custom User Properties

clock January 21, 2013 06:43 by author Scott

Today post, I will show you how to integrate EF5 CodeFirst nicely with SimpleMembership and at the same time, seeding some of your users, roles and associating users to roles while supporting custom fields/properties during registration.

I think this is a nice to have, especially during PoC development where you could be developing features that depend on authentication and authorization while making schema changes with EF CodeFirst. The last thing you want to do is run update-database for migrations and have to manually re-insert/re-seed all your users, roles and associating the two every time you ran migrations (e.g. update-database -force from the Package Manager Console).

First, create an “Internet Application” ASP.NET MVC4 Project, because this is the only out of the box MVC template that has the new SimpleMembershipProvider wired up out of the box. One of the features I like the most about the SimpleMembershipProvider is it gives you total control of the highly requested “User” table/entity. Meaning you integrate SimpleMembershipProvider with your own user table, as long as it has a UserId and UserName fields in your table.

Explicitly wire up the providers even though this is implied, so that when do run the “update-database” command from the Package Manager Console for migrations we can use the native “Roles” Api.

In the “System.Web” Section add:

01    <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
02      <providers>
03        <clear/>
04        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
05      </providers>
06    </roleManager>
07    <membership defaultProvider="SimpleMembershipProvider">
08      <providers>
09        <clear/>
10        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
11      </providers>
12    </membership>

Let’s add a custom field to the User table by adding a Mobile property to the UserProfile entity (MVC4SimpleMembershipCodeFirstSeedingEF5/Models/AccountModel.cs).

1     [Table("UserProfile")]
2     public class UserProfile
3     {
4         [Key]
5         [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
6         public int UserId { get; set; }
7         public string UserName { get; set; }
8         public string Mobile { get; set; }
9     }

Enable EF5 CodeFirst Migrations

Seed your Roles and any Users you want to provision, also note the WebSecurity.InitializeDatabaseConnection method we are invoking. This method is what tells SimpleMembership which table to use when working with Users and which columns are for the UserId and UserName. I’m also going to demonstrate how you can hydrate additional custom columns such as requiring a User’s mobile number when registering on the site.

01    #region
02   
03    using System.Data.Entity.Migrations;
04    using System.Linq;
05    using System.Web.Security;
06    using MVC4SimpleMembershipCodeFirstSeedingEF5.Models;
07    using WebMatrix.WebData;
08   
09    #endregion
10   
11    namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations
12    {
13        internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
14        {
15            public Configuration()
16            {
17                AutomaticMigrationsEnabled = true;
18            }
19   
20            protected override void Seed(UsersContext context)
21            {
22                WebSecurity.InitializeDatabaseConnection(
23                    "DefaultConnection",
24                    "UserProfile",
25                    "UserId",
26                    "UserName", autoCreateTables: true);
27   
28                if (!Roles.RoleExists("Administrator"))
29                    Roles.CreateRole("Administrator");
30   
31                if (!WebSecurity.UserExists("lelong37"))
32                    WebSecurity.CreateUserAndAccount(
33                        "lelong37",
34                        "password",
35                        new {Mobile = "+19725000000"});
36   
37                if (!Roles.GetRolesForUser("lelong37").Contains("Administrator"))
38                    Roles.AddUsersToRoles(new[] {"lelong37"}, new[] {"Administrator"});
39            }
40        }
41    }

Now, run the update-database -verbose command from Package Manager Console, we are using the -verbose switch so that we can get better visibility on what’s getting executed on SQL. Notice the Mobile field is being created.

Let’s go ahead and do a sanity check and make sure all of our Users and Roles were provisioned correctly from the Seed method in our migration configuration, by executing a few queries.

01           SELECT TOP 1000 [UserId]
02                 ,[UserName]
03                 ,[Mobile]
04             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[UserProfile]
05             
06             SELECT TOP 1000 [RoleId]
07                 ,[RoleName]
08             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[webpages_Roles]
09             
10             SELECT TOP 1000 [UserId]
11                 ,[RoleId]
12             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[webpages_UsersInRoles]

Results



- Users were inserted
- Roles were provisioned
- The user “LeLong37″ was added and associated to the Administrator role

Finally for a sanity check, let’s go ahead and run the app and sign-in with the provisioned user from our Seed method.

One last thing, let’s go ahead and modify our Register view, Register model and AccountController to gather the user’s mobile number during registration.

Register View (Register.cshtml)

01           @model MVC4SimpleMembershipCodeFirstSeedingEF5.Models.RegisterModel
02           @{
03               ViewBag.Title = "Register";
04           }
05          
06           <hgroup class="title">
07               <h1>@ViewBag.Title.</h1>
08               <h2>Create a new account.</h2>
09           </hgroup>
10          
11           @using (Html.BeginForm()) {
12               @Html.AntiForgeryToken()
13               @Html.ValidationSummary()
14          
15               <fieldset>
16                   <legend>Registration Form</legend>
17                   <ol>
18                       <li>
19                           @Html.LabelFor(m => m.UserName)
20                           @Html.TextBoxFor(m => m.UserName)
21                       </li>
22                       <li>
23                           @Html.LabelFor(m => m.Password)
24                           @Html.PasswordFor(m => m.Password)
25                       </li>
26                       <li>
27                           @Html.LabelFor(m => m.ConfirmPassword)
28                           @Html.PasswordFor(m => m.ConfirmPassword)
29                       </li>
30                       <li>
31                           @Html.LabelFor(m => m.Mobile)
32                           @Html.TextBoxFor(m => m.Mobile)
33                       </li>
34                   </ol>
35                   <input type="submit" value="Register" />
36               </fieldset>
37           }
38          
39           @section Scripts {
40               @Scripts.Render("~/bundles/jqueryval")
41           }

Register model (AccountModel.cs)

01           public class RegisterModel
02           {
03               [Required]
04               [Display(Name = "User name")]
05               public string UserName { get; set; }
06          
07               [Required]
08               [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
09               [DataType(DataType.Password)]
10              [Display(Name = "Password")]
11               public string Password { get; set; }
12          
13               [DataType(DataType.Password)]
14               [Display(Name = "Confirm password")]
15               [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
16               public string ConfirmPassword { get; set; }
17          
18               [Required]
19               [DataType(DataType.PhoneNumber)]
20               [Display(Name = "Mobile")]
21               public string Mobile { get; set; }
22           }

Register Action (AccountController.cs)

01           [HttpPost]
02           [AllowAnonymous]
03           [ValidateAntiForgeryToken]
04           public ActionResult Register(RegisterModel model)
05           {
06               if (ModelState.IsValid)
07               {
08                   // Attempt to register the user
09                   try
10                   {
11                       WebSecurity.CreateUserAndAccount(
12                           model.UserName,
13                           model.Password,
14                           new { Mobile = model.Mobile },
15                           false);
16          
17                       WebSecurity.Login(model.UserName, model.Password);
18                       return RedirectToAction("Index", "Home");
19                   }
20                   catch (MembershipCreateUserException e)
21                   {
22                       ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
23                   }
24               }
25          
26               // If we got this far, something failed, redisplay form
27               return View(model);
28           }

Finally, let’s register.

Let’s go ahead and run our SQL queries again and make sure the mobile number was actually saved to our UserProfile table during the registration.

Sweet! Registration successful, with mobile number saved to the UserProfile table.

Happy Coding…!

 



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Create Mobile-Friendly HTML5 Forms with ASP.NET MVC 4

clock December 20, 2012 05:22 by author Scott

Mobilized Web Project Templates in Visual Studio 2010

The MVC 4 Mobile project template in Visual Studio 2010 contains all the files and references necessary to create a mobile-friendly Web site. When you create a new MVC 4 Mobile project, you’ll notice the familiar Models, Views and Controllers folders requisite for all MVC 4 projects (mobile or not) alongside new or modified scripts in the \Scripts folder. The \Scripts folder is where you’ll find the many jQuery files that serve as an API for building mobile-friendly Web sites, in particular, the jquery.mobile-1.0b2.js file for development and its minified partner, jquery.mobile-1.0b2.min.js, for deployment.

The \Content folder contains the location for style sheets, images and design-related files. Keep in mind that the jquery.mobile-1.0b2.css style sheet defines a look and feel that specifically targets multiple mobile platforms. (See http://jquerymobile.com/gbs/ for a list of supported mobile and tablet platforms.) Much like JavaScript files, there are two style sheets: a fat version for development and a minified version for production.

Data Sources for HTML5 Forms: MVC 4 Models and ViewModels

Regardless of whether the target is mobile or desktop, HTML5 form elements map to a property of an entity in a model or a ViewModel. Because models expose varied data and data types, their representation in the user interface requires varied visual elements, such as text boxes, drop-down lists, check boxes and buttons. You can see the full set of available controls or elements at the jQuery Mobile Web site’s Form Element Gallery.

Simple forms that contain only text inputs and buttons are not the norm. Most forms have several types of data. Because of this data variety, coding and maintenance will be easier if you use a ViewModel. ViewModels are a combination of one or more types that together shape data that goes to the view for consumption and rendering.

Let’s say you want to build a quick way for users of your Web site to provide feedback. You need to collect the user’s name, the type of feedback the user wants to leave, the comment itself, and the priority of the comment—that is, whether or not it’s urgent. Figure 1 shows how the FeedbackModel class definition captures these features in simple data structures such as strings, an int, and a Boolean.

public class FeedbackModel
{
    public string CustomerName { get; set; }
    public int FeedbackType { get; set; }
    public string Message { get; set; }
    public bool IsUrgent { get; set; }
}

Figure 1 Feedback Model

The FeedbackType property in Figure 1 is of type int, and it corresponds to the value the user selects at run time in the feedback type drop-down list defined in Figure 3.

Figure 2 contains the definition for the FeedbackViewModel, which is a combination of the FeedbackModel described in Figure 1 and the FeedbackType class (described in Figure 3).

public class FeedbackViewModel
{
    public FeedbackModel Feedback { get; set; }
    public FeedbackType FeedbackType { get; set; }        
    public FeedbackViewModel()
    {
        Feedback = new FeedbackModel();
        FeedbackType = new FeedbackType();
    }
}

Figure 2 Feedback ViewModel Containing the FeedbackModel and FeedbackType Properties

The use of the FeedbackType property highlights the purpose of ViewModels, which, as I mentioned earlier, is to shape disparate data sources or models together to form a single consumable source from the view, using strongly typed syntax.

While you can represent most of the data in a simple ViewModel as text boxes or check boxes, you also need to capture the type of feedback, which is a list of name-value pairs exposed in code as a more complex dictionary object. Figure 3 shows the FeedbackType class and the dictionary contained within it.

public class FeedbackType
{
    public static SelectList FeedbackSelectList
    {
        get { return new SelectList(FeedbackDictionary, "Value", "Key"); }
    }
    public static readonly IDictionary<string, int> 
         FeedbackDictionary = new Dictionary<string, int> 
    { 
        { "Select the type ...", 0 },
        { "Leave a compliment", 1 },
        { "Leave a complaint", 2 },
        { "Leave some SPAM", 3 },
        { "Other", 9 }
    };
}

Figure 3 FeedbackType Class, Including User Feedback Types

Now that the ViewModel is complete, the controller must pass it to the view for rendering. This straightforward code is in Figure 4 and is virtually identical to code that passes back a model.

public ActionResult Feedback()
{
    FeedbackViewModel model = new FeedbackViewModel();
    return View(model);
}

Figure 4 Controller Passing the ViewModel to the View

The next step in the process is setting up the view.

Creating HTML5 Mobile Forms in ASP.NET MVC 4 Views

You use the standard Add New Item command in Visual Studio 2010 to create feedback.cshtml, the view that will host your HTML5 form. ASP.NET MVC 4 favors a development technique named convention over configuration, and the convention is to match the name of the action method (Feedback) in the controller in Figure 4 with the name of the view, that is, feedback.cshtml. You can find the Add New Item command from the shortcut menu in Solution Explorer or the Project menu.

Inside the view, various ASP.NET MVC 4 Html Helpers present components of the FeedbackViewModel by rendering HTML elements that best fit the data types they map to in the ViewModel. For example, CustomerName renders as a standard single-line text box, while the Message property renders as a text area. FeedbackType renders as an HTML drop-down list so that the user can easily select an item rather than manually enter it. Figure 5 shows that there is no lack of Html Helpers to choose from for building forms.

@using (Html.BeginForm( "Results","Home")) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Leave some feedback!</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Feedback.CustomerName)
            @Html.ValidationMessageFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Feedback.FeedbackType, 
                 FeedbackType.FeedbackSelectList) 
            @Html.ValidationMessageFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.Message)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Feedback.Message)
            @Html.ValidationMessageFor(model => model.Feedback.Message)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.IsUrgent)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Feedback.IsUrgent)
            @Html.ValidationMessageFor(model => model.Feedback.IsUrgent)
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Figure 5 Html Helpers

With the ViewModel, controller and view, the form is now ready to test in the browser.

Testing the HTML Form on the Windows Phone 7 Emulator

Running a browser from Visual Studio is the easiest way to test the form, but the look and feel doesn’t behave in a very mobile-like way. For viewing the output and testing the form, the Windows Phone 7 Emulator works perfectly.

The HTML5 form displays in the Windows Phone 7 Emulator, as shown in Figure 6. You can enter a name, select a type from the drop-down list, fill in the comments and submit the form. Without modifications to the default styling provided by jQuery Mobile style sheets, the overall HTML5 form looks like the image on the left side of Figure 6. After tapping on the drop-down, the list of items looks like the image on the right side of Figure 6. Tapping a list item to select it returns the user to the form.

Figure 6 Interacting with the Windows Phone 7 Emulator

Submitting the form directs the browser to send the form information to the Home controller because of the call to the Html Helper, Html.BeginForm( "Results","Home"). The BeginForm method directs the HTTP request to the HomeController controller and then runs the Results action method, as the arguments denote.

Before the form submission process sends the HTTP Request to the server, however, client-side validation needs to happen. Annotating the data model accomplishes this task nicely. In addition to validation, data annotations provide a way for the Html.Label and Html.LabelFor helpers to produce customized property labels. Figure 7 details the entire data model with attributes for both validation and aesthetic annotations, and Figure 8 illustrates their results in the Windows Phone 7 Emulator.

public class FeedbackModel
{
    [Display(Name = "Who are you?")]
    [Required()]
    public string CustomerName { get; set; }
    [Display(Name = "Your feedback is about...")]
    public int FeedbackType { get; set; }
    [Display(Name = "Leave your message!")]
    [Required()]
    public string Message { get; set; }
    [Display(Name = "Is this urgent?")]
    public bool IsUrgent { get; set; }
}

Figure 7 Complete Data Model with Annotations

Figure 8 Left: Data Annotation Validations; Right: Data Annotation Aesthetics

You can customize the error message of the Required attribute to make the user interface friendlier. There are also many more annotations available in the System.Data.DataAnnotations namespace. If you can’t find a data annotation that fits your validation, aesthetic or security needs, inheriting from the System.Attribute class and extending it gives you that flexibility.

From the Phone to the Server Through HTTP POST

Once the user taps the submit button on the phone—and assuming the form passes validation—an HTTP POST Request is initiated and the data travels to the controller and action method designated in the Html.BeginForm method (as was shown in Figure 5). The sample from Figure 9 shows the controller code that lives in the HomeController and processes the data that the HTTP Request sends. Because of the power of ASP.NET MVC 4 model binding, you can access the HTML form values with the same strongly typed object used to create the form – your ViewModel.

[HttpPost()]
public ActionResult Results(FeedbackViewModel model)
{
    // calls to code to update model, validation, LOB code, etc...
    return View(model);
}

Figure 9 Capturing the HTTP POST Data in the Controller

When capturing HTTP POST data, data annotations once again assist in the task, since action methods that have no attribute stating the type of HTTP verb default to HTTP GET. 

Conclusion

Creating shiny new forms for mobile devices as well as desktops has never been easier with the partnership between ASP.NET MVC 4, jQuery Mobile and HTML5.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Mobile Features in ASP.NET MVC 4

clock November 15, 2012 07:37 by author Scott

ASP.NET MVC 4 Developer Preview is out and has some nifty new mobile features that will allow you to target mobile devices.

Mobile views

The new “Display Modes” feature lets an application render a specific view based on the device making the request. A desktop browser accessing a page might cause Index.cshtml to be rendered, but if the request comes from an iPad or an Andriod phone, Index.mobile.cshtml may be rendered. This convention-based approach lets you tailor your views without requiring any code changes.

The suffix “mobile” works out of the box, but you can also register your own display modes that target specific devices any particular way you wish. In the global.asax you could register something like the following:

DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
   ContextCondition = (context => context.Request.UserAgent.IndexOf
       ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});


This will register a mode specifically for iPhones, and allow you to create view pages with “iPhone” as a suffix, such as MyView.iPhone.cshtml.

See the release notes for additional details.

Programmatically detecting a mobile device

You may begin to add some mobile views to your application, only to realize that you actually need to customize more than just the way your views are rendered. Maybe you need to add or remove some of the data your page is querying or do something different altogether. I recently created a mobile version of this blog and couldn’t just use home controller action as-is. I wanted my mobile view to list a summary of all of my blog posts, rather than the full content of just the first 3 posts, which is what you see in a desktop browser.

HttpBrowserCapabilitiesBase browser = HttpContext.GetOverriddenBrowser();

//Some of the many properties, with values as seen from a Windows 7 Phone (emulator):

browser.Type; //IEMobile9

browser.Id; //iemobile
browser.MajorVersion; //9
browser.IsMobileDevice; //true
browser.InputType; //virtualKeyboard
browser.Crawler; //false


Simply call HttpContext.GetOverridenBrowser() to get access to the browser capabilities and you can determine whether it’s mobile, and act accordingly.  This method is an extension method in the System.Web.WebPages assembly, so don’t forget to add a using statement for this namespace!

Overriding the browser type

Detecting a mobile device like this isn’t new, of course. The first version of ASP.NET MVC allowed you to inspect the attributes of the requesting user-agent and chose the proper view to render. The downside of this is that there was no out-of-the-box way for a user to override this. Ever visit a site with your mobile phone and be presented with a stripped down view when you desperately wanted to see the full desktop-browser version, but couldn’t?

MVC 4 has this capability out-of-the-box with the SetOverriddenBrowser() extension method. You can call this and specify a browser type override. This is what the view switcher does in the jQuery.Mobile.MVC sample NuGet package, letting a user select whether they wish to be handled as a desktop or mobile device:

public RedirectResult SwitchView(bool mobile, string returnUrl) {
    if (Request.Browser.IsMobileDevice == mobile)
        HttpContext.ClearOverriddenBrowser();
    else
        HttpContext.SetOverriddenBrowser(mobile ? BrowserOverride.Mobile : BrowserOverride.Desktop);

    return Redirect(returnUrl);
}


The cool stuff comes from HTML5 and jQuery

ASP.NET MVC 4’s mobile features aren’t all that exciting to tell you the truth. The only new features so far are just some helpers and tooling around a technique that’s been around forever. That said, it’s a great addition to the framework.

What's really exciting is the things jQuery Mobile and HTML5 bring to the table, allowing you easily build slick UIs that will look great on a phone or tablet and rival a native application. For more on that, definitely check out the tutorial over on the ASP.NET website that will use these new MVC 4 features and jQuery Mobile.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Installation Error - Incompatible with .NET 4.5

clock November 1, 2012 09:22 by author Scott

Introduction

When you install ASP.NET MVC 4 for Visual Studio 2010, If you are already using 4.5 framework in your box then you might get some strange errors.

Background

In this case I already having .NET Framework 4.5 RC and I want to install ASP.NET MVC 4 for Visual Studio 2010.

I tried using the standalone installer for ASP.NET MVC 4 for Visual Studio 2010 but it throws me below error



Yes, you’ll see this strange error.
  The error said that Visual Studio 2010 needs .NET Framework 4.5. So, how to fix this error.

Solution


To resolve this issue I removed the .NET Framework
4.5 RC from local box.



And the second is uninstalling the .NET Framework 4.5 also removes pre-existing .NET Framework 4 files. If you want to go back to the .NET Framework 4, you must reinstall it and any updates to it.


If you are not installing .NET Framework 4.0 after uninstallation of Framework 4.5 then you will get another error saying something like 'Framework 4.0 not found".

Hope it helps!



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Upgrade ASP.NET MVC 3 Project to ASP.NET MVC 4 Project

clock October 24, 2012 11:02 by author Scott

ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, We can run both version of ASP.NET MVC projects on same machine.

If we would like upgrade an ASP.NET MVC 3 Project to ASP.NET MVC 4 Project, they are multiple ways. The simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match the old project. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.


To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:


1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):


System.Web.Mvc, Version=3.0.0.0

System.Web.WebPages, Version=1.0.0.0
System.Web.Helpers, Version=1.0.0.0
System.Web.WebPages.Razor, Version=1.0.0.0

with the following corresponding text:


System.Web.Mvc, Version=4.0.0.0

System.Web.WebPages, Version=2.0.0.0
System.Web.Helpers, Version=2.0.0.0
System.Web.WebPages.Razor, Version=2.0.0.0

2. In the root Web.config file, update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "
true":



3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 (RC) package, Click OK.


4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.


5. Locate the ProjectTypeGuids element and replace
{E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.

6. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:




Looking for ASP.NET MVC 4 Hosting? Find an affordable ASP.NET MVC 4 Hosting with HostForLIFE.eu

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET Single Page Application

clock October 22, 2012 09:23 by author Scott

What is Single Page Application?

Single Page Application is an architecture for web applications. It combines the best of web and desktop, built with HTML5 and JavaScript.Single Page Applications are rich and responsive. You do not need any browser plug-ins needs to install for this architecture, it is a standard web technology that is going to work on any device, operating system and browser.

The reference for this post is http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159 from Steve Sanderson’s Techdays talk,

You can develop Single Page Applications using ASP.NET MVC\Web Forms technologies.

Benefits

1. Great user experience
– It means speed, when it comes to changing of display of user interface and navigate around, we want an instance response from the application which you can get from this architecture.

2. Run on any device

3. Working off-line
– It is an interesting benefit which is just becoming possible now.

4. App-store deployable
- It is bit advanced programming but you can deploy your applications to windows market place or Apple app-store etc. This is now possible with Phone-gap third party tool for developing apps for mobiles.

The Architecture diagram looks as below



Typical Web architecture contains a server and client, where server contains an endpoint to server HTML/CSS and JS. The client side this being rendered as Visible UI and contains some javascript as well that is web technology.


What is different in Single Page Applications?

With single page web applications, you also tend to have an data end points on server and it is going to return JSON\XML to your application, You can use this data on client data access layer and render that data to UI.


We also want to have fast UI navigation, to done that we have Navigation API which allows you to book marking, navigate forth and back without talking to the server.

We can also make available all right hand side in the diagram offline. You can use local storage apis in HTML5 to work with the data offline.

Using the new Single Page Application project template and scaffolder

Create a new ASP.NET MVC application in Visual Studio, You can install MVC4 beta from here.



It will prompt you to select the project template there you can select Single Page Application project template as shown below



It creates a MVC application but the difference is it creates additional javascript libraries to make it easier for you build single page applications. If you want to use scaffolding then you can use a model class named TodoItem which will be created for you in model folder

To build a sample Single Page application using scaffolding, Add a controller to your solution



Choose the Single Page application template in controller dialogue box



Now run the application then you should be able to see the below output



What is different from other scaffolding applications is it follows single page application architecture and when you hit the browser back and forward it would not talk to the server. It also follows the all principles that we discussed on top.

 



European ASP.NET MVC Hosting - Amsterdam :: Use ASP.NET MVC Validation Attributes outside of ASP.Net

clock October 15, 2012 06:34 by author Scott

Some people love them, others absolutely hate them, but if you ask me one of the coolest features in ASP.Net MVC is the Data Annotations that you use to decorate your ASP.Net MVC classes for validation. But one of the coolest things that came along in .Net 4.0 was support for this across the whole framework – even outside of ASP.Net MVC!

When working on projects outside of ASP.Net MVC its still just as relevant to write validation for your classes and their respective properties before you fire actions, communicate them to another class or simply add something to a database (among the 4 million other times validation can come in handy).


Taking what we know from ASP.Net MVC, we can easily add this functionality to the public properties of any class in any project in .Net 4, be it a Console App, Web Service, SilverLight, Windows Phone 7 – you name it.


This also means that any common libraries you use between multiple projects can have simple Data Annotations added in one place and validated everywhere – keeping your validation logic all in one place.


Getting down to business

In the project that holds the data model classes you want to add validation to, add a reference to the framework namespace
System.ComponentModel.DataAnnotations



Now open the class you want to add validation to.


We are going to add the following to it:


- Add a class level meta data attribute telling our validator what type of class it is

- Add your validation decorations to any properties exactly as you would in ASP.Net MVC

In my example below, I demonstrate how to do this with a class named Person. You can see I've added a MetadataTypeAttribute of type Person above the class declaration. I’ve also added a required field decoration to the public Name property of this class.


[
MetadataTypeAttribute(typeof(Person))]
class
Person
{

    [Required(ErrorMessage = "You must enter a name")]
    public string Name { get; set; }
}


Now I've got to create a new class that we will use to validate our decorated attributes against objects – in this instance our Person class above, but the same code will work for any class with the correct decorations.


Create a new class in your project and call is
ClassValidator.

Paste the following code into that file:


public class
ClassValidator
{

    public ClassValidator(object objectToValidate)
    {
        objectBeingValidated = objectToValidate;
    }

    private static object objectBeingValidated { get; set; }

    public List<ValidationResult> ValidationErrors { get; private set; }

    public bool IsValid()
    {
        if (objectBeingValidated != null)
        {
            ValidationErrors = new List<ValidationResult>();
            var context = new ValidationContext(objectBeingValidated,
                null,
                null);

            bool isValid = Validator.TryValidateObject(objectBeingValidated,
                context,
                ValidationErrors);

            if (!isValid)
            {
                return false;
            }
            return true;
        }
        return false;
    }
}


And we are done - That is all we need!


Using the Code

To use the above example, all you need to do, is create an instance of our ClassValidator and pass in the object we want to validate at initialisation.


We can then call the IsValid() method against it to find out if our class validates and a list of any validation errors will then be available in the public ValidationErrors property of our ClassValidator.

My example below demonstrates this usage in a console application that does the following:

-
Creates an instance of the example Person object
- Doesn’t set any properties of this Person object (so our Name property will be Null - and therefore invalid)
-
Creates a ClassValidator and passes in my newly created Person, and then calls IsValid against it.
-
Prints all the errors found to the console.

Person p = new Person();


Console.WriteLine("Attempting to validate the person object");


ClassValidator validator = new ClassValidator(p);


Console.WriteLine("Is object valid of not?: {0}",validator.IsValid());


foreach
(var error in validator.ValidationErrors)
{

    Console.WriteLine("Error in Person object: {0}", error.ErrorMessage);
}

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Implementing custom XmlMediaTypeFormatter that ignores XML namespaces in ASP.NET MVC 4

clock September 11, 2012 07:31 by author Scott

In this blog post I will show how to implement a custom XmlMediaTypeFormatter that extends the default ASP.NET Web API XmlMediaTypeFormatter in a way that it ignores XML namespaces when parsing xml messages.

By default the ASP.NET Web API
XmlMediaTypeFormatter is not able to parse XML requests that contain any XML namespace declarations. If you would like to support clients, that (for any reason) send messages containing XML namespaces you can use the IgnoreNamespacesXmlMediaTypeFormatter that is defined as follows:

public
class IgnoreNamespacesXmlMediaTypeFormatter : XmlMediaTypeFormatter
{

  // See http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
  private const string NamespaceRemover =
    @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
        <xsl:output method='xml' indent='no'/>
        <xsl:template match='/|comment()|processing-instruction()'>
          <xsl:copy>
            <xsl:apply-templates/>
          </xsl:copy>
        </xsl:template>
        <xsl:template match='*'>
          <xsl:element name='{local-name()}'>
            <xsl:apply-templates select='@*|node()'/>
          </xsl:element>
        </xsl:template>
        <xsl:template match='@*'>
          <xsl:attribute name='{local-name()}'>
            <xsl:value-of select='.'/>
          </xsl:attribute>
        </xsl:template>
      </xsl:stylesheet>";

  private readonly XslCompiledTransform _xlstTransformer;

  public IgnoreNamespacesXmlMediaTypeFormatter()
  {
    var xslt = XDocument.Parse(NamespaceRemover, LoadOptions.PreserveWhitespace);
    _xlstTransformer = new XslCompiledTransform();
    _xlstTransformer.Load(xslt.CreateReader(), new XsltSettings(), new XmlUrlResolver());
  }

  public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
  {
    try
    {
      // Read XML
      var xmlDocument = XDocument.Load(new XmlTextReader(stream));

      // Transform XML
      var resultStream = new MemoryStream();
      _xlstTransformer.Transform(xmlDocument.CreateReader(), XmlWriter.Create(resultStream, new XmlWriterSettings() { OmitXmlDeclaration = true }));
      resultStream.Position = 0;

      // Process request with XmlMediaTypeFormatter default functionality
      return base.ReadFromStreamAsync(type, resultStream, contentHeaders, formatterLogger);
    }
    catch (XmlException)
    {
      return base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
    }
  }
}


In detail the
IgnoreNamespacesXmlMediaTypeFormatter removes the XML namespace declarations from the XML message and passes the modified XML to the base class to use the default XmlMediaTypeFormatter functionality. Removing the XML namespaces is done with a XSLT transformation (see http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl).

To activate the
IgnoreNamespacesXmlMediaTypeFormatter add the following lines in the file Global.asax.cs:

protected
void Application_Start()
{

  [...]
  // Remove default XmlFormatter and add (customized) IgnoreNamespacesXmlMediaTypeFormatter

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

  var ignoreNamespacesXmlMediaTypeFormatter = new IgnoreNamespacesXmlMediaTypeFormatter{ UseXmlSerializer = true };

GlobalConfiguration.Configuration.Formatters.Add(ignoreNamespacesXmlMediaTypeFormatter);

  [...]
}

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Heads up on a hidden breaking change in ASP.NET MVC 4

clock August 24, 2012 07:51 by author Scott

If you use an Editor Template for DateTime and use the DataTypeAttribute with either or DataType.Date and DataType.DateTime in ASP.NET MVC 2 or 3 and happen to upgrade to ASP.NET MVC 4 be aware!

ASP.NET MVC 4 introduces two new internal editor templates for properties marked as DataType.Date and DataType.DateTime to render HTML5 input types (date and datetime accordingly).

The unexpected side-effect of this is that if you were previously capturing all DateTime type editing through a DateTime editor template now if your property is marked as DataType.Date ASP.NET MVC 4 will use the new internal Date editor template instead of your DateTime editor template.

The solution is to provide a Date.cshtml editor template along your DateTime.cshtml editor template.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Create Separate Web API’s Action for Mobile Request: ASP.NET MVC 4

clock June 19, 2012 07:11 by author Scott

ASP.NET MVC 4.0 has two great features: One is Display Mode allows you to create mobile-specific and desktop-specific views and Second is Web API platform for building RESTful applications. Sometimes, You might need to return different data or perform different operations for desktop and mobile request. This article explains how to implement separate actions for mobile request keeping same URL format in Web API.

1. In Visual Studio, Select File > New Project > ASP.NET MVC 4 Web Application > Enter name > OK


2. Select ‘Web API‘ > View Engine: ‘Razor‘ > OK


3. You’ll get default ValuesController. When you access <your app url>/api/Values, the array of string value1, value2 is returned.


To create separate action for mobile request, We are going to create separate controller having ‘Mobile‘ suffix.


Right Click on ‘Controllers‘ folder > Add Controller > Give Name ‘ValuesMobileController‘ > Template: ‘API Controller with empty read/write actions‘ > Add


To differentiate both controllers, replace value1, value2 to mobile-value1, mobile-value2 in get method.


4. Now our object is to call action of Mobile controller when request comes from mobile device.


In Global.asax:


default api route:


routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );

Change it to


routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           ).RouteHandler = new MyRouteHandler();

and add following class:


public class MyRouteHandler : HttpControllerRouteHandler
   {
       protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
       {
           //Check whether request comes from mobile browser
           if (requestContext.HttpContext.Request.Browser.IsMobileDevice)
           {
               string controller = requestContext.RouteData.Values["controller"].ToString();
               requestContext.RouteData.Values["controller"] = controller + "Mobile";
           }
           return new MyHttpControllerHandler(requestContext.RouteData);
       }
   }

   public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
   {
       public MyHttpControllerHandler(RouteData routeData)
           : base(routeData)
       {
       }
   }

You have to import following namespaces:


using System.Web.Http.WebHost;
using System.Web.SessionState;

In this RouteHandler, Request.Browser.IsMobileDevice checks whether request comes from mobile browser and change controller name with ‘Mobile‘ suffix.

Now run app on browser, For testing, You can change user-agent to iPhone with user agent switcher Firefox add-on and open same URL. you’ll get mobile-value1 and mobile-value2.



Hope it helps

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in