Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

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

nopCommerce 3.30 Hosting with ASPHostPortal.com :: How to Enable SSL (https) in nopCommerce

clock April 14, 2014 08:19 by author Kenny

nopCommerce is one of the most popular ASP.NET shopping cart applications which you can use it for designing your business website for free. nopCommerce is an open source e-commerce solution that contains both a catalog frontend and an administration tool backend. nopCommerce is a fully customizable shopping cart. It's stable and highly usable. From downloads to documentation, nopCommerce.com offers a comprehensive base of information, resources, and support to the nopCommerce community. nopCommerce is a complete open source shopping cart softare, the first edition was released in October 2010, we can say this is still a very new shopping cart application in the market, but their users are growing super-fast in the past 3 years. nopCommerce is a fully customizable shopping cart and you can easily installed it in your hosting account. You just need to download the instalaltion file from official website and use FTP to upload it into your hosting server and unzip the file, then you have to create MSSQL 2005 or 2008 database, and you can install it for your website now.

As the Internet grows as a medium of communication, commerce and interaction, so do the prevalence of risks and security threats. One way to effectively protect your domain is with an SSL certificate. The primary reason why SSL is used is to keep sensitive information sent across the Internet encrypted so that only the intended recipient can understand it. This is important because the information you send on the Internet is passed from computer to computer to get to the destination server. Any computer in between you and the server can see your credit card numbers, usernames and passwords, and other sensitive information if it is not encrypted with an SSL certificate. When an SSL certificate is used, the information becomes unreadable to everyone except for the server you are sending the information to. This protects it from hackers and identity thieves.

In this article, i'm going to explain about how to enable SSL in nopCommerce, you will first need to purchase an SSL certificate and dedicated IP. This article assumes that you already purchase an SSL from SSL provider.

  • Install SSL on your web server
  • Open web.config file
  • Set UseSSL value to true (<add key=”UseSSL” value=”true” /> )
  • Then just save the file.

nopCommerce automatically switched to SSL when required ( for example, register, login and checkout admin ect.)

Get SharedSSLUrl from your hosting provider
Open the web.config and edit the following values

<add key=”UseSSL” value=”true” />
<add key=”SharedSSLUrl” value=”https://secure.yourhostingcompany.com/~username” />
<add key=”NonSharedSSLUrl” value=”https://secureyourhostingcompany.com/~username” /> 


Free Trial ASP.NET MVC 5 Hosting :: ASP.NET MVC 5 and Bootstrap 3 CSS Framework

clock March 19, 2014 07:39 by author Kenny

ASP.NET MVC 5 uses Bootstrap 3 as the CSS Framework in its default ASP.NET Web Application Tempate. This is a nice touch as most ASP.NET MVC developers have at least played with Bootstrap and are designing responsive websites. I'll mention the use of Bootstrap here briefly as there really isn't much to it.

When you create a new ASP.NET MVC 5 Web Application in Visual Studio 2013 it is using Bootstrap 3 as its default CSS Framework. You get the pleasure of the responsive navigation and website along with all the typography and other bells and whistles you expect from Bootstrap 3.

Inside the ASP.NET MVC 5 Website Template you will find the bootstrap.css and bootstrap.min.css stylesheets as well as the bootstrap.js and bootstrap.min.js scripts. The _Layout.cshtml view and other views are marked up appropriately using the CSS selectors in Bootstrap 3.
By default, the ASP.NET MVC Website Template uses a couple of bundles that use both Bootstrap 3 CSS as well as Modernizr. Check out the Layout.cshtml view to see the use of two of the bundles.
  @Styles.Render("~/Content/css")
  @Scripts.Render("~/bundles/modernizr")


You will find these bundles configured in the BundleConfig.cs file in App_Start.
  bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
    "~/Scripts/modernizr-*"));

  bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/bootstrap.css",
    "~/Content/site.css"));

And, of course, the CSS selectors and markup in the new ASP.NET MVC 5 Views are based on Bootstrap 3.
This isn't a huge deal, but it's still nice to see ASP.NET MVC 5 using Bootstrap 3 by default. Certainly, you can remove it for Foundation, Skeleton, or other CSS and JavaScript Framework of your choice.



Free, Best and Reliable Entity Framework 6 Hosting with ASPHostPortal.com

clock December 10, 2013 06:57 by author Ben

