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 :: How to Create Async Controllers with MVC 4

clock August 9, 2013 08:59 by author Scott

In this post I will show how to create async controllers in MVC 4.

The way to build asynchronous controllers has been completely changed compared to how it was done in MVC3 with the AsyncController superclass. This class and the inherent complexity in using it are gone in MVC4.

Start Visual Studio 2012 and create an MVC4 Web Application and choose the Internet template. Create a folder called “Services” in the solution. Insert two classes in this folder: DatabaseService and CalculationService. They represent long running calls to external services and have the following content:

DatabaseService.cs:

public class DatabaseService
    {
        public string GetData()
        {
            StringBuilder dataBuilder = new StringBuilder();
            dataBuilder.Append("Starting GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            Thread.Sleep(2000);
            dataBuilder.Append("Results from the database. ").Append(Environment.NewLine);
            dataBuilder.Append("Finishing GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return dataBuilder.ToString();
        }
    }

CalculationService.cs:

public class CalculationService
    {
        public string GetResult()
        {
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.Append("Starting GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            Thread.Sleep(2000);
            resultBuilder.Append("This is the result of a long running calculation. ");
            resultBuilder.Append("Finishing GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return resultBuilder.ToString();
        }
    }

There should be nothing complicated in either class implementation.

Create another folder in the solution called ViewModels. Add a class called HomePageViewModel in that folder:

public class HomePageViewModel
    {
        public List<String> Messages { get; set; } 

        public void AddMessage(string message)
        {
            if (Messages == null)
            {
                Messages = new List<string>();
            }
            Messages.Add(message);
        }
    }

Navigate to the Index action of the Home controller and modify it as follows:

public ActionResult Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 
            viewModel.AddMessage(calcService.GetResult());
            viewModel.AddMessage(dataService.GetData()); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Nothing complicated here either: we’re just adding messages to the view model, show the thread ids and measure the time it takes to complete the action.

Modify Index.cshtml of the Home view as follows:

@model Mvc4.ViewModels.HomePageViewModel
@{
    ViewBag.Title = "Home Page";


<ul>
    @foreach (String message in Model.Messages)
    {
        <li>@message</li>
    }
</ul>

So when you run the web page you should see an output similar to the following:

It’s easy to see the following:

  • The Index() action blocks the thread when it calls CalculationService and DatabaseService
  • The total processing time took about 4 seconds in total
  • All involved methods executed on the same thread

Now our goal is to make this process more efficient: as it stands now the main thread is only sitting idle for most of the processing time. This can be a serious problem if we’re intending to build a scalable and responsive application.

We need to make a couple of changes to our code:

  • The Index() action needs to return a Task of type ActionResult and turned to an async method: we do not directly return an ActionResult but a Task that represents an ActionResult
  • Remember that if an action is of type async then it needs to have its pair ‘await’ somewhere in the method body
  • We have two long running method calls within the Index() action, so we’ll instruct MVC4 to await them
  • Since we’ll await those two method calls we need to insert async versions of DatabaseService.GetData() and CalculationService.GetResult() as well: they in turn must also return Tasks of type string instead of plain string

Using our experience from the Console app in the previous post we’ll include an async version of GetResult() in CalculationService.cs:

public async Task<String> GetResultAsync()
        {
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.Append("Starting GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            await Task.Delay(2000);
            resultBuilder.Append("This is the result of a long running calculation. ");
            resultBuilder.Append("Finishing GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return resultBuilder.ToString();
        }

We’ll also insert a GetDataAsync() in DatabaseService.cs:

public async Task<String> GetDataAsync()
        {
            StringBuilder dataBuilder = new StringBuilder();
            dataBuilder.Append("Starting GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            await Task.Delay(2000);
            dataBuilder.Append("Results from the database. ").Append(Environment.NewLine);
            dataBuilder.Append("Finishing GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return dataBuilder.ToString();
        }

Update the Index action of the Home controller to call the async method versions of the services:

public async Task Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 

            string calculationResult = await calcService.GetResultAsync();
            string databaseResult = await dataService.GetDataAsync(); 

            viewModel.AddMessage(calculationResult);
            viewModel.AddMessage(databaseResult); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Run the web app now and you may see an output similar to the following:

Note the following:

  • The Index action started on thread id 10
  • The same thread enters GetResultAsync
  • The main thread exits GetResultAsync at the await keyword and thread 9 takes over
  • Thread 9 enters GetDataAsync and exits at the await keyword and thread 5 takes over
  • Thread 5 finished Index()
  • The total processing time is still about 4 seconds, but remember from the previous post: if you want to couple asynchronous methods with concurrency you need to include the TPL as well. This will be resolved later in this post.

The output on your screen may be different when you run the sample. It is not guaranteed that 3 different threads will be involved throughout the lifetime of the Index() action. It depends on the availability of threads, may only be 2 in total.

If you are working with WCF services and add a service reference to your project then you’ll have the option to generate the Async() versions of the service calls automatically. Make sure to select the ‘Allow generation of asynchronous operations’ checkbox and the ‘Generate task-based operations’ radiobutton in the Service Reference Settings window.

.NET4.5 is now interspersed with built-in async versions of long running and/or remote methods. Typical examples include: HttpClient.SendAsync that returns a Task of type HttpResponseMessage, or HttpContent.ReadAsStringAsync that returns a Task of type String.

We can now introduce TPL to make the service calls run in parallel. As it stands now the Index action first waits for GetResultAsync to finish before it goes on with GetDataAsync. Ideally Index should wait for both actions to complete in parallel and not one after the other. We will basically hold a reference to the Task values returned by the services and await them both together.

Update the Index action as follows:

public async Task<ActionResult> Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 

            Task<String> calculationResultTask = calcService.GetResultAsync();
            Task<String> databaseResultTask = dataService.GetDataAsync(); 

            await Task.WhenAll(calculationResultTask, databaseResultTask); 

            viewModel.AddMessage(calculationResultTask.Result);
            viewModel.AddMessage(databaseResultTask.Result); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Note the following:

  • We do not await the two service calls one by one
  • Both of them will be awaited using Task.WhenAll
  • Task.WhenAll accepts an array of Task objects that should run in parallel
  • Task.WhenAll will block until all tasks in the array have finished
  • The await keyword will make sure that Index will wait upon all tasks to complete in the array
  • To retrieve the returned value from the service calls just use the Result property of the Task object: this will be populated if the Task has a return value i.e. it is a Task of some type

When you run the updated Index page you may see something like this:

Again, your results will almost certainly differ. Which thread is allocated to which task is up to the thread scheduler. Refresh the page a couple of times to see some different results.



European ASP.NET MVC 4 Hosting - Amsterdam :: Tips to Enable and Disable Client Side Validation in MVC

clock August 5, 2013 10:38 by author Scott

In this article, I would like to demonstrate various ways for enabling or disabling the client side validation in ASP.NET MVC  3/4.

Enable Client-Side Validation in MVC

For enabling client side validation, we required to include the jQuery min, validate & unobtrusive scripts in our view or layout page in the following order.

<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

The order of included files as shown above, is fixed since below javascript library depends on top javascript library.

Enabling and Disabling Client-Side Validation at Application Level

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level.

<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

For client-side validation, the values of above both the keys must be true. When we create new project using Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.

We can also enable the client-side validation programmatically. For this we need to do code with in the Application_Start() event of the Global.asax, as shown below.

protected void Application_Start()
{
//Enable or Disable Client Side Validation at Application Level
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

Enabling and Disabling Client-Side Validation for Specific View

We can also enable or disable client-side validation for a specific view. For this we required to enable or disable client side validation inside a Razor code block as shown below. This option will overrides the application level settings for that specific view.

@model MvcApp.Models.Appointment
@{
ViewBag.Title = "Make A Booking";
HtmlHelper.ClientValidationEnabled = false;
}
...

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Create Custom HTML Helpers in ASP.NET MVC 4

clock July 29, 2013 08:39 by author Scott

HTML Helpers are nothing but the way of rendering HTML on the view page in ASP.NET MVC. Typically what we have in traditional ASP.NET web forms is Web Controls to achieve same functionality but with the evolution of MVC pattern , you don't have any web controls to add on to the view pages.

In simple words - it is just a method which returns you a string , and string is HTML.

Example of HTML Helpers:

ASP.NET MVC framework ships with various inbuilt HTML helpers such as ActionLink , Label.
Lets take a look at how a HTML helper is added to the view page. I am considering Razor view engine for this example.

@Html.ActionLink("Display Name of Link", "MethodName", "ControllerName");

Example above shows how OOB Action Link is used to render the HTML hyperlink on the view page.

Another example is shown as below where it is used to render the Html label tag to render Store Name property of model class. 

@Html.LabelFor(model => model.StoreName)

Why to use Html Helpers?

Question might have poped up in your mind by now that Html helpers are just going to render the string of html then why do I need to use them ? If I know the Html syntax then why not add the Html directly on to the view page? 

Answer is simple, it depends how clean and consistent you want to make your application. of course you can do the direct addition of html tags on your view pages but if you observe second example - you can see that it is simply rendering the label tag on view page for a property in model at run time. so it just for making developer's life more easy and to have the cleaner html for your view page.

Need of Custom Html Helpers?

Well, there is always need to do some custom stuff on top of what framework offers, and reason for doing this is either business requirement or to get things done in smarter way.

Writing a custom Html helper is nothing but writing an extension method. you are actually writing an extension method for HtmlHelper class.

Being a SharePoint developer I always find this task similar to creation of a web control where you override the render method of base class and do the custom Html rendering. 

Creating Custom Html Helper

All right , for demo purpose I will keep the example simple - I will simply write an Html helper which will render the header of any content on view page.

This is done simply by using the <header> tag of Html 5.

Step 1: Define your custom static class for creation of your custom Html helpers

public static class DemoCustomHtmlHelpers
{

}

Step 2: Add static method to the class and make sure that return type is MvcHtmlString. Write an input paramter of method as HtmlHelper and also a string for which the header tag needs to be generated.

You might need to add System.Web.Mvc namespace to your class.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{         


}

Step 3 : Add the rendering logic in the method , you can take help from TagBuilder class to generate Html tags to be rendered.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{
   var tagBuilder = new TagBuilder("header");
   tagBuilder.InnerHtml = content;
   return new MvcHtmlString(tagBuilder.ToString());
}

Step 4: Build the project and open any of the view page. Now you can use your custom Html helper to render the header. Make sure that your view page has correct using namespace for using your custom Html helper extension.

@Html.Header("Create")

When you observe the view page's Html , you will be finding the generated Html tag by our Custom Html helper extension

<header>Create</header>

Now, you can also try it and have fun with your own scenario.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Using MVC 4 to Run Sitecore

clock July 17, 2013 11:19 by author Scott

ASP.NET MVC is everywhere, and if you judge from the the job adverts ASP.NET Web Forms is rapidly being consigned to the “legacy” category. So where does that leave developers like me, currently using Sitecore?
Although it seems to me that Sitecore is Web Forms to it’s back teeth, there are nevertheless some signs that it too is going MVC.

From Sitecore version 6.6 there is support for MVC straight out of the tin (or the installer, at least). This is great but how do you get from that install to not just an MVC project, but MVC 4 (.NET 4.5) using Visual Studio 2012?
The steps are available around and about, but this post seeks to update the process to the latest version of Sitecore and pull it all together.

If you are really new to Sitecore MVC, probably the best place to start is here.

1. Create a Visual Studio Project from the install

a.) Using the latest version of Sitecore (Sitecore 6.6.0 rev. 130214), create a new instance
b.) Create a new Empty Website with Visual Studio 2012 using .NET 4 (but NOT MVC)
c.) Copy the Sitecore instance into your Empty Project Directory, and include the files (and Assembly References) into it. I found that the best way to get the Assemblies in was to copy them to a third directory (not the bin directory), then browse to that and Visual Studio will add them, nice and cleanly.
d.) Take the global.asax from the Sitecore Instance, pull out the inline code and paste it into a new global.asax.cs
e.) Publish the Site

2. Make the project MVC3

a.) Unload the project, then right-mouse click to edit the project file. In the project file you will find an element

<ProjectTypeGuids>

add this GUID to it at the front of the list, separated by a semi-colon:
{E53F8FEA-EAE0-44A6-8774-FFD645390401};

b.) Reload the project you now have an MVC3 Sitecore project.

c.) You should now confirm that MVC3 is working:

(this taken from John West’s blog)

Create a the subdirectory /Views containing a nested subdirectory named Sitecore.
Create the /Views/Sitecore/index.cshtml file containing some Razor code (note that the @inherits directive is not necessary if the /Views subdirectory contains the proper web.config file, such as that installed when you create an MVC project in Visual Studio):

@inherits System.Web.Mvc.WebViewPage
@{
  Layout = null;
}
<html>
  <body>
  <h4>Index.cshtml</h4>
  <div>Model:
@{
  if (Model == null)
  {
<text>null</text>
  }
  else
  {
@Model.GetType();
  }
}
    </div>
  </body>
</html>

In the Sitecore Content Editor user interface, navigate to the /sitecore/layout/Layouts/Sample Layout item that defines the default layout.
Click the Content Tab.

In the Path field, enter /Views/Sitecore/index.cshtml, and save.

Either publish the layout definition item and view the home page of the published site (http://playground – not http://playground/default.aspx), or use the Page Editor. You should see content such as the following:

Index.cshtml

Model: Sitecore.Mvc.Presentation.RenderingModel

3. Make the Project MVC 4

a.) In the project Website Properties change the Target Framework to .NET 4.5

b.) Update the references from MVC3 to MVC4

all references in .config files need to reflect these versions:
System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″
System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
System.Web.Helpers, Version=2.0.0.0, Culture=neutral, publicKeyToken=”31bf3856ad364e35″
System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35

these appSettings need to be added to the web.config:

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
  <add key="PreserveLoginUrl" value="true" />
</appSettings>

further details here:

c.) In Solution Explorer, right-click on the References and select Manage NuGet Packages. In the left pane, select Online\NuGet official package source, then update the following:

