Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

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

Windows 2008 Hosting Tips :: Installing IIS 7.5 on Windows Server 2008/2008 R2

clock July 1, 2013 09:05 by author Mike

IIS (Internet Information Services) Version 7.5 – is a web server application and a set of feature extension modules created by Microsoft for use with Microsoft Windows. Released with Windows Server 2008 R2 and Windows 7. The installation procedure to install IIS 7.5 is slightly different depending on which operating system you are using, so you will need to make sure you follow the correct method below for your operating system.

Follow this steps to install:

  • Navigate to Start\Control Panel\Administrative Tools and open Server Manager.
  • In the tree menu on the left, select Roles.
  • In the main window, find the sub-section Roles Summary (it should be at the top) and click Add Roles.
  • On the pop-up window, read the security warnings and then select Next.
  • Select Web Server (IIS) from the list of check box options.
  • After reading the introduction to IIS, click Next to continue
  • From the check boxes, find the Application Development section and select CGI. This will allow us to install PHP later without any modifications.

 

  • Click Next to continue.
  • Click Install to begin the installation.
  • After installation has finished, click Close.

To check the installation, you can follow this steps:
- Navigate to Start\Control Panel\Administrative Tools and open Internet Information Services (IIS) Manager.

 

If it's installed properly you'll be introduced with the IIS Manager window, shown below.

That's it, IIS 7.5 is now installed and ready to be put into service.



IIS 7.5 Hosting - ASPHostPortal :: IIS 7.5 AppPool Identities

clock May 27, 2013 10:16 by author Ben

Windows 7 and Windows Server 2008 R2 ship with IIS 7.5. It's called Application Pool Identities. Application Pool Identities allows you to run Application Pools under an unique account without having to create and manage domain or local accounts. The name of the Application Pool account corresponds to the name of the Application Pool. The image below shows an IIS worker process (w3wp.exe) running as the DefaultAppPool identity.

Application Pool Identity Accounts
Worker processes in IIS 6 and 7 run as NETWORKSERVICE by default. NETWORKSERVICE is a built-in Windows identity. It doesn't require a password and it has only user privileges, i.e. it is relatively low-privileged. Running as a low-privileged account is a good security practice because then a software bug can't be used by a malicious user to take over the whole system. The problem is however that over time more and more Windows system services started to run as NETWORKSERVICE and services running as NETWORKSERVICE can tamper with other services running under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code) it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities. The Windows operating system provides a feature called "Virtual Accounts" that allows IIS to create unique identities for each of its Application Pools. Click here for more information about Virtual Accounts.

Configuring IIS Application Pool Identities
If you are running IIS 7.5 on Windows Server 2008 R2 you don't have to do anything. For every Application Pool you create the IIS Admin Process (WAS) will create a virtual account with the name of the new Application Pool and run the Application Pool's worker processes under this account. If you are running Windows Server 2008 you have to change the IdentityType property of the Application Pool you created to "AppPoolIdentity". Here is how:

  • Open the IIS Management Console (INETMGR.MSC).
  • Open the Application Pools node underneath the machine node. Select the Application Pool you want to change to run under an automatically generated Application Pool Identity.
  • Right click the Application Pool and select "Advanced Settings..."

Configure AppPool Identity

  • Select the "Identity" list item and click the button with the three dots.
  • The following dialog appears.

Select the Identity Type "ApplicationPoolIdentity" from the combo box

  • select the Identity Type "ApplicationPoolIdentity" from the combo box

Securing Resources
Whenever a new Application Pool is created the IIS management process creates a security identifier (SID) representing the name of the Application Pool itself, i.e. if you create an Application Pool with the name "MyNewAppPool" a security identifier with the name "MyNewAppPool" is created in the Windows Security system. From this point on resources can be secured using this identity. The identity is not a real user account however, i.e. it will not show up as a user in the Windows User Management Console. You can try this by selecting a file in Windows Explorer and adding the "DefaultAppPool" identity to its Access Control List (ACL).

  1. Open Windows Explorer
  2. Select a file or directory
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select your machine.
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box
  8. Click the "Check Names" button and click "OK".

By doing this the file or directory you selected will now also allow the "DefaultAppPool" identity access. You can do this via the command-line using the ICACLS tool. The following example gives full access to the DefaultAppPool identity.

