Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

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

SQL Server 2012 Hosting - How To Create Contained Databases in SQL Server 2012

clock April 29, 2013 08:52 by author andy_yo

Contained databases are a new feature in SQL Server 2012 and are defined on MSDN Library as ”a database that is isolated from other databases and from the instance of SQL Server that hosts the database”.

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 containment setting of a database can be NONE, PARTIAL or FULL. But only NONE and PARTIAL are supported on SQL Server 2012.

Benefits and characteristics.
The following are some of the benefits and characteristics that contained databases have:

  • They make easier to migrate databases from one server to another. Errors related to orphan users are no longer an issue with contained databases, since a contained database user can now be created without an associated login.
  • Authentication can now occur at the database level.
  • Contained database users can be Windows and SQL Server authentication users.
  • A contained database user can access only contained database objects. They cannot access system databases and cannot access server objects.
  • Metadata is stored on the contained database and not stored on system databases. This makes contained databases more portable than the databases we know. 

Disadvantages and limitations.
Some disadvantages and limitations are the following:

  • There are some security concerns. A database owner can create contained database users without the permission of a DBA. The possibility of denial of service attacks exist with contained databases using AUTO_CLOSE option. For security best practices about contained databases, please see the references shown at the end of the article.
  • Partially contained databases cannot use replication, change data capture, change tracking, numbered procedures, schema-bound objects that depend on built-in functions with collation changes. You may find more limitations on the references shown at the end of this article.

Requirements of contained databases.

  • It is required to enable contained databases on the instance.
  • The contained database needs to be added to the connection string or specified when connecting via SQL Server Management Studio.

Step-by-step instructions on how to create a contained database.
To be able to create contained databases on a SQL Server 2012 instance, we need to enable the contained database authentication option on the instance.
Open SQL Server 2012 Management Studio, connect to the instance, make a right click on the name of the instance on Object Explorer, select the Advanced page on the "Select a page" panel, and set to true the "Enable Contained Databases" option.


Alternatively, you can use sp_configure system stored procedure to enable contained databases on the instance, as shown below

EXEC sp_configure 'show advanced', 1
GO
RECONFIGURE
GO

EXEC sp_configure 'contained database authentication', 1
GO
RECONFIGURE
GO

When a database is created the "Containment type" should be set to "partial" to make the database a contained database, as shown below.

This can be done using T-SQL too, as shown below.

A contained database allows the creation of a database user that is not associated to an instance login. A contained database user can be created expanding the Security folder on the contained database, making a right click on the Users folder and selecting the "New User" option.

Next, set the user type to "SQL user with password", assign a user name, set the password for the database user and specify the default schema for the user.

Specify the roles for this user on the database and click OK.

If you would like to create the contained database user using T-SQL, please see the example below.
CREATE USER [MorilloCD2User]
    WITH PASSWORD=[email protected]',
   
DEFAULT_SCHEMA=[dbo]
GO

To connect a contained database user to a contained database, the database name should be specified on the connection string. If you are using SQL Server Management Studio, on the Connect to Server dialog specify the authentication, specify the user name, provide the password, click on the Options button and specify the database name on the "Connect to database" combo box.



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.



Top 5 Features of ASP.NET MVC Framework 4

clock April 12, 2013 12:27 by author Ben

ASP.NET MVC framework is designed to create web applications which can be accessed over the URLs like RESTful services. The application layers will clearly be segregated into Views, Models and Controllers. ASP.NET MVC Framework 4 is available as a separate installer for Visual Studio 2010 and comes out of the box with Visual Studio 2012. In this article I will explain my top 5 features or improvements in ASP.NET MVC 4 framework.

1. New Project Templates

There are a couple of new project templates added for ASP.NET MVC Framework version 4 named web API template and mobile application template. In the RC version of the product there was another template called Single Page Application (SPA) template but it was removed during the RTM.

Web API
Web API templates are used to create HTTP services. These HTTP services can be accessed directly by a variety of clients from tablets, and smart phones to normal PC browsers. It also helps the developers to implement RESTFul architecture in an MVC application. This template is a powerful tool since it paves an easy way for developers to create HTTP services utilizing the core ASP.NET MVC capabilities like Routing, Filters, Query composition, etc.

Mobile Application
As usage of the internet over mobile devices is becoming high, most companies started developing mobile specific applications. Microsoft has wisely included the mobile application template, which will support developing a pure mobile ASP.NET MVC web application. It will include the HTML helpers for mobile specific markups, and mobile specific plug-ins like jQuery mobile, etc.

2. Adaptive Rendering - ViewPort Tag & @media CSS

The ViewPort is a <meta> tag added to the client razor view, which will ensure that the page content is displayed in an optimum way despite if the client is a mobile device or a desktop. Without the ViewPort <meta> tag the same web page will be displayed on a mobile device as that of the desktop whereas the mobile device has a smaller screen than a desktop. It makes the usability of the application difficult on the mobile device. The below mentioned ViewPort tag solves this problem.

<meta name="viewport" content="width=device-width" />


The ViewPort tag does content resizing only at the page level. If the developer wants to customize each control styling based on the client device then the @media CSS tag can be used. It applies / overrides the CSS based on the size of the client screen.

   @media only screen and (max-width: 650 px)    
    {   
           /*CSS in this section will be applied when the request is made by a device with a screen and the width is less than 650 pixels*/    
           /*Custom CSS*/    
    }

3. Display Modes

This feature enables the developers to have different sets of views for each device and load them based on who is accessing the web application. This is required when the requirement is to change the view, content, control look or the operations different from device to device.
In order to have the display modes working, the razor views should be named as _Layout.mobile.cshtml and _Layout.cshtml. The idea is to load the former template view when accessed from a mobile device and to load the later one when accessed from a desktop. In the global.asax Application_Start event add the code below and MVC 4 takes care of doing it automatically.

 DefaultDisplayMode mobileDisplayMode = new DefaultDisplayMode("mobile")
                {
                    ContextCondition = (context => context.Request.Browser.IsMobileDevice)
                };

 DisplayModeProvider.Instance.Modes.Insert(0, mobileDisplayMode);

4. Support for Async Controller Actions

The Asp.Net MVC 4 application developed on .net framework 4.5 will support asynchronous action methods. An asynchronous controller action method will return a Task of ActionResult and will use async / await keywords. Below is a sample async action method.

namespace MvcApplication1.Controllers
    {
         public class HomeController : Controller
        {
     //Asynchronous Action Method of the controller
            public async Task<ActionResult> GreetAsync()
            {
                return View(await GetGreetMessageAync());
            }
            private async Task<string> GetGreetMessageAync()
            {
                string greetingText = String.Empty;
                await Task.Run(() =>
                    {
                        greetingText = "Welcome to async MVC action method demo";
                    });
                return greetingText;
            }
        }
    }

5. App_Start Folder

Another improvement, which I see with respect to the ASP.NET MVC solution architecture, is the introduction of App_Start folder, which helps in grouping all the code that is used for configuring the behavior of the Asp.Net MVC framework application. In the earlier versions on ASP.NET MVC all the configurations were directly done inside the global.ascx. Below are few of the config files that are added to the folder by default in an internet application template.

a.  AuthConfig.cs
b. BundleConfig.cs
c.  FilterConfig.cs
d. RouteConfig.cs
e. WebApiConfig.cs

ASP.NET MVC 4 also has lot of other features like the OAuth, bundling & minification, etc.



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.

 



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


Author Link


Corporate Address (Location)

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

Sign in