ASP.NET MVC 4
(Optional) jQuery, jQuery Validation and jQuery UI
(Optional) Entity Framework
(Optonal) Modernizr

d.) Update ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

e.) 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:

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

f.) Finally, there is an incompatability with the Sitecore login page under .NET 4.5, to do with the use of an iframe. The file sitecore/login/default.aspx contains an iframe to the SDN that .NET 4.5 doesn’t like. Replace it with a div:

<iframe id="SDN">
  <div id="StartPage" runat="server" allowtransparency="true"
 frameborder="0" scrolling="auto" marginheight="0" marginwidth="0"
 style="display: none"></div>
</iframe> 

<div id="SDN">
  <div id="StartPage" runat="server" allowtransparency="true"
 frameborder="0" scrolling="auto" marginheight="0" marginwidth="0"
 style="display: none"></div>
</div>

and you’re off to the races. More detail here.

I should point out, of course that .NET 4.5 is not supported as yet by Sitecore, but with this you can play with 4.5… until Sitecore 7 arrives.

Good luck.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Enhanced Default Template MVC 4

clock July 5, 2013 07:10 by author Scott

MVC 4 introduces many new features. In today post, I will talk about MVC 4 and enhanced default templates.

When you create a new project, the default website looks quite different from previous versions.  Besides the improved aesthetics, the default website has improved functionality thanks to a technique called adaptive rendering.