On Windows 7 and Windows Server 2008 R2 the default is to run Application Pools as this security identifier, i.e. as the Application Pool Identity. To make this happen a new identity type with the name "AppPoolIdentity" was introduced. If the "AppPoolIdentity" identity type is selected (default on Windows 7 and Windows Server 2008 R2) IIS will run worker processes as the Application Pool identity. With every other identity type the security identifier will only be injected into the access token of the process. If the identifier is injected content can still be ACLed for the AppPool identity but the owner of the token is probably not unique. Here is an article that explains this concept.

Accessing the Network
Using the NETWORKSERVICE account in a domain environment has a great benefit. Worker process running as NETWORKSERVICE access the network as the machine account. Machine accounts are generated when a machine is joined to a domain. They look like this: <domainname>\<machinename>$, for example: mydomain\machine1$ The nice thing about this is that network resources like file shares or SQL Server databases can be ACLed to allow access for this machine account.

What about AppPool identities?
The good news is that Application Pool identities also use the machine account to access network resources. No changes are required.



IIS 7.5 Hosting - ASPHostPortal :: GZIP compression in IIS 7.5 for JSON response

clock May 15, 2013 12:20 by author Ben

Recently we need to build some RESTful services that responded with JSON and to my surprise these responses are not compressed when I fired up Fiddler and check the Transformer tab.

After enabling Failed Request Tracing in IIS by going to IIS Manager > Web Site > Right Panel > Actions Configure > Failed Request Tracing.

On the same page with the Right Panel of "Actions", under the IIS area, click into Failed Request Tracing Rules.

From there, at the Right Panel, click "Add..." > Specify Content to Trace > All content(*) > Status code(s): type in "200" > Finish.

You should make sure no other request is hitting on the same server at the same time to minimize the logging file creation, which is based on request, if you only have one request when you turn this on, there should only be one fr000001.xml file created in %windir%\inetpub\logs\FailedReqLogFiles\W3SVC1, open that in Internat Explorer and click on Request Details > Search for Compression, expand the corresponding node > Mine says in the node dynamic compression > not success > no_matching_content_type.

So it seems that even though by default HTTP Compression is enabled in IIS 7.5, there are only 3 content types that IIS recognizes and will actually perform the compression.

You can check this in IIS Manager > YOUR_SERVER > Under Management section > Configuration Editor > Expand the system.webServer > httpCompression > dynamicTypes

When you have a RESTful service that serve JSON based response and you would like that to be gzip/compressed whenever client's request includes in the header "Accept-Encoding: gzip", you must update this list to include both mime types

application/json
application/json;
charset=utf-8


in the list, you can either start adding these 2 type in the editor itself or you can run a command line tool AppCmd.exe from %windir%\system32\inetsrv directory, the full command is

appcmd.exe set config -section:system.webServer/httpCompression /+"dynamicTypes.[mimeType='application/json; charset=utf-8',enabled='True']" /commit:apphost

Remember to apply your settings if you are using the GUI editor, I used the command line tool because this is the only one that will add the type along with the "Entry Path", adding through the GUI editor for some reason doesn't add any Entry Type, it still works but I just don't like missing anything.

Now, restart IIS and you can check again in Fiddler and Viola! Now it says GZIP Encoding. You can "Click here to transform" to see the data :)



IIS 7.0 Hosting - ASPHostPortal :: Securing IIS 7.0 Web Server on Windows 2007

clock May 8, 2013 08:51 by author Ben

Hacking a Web Server
With the advent of Windows 2007 and IIS 7.0 there was a sharp turn in the way hosting services were being provided on Windows platform few years back. Today, web servers running on Internet Information Services 7.0 (IIS 7.0) are highly popular worldwide - thanks to the .NET and AJAX revolution for designing web applications. Unfortunately, this also makes IIS web servers a popular target amongst hacking groups and almost every day we read about the new exploits being traced out and patched. That does not mean that Windows is not as secured as Linux. In fact, it's good that we see so many patches being released for Windows platform as it clearly shows that the vulnerabilities have been identified and blocked.

Many server administrators have a hard time coping up with patch management on multiple servers thus making it easy for hackers to find a vulnerable web server on the Internet. One good way I have found to ensure servers are patched is to use Nagios to run an external script on a remote host, in turn alerting on the big screen which servers need patches and a reboot after the patch has been applied. In other words, it is not a difficult task for an intruder to gain access to a vulnerable server if the web server is not secured and then compromise it further to an extent that there is no option left for the administrator but to do a fresh OS install and restore from backups.
Many tools are available on the Internet which allows an experienced or a beginner hacker to identify an exploit and gain access to a web server. The most common of them are:

1. IPP (Internet Printing Protocol) - which makes use of the IPP buffer overflow. The hacking application sends out an actual string that overflows the stack and opens up a window to execute custom shell code. It connects the CMD.EXE file to a specified port on the attacker's side and the hacker is provided with a command shell and system access.

2. UNICODE and CGI-Decode - where the hacker uses the browser on his or her computer to run malicious scripts on the targeted server. The script is executed using the IUSR_ account also called the "anonymous account" in IIS. Using this type of scripts a directory transversal attack can be performed to gain further access to the system.

Over these years, I've seen that most of the time, attacks on a IIS web server result due to poor server administration, lack of patch management, bad configuration of security, etc. It is not the OS or the application to blame but the basic configuration of the server is the main culprit. I've outlined below a checklist with an explanation to each item. These if followed correctly would help prevent lot of web attacks on an IIS web server.

Secure the Operating System
The first step is to secure the operating system which runs the web server. Ensure that the Windows 2007 Server is running the latest service pack which includes a number of key security enhancements.

Always use NTFS File System
NTFS file system provides granular control over user permissions and lets you give users only access to what they absolutely need on a file or inside a folder.

Remove Unwanted Applications and Services
The more applications and services that you run on a server, the larger the attack surface for a potential intruder. For example, if you do not need File and Printer sharing capabilities on your shared hosting platform, disable that service.

Use Least Privileged Accounts for Service
Always use the local system account for starting services. By default Windows Server 2007 has reduced the need for service accounts in many instances, but they are still necessary for some third-party applications. Use local system accounts in this case rather than using a domain account. Using a local system account means you are containing a breach to a single server.

Rename Administrator and Disable Guest
Ensure that the default account called Guest is disabled even though this is a less privileged account. Moreover, the Administrator account is the favorite targets for hackers and most of the malicious scripts out there use this to exploit and vulnerable server. Rename the administrator account to something else so that the scripts or programs that have a check for these accounts hard-coded fail.

Disable NetBIOS over TCP/IP and SMB
NetBIOS is a broadcast-based, non-routable and insecure protocol, and it scales poorly mostly because it was designed with a flat namespace. Web servers and Domain Name System (DNS) servers do not require NetBIOS and Server Message Block (SMB). This protocol should be disabled to reduce the threat of user enumeration.

To disable NetBIOS over TCP/IP, right click the network connection facing the Internet and select Properties. Open the Advanced TCP/IP settings and go to the WINS tab. The option for disabling NetBIOS TCP/IP should be visible now.

To disable SMB, simply uncheck the File and Print Sharing for Microsoft Networks and Client for Microsoft Networks. A word of caution though - if you are using network shares to store content skip this. Only perform this if you are sure that your Web Server is a stand-alone server.

