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 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 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

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 2

clock June 4, 2012 08:29 by author Scott

Please see the previous post at here.

Once I removed all the TasksController files and the TodoItem, I chose the Models folder, right click and “Add New Item” and searched for “ADO.NET Entity Model” and added it to the folder.




It allowed me to connect to the Northwind database through “Generate from database” and I selected just three tables “Products”, “Categories” and “Suppliers” table for simplicity. At the end of the wizard, we get a EDMX design file with the 3 tables. On this screen I right clicked and choose “Add Code Generation Item” as below




and then in the dialog that came up, chose the “ADO.NET DbContext Generator” and Added (note, if you don’t see this template, you probably don’t have
Entity Framework 4.1 installed)

This step created the Model1.Context (not required for us though) and the Model1.tt template which groups the individual class files for each of the tables above (these are required)


The next thing I did, was to remove the NorthwindEntities connectionstring that got automatically added when we followed the ADO.NET Entity Model wizard. We don’t need this connection string.


Also, I deleted the Model1.Context file and also the Model1.cs files which are not required (we will be generating a new context to suit our database name)




Note that these files are not required only for our SPA approach here and they are required when working with EF CodeFirst normally as they do the DbSet Tracking and whole bunch of things


So, we now have the basic model classes required for wiring up our Controller required to create the SPA Pages. One important thing I learnt in this process was that, I had to edit the Model classes as follows:-


In Supplier.cs added the “private” keyword to the ICollection<Products> property. Same is the case with Category.cs. Otherwise you would run into an
error explained here.



After this, I added Controller for Products as per the settings below (Right Click Controller – Add –Controller)




Note several important things. I have chosen the “Single Page Application with read/write actions and views, using Entity Framework” template under Scaffolding options. Also, I have edited the Data context class and made it simply MvcApplication126.Models.Northwind. This would be referenced in the web.config connection string as well so that SPA picks up our existing Northwind database instead of creating a new one.


Once you click “Add” the following files are generated.


Under Controllers


- NorthwindController.cs

- NorthwindController.Product.cs
- ProductsController.cs

Under Scripts


- ProductsviewModel.js


Under Views


- Products folder and the Views and Partial Views required


Repeat the steps for adding Controllers for “Categories” and “Suppliers” and the only change would be the respective Model Classes.


One important thing to do is to add the following connectionstring to the web.config file


<add name="Northwind" connectionString="Data Source=SERVERNAME;Initial Catalog=Northwind;User Id=YOUR USER NAME;Password=YOUR PASSWORD" providerName="System.Data.SqlClient" />


Then, when you run the project, it opens up the default Home Page.


- Navigate to /Products and it should load the list of Products from Northwind database.

- Click on each product and edit and note that everything happens in a single page inline.
- Just notice the URLs change in pattern with hash tags.
- Notice that the Categories and Suppliers are wired up as dropdownlists since these are foreign key references.
- Notice that all the items load asynchronously

I went ahead and edited the Shared –> Layout.cshtml under Views folder to add Menu Items for Products, Categories and Suppliers, as below:-


<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Products", "Index", "Products")</li>
<li>@Html.ActionLink("Categories", "Index", "Categories")</li>
<li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>


Now, we have our full blown Northwind Traders Application running as a SPA.


You can download the sample from
https://skydrive.live.com/redir.aspx?cid=069f94a102eff49a&resid=69F94A102EFF49A!919&parid=root

 

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Create a Mobile Application in ASP.NET MVC 4

clock March 26, 2012 07:51 by author Scott

In this post, I will show you three new functionalities brought by MVC4 for mobile websites.

-          The mobile Application Template

-          The View Switcher

-          The Display mode by Browser type

Smartphone and tablet are able to read websites not optimized for tiny screen but if a user can jump automatically on an optimized version of the website, it’s better for everyone!

One interesting feature of this new version of the ASP.NET MVC framework 4 is the new
Mobile Application template. With this template you’ll be able to develop quickly a website especially for mobile and tablet.

1 – Create a full-mobile Website


In Visual Studio, Create a new MVC4 project and select the “Mobile Application” template.




I consider that you’ve already develop a classic MVC application. If true, you will not be surprised by the generated project. It’s almost the same as a classic MVC desktop website.


So what the difference?

In the “content” folder you will find another JavaScript library:
jQuery Mobile. ASP.NET MVC4 Mobile Template is based on the famous JavaScript framework for mobile application. You can learn a lot if you visit the jQuery mobile website.



Models and Controller are similar to a classic MVC Application.

In the view, you just have to add some tag to tell how jQuery mobile needs to display the page.

If we take a look at this code (Menu of the website generated by MVC4), you will probably recognize the Razor syntax. Nothing change when you want to develop Mobile Application with MVC4. You just have to use special attribute in your HTML.

Here, we declare a classic HTML list….and jQuery Mobile will transform it into an accessible list for mobile devices user.

<ul data-role="listview" data-inset="true">

<li data-role="list-divider">Navigation</li>

<li>@Html.ActionLink("About", "About", "Home")</li>

<li>@Html.ActionLink("Contact", "Contact", "Home")</li>

</ul>

 

 



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