Adaptive rendering is where the page is rendered specific to the browser without any customization.  This is an absolute must for most developers today; write once, run everywhere.  The adaptive rendering is made possible thanks to a new CSS type -> media queries

@media all and (min-width: 640px) { #media-queries-1 { background-color: #0f0; } }
@media screen and (max-width: 2000px) { #media-queries-2 { background-color: #0f0; } }

After you creating a new website, you’ll be able to see the improvements in the default layout.

To see the adaptive rendering in action, open the page using a mobile device.

Here’s how the page looks on an iPhone.

And here’s how the page look on an iPad.

The page renders differently depending on the size of the screen.  Making the page do that without media queries is tricky.  Using media queries makes it simple.

One final thing to note is the default template takes advantage of jQuery UI also.  The Login and Register links show you how to use this JavaScript library to  provide a richer UI.  You can read all about the other features that are available to you with jQuery UI here.

Testing with Emulators

The best way I found to test what the site will look like is with FireFox and User Agent Switcher add-on,
which changes the user agent that’s sent to the browser.  That can be downloaded
here.



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Fix CSS Problem in ASP.NET MVC 4

clock July 1, 2013 12:10 by author Scott

Some of you will face this problem when using Bundling and Minification in ASP.NET MVC 4. This post cover about how to fix relative CSS Path in ASP.NET MVC 4.

Recently, I hit a known problem with deploying to IIS virtual directories. It’s not a problem for ASP.NET which understands virtual directories and so if you ask for “~” or “/” will return “yoursite/virtualfolder”. However, JavaScript is run under IIS, which doesn’t understand this idea so well. Do “/” in JS and you’ll get back “yoursite” NOT “yoursite/virtualfolder”.

So what’s the fix? Well, for JavaScript there are a couple of answers. So I check my javascript. Based on this answer, I came up with this:

1. Add a hidden field to a masterpage:

  @Html.Hidden("HiddenCurrentUrl",  Url.Content("~"))

2. As one of the first things you do, ensure this JS runs. All it does it take the value in the field and store it:

var baseUrl = "";
baseUrl = $("#HiddenCurrentUrl").val();


3. Use baseUrl wherever you need to call things in JavaScript:

Silverlight.createObject(
            baseUrl + "ClientBin/SilverlightBridge.xap",  // source
            ...
        );

Hmm… But you know, that is not the problem. The problem is with the CSS file

    .link-button.cancel {
        background-image: url('../Images/appbar.cancel.darkgrey.png');
    }

A similar problem occures where these URLs start with a slash(/) because IIS interprets that incorrectly. You can’t invoke ASP.NET, which does know the right root into a CSS file

After some messing around, I came to this compromise, which works well. It also exposes some of the hidden power of using Bundling:

  1. For any images you reference in CSS, move them into a relative folder, such as /images near the CSS. I know, this may be an unacceptable compromise for you. But actually, it makes a lot of sense. The image is probably only used by the CSS so it makes sense to have it nearby, not in some global /images folder.  
  2. In order to make this work, you need to get your CSS (which you’ve bundled up) into the same place relative to the images you’re reference, or at least, you need to cheat the browser into thinking this happening.
  3. So, for instance:

      bundles.Add(new StyleBundle("~/Content/DataTableStyle").Include(


    comes out the other end as:

Don’t forget that all your “static” content, such as images won’t be affected by Bundling and can be referenced using the folder structure you expect, i.e. the one you’ve set up in Visual Studio.

So… when you create the Style Bundle you give it a name which reflects where you have it in your Visual Studio folder structure, then it will pop out the other end in the same place, relatively, to the image files which it’s references! And because the Bundling is happening via ASP.NET, the URL of the CSS file, and wherever it is referenced, works fine in virtual directories!



European ASP.NET MVC 4 Hosting - Amsterdam :: What is PRG and Using PRG on MVC 4

clock June 18, 2013 06:55 by author Scott

Hellooo….. Today post I will talk about what is PRG in ASP.NET MVC 4 and how to use it. Before we start, the question is what is PRG?

What is the PRG Pattern ?

  • PRG stands for "Post/Redirect/Get"
  • Instead of returning an HTML page directly,
  • The POST operation returns a redirection command (using the HTTP 303 response code (sometimes 302)
  • together with the HTTP "Location" response header),
  • Instructing the browser to load a different page using an HTTP GET request
  • The result page can then safely be bookmarked or reloaded without unexpected side effects

How to Explain this by using an Example ?

  • Here I'm going to use User Registration function as an example
  • If the Registration attempt is Successful, the user should be redirected to his Home page
  • Otherwise they should be redirected back to the Registration page

Image 1 : Shows Action Methods Interaction When do Registration

AccountController.cs        

Code for the Register Action Method (Get) for Displaying Register View is as below

        /// <summary>
        /// for displaying Register View
        /// </summary>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
              }

Image 2 : Register View

Code for the Register Action Method (Post) for Processing the Registration and Shows Register Page again is as below

        /// <summary>
        /// for Registering the User
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
          if (ModelState.IsValid)
          {
            // Attempt to register the user
            try
             {
               WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
               WebSecurity.Login(model.UserName, model.Password);
               ViewBag.Message = "Successfully Registered!";
               return View(model);//PRG has not been Maintained
             }
              catch (MembershipCreateUserException e)
             {
                 ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
             }
          }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

Image 3 : New user has been Created



- At this point If you try to Refresh (F5) or Reload the Page,You'll see below mentioned kind of Security Alert Message Box

Image 4 : Register form with "Confirm Form Resubmission" Message Box



- After that If you try to press "Continue" Button, You'll see below mentioned Run time exception
- But for another situation this may be Data Duplication issue etc.

Image 5 : Run time Exception

How to Get Rid Of this Issue ?

  • You have to maintain PRG Pattern with your Return type, After finishing the Successful Registration
  • To properly perform PRG you must return a redirecting ViewResult from your Action
  • Such as RedirectToAction, otherwise you'll get the dialog box pictured above (i.e. Image 4)

Code for the Properly Perform PRG Pattern is Maintaining Register Action Method is as below

    /// <summary>
    /// for Registering the User
    /// </summary>
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
     {
      if (ModelState.IsValid)
      {
       // Attempt to register the user
       try
       {
         WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
         WebSecurity.Login(model.UserName, model.Password);
         ViewBag.Message = "Successfully Registered!";
         return RedirectToAction("Index""Home");//PRG has been Maintained
        }
        catch (MembershipCreateUserException e)
        {
          ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
      }
       // If we got this far, something failed, redisplay form
       return View(model);
     }

Image 6 : Home page

DONE!!



European ASP.NET MVC 4 Hosting - Amsterdam :: Revisiting IBundleTransform ASP.NET 4.5 and MVC 4

clock May 13, 2013 10:26 by author Scott

Web optimization frameworks include two defaults transform type JsMinify and CssMinify which is used by ScriptBundle and StyleBundle respectively. However we can create our own custom transform type to processe references as per our need. To create custom transform type, we need to create class which implements IBundleTransform interface.

IBundleTransform interface define a method named Process which process bundle response. In developer preview version, Process method had only one parameter of type BundleResponse, however onwards RC release, Process method introduced one more parameter of type BundleContext. In this post, we will see how we can utilize this additional parameter while creating our custom transform type.

BundleContext

As name suggest, with BundleContext, we can get information about bundles which could include existing bundle information, bundle url, HTTP context for bundle, etc. Following is the list of all property of BundleContext.

- BundleContext.BundleCollection : We can get collection of all bundles including default and custom bundle in application through this property.

- BundleContext.BundleVirtualPath : This property expose virtual bundle url i.e. ~/bundles/MyBundle.

- BundleContext.HttpContext : This property is type of HttpContextBase, and we can have access of HTTP context through this property. This is very much useful property when we are creating transform type which generate dynamic response. For e.g. we can access query string parameter passed to bundle url (~/bundles/MyBundle?id=123) through this property (context.HttpContext.Request.QueryString["id"]) and we can use it to create dynamic bundle response.

- BundleContext.UseServerCache : Default value of this property is true. It means only first request to bundle url will be intercepted by transform types and once response is generated it will be stored in server cache and further request to bundle url will be served from server cache without processing it. This will help to reduce bundle processing time and to increase performance. If we set BundleContext.UseServerCache to false then all request will be processed by transform type this is only necessary when bundle url are generating dynamic response. See detailed walkthrough later in this post showing how to use this property in accordance with BundleResponse.Cacheability.

- BundleContext.EnableInstrumentation : Default value of this property is false. This is used for tracing and analysis purpose. We can check value of this property and can write tracing code accordingly. We can also set true to this property to enable instrumentation for further lifecycle of Web optimization frameworks for current bundle request.

BundleResponse

BundleResponse is used to retrieve list of files included in bundle so we can process it and generate response for bundle. As BundleResponse is used to generate response of bundles, it needs to take care of two primary properties of generated response. One is response content type and another one is HTTP Cache-Control header. So BundleResponse also expose properties for the same. Following is the list of all properties in BundleResponse class.

- BundleResponse.Files : This is IEnumerable collection of files which is included in bundle. We can iterate through this collection and process file content to generate bundle response.

- BundleResponse.ContentType : Through this property, we can set content type for bundle so that browser can render it appropriately. Default content type "text/html".

- BundleResponse.Cacheability : We can use this property to set Cache-Control HTTP header of bundled response. Default value of this property is Public.

- BundleResponse.Content : Anything which we set as a value of this property, that content will be sent back to browser as a response of bundle.

Following is the complete code which shows how to create custom transform type and how we can use it with bundling.

public class CustomTransformType : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        string strBundleResponse = string.Empty;
        foreach (FileInfo file in response.Files)
        {
            // PROCESS FILE CONTENT
        }
        response.Content = strBundleResponse;
    }


Bundle myBundle = new Bundle("~/bundles/MyBundle", new CustomTransformType());
myBundle.Include("~/path/to/file");
bundles.Add(myBundle);

Bundle and truly dynamic response

As we noted earlier, we can set BundleContext.UseServerCache to false in order to process all bundle request and generate dynamic response. Let try to simulate this by small walkthrough and see it works or we need to take care any additional parameter.

public void Process(BundleContext context, BundleResponse response)

{
    context.UseServerCache = false;
    response.Content = DateTime.Now.ToString();
}


We are returning current date time with UseServerCache set to false. Now try to hit bundle url multiple times by pressing F5. Oops… it seems it has processed bundle response only first time. Let dig more into this, open another browser and hit same url… ahmm it seems it has processed bundle response one more time… again press F5 multiple times…bad luck

As we can see, it seems (read again it seems) it is processing bundle response only first time for separate client (is it really? nop). Nop this is not the case. In fact this is how client deals with it due to HTTP cache control header. Confused? See response header of bundle url to get more information.

As we noted earlier default value of BundleResponse.Cacheability is Public. So even if we have set BundleContext.UseServerCache to false then also due to Expires response header and Public Cache-Control header client is not sending request back to server. So in this case we need to also set BundleResponse.Cacheability to NoCache. We can also set it to Private but in some client we need to press Ctrl + F5 to refresh bundle response.

public void Process(BundleContext context, BundleResponse response)
{
    context.UseServerCache = false;
    response.Cacheability = HttpCacheability.NoCache;
    response.Content = DateTime.Now.ToString();
}

After setting BundleResponse.Cacheability to NoCache try to refresh bundle url again now it is re generating bundle response on each request.



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Upload a file in MVC4 C#5 .NET 4.5

clock May 3, 2013 06:33 by author Scott

One of the features of this so called killer app will be to upload pictures (nothing special I agree). But how would I do this for all the clients I hope to support (WinRT/WP7/Html5/IOS).

Let me first present the server that will be used for all these clients, I’ll then follow up with what I consider to be the simplest client a html5 browser!

Server

So I fired up VS11 and created a new MVC4 application using .net 4.5 / C#  and the WebApi template.

I then added a controller called FileUploadController.cs

   1:  using System.Collections.Generic;
   2:  using System.Linq;
   3:  using System.Net;
   4:  using System.Net.Http;
   5:  using System.Threading.Tasks;
   6:  using System.Web.Http;
   7:   
   8:  namespace MvcApplication16.Controllers
   9:  {
  10:      public class FileUploadController : ApiController
  11:      {
  12:          public async Task<IEnumerable<string>> PostMultipartStream()
  13:          {
  14:              // Check we're uploading a file
  15:              if (!Request.Content.IsMimeMultipartContent("form-data"))           
  16:                  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  17:                 
  18:              // Create the stream provider, and tell it sort files in my c:\temp\uploads folder
  19:              var provider = new MultipartFormDataStreamProvider("c:\\temp\\uploads");
  20:   
  21:              // Read using the stream
  22:              var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);           
  23:          
  24:              // Create response.
  25:              return provider.BodyPartFileNames.Select(kv => kv.Value);           
  26:          }
  27:      }
  28:      
  29:  }

You can see from line 12 that I’ve made this operation async, you’ve really got to admire the simplicity of async/await construct in .net 4.5! In line 22 you can see that the compiler and some state machine magic allow the freeing up of the asp worker thread…..

HTML5 Client

The client couldn’t have been easier, fist a look at it in the browser

   7:      <meta name="viewport" content="width=device-width" />
   8:  </head>
   9:  <body>
  10:      @using (Html.BeginForm("FileUpload", "api", FormMethod.Post, new { enctype = "multipart/form-data" }))
  11:      {
  12:          <div>Please select some files</div>
  13:          <input name="data" type="file" multiple>
  14:          <input type="submit" />           
  15:      }
  16:  </body>
  17:  </html>

The important part above is using the enctype attribute, in fact line 10 loosely translates to

<form action="~/api/FileUpload" enctype="multipart/form-data" method="POST">

Don’t believe me? Then try VS11’s awesome new feature – page inspector

Right click on the html and choose view in page inspector

and we’re done! Of course in the real world we’ll use ajax with a few trick re sandbox, but here’s the response in the browser with xml.

I’ll hopefully follow up with the samples for the client list below when I get to the respective development machines.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Using MySql 5 as Membership Backend for ASP.NET 4.5 MVC 4 Application

clock May 1, 2013 09:18 by author Scott

Oracle provide MySql ASP.Net web providers through NuGet – search for MySql.Web. Using the MySql providers you can easily use MySql as your membership/profile/role backend for an ASP.Net application.

I am going to demonstrate using it as the membership provider for an MVC 4 application using Razor but the steps are almost identical for the ASPX views.

Web.config for MySql Membership Provider

Use the following configuration in your web.config file:

1              <membership defaultProvider="MySqlMembershipProvider">
2              <providers>
3              <clear />
4              <add name="MySqlMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.5.4.0, PublicKeyToken=c5687fc88969c44d"
5              autogenerateschema="true"
6              connectionStringName="*NAME_OF_YOUR_CONN_STRING*"
7              enablePasswordRetrieval="false"
8              enablePasswordReset="true"
9              requiresQuestionAndAnswer="false"
10           requiresUniqueEmail="false"
11           passwordFormat="Hashed"
12           maxInvalidPasswordAttempts="5"
13           minRequiredPasswordLength="6"
14           minRequiredNonalphanumericCharacters="0"
15           passwordAttemptWindow="10"
16           passwordStrengthRegularExpression=""
17           applicationName="/" />
18           </providers>
19           </membership>

Obviously you also need to configure a valid MySql connection string, create a MySql schema, change any other security settings you want and put the name of your connection string into the provider configuration but your on your own doing that.

Create Tables

Once you have the initial setup done open the ASP.Net configuration website (VS2012: Project menu -> ASP.NET Configuration – at the bottom of the menu) and create a user in the security tab. Doing this will create the database structure and a new user providing you have set the configuration up correctly.

Unbreak the MVC 4 AccountController

This is a simple fix for getting MySql up and running. Basically we just rollback the AccountController to use the old style MembershipProvider which is supported by the MySql MembershipProvider.

  1. Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view
  2. Create a new MVC 3 web application
  3. Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application
  4. Replace @Html.Partial(“_LoginPartial”) in the shared _Layout view with @Html.Partial(“_LogOnPartial”)

This won’t support OAuth authentication but will get your MySql Membership provider up and running with ASP.Net 4.5 and MVC 4.

Raw SQL for MySql Membership Tables

If you want to directly create the membership data structure without using the ASP.NET configuration tools use the following SQL as a base and modify SCHEMA_NAME and collation to be what you require.

1              -- -----------------------------------------------------
2              -- Table `SCHEMA_NAME`.`my_aspnet_applications`
3              -- -----------------------------------------------------
4              CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_applications` (
5                `id` INT(11) NOT NULL AUTO_INCREMENT ,
6                `name` VARCHAR(256) NULL DEFAULT NULL ,
7                `description` VARCHAR(256) NULL DEFAULT NULL ,
8                PRIMARY KEY (`id`) )
9              ENGINE = InnoDB
10           AUTO_INCREMENT = 2
11           DEFAULT CHARACTER SET = latin1
12           COLLATE = latin1_swedish_ci;
13           -- -----------------------------------------------------
14           -- Table `SCHEMA_NAME`.`my_aspnet_membership`
15           -- -----------------------------------------------------
16           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_membership` (
17             `userId` INT(11) NOT NULL DEFAULT '0' ,
18             `Email` VARCHAR(128) NULL DEFAULT NULL ,
19             `Comment` VARCHAR(255) NULL DEFAULT NULL ,
20             `Password` VARCHAR(128) NOT NULL ,
21             `PasswordKey` CHAR(32) NULL DEFAULT NULL ,
22             `PasswordFormat` TINYINT(4) NULL DEFAULT NULL ,
23             `PasswordQuestion` VARCHAR(255) NULL DEFAULT NULL ,
24             `PasswordAnswer` VARCHAR(255) NULL DEFAULT NULL ,
25             `IsApproved` TINYINT(1) NULL DEFAULT NULL ,
26             `LastActivityDate` DATETIME NULL DEFAULT NULL ,
27             `LastLoginDate` DATETIME NULL DEFAULT NULL ,
28             `LastPasswordChangedDate` DATETIME NULL DEFAULT NULL ,
29             `CreationDate` DATETIME NULL DEFAULT NULL ,
30             `IsLockedOut` TINYINT(1) NULL DEFAULT NULL ,
31             `LastLockedOutDate` DATETIME NULL DEFAULT NULL ,
32             `FailedPasswordAttemptCount` INT(10) UNSIGNED NULL DEFAULT NULL ,
33             `FailedPasswordAttemptWindowStart` DATETIME NULL DEFAULT NULL ,
34             `FailedPasswordAnswerAttemptCount` INT(10) UNSIGNED NULL DEFAULT NULL ,
35             `FailedPasswordAnswerAttemptWindowStart` DATETIME NULL DEFAULT NULL ,
36             PRIMARY KEY (`userId`) )
37           ENGINE = InnoDB
38           DEFAULT CHARACTER SET = latin1
39           COLLATE = latin1_swedish_ci
40           COMMENT = '2';
41           -- -----------------------------------------------------
42           -- Table `SCHEMA_NAME`.`my_aspnet_profiles`
43           -- -----------------------------------------------------
44           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_profiles` (
45             `userId` INT(11) NOT NULL ,
46             `valueindex` LONGTEXT NULL DEFAULT NULL ,
47             `stringdata` LONGTEXT NULL DEFAULT NULL ,
48             `binarydata` LONGBLOB NULL DEFAULT NULL ,
49             `lastUpdatedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
50             PRIMARY KEY (`userId`) )
51           ENGINE = InnoDB
52           DEFAULT CHARACTER SET = latin1
53           COLLATE = latin1_swedish_ci;
54           -- -----------------------------------------------------
55           -- Table `SCHEMA_NAME`.`my_aspnet_roles`
56           -- -----------------------------------------------------
57           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_roles` (
58             `id` INT(11) NOT NULL AUTO_INCREMENT ,
59             `applicationId` INT(11) NOT NULL ,
60            `name` VARCHAR(255) NOT NULL ,
61             PRIMARY KEY (`id`) )
62           ENGINE = InnoDB
63           DEFAULT CHARACTER SET = latin1
64           COLLATE = latin1_swedish_ci
65           ROW_FORMAT = DYNAMIC;
66           -- -----------------------------------------------------
67           -- Table `SCHEMA_NAME`.`my_aspnet_schemaversion`
68           -- -----------------------------------------------------
69           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_schemaversion` (
70             `version` INT(11) NULL DEFAULT NULL )
71           ENGINE = InnoDB
72           DEFAULT CHARACTER SET = latin1
73           COLLATE = latin1_swedish_ci;
74           -- -----------------------------------------------------
75           -- Table `SCHEMA_NAME`.`my_aspnet_sessioncleanup`
76           -- -----------------------------------------------------
77           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_sessioncleanup` (
78             `LastRun` DATETIME NOT NULL ,
79             `IntervalMinutes` INT(11) NOT NULL )
80           ENGINE = InnoDB
81           DEFAULT CHARACTER SET = latin1
82           COLLATE = latin1_swedish_ci;
83           -- -----------------------------------------------------
84           -- Table `SCHEMA_NAME`.`my_aspnet_sessions`
85           -- -----------------------------------------------------
86           CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_sessions` (
87             `SessionId` VARCHAR(255) NOT NULL ,
88             `ApplicationId` INT(11) NOT NULL ,
89             `Created` DATETIME NOT NULL ,
90             `Expires` DATETIME NOT NULL ,
91            `LockDate` DATETIME NOT NULL ,
92             `LockId` INT(11) NOT NULL ,
93             `Timeout` INT(11) NOT NULL ,
94             `Locked` TINYINT(1) NOT NULL ,
95             `SessionItems` LONGBLOB NULL DEFAULT NULL ,
96             `Flags` INT(11) NOT NULL ,
97             PRIMARY KEY (`SessionId`, `ApplicationId`) )
98           ENGINE = InnoDB
99           DEFAULT CHARACTER SET = latin1
100         COLLATE = latin1_swedish_ci;
101         -- -----------------------------------------------------
102         -- Table `SCHEMA_NAME`.`my_aspnet_users`
103         -- -----------------------------------------------------
104         CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_users` (
105           `id` INT(11) NOT NULL AUTO_INCREMENT ,
106           `applicationId` INT(11) NOT NULL ,
107          `name` VARCHAR(256) NOT NULL ,
108           `isAnonymous` TINYINT(1) NOT NULL DEFAULT '1' ,
109           `lastActivityDate` DATETIME NULL DEFAULT NULL ,
110           PRIMARY KEY (`id`) )
111         ENGINE = InnoDB
112         AUTO_INCREMENT = 2
113         DEFAULT CHARACTER SET = latin1
114         COLLATE = latin1_swedish_ci;
115         -- -----------------------------------------------------
116         -- Table `SCHEMA_NAME`.`my_aspnet_usersinroles`
117         -- -----------------------------------------------------
118         CREATE  TABLE IF NOT EXISTS `SCHEMA_NAME`.`my_aspnet_usersinroles` (
119           `userId` INT(11) NOT NULL DEFAULT '0' ,
120           `roleId` INT(11) NOT NULL DEFAULT '0' ,
121           PRIMARY KEY (`userId`, `roleId`) )
122         ENGINE = InnoDB
123         DEFAULT CHARACTER SET = latin1
124         COLLATE = latin1_swedish_ci
125         ROW_FORMAT = DYNAMIC;

 



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