Schedule Patch Management
Make a plan for patch management and stick to it. Subscribe to Microsoft Security Notification Service (http://www.microsoft.com/technet/security/bulletin/notify.asp) to stay updated on the latest release of patches and updates from Microsoft. Configure your server's Automatic Update to notify you on availability of new patches if you would like to review them before installation.

Run MBSA Scan
This is one of the best way to identify security issues on your servers. Download the Microsoft Base Line Security tool and run it on the server. It will give you details of security issues with user accounts, permissions, missing patches and updates and much more.

That's it to the basic of securing the operating system. There are more fixes which can be performed for further securing the server but they are beyond the scope of this article. Let's now move on to securing the IIS web server.

IIS 7.0 when setup is secured by default. When we say this, it means that when a fresh installation of IIS is done, it prevents scripts from running on the web server unless specified. When IIS is first installed, it serves only HTML pages and all dynamic content is blocked by default. This means that the web server will not serve or parse dynamic pages like ASP, ASP.NET, etc. Since that is not what a web server is meant to do, the default configuration is changed to allow these extensions. Listed below are some basic points that guide you to securing the web server further:

Latest Patches and Updates
Ensure that the latest patches, updates and service packs have been installed for .NET Framework. These patches and updates fix lot of issues which enhances the security of the web server.

Isolate Operating System
Do not run your web server from the default InetPub folder. If you have the option to partition your hard disks then use the C: drive for Operating System files and store all your client web sites on another partition. Relocate web root directories and virtual directories to a non-system partition to help protect against directory traversal attacks.

IISLockDown Tool
There are some benefits to this tool and there are some drawbacks, however, so use it cautiously. If your web server interacts with other servers, test the lockdown tool to make sure it is configured so that connectivity to backend services is not lost.

Permissions for Web Content
Ensure that Script Source Access is never enabled under a web site's property. If this option is enabled, users can access source files. If Read is selected, source can be read; if Write is selected, source can be written to. To ensure that it is disabled, open IIS, right click the Websites folder and select Properties. Clear the check box if it is enabled and propagate it to all child websites.

Enable Only Required Web Server Extensions
IIS 7.0 by default does not allow any dynamic content to be parsed. To allow a dynamic page to be executed, you need to enable the relevant extension from the Web Service Extensions property page. Always ensure that "All Unknown CGI Extensions" and "All Unknown ISAPI Extensions" are disabled all the time. If WebDAV and Internet Data Connector are not required, disable that too.

Disable Parent Paths
This is the worst of all and thanks to Microsoft, it is disabled in IIS 7.0 by default. The Parent Paths option permits programmers to use ".." in calls to functions by allowing paths that are relative to the current directory using the ..notation. Setting this property to True may constitute a security risk because an include path can access critical or confidential files outside the root directory of the application. Since most of the programmers and third-party readymade applications use this notation, I leave it up to you to decide if this needs to be enabled or disabled. The workaround to Parent Paths is to use the Server.MapPath option in your dynamic scripts.

Disable Default Web Site
If not required, stop the Default Web Site which is created when IIS 7.0 is installed or change the property of Default Web Site to run on a specific IP address along with a Host Header. Never keep it running on All Unassigned as most of the ready-made hacking packages identify a vulnerable web server from IP address rather than a domain name. If your Default Web Site is running on All Unassigned, it means that it can serve content over an IP address in the URL rather than the domain name.

Use Application Isolation
I like this feature in IIS 7.0 which allows you to isolate applications in application pools. By creating new application pools and assigning web sites and applications to them, you can make your server more efficient and reliable as it ensures that other applications or sites do not get affected due to a faulty application running under that pool.

Summary
All of the aforementioned IIS tips and tools are natively available in Windows. Don't forget to try just one at a time before you test your Web accessibility. It could be disastrous if all of these were implemented at the same time making you wonder what is causing a problem in case you start having issues.

Final tip: Go to your Web server and Run "netstat -an" (without quotes) at the command line. Observe how many different IP addresses are trying to gain connectivity to your machine, mostly via port 80. If you see that you have IP addresses established at a number of higher ports, then you've already got a bit of investigating to do.



WebMatrix Hosting – ASPHostPortal.com :: Quick Start screen

clock May 8, 2013 08:05 by author Ben

Microsoft has just introduced the new version of WebMatrix. When this post is written it’s still in BETA version.

if you were ASP.NET developer when it’s in 1.1 version, you might ever tried WebMatrix, it was free as it’s today. At that time there was no Express edition of Visual Studio and WebMatrix was the free tool to develop ASP.NET website if you didn’t want to buy Visual Studio.

What is this?
WebMatrix is everything you need to build Web sites using Windows. It includes IIS Developer Express (a development Web server), ASP.NET (a Web framework), and SQL Server Compact (an embedded database). It streamlines Web site development and makes it easy to start Web sites from popular open-source apps. The skills and code you develop with WebMatrix transition seamlessly to Visual Studio and SQL Server.

Why Use It?
You will use the same powerful Web server, database engine and web framework that will run your Web site on the Internet, which makes the transition from development to product seamless. Beyond ensuring everything just works, WebMatrix includes new features that make Web development easier.

Who’s it for?
WebMatrix is for developers, students, or just about anyone who just wants a small and simple way to build Web sites. Start coding, testing, and deploying your own Web sites without having to worry about configuring your own Web server, managing databases, or learning a lot of concepts. WebMatrix makes Web site development easy.

Code Without Boundaries
WebMatrix provides an easy way to get started with Web development. With an integrated code editor and a database editor, Web site and server management, search optimization, FTP publishing, and more, WebMatrix provides a fresh, new Web site development experience that seamlessly bridges all the key components you need in order to create, run, and deploy a Web site.

As your needs grow, the code and skills you develop can seamlessly transition to Visual Studio – Microsoft’s premier development suite.

WebMatrix – Quick Start screen
On first-time run of Microsoft WebMatrix, below screen will be the default screen on WebMatrix.

if you don’t like it you can disable it by giving “Do not show this screen on start-up” a check mark. It will then run My Sites as default screen and open the last site you’re working with.

Later you want the Quick Start screen to get back you can close the opened site it will bring you the Quick Start screen and you can remove the check mark if you want.

Okay let’s try the menu item one by one.

My Sites
It will open a dialog with all sites you ever worked with in the list. Select a site and click OK button to open, or you can just double click the site.

I found that there is no way to remove a site from the list at this Beta version. Maybe it will be added in the newer version… let’s hope… err suggest to them.

Site From Web Gallery
This option will open a dialog to select a website or application from Web Gallery. This is the same as installing community website or application using Web PI but in this Microsoft WebMatrix the website or application will not be installed in IIS but rather they will be stored in %user%\Documents\My Web Sites folder and will be run in IIS Developer Express by default when you’re working with the site on WebMatrix. (if you want you can also add the website or application to your computer IIS manually)

Site From Template
This is where all funs will start. You can create your own site from online templates listed there.

When you create a new site from template, you will find that there are new extensions .cshtml and .vbhtml – yep they are new extension introduced by Microsoft as ASP.NET Web Page and  it supports Razor Syntax.



$50.00 Cheap and Reliable Windows Cloud Server with ASPHostPortal.com

clock May 6, 2013 11:43 by author Jervis

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 details. Now, ASPHostPortal.com proudly announces the most affordable, reliable and cheap Windows Cloud Server on our hosting environment.

 

Microsoft literally built in to Windows Server 2012 hundreds of enhancements and new features. Below are several points highlighted by Microsoft:

  1. Powerful. It delivers the power of many servers, with the simplicity of one. Windows Server 2012 offers you excellent economics by providing an integrated, highly available, and easy-to-manage multiple-server platform.
  2. Continuous availability. New and improved features offer cost-effective IT service with high levels of uptime. Servers are designed to endure failures without disrupting services to users.
  3. Open. Windows Server 2012 enables business-critical applications and enhances support for open standards, open source applications, and various development languages.
  4. Flexible. Windows Server 2012 enables symmetrical or hybrid applications across the data center and the cloud. You can build applications that use distributed and temporally decoupled components.

From just $50.00/month, you can get a dedicated cloud server with the following specifications:

- Windows 2008 R2 / Windows 2012 Standard Edition OS
- 1 Core Processor
- 1 GB RAM
- 100 GB SAN Storage
- 1000 GB Bandwidth
- 100 Mbps Connection Speed
- Full 24/7 RDP Access
- Full 24/7 Windows Firewall Protection
- Choice of United States, European (Amsterdam), and Asia (Singapore) Data Center

“As a leader in Windows Hosting, and having worked closely with Microsoft to reach this point, we’re moving forward with expectant anticipation for serving our loyal clients with Windows Cloud Server Solutions.” Said Dean Thomas, Manager at ASPHostPortal.com.

For more details, please visit http://www.asphostportal.com/Windows-Cloud-Server-Hosting-Plans.aspx.

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 :: How to Customize oAuth Login UI in ASP.NET 4.5 and MVC 4

clock May 3, 2013 08:32 by author Jervis

In this quick post, we will see how to customize, oAuth Login UI in ASP.NET 4.5 and MVC 4.

One of the common requirements with oAuth login is that displaying respective provider’s logo or image.

In ASP.NET 4.5 and MVC 4, we can register oAuth provider in App_Start/AuthConfig.cs file and here we can also pass additional data to oAuth provider if any. We can use this extra data dictionary to pass oAuth provider’s image url to view and based on it we can display image for respective provider.

As we can see in above code snippet that we are passing Icon url with extra data. So we can now access this Icon url from view. Open Views/Account/_ExternalLoginsListPartial.cshtml and replace the classic button markup with below code snippet.

Now run the application by pressing F5 and wow we have brand new login UI for oAuth provider.

ASP.NET MVC 4 Hosting start from $3.00/month. Check it out for more information!!

 



ASP.NET MVC 4 Hosting - ASPHostPortal :: Multiple Views and DisplayMode Providers in ASP.NET MVC 4

clock April 8, 2013 12:35 by author Jervis

All in all, the biggest difference between ASP.NET MVC and ASP.NET Web Forms is the neat separation that exists in ASP.NET MVC between the actions that follows a request and the generation of the subsequent response for the browser.

The request lifecycle In Web Forms was a continuous flow. Firstly, a Page object was created from default settings hard-coded in the ASPX file and then initialized to the last known good state read from the viewstate field. The user code had then a chance to further update the state of the Page object before the postback event was handled and the state of the page to render back to the user was prepared.

All this happened in a single procedure: There was little chance for developers to serve different views in front of the same request. On the other hand, Web Forms is built around the concept of a “page”. If you request a page, you’re going to get “that” page. Subsequently, if you request default.aspx from a site intended for desktop use why should you be expecting to receive a mobile optimized page instead if you’re making the request from a mobile device? If you want a mobile page, you just set up a new mobile site and make it reachable through a different URL. At that point, you have a distinct “page” to invoke and it all works as expected.

Web Forms at some point was also extended with convention-based tricks to automatically serve different master pages to different browsers and also to make server controls capable of returning different values for different browsers. Nevertheless, Web Forms serves the vision of the web world that was mainstream more than a decade ago. Unless you have serious backward compatibility reasons, you should definitely consider making the step forward to ASP.NET MVC; and use ASP.NET MVC for any new development.

Anyway, this article is NOT about the endless debate the relative merits of Web Forms and MVC—there’s really nothing to discuss there. This article is about new features introduced in ASP.NET MVC 4 to make it really easy and effective to serve different views in front of the same request.

Display Modes

Here’s the classic example where display modes fit in. Suppose you have a Home controller with an Index method.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

As you know, you should also have a file named index.cshtml located under the Views/Home folder in the project. This file will provide the HTML for the browser. In the body of the Index method above you code (or better, you invoke from other components) the logic required to serve the request. If, by executing this piece of logic, data is produced which needs to be embedded in the view, then you pass this data down to the view object by adding an argument to the View method.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = ProcessRequestAndGetData();
        return View(model);
    }
}