Entity Framework is actively developed by the Entity Framework team which is assigned to the Microsoft Open Tech Hub and in collaboration with a community of open source developers. Together we are dedicated to creating the best possible data access experience for .NET developers.
The Entity Framework version 6 Release Candidate is now available to developers for immediate download. The open source object-relational mapper is designed to enable .NET developers to work with relational data using domain-specific objects. Entity Framework allows programmers to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database.


There are The Top features of Entity Framework 6 :

  • Connection Resiliency - enables automatic recovery from transient connection failures.
  • Async Query and Save - dds support for the task-based asynchronous patterns that were introduced in .NET 4.5. With .NET 4.5 Microsoft introduced async and await keywords but in EF 5 Microsoft didn't have time to add support for async query and save but now with EF6 it is supported.
  • Code-Based Configuration - gives you the option of performing configuration - that was traditionally performed in a config file - in code.
  • Dependency Resolution - introduces support for the Service Locator pattern and we’ve factored out some pieces of functionality that can be replaced with custom implementations.
  • Interception/SQL logging - provides low-level building blocks for interception of EF operations with simple SQL logging built on top.
  • Testability improvements - make it easier to create test doubles for DbContext and DbSet.
  • Features that come for free - These are capabilities that are part of the core. You don’t even have to know they’re there to benefit from them, much less learn any new coding. This group includes features such as performance gains brought by a rewritten view-generation engine and query compilation modifications, stability granted by the ability of DbContext to use an already open connection, and a changed database setting for SQL Server databases created by Entity Framework.
  • DbContext can now be created with a DbConnection that is already opened - which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components where you can not guarantee the state of the connection).


Top Reasons To Choose Entity Framework 6 Hosting

  • Fast and Secure Server - Our powerfull servers are especially optimized and ensure the best Entity Framework 6 performance. We have best data centers on three continent, unique account isolation for security, and 24/7 proactive uptime monitoring.
  • Best and Friendly Support - Our support team is extremely fast and can help you with setting up and using Entity Framework 6 on your account. Our customer support will help you 24 hours a day, 7 days a week and 365 days a year.
  • Dedicated Application Pool - With us, your site will be hosted using isolated application pool in order to meet maximum security standard and reliability.
  • Uptime & Support Guarantees - We are so confident in our hosting services we will not only provide you with a 30 days money back guarantee, but also we give you a 99.9% uptime guarantee.
  • World Class Control Panel - We use World Class Plesk Control Panel that support one-click installation.

So, you'll get the best, cheap and reliable Entity Framework 6 hosting with us. Why wait longer?



ASP.NET MVC Hosting - ASPHostPortal.com :: ASP.NET MVC Request Life Cycle

clock October 30, 2013 06:09 by author Ben

There are primarily seven stages in the ASP.Net Request Life Cycle :

1. Routing
Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the request’s URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. The default one calls theMvcHandler. The routing engine returns a 404 HTTP status code against that request if the patterns is not found in the Route Table. When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.


2. MVCRouteHandler
MVC handler is responsible for initiating MVC applications. The MvcRouteHandler object creates an instance of the MvcHandler and passes the instance of RequestContext to MvcHandler.
MvcHandler is implemented from ITttpHandler and it cannot map as a handler. This class does not support a parameterless constructor. It takes RequestContext as a parameter.

3. Action Execution
Once the controller has been instantiated, Controller's ActionInvoker determines which specific action to invoke on the controller. Action to be execute is chosen based on attributes ActionNameSelectorAttribute (by default method which have the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than one method found, the correct one is chosen with the help of this attribute).


ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information


4. Controller
MVCHandler receives a controller instance from the MVC controller factory (IControllerFactory). This controller handles further processing of the request. The MVCHandler object uses RequestContext (passed as a constructor parameter) instance to identify the IControllerFactory object to create the controller instance. The MvcHandler instance calls the Execute method of controller.


5. View Engine
View Result is responsible for selecting and involving the appropriate View Engine. A View Engine is responsible for rendering HTML to the browser. The View Engine template has different syntax to implement the view. Currently there are four builtin View Engines (Razor, ASPX, Spark and NHaml) supported by MVC. We can also create our own custom View Engine to render a view. All the View Engines may not be supported in all versions of MVC. We can also use multiple View Engines simultaneously in ASP.NET MVC.

6. View Result
The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.



How To Enable .CSHTML Support In Windows Server 2012

clock October 24, 2013 12:25 by author andry