So far so good.

Now in ASP.NET MVC 4 there’s an extra piece of magic that you might not know about yet. To experience the thrill of it, you add a new file to the Views/Home folder named index.mobile.cshtml. You can give this file any content you like; just make sure the content is different from the aforementioned index.cshtml.

Now launch the sample site and visit it with both a regular desktop browser, Internet Explorer perhaps, and a mobile browser. You can use the Windows Phone emulator or perhaps Opera Emulator. However, the simplest thing you can do to test the feature without much pain is to hit F12 and bring up the IE Developer’s Tools window. From there, you set a fake user agent that matches a mobile device. If you are clueless about what to enter, here’s a suggestion that matches an iPhone running iPhone OS 6:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko)

Quite surprisingly, the view you get for the same home/index URL is the mobile view as coded in the file index.mobile.cshtml.

What the heck is going on? Is this pure magic?

Even though I’m a firm believer that there can’t be any magic in software, well, I faced some terrible doubts until I found out about display modes.

Display Modes: Where Are Them?

To spot where display modes are and the role they play, I then used .NET Reflector to statically track the code path starting with the View method on the Controller class. From the View method, the code flow reaches the selected view engine—the RazorViewEngineclass in all cases in which CSHTML views are used. In ASP.NET MVC 4 all standard view engines inherit from the same base class—VirtualPathProviderViewEngine. This class has a new protected property named DisplayModeProvider. This property is of typeDisplayModeProvider. TheVirtualPathProviderViewEngine lists some helper methods through which the view name is resolved. The view engine receives the view name as set at the controller level: it can be name like “index” or it can be the empty string, as in the example above. If no view name is provided the view engine assumes it is the name of the action.

In ASP.NET MVC 4, an extra step takes place in theVirtualPathProviderViewEngine base class from which both WebFormsViewEngine and RazorViewEngine inherit. During the resolution of the view name, the view engine queries theDisplayModeProvider object to see if any of the registered display modes can be applied to the requested view. If a match is found, then the original view name is changed to point to the CSHTML file that represents the match. So, for instance, it may happen that “index” becomes “index.mobile”.

Let’s now explore further the internals of the DisplayModeProvider class.

The DisplayModeProvider Class

The documentation refers to this class as being internal to the framework; however, it has a few public members that you might, and should, be using in order to extend your site with multiple ad hoc views. The class has a static constructor that .NET Reflector decompiles as below:

static DisplayModeProvider()
{
    MobileDisplayModeId = "Mobile";
    DefaultDisplayModeId = string.Empty;
    _displayModeKey = new object();
    _instance = new DisplayModeProvider();
}

And here’s the constructor instead:

internal DisplayModeProvider()
{
    List list = new List();
    DefaultDisplayMode mode = new DefaultDisplayMode(MobileDisplayModeId) {
        ContextCondition = context => context.GetOverriddenBrowser().IsMobileDevice
    };
    list.Add(mode);
    list.Add(new DefaultDisplayMode());
    this._displayModes = list;
}

It turns out that DisplayModeProvider holds a list of DefaultDisplayMode objects each representing a display mode. By default, the provider holds two display modes: default and mobile. The default display mode is characterized by the empty string; the mobile display mode is characterized by the “mobile” string. These strings basically identify the suffix appended to the view name. This is where file name index.mobile.cshtml comes from.

It is interesting to focus on the following code:

DefaultDisplayMode mode = new DefaultDisplayMode(MobileDisplayModeId) {
     ContextCondition = context =>
context.GetOverriddenBrowser().IsMobileDevice
};

In spite of a misleading name, the DefaultDisplayMode class is just the official class that represents a display mode. As I see things, the “Default” prefix in the name is just out of place. A display mode class is built around two main pieces of information: suffix name and matching rule. In the code snippet above, a new display mode class is created with the suffix of “mobile”—the actual value of the MobileDisplayModeIdfield—and a matching rule assigned to the ContextConditionproperty. Property ContextCondition is a delegate as below:

Func<HttpContextBase, Boolean>

The purpose of the delegate is to analyze the HTTP context of the current request and return a Boolean answer to the question: should this display mode be used to serve the current request? How the Boolean response is found is entirely up to the implementation. As defined above, the mobile display mode parses the user agent string that comes with the request and seeks to find known keywords that would mark it for that of a mobile device. I’ll return on this point in a moment.

Listing Current Display Modes

You hardly have the need to do this in code, but I encourage you to try that out for pure fun. Here’s the code that reads and displays the currently available modes:

<ul>
    @{
        foreach(var d in DisplayModeProvider.Instance.Modes)
        {
            <li>@(String.IsNullOrEmpty(d.DisplayModeId) ?"default" :d.DisplayModeId)</li>
        }
    }
</ul>

You use the Instance static member to access the singleton instance of the DisplayModeProvider class and flip through the Modes property. By the way, the getter of the Modes property just returns the value stored in the internal _displayModes field dissected earlier through .NET Reflector.

Beyond the Default Configuration

The default and mobile display modes come free out of the box, but honestly they are not worth the cost. I have two reasons to say this. First, modern web sites need more than just a mobile/desktop dichotomy for views. You might want to distinguish tablets, smartphones, legacy phones, perhaps smart TVs. Sometimes this can be achieved with CSS media queries; sometimes you need to do server-side detection of the device via its provided user agent string. This leads to the second reason I have to blissfully ignore the default ASP.NET MVC configuration. Even if a plain desktop/mobile dichotomy works for your site, the point is that the logic behind the mobile context condition is weak and flaky. It has good chances to work with iPhone and BlackBerry devices; it may not even work with Windows Phone and Android devices—let alone with older and simpler devices. The method IsMobileDevice you have seen referenced a while back does sniffing of the user agent string based on the information it can find in the following .browser files you get installed with ASP.NET.

The model is clearly extensible and you can add more information at any time; but writing a .browser file may not be easy and the burden of testing, checking, and further extending the database is entirely on your shoulders.

The figure proves that I added a fairly large (18 MB) browser file—an XML file actually—named mobile.browser. That file comes from an old Microsoft project now discontinued and contains a reasonable amount of devices as of summer of 2011. All devices and browsers which came next are not correctly detected.

In the end, display modes are an excellent piece of infrastructure but require a bit of work on your end for configuration and additional tools to do view routing work effectively. The siren call about ASP.NET MVC being fully mobile aware is just a siren call.

What Can You Do About It?

You use display modes to give your site multiple views in front of the same URL. More concretely, this mostly means using defining a display mode for each device, or class of devices, you’re interested in. You could create an iPhone display mode for example. Likewise, you could create a tablet display mode. Here’s some code:

var modeTablet = new DefaultDisplayMode("tablet")

{
   ContextCondition = (c => IsTablet(c.Request))
};var modeDesktop = new DefaultDisplayMode("")
{
   ContextCondition = (c => return true)
};
displayModes.Clear();
displayModes.Add(modeTablet);
displayModes.Add(modeDesktop);

When run from Application_Start, the code drops default modes and defines two new modes: tablet and desktop. The tablet mode is added first and will be checked first. The internal logic that finds the appropriate display mode, in fact, stops at first match. If the HTTP request is not matched to a tablet, it is then treated by default with a view optimized for a desktop device.

How would you reliably determine whether a given request comes from a tablet? It’s all about sniffing the user agent string; but you need a professional tool for that. The answer is getting a commercial license from a Device Description Repository vendor like ScientiaMobile for WURFL. Note that WURFL is only the most widely used (Facebook and Google use it) device database; it is free for open source projects and has a partly free cloud version. Other products exist too. But my point here is that you should not spend a second on crafting your own solution for sniffing user agent strings.

 



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

 

 



DotNetNuke Hosting - DotNetNuke versus Joomla

clock February 5, 2013 05:45 by author andy_yo

DotNetNuke and Joomla are two very popular CMS (Content Management Systems) based on different technologies. DotNetNuke is a content management system written in Visual Basic and based on the Asp.Net framework, whereas Joomla is based on the popular PHP framework. Each has its own advantages and disadvantages which we will discuss further in detail.

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

Core Functionality: DNN offers extensive core functionalities in front of which Joomla seems a little weak. DNN offers features like database replication, event management, photo gallery and built-in forum system. Joomla also offers various functionalities that are not available in any other PHP based CMS, such as load balancing and a trash bin to ensure that articles are not accidentlly deleted. However, Joomla still falls short of DNN in context of their core functionalities.

Customization and Extensions: Joomla compensates the lack of core functionalities by allowing extensive third party plugins and customization facilities. Joomla provides a core framework around which developers can develop any site with desired functionalities. There is a plugin available for everything in Joomla therefore extra functionality can be added and customized according to client's requirements. Moreover, vast number of templates are available on the internet from which developers can chose the suitable themes and customize them according to their needs.

However, the template designs in Joomla are often based upon similar layouts which usually end up in the development of too many similar looking websites with slight changes in the design and color. DNN however offers a high level of flexibility thus provides an opportunity to create unique websites.

Basic Technology: Both Joomla and DotNetNuke are built upon different technologies which makes it essential to take their technical differences into account. Joomla uses technologies like PHP and MySQL backend which are extensively used for web development and web application development. On the other hand, DotNetNuke uses technically superior Asp.net framework from Microsoft which is too expensive for regular web-hosting environment. However, small and medium businesses usually have servers running on Microsoft's IIS which eliminates the open source advantage of Joomla.

DotNetNuke is more useful and feasible for corporate and enterprise intranets which require to integrate with the existing systems that are usually built using the same technology. They require sophistication, flexibility and robustness which are offered by DNN and can also be easily afforded by enterprises. Whereas, Joomla is designed to provide quick, expandable and cost effective web presence.

Support: The DotNetNuke offers extensive support depending upon the edition you have. The basic version provides developers forum through which users can get assistance from various other developers active on the forum. The paid "professional" version offers unlimited online support whereas the "Elite" edition provides live telephonic support with response under 2 hours. Joomla does not provide paid support system but there are various third party organizations offering training and support for Joomla.

The paid versions of DotNetNuke, i.e. "professional" and "elite" version are extensively tested and verified officially which makes them a good choice for business applications that require stability and perfectness.

Ease of Usage: DotNetNuke allows for quick and easy content editing functionality whereas in Joomla users have to first sign into a different section on the site before they can make changes to content. You can easily change the position of modules in DNN by drag and drop functionality which makes it so easier. Apart from this both the frameworks offer similar ease of use via features such as built in macro languages, ability to mass upload and search engine friendly URLs.

While comparing them we just cannot declare one better than the other as each has some advantages and disadvantages of its own. What we can say with certainty is that DotNetNuke is better for business applications and creation of business scale websites whereas Joomla is ideal for making quick, functional and cost effective web sites.

 

 



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