C# ("C sharp")is  HTML webpage file used by Razor, an ASP.NET view engine used for generating Web pages for a user's Web browser; similar to a standard ASP.NET webpage (.ASP or .ASPX file), but uses a slightly different syntax; runs on a Web server, which generates the HTML for the client Web browser; can be programmed with syntax highlighting.

If we build a website that contains .cshtml file, we must enable .cshtml file. At the below, there is an error message if we don’t enable .cshml file.

To enable .cshtml file on windows Server 2012, There are steps to solve that problem. Open your IIS.

Expand “server”-> “sites” and choose “domain”.  Then click on Handler Mapping.

You can't find .cshtml. After that, choose “Revert to Parent” on right tab.

Select "Yes" and Look,what the difference with the previous image.

.cshtml file are enable and available. Now browse the domain. If you still can not access and have an error. You should check the .NET version. Remember that .Cshtml file can only be run on .NET version 4 and above.

To check the .Net version, select "application pools" -> right click on "domain_name" -> "Basic settings" -> choose .Net 4 version -> "Ok".

Now you can browse your domain with .cshtml file. Here is screenshot.



Free ASP.NET hosting - ASPHostPortal.com :: ASPHostPortal.com Proudly Announces Free Trial Windows ASP.NET Hosting

clock October 3, 2013 10:28 by author Ben

ASPHostPortal.com is a premier Windows and ASP.NET Web hosting company that specializes in Windows and ASP.NET-based hosting. We proudly announces 7 Day Free Trial Windows and ASP.NET Hosting to all new customers. The intention of this FREE TRIAL service is to give our customers a "feel and touch" of our system. This free trial is offered for the next 7 days and at anytime, our customers can always cancel the service.

 

The 7 Day Free Trial is available with the following features:

- Unlimited Domains
- 5 GB Disk Space
- 60 GB of Bandwidth
- 2 MS SQL Database
- Unlimited Email Account
- Support ASP.NET 4.5
- Support MVC 4.0
- Support SQL Server 2012
- Free Installations of ASP.NET And PHP Applications

ASPHostPortal.com believes that all customers should be given a free trial before buying into a service and with such approach, customers are confident that the product / service that they choose is not faulty or wrong. Even we provide free trial service for 7 days, we always provide superior 24/7 customer service, 99,9% uptime guarantee on our world class data center. On this free trial service, our customer still can choose from our three different data centre locations, namely Singapore, United States and Amsterdam (The Netherlands)

Anyone is welcome to come and try us before they decide whether or not they want to buy. If the service does not meet your expectations, our customer can simply cancel before the end of the free trial period.

For all the details of packages available visit ASPHostPortal.com

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET MVC 4 Hosting - ASPHostPortal :: Build Mobile Applications With ASP.NET MVC 4.5

clock August 20, 2013 05:56 by author Ben

The MVC 4 release is building on a pretty mature base and is able to focus on some more advanced scenarios. Some top features include:

  • ASP.NET Web API
  • Enhancements to default project templates
  • Mobile project template using jQuery Mobile
  • Display Modes
  • Task support for Asynchronous Controllers
  • Bundling and minification

The following sections provide an overview of these features. We’ll be going into them in more detail throughout the book.
Developing MVC 4 applications with Visual Studio 2011 Developers Preview is quite jump-start for developers as it has inbuilt support for JQuery Mobile css & javascripts, nice intellisense for HTML 5 , CSS 3 media queries. MVC 4 developers preview was built keeping in mind the Mobile Web Developers who wants keen support of rich MVC in Mobile Web.

  • Lets start to develop MVC 4 mobile application with JQuery Mobile, HTML5, CSS3 in VS 2011 developers preview.

  • Select your MVC 4 application domain either Internet/Intranet/Mobile Web application  with default Razor or ASPX syntaxes. For my demo , selected Mobile Web application in VS 2011 Developer Preview.

  • Next, write some JQuery Mobile application code to check th UI view in SmartPhones while Model & Controller logic remains same & could change according to business requirements.
  • Database -> Entity Framework (EF) -> Model in MVC 4(Entities) (DAL)-> Controllers (Business Logic Layer)(BLL) -> View(s) -> Master(_Layout.cshtml) is the default development path in MVC 4 Web & mobile application.

  • Next , Check the nice intellisense support for HTML5 , JQuery Mobile in Visual Studio 2011 Developer Preview.

  • Check out the MVC 4 Mobile Web applications with JQuery Mobile , HTML5 , CSS 3 media queries in Smart Devices.
  • JQuery Mobile View in iPhone of MVC 4 Mobile application:

 



Windows Cloud Server Hosting :: Comparison between Cloud Server and VPS

clock May 1, 2013 12:23 by author Ben

There is a lot of confusion in the industry especially in the web hosting world regarding the differences between a VPS server and a Cloud Server.  Many companies seem to use these terms loosely or interchangeably when discussing Virtual Servers, so we felt that it was time to cut through the hype so users would understand the differences and be able to choose the best option to meet their needs.


What exactly is a VPS ?
A VPS is sometimes referred to as a 'Virtual Private Server' or 'Node.'  A VPS gets its name from one shared physical server (or node) that is divided up into several smaller 'virtual' server slices.  Each slice is sold to a different customer for their use.   A traditional VPS platform can only run one operating system on each physical server.  VPS customers on the same physical server will all be using the same operating system.   Typically, VPS providers use a legacy technology called a 'container' to isolate multiple users on a single server from one another while slicing up a single shared instance of the operating system.

A VPS is typically used in Web Hosting
VPS are popular with web hosting companies who typically sell them to customers who need more machine resources for their website than what can be provided by a typical web server that is hosting hundreds of websites.  These types of customers may choose a VPS on which to build a large e-commerce site, a database-driven web application or to run a social network.  A VPS may be a better choice in some cases, especially when the customer may not be ready for a fully 'dedicated' server exclusively for their use which can be a costly proposition.

No isolation from other customer resource demands when running on a VPS
Many customers who choose a VPS will at some point experience some problems that are pervasive among VPS platforms.  What they may not realize is that there is no isolation from other customers' application demands on the server.  If one VPS customer is running an application that uses most of the CPU, all the other VPS customers will be affected.  It is a common occurrence that when all the machine resources of the server get used up by other VPS customers housed on the same machine, that an application or website may run very slowly or even grind to a halt and stop running altogether.  Customers whose applications stop running may have to log-in and restart them, but there is no guarantee that they will continue to run if the machine resources are already being taxed.

VPS nodes are oversold causing servers to slow down or crash
By far the single largest problem with a VPS is that VPS providers typically oversell their nodes, making one physical host machine run far too many customers.  This turns into a resource allocation nightmare causing poor performance or server crashes that affects all the customers on that node.  If the physical server fails, all VPS customers on that server will go down.  This is why a VPS cannot provide you with high-availability.  Unfortunately, a customer cannot predict when this might happen, but inevitably it will.    

A VPS cannot be scaled to accommodate peak traffic times or customer growth
While a VPS may provide a customer with a small portion of dedicated memory, there is generally no dedicated CPU allocation, no disk I/O, network I/O, etc.  Additionally, most VPS providers only offer small amounts of memory resources.  When more is needed, or when a customer suffers enough downtime, they encourage the customer to move onto a larger VPS, or move to a 'dedicated' server (for their use alone).  This is because a VPS node cannot be scaled to accommodate the growing needs of an individual customer.  

Why not use a Dedicated Server?
Dedicated servers are not usually the first option to be considered since they can be more than ten times the cost of a VPS.  Customers often find themselves in situations where they don't need a dedicated server 24/7, but when the performance of their VPS becomes unacceptable, or they have significant periodic spikes in website traffic, they end up migrating to a dedicated server to avoid slow response and to accommodate high peak times in website traffic.  This comes at a cost, not only the cost associated with dedicated server hardware that may be actually under-utilized a majority of the time, but also the time and expense of migrating the application to a new server, which may take several days to complete. 

VPS Security Concerns
There are notable security concerns with a VPS.  If a customer on your shared server does not take security seriously, and is hacked or receives a malicious virus, then your VPS applications could also be negatively affected.  You must remember that on a VPS node, you have no knowledge or any control over what other customers may be doing.  For this reason, a VPS should never be considered for any critical business application.   

Muddying the Water
Unfortunately, web hosting companies often muddy the water when customers start asking about cloud servers and the differences between a VPS and a Cloud Server.  Whether it is deliberately done or just out of ignorance, some say there is no difference at all.  Some even claim that a VPS and Cloud Server are the same thing since they are both "virtual servers" and the only difference is in the way they are billed.   This simply is not the case.  Typically when companies make these types of claims, it is because they do not have a true cloud computing infrastructure to offer their customers.   Some VPS companies will even refer to their services as Cloud Hosting, trying to capitalize on the cloud computing trend, which adds to the confusion for customers trying to understand the differences to make the right choice. 


The ASPHostPortal.com Cloud Difference
As previously stated, traditional VPS providers slice up large dedicated servers to share between customers.  By contrast, a Cloud Server is a virtual server instance that provides the user with a dedicated and protected set of machine resources.  On a Cloud Infrastructure, each cloud server is completely isolated from another, providing customers with the ability to scale their server resources on-demand.  With a cloud server you always get the full amount of allocated CPU, Memory, Disks, etc. that you are paying for.  Due to the nature of their architecture, cloud servers cannot be 'overrsold.'

Install the Operating System of your Choice
The KVM technology which serves as the foundation for the ASPHostPortal.com Cloud enables every user to run their own isolated copy of an operating system of their choice, providing the user with more control over their virtual server environment.  This enables the customer to experience higher performance, deeper configurability, stronger isolation and security guarantees.

Automated Server Deployment 
ASPHostPortal.com Cloud Servers allow you to resize your server instances in near real-time without any data migration or reconfiguration of the server/OS at all, something that is not possible with a VPS platform.  Also, ASPHostPortal.com Cloud Servers employ automated ordering and deployment of computing resources including the ability to spin-up additional servers instantly or add capacity as needed.  This can be accomplished using our easy web control panel or programmatically via our robust API.  Such features are not available with a VPS platform.

Custom Configurations
Unlike a VPS, ASPHostPortal.com customers can deploy a unique server configuration and custom network architecture including VLANs, Firewalls, Load Balancing and Static IP addresses.

Availability Guarantees
Keep in mind that while on a VPS, if the physical server fails, all VPS customers on that server will go down.  Cloud Servers offer High-Availability, so if a physical server fails, a cloud server is automatically migrated to another physical server without experiencing an outage.  ASPHostPortal.com offers a Reliability Guarantee with 100% Uptime.  Our industry-leading Service Level Agreement provides 100x credits for any downtime.

Data Security
Unlike a VPS, Cloud Servers run in a secure environment providing you with your own isolated server instance with no risk to your data.  If a cloud server customer gets a virus or is hacked, other customers' servers will not be affected.  In addition, each cloud customer can implement their own additional security measures for their individual users since they have full control of their server configuration, operating system and applications.

Unbundled Computing Resources
Unlike most Cloud Infrastructure providers, ASPHostPortal.com provides you with unbundled computing resources so you can select the amount of CPU, Memory and Storage of each server to meet the exacting demands of your applications.  For example, you may have an application that is much more demanding of the CPU than Memory.  On the ASPHostPortal.com Cloud, you can deploy a server with more CPU power and less Memory so you can truly match the resources to the application, rather than having to pay for a defined set of resources that may not be fully utilized.  This not only helps to improve the performance of your applications, but can save you a significant amount of money over the life of the application. 

Cost Advantages
A few years ago, many could argue that VPS servers were less expensive than cloud servers.  Much has changed in the last couple of years and this is no longer the case.  Next generation cloud servers like those available from ASPHostPortal.com offer customers a much greater value than a VPS for about the same cost.  The shift in computing dynamics has led more companies to embrace cloud technologies rather than to purchase, constantly upgrade and routinely maintain their own server hardware.  Cloud computing has been proven to be a secure, reliable, scalable and cost-effective computing environment for countless applications, from large enterprise workloads to mobile web applications and everything in-between.



ASP.NET MVC 4 Hosting - Adaptive Rendering in ASP.NET MVC 4

clock April 25, 2013 08:50 by author andy_yo

Adaptive Rendering also called responsive design taking the advantage of existing HTML markup and CSS to use inside the ASP.NET Web applications. This post outlines about Adaptive Rendering, display modes and out of the box ASP.NET MVC mobile template. What is unique about .NET 4.5 application templates that ships out-of-the box uses a technique called responsive design. Responsive design is functionality of CSS to redefine the layout properties of your page based on the web and devices that you are using.

About ASPHostPortal.com
ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

The desktop experience of the default ASP.NET MVC4 application after running and resizing the browser windows looks as below


Once you are under 850 pixel width restriction, CSS will automatically compute with new set of rules for rendering the screen , it is standard CSS nothing specific to .NET.


Display Modes

Add a new view to your ASP.NET MVC 4 project called Index.mobile


Instead of building the mobile view from scratch, take index view mark up and paste in the new view and browse the view in mobile emulator and it will render you .index.mobile.cshtml page

what if you want to customise the view to specific type of device or model, you can do this inside Visual Studio. Open the Global.asax file and register the new view type with display mode provider as shown below

insert the display mode at the beginning of the stack.The contextcondition can be based on cookies, user context and headers as long as the result resolved to true or false. Now create a  new view index.WindowsPhone.cshtml in your project and change the header text so that you know it is your custom display mode, now run the application with browser you will get index.cshtml view, run with specific device emulator then you will get that index.windowsphone.cshtml view as shown below

so you can use the same URL to target different devices based on custom view and criteria.

Mobile Template

You have new template for Mobile Web applications in ASP.NET 4.5 MVC, create a new project and select the Mobile Template as shown below

Now run the application in browser for desktop view, you will notice that look is mobilish…. and then run in mobile emulator and it looks as below

It uses the JQuery UI to render the elements.If you open the index file then you will notice some html attributes that are specific to JQuery UI.



ASP.NET MVC 4 Hosting - Overriding Browser Capabilities in MCV 4

clock March 4, 2013 09:31 by author andy_yo

The new System.Web.WebPages 2.0.0.0 assembly that ships with the latest MVC4 contains a pretty cool feature that lets you override the current browser capabilities. Sure, most modern browsers let you set a custom user agent string out of the box or via extensions. However, there are certain scenarios, where you would want to switch the user agent on the server side. That’s where the BrowserHelpers class comes in handy.

Override Browser Context

A good example where you want to use override the browser capabilities is when developing mobile views. You may not want to simulate a particular device, you just want to tell ASP.NET that the client is a mobile device and to use the .mobile view.  You can call SetOverridenBrowser extension method and pass in BrowserOverride enum (Mobile/Desktop options).

public ActionResult Mobile()
{
    HttpContext.SetOverriddenBrowser(BrowserOverride.Mobile);
    return RedirectToAction("Index");
}

If you want, you can override the browser full UserAgent by calling SetOverridenBrowser extension method on HttpContextBase

public ActionResult Iphone()
{
  HttpContext.SetOverriddenBrowser("Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7");
    return RedirectToAction("Index");
}

And then, in order the clear the override, simple call the ClearOverridenBrowser extension method

public ActionResult Clear()
{
    HttpContext.ClearOverriddenBrowser();
    return RedirectToAction("Index");
}

What is happening under the hood

When you call the SetOverridenBrower method, ASP.NET sets a “.ASPXBrowserOverride” cookie. This is done using CookieBrowserOverrideStore from System.Web.Webpages, which implements BrowserOverrideStore – if you’re interested, check it out in dotpeek.

The value of the cookie is the user agent that you have set or in the case of the BrowserOverride.Mobile enum: Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 8.12; MSIEMobile 6.0). The expiry date is set for 7 days so the override will be in place even if you re-open your browser. Calling ClearOverridenBrowser simply clears the cookie.

Create Mobile Switched Filter

The jQuery.Mobile.MVC package comes with the ViewSwitcher razor partial and the ViewSwitcherController. This does more or less exactly what I described above. However, if you are lazy like me, you may want to switch between mobile/desktop views using QueryString rather than controller/actions.  This is useful when you want to just quickly check your mobile views.

public class BrowserCapabilitiesSwitcherFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var switchParameter = filterContext.RequestContext.HttpContext.Request.QueryString["switch"];
        if(string.IsNullOrEmpty(switchParameter))
            return;
        var browserOverride = BrowserOverride.Desktop;
        if(Enum.TryParse(switchParameter, true, out browserOverride))
        {
            //switch between BrowserOverride.Desktop / BrowserOverride.Mobile
            filterContext.RequestContext.HttpContext.SetOverriddenBrowser(browserOverride);
        }
        else
        {
            //set the user-agent string
            filterContext.RequestContext.HttpContext.SetOverriddenBrowser(switchParameter);
        }           
    }
}

Simply use it by typing http://yoursite.com/page?switch=Mobile to preview in mobile and then http://yoursite.com/page?switch=Desktop to switch back. For the more adventurous, you can pass in the user agent directly http://yoursite.com/page?switch=UserAgentString

 

 



About ASPHostPortal.com

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

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

 photo ahp banner aspnet-01_zps87l92lcl.png

Author Link

Corporate Address (Location)

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

Sign in