15 Visual Studio Project Templates To Jump Start Your Code

https://visualstudiomagazine.com/Articles/2015/08/01/15-Visual-Studio-Project-Templates.aspx?Page=1

Next time you’re starting a new development project, skip the tedious configuration and setup with these handy templates.

In this space, I typically write about tools that help you build, manage, test or deploy software development projects. The one part of the project I’ve mostly ignored thus far is perhaps the most important: Getting started.

New work typically starts with an idea, then File | New | Project. Then what? Most IDEs, Visual Studio included, provide some basic project templates that include commonly used files, folders, libraries, and so on for various development tasks or targets. But if your needs lie beyond the boundaries of those few supported project scenarios, your next task is likely to involve some (and possibly a lot of …) dull configuration and scaffolding work before you type the first line of code.

Fortunately, enterprising folks in the development community created Visual Studio templates specially tuned for a staggering number of project types, target platforms, development stacks, and software frameworks. Here’s a look at a few of them.

Truly Blank
The most basic scenario is creating a bare-bones project with no added packages, but it turns out that the “Blank App” template in Visual Studio 2015 isn’t really blank after all. By default, it includes a number of NuGet packages you might not want in a simple project.

Weston Thayer thought this was weird, so he created a Truely Blank App template that has most of the NuGet packages removed and turns off the frame rate counter as well. You can read more about what Thayer is doing over at his blog Cryclops | sad cyclops.

NuGet Packager
Speaking of NuGet, Ove Andersen has written a NuGet Packager template that greatly simplifies the process of setting up, packaging, building and publishing NuGet projects.

 

Anderson’s template follows the “Creating and Publishing a Package” standard conventions in the NuGet documentation and just takes the dirty work out of the process. It supports Visual Studio 2013, 2012, and 2010. Visual Studio 2015 support has been added, too, but wasn’t in the project description when this article was posted.

Windows Internet of Things
Something I missed until looking these templates up: Microsoft is creating an Internet of Things (IoT) platform alongside Windows 10 and Microsoft Azure. Windows 10 IoT: Powering the Internet of Things explains some of the strategy here, including a version of Windows 10 for small devices!

Interested in building Windows 10 IoT projects? Well, just fire up Visual Studio 2015 along with the Windows IoT Core Project Templates and start coding. Microsoft is calling these “Universal Windows Platform (UWP) templates,” and they support writing headless Background Applications in C#, C++, JavaScript, and Visual Basic or console applications in C++. Target platforms include Raspberry Pi 2 and Minnowboard Max.

For further information, including documentation and sample projects, check out theWindows IoT Dev Center and the IoT videos on Channel 9.

Apache Cordova
Apache Cordova, formerly known as PhoneGap, is a popular framework for cross-platform application development in HTML, CSS, and JavaScript. Best known for writing mobile apps, Cordova has been extended into other realms.

Apache Cordova Template for Windows 10 is a project by Microsoft’s Kirupa Chinnathambithat takes advantage of new Apache Cordova features to create Visual Studio 2015 projects that target Windows 10 in addition to Android and iOS. To learn more about this new option for Windows app development see “Introducing the Windows 10 Apache Cordova Platform” on the Visual Studio Blog and “What’s New in Windows 10 for Cordova” over on GitHub.

For more typical mobile application Cordova projects targeting Android, iOS, and Windows Phone, take a look at the Cordova Multiplatform Template, which uses Gulp/Node, Ionic/Angular, SASS, and TypeScript. The template was created by Quique Fdez Guerra. You can learn more, find documentation, and play with a demo at the Cordova Multiplatform Template Web site and learn more on the CKGrafico blog (¡En español!).

Caliburn.Micro
Like using Caliburn.Micro as the base framework for your XAML MVC/MVVM applications? Bogdan Bujdea created a simple Caliburn.Micro Windows 10 Template for Visual Studio 2015. Now you don’t have to waste any time installing Caliburn.Micro for a new project. Just open the template and start coding.

Cool backstory here: Just getting started with developing for Windows 10, Bujdea was inspired by other community contributions that helped him learn. So he decided to create the Caliburn.Micro Windows 10 Template and share it right back. High five! Read the story over onBujdea’s blog.

SOLID Enterprise Apps
If you’re starting a new project and want to get it organized right from the start, take a look atAlexander Viken’s Enterprise Application SOLID Solution template, which sets up a boilerplate solution containing five projects in solution folders based on the SOLID principles. By default it sets up Documentation, Presentation, Business, Domain, Data, Cross-Cutting, and Deployment layer folders for your solution, and pre-configures the Business, Domain, Data, and Cross-Cutting layers with boilerplate code and test projects.

If you’re not familiar with the SOLID principles for object-oriented programming, definitely read Uncle Bob’s original “PrinciplesOfOOD” article, as well as Samuel Oloruntoba’s “S.O.L.I.D: The First 5 Principles of Object Oriented Design” (with handy code examples) and William Durand’s “From STUPID to SOLID Code!

Data-Driven Dynamic MVC
Here’s an interesting idea for building data-centric Web applications: Chis Perry’s Dynamic MVC template (also available as the Dynamic MVC NuGet package) lets you dynamically create Controller methods and routes based on metadata from your Model objects. Perry has a series of project-based tutorials on the Dynamic MVC Web site showing you how it works. I see a lot of potential for bad data-myopic implementation here, but also a lot of potential for building data-smart apps if used wisely.

Web Applications
Speaking of the World Wide Web, it probably wouldn’t surprise you to know that there are dozens of Visual Studio Web application templates covering almost every conceivable combination of technology stack and JavaScript framework. It looks to me like popular choices are converging on mash-ups with one or more of the following: Angular, Bootstrap, SASS, and LESS. Here are a few new choices and very popular old ones.

Let’s start out with Aby Mathew’s ASPNET MVC ANGULAR Project Template, which is configured up front with ASP.NET MVC 5.0, Angular, and Web API 2.0, along with Bootstrap and Angular’s ng-grid Data Grid (soon to be known as UI Grid).

Muhammad Rehan Saeed put together a very comprehensive ASP.NET MVC Boilerplatetemplate based on Microsoft’s default ASP.NET MVC template, but with a greater emphasis on security, performance, search engine optimization (SEO) and social media integration, accessibility, and browser compatibility, among other features, right out of the box. A key, unique feature added by Saeed: “liberal use of comments and even gives you a checklist of tasks which you need to perform to make it even better.”

The AngularJS SPA Template, by Konstantin Tarkus, is a port of the Angular Seed project optimized for creating single-page Web application (SPA) projects in Visual Studio. It includes AngularJS, Bootstrap 3, HTML5 Boilerplate, Razor, and the ASP.NET Web Optimization Framework. This looks like a really well thought out starting point for SPA apps.

Advertisements

10 Good Practices for ASP.NET MVC Apps

http://www.codemag.com/article/1405071

 

By Leonardo Esposito

CODE Consulting
inShare

Leonardo Esposito

Dino Esposito is the author of “Programming ASP.NET MVC” for Microsoft Press as well as “Programming ASP.NET 4” and other bestselling books such as “Microsoft ® .NET: Architecting Applications for the Enterprise”. Regular contributor to MSDN Magazine and DevProConnections Magazine, Dino is a frequent speaker at industry events all over the world including Microsoft TechED and DevConnections. After a decade of Web development, Dino jumped on the mobile bandwagon and is actively developing for iOs, Android and WP7.

This article was published in:
This article was filed under:

ASP.NETASP.NET MVCDesign PatternsDevelopment ProcessWeb Development (general)DevNet – Web
Advertisement:

When you open up Visual Studio 2013 with the intent of building a new ASP.NET MVC 5 project, you find only one option: an ASP.NET Web Application. This is great, as it represents a moment of clarity in a whirlpool of similar-looking and confusing options. So you click and are presented with various options as to the type of project to create. You want ASP.NET MVC, right? So you pick up the MVC option. What you obtain is a no-op demo application that was probably meant to give you an idea of what it means to code for ASP.NET MVC. Even though the result does nothing, the resulting project is fairly overloaded.

You’ll also find several Nuget packages and assemblies referenced that are not required by the sample application, yet are already there to save time for when you need them in action. This is not a bad idea in theory, as nearly any ASP.NET website ends up using jQuery, Bootstrap, Modernizr, Web Optimization, and others. And if you don’t like it, you still have the option of starting with an empty project and adding MVC scaffolding. This is better, as it delivers a more nimble project even though there are many references that are useless at first. The truth is that any expert developer has his own favorite initial layout of the startup project, including must-have packages and scripts.

Although I may be tempted, I don’t want to push my own ideal project layout on you. My purpose, instead, is applying the Occam’s Razor to the ASP.NET MVC project templates that you get in Visual Studio 2013. I’ll start with the organization of project folders and proceed through startup code, bundling, HTML layout, controllers, layers, HTTP endpoints, and multi-device views. Overall, here are ten good practices for sane ASP.NET MVC 5 development.

Advertisement

#1: Project Folders and Namespaces
Let’s say you used the Visual Studio 2013 project template to create a new project. It works, but it’s rather bloated. Figure 1 shows the list of unnecessary references detected by ReSharper.
Figure 1 : Unnecessary references in the ASP.NET MVC project built with the default Visual Studio 2013 template
It’s even more interesting to look at the remaining references. Figure 2 shows what you really need to have referenced in order to run a nearly dummy ASP.NET MVC application.
Figure 2 : Strictly required assemblies in a basic ASP.NET MVC 5 project
Here’s the minimal collection of Nuget packages you need in ASP.NET MVC.

<packages>
<package id=”Microsoft.AspNet.Mvc”
version=”5.0.0″
targetFramework=”net45″ />
<package id=”Microsoft.AspNet.Razor”
version=”3.0.0″
targetFramework=”net45″ />
<package id=”Microsoft.AspNet.WebPages”
version=”3.0.0″
targetFramework=”net45″ />
</packages>
The project contains the folders listed in Table 1.

When you start adding Nuget packages, some other conventions start appearing such as the Scripts folder for Modernizr and for jQuery and its plugins. You may also find a Content folder for Bootstrap style sheets and a separate Fonts folder for Bootstrap’s glyph icons.

I find such a project structure rather confusing and usually manage to clean it up a little bit. For example, I like to place all content (images, style sheets, scripts, fonts) under the same folder. I also don’t much like the name Models. (I don’t like the name App_Start either but I’ll return to that in a moment.) I sometimes rename Models to ViewModels and give it a structure similar to Views: one subfolder per controller. In really complex sites, I also do something even more sophisticated. The Models folder remains as is, except that two subfolders are addedLInput and View, as shown in Figure 3.
Figure 3 : Content and Models folder internal structure
Generally speaking, there are quite a few flavors of models. One is the collection of classes through which controllers receive data. Populated from the model binding layer, these classes are used as input parameters of controller methods. I collectively call them the input model and define them in the Input subfolder. Similarly, classes used to carry data into the Razor views collectively form the view model and are placed under the Models/View folder. Both input and view models are then split on a per-controller basis.

One more thing to note is the matching between project folders and namespaces. In ASP.NET it’s a choice rather than an enforced rule. So you can freely decide to ignore it and still be happy, as I did for years. At some point—but it was several years ago—I realized that maintaining the same structure between namespaces and physical folders was making a lot of things easier. And when I figured out that code assistant tools were making renaming and moving classes as easy as click-and-confirm, well, I turned it into enforcement for any of my successive projects.

#2 Initial Configuration
A lot of Web applications need some initialization code that runs upon startup. This code is usually invoked explicitly from the Application_Start event handler. An interesting convention introduced with ASP.NET MVC 4 is the use of xxxConfig classes. Here’s an example that configures MVC routes:

public class RouteConfig
{
public static void RegisterRoutes(
RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new {
controller = “Home”,
action = “Index”,
id = UrlParameter.Optional
});
}
}
The code in global_asax looks like this:

RouteConfig.RegisterRoutes(RouteTable.Routes);
For consistency, you can use the same pattern to add your own classes that take care of application-specific initialization tasks. More often than not, initialization tasks populate some ASP.NET MVC internal dictionaries, such as the RouteTable.Routes dictionary of the last snippet (just after the heading for #2).For testability purposes, I highly recommend that xxxConfig methods are publicly callable methods that get system collections injected. As an example, here’s how you can arrange unit tests on MVC routes.

[TestMethod]
public void Test_If_Given_Route_Works()
{
// Arrange
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
RouteData routeData = null;
// Act & Assert whether the right route was found
var expectedRoute = “{controller}/{action}/{id}”;
routeData = GetRouteDataFor(“~/product/id/123”,
routes); Assert.AreEqual(((Route) routeData.Route).Url,
expectedRoute);}
Note that the code snippet doesn’t include the full details of the code for custom GetRouteDataFor method. Anyway, the method uses a mocking framework to mock HttpContextBase and then invokes method GetRouteData on RouteCollection passing the mocked context.

var routeData = routes.GetRouteData(httpContextMock);
Many developers just don’t like the underscore convention in the name of some ASP.NET folders, particularly the App_Start folder. Is it safe to rename this folder to something like Config? The answer is: it’s generally safe but it actually depends on what you do in the project.

The possible sore point is the use of the WebActivator Nuget package in the project, either direct or through packages that have dependencies on it. WebActivator is a package specifically created to let other Nuget packages easily add startup and shutdown code to a Web application without making any direct changes to global.asax. WebActivator was created only for the purposes of making Nuget packages seamlessly extend existing Web applications. As WebActivator relies on an App_Start folder, renaming it may cause you some headaches if you extensively add/refresh Nuget packages that depend on WebActivator. Except for this, there are no problems in renaming App_Start to whatever you like most.

#3 Bundling and Minifying CSS Files
Too many requests from a single HTML page may cause significant delays and affect the overall time-to-last-byte metrics for a site. Bundling is therefore the process of grouping distinct resources such as CSS files into a single downloadable resource. In this way, multiple and logically distinct CSS files can be downloaded through a single HTTP request.

Minification, on the other hand, is the process that removes all unnecessary characters from a text-based resource without altering the expected functionality. Minification involves shortening identifiers, renaming functions, removing comments and white-space characters. In general, minification refers to removing everything that’s been added mostly for readability purposes, including long descriptive member names.

Advertisement

Although bundling and minification can be applied together, they remain independent processes. On a production site, there’s usually no reason not to bundle minified CSS and script files. The only exception is for large and very common resources that might be served through a Content Delivery Network (CDN). The jQuery library is a great example.

Bundling requires the Microsoft ASP.NET Web Optimization Framework available as a Nuget package. Downloading the Optimization Framework also adds a few more references to the project. In particular, they are WebGrease and Microsoft Infrastructure. These, in turn, bring their own dependencies for the final graph, shown in Figure 4.
Figure 4 : Graph of Nuget dependencies for bundling and minification
Bundles are created programmatically during the application startup in global.asax. Also in this case, you can use the xxxConfig pattern and add some BundlesConfig class to the App_Startup folder. The BundleConfig class contains at least one method with code very close to the following snippet.

public static void RegisterBundles(
BundleCollection bundles)
{
bundles.Add(new StyleBundle(“~/Content/Styles”)
.Include(“~/Content/Styles/bootstrap.css”,
“~/Content/Styles/myapp.css”));
}
The code creates a new bundle object for CSS content and populates it with distinct CSS files defined within the project. Note that the Include method refers to physical paths within the project where the source code to bundle is located. The argument passed to the StyleBundle class constructor instead is the public name of the bundle and the URL through which it will be retrieved from pages. There are quite a few ways to indicate the CSS files to bundle. In addition to listing them explicitly, you can use a wildcard expression:

bundles.Add(new Bundle(“~/css”)
.Include(“~/content/styles/*.css”);
Once CSS bundles are defined invoking them is as easy as using the Styles object:

@Styles.Render(“~/Bundles/Css”)
As you can figure from the last two snippets, ASP.NET optimization extensions come with two flavors of bundle classes: the Bundle class and the StyleBundle class. The former only does bundling; the latter does both bundling and minification. Minification occurs through the services of an additional class. The default CSS minifier class is CssMinify and it is based on some logic packaged in WebGrease. Switching to a different minifier is easy too. All you do is using a different constructor on the StyleBundle class. You use the constructor with two arguments, the second of which is your own implementation of IBundleTransform.

#4 Bundling and Minifying Script Files
Bundling and minification apply to script files in much the same way as bundling and minifying CSS files. The only minor difference is that for frequently used script files (such as jQuery) you might want to use a CDN for even better performance. In operational terms, bundling and minifying script files requires the same process and logic as CSS files. You use the Bundle class if you’re only concerned about packing multiple files together so that they are captured in a single download and cached on the client. Otherwise, if you also want minifying, you use the ScriptBundle class.

bundles.Add(new ScriptBundle(“~/Bundles/Core”)
.Include(
“~/Content/Scripts/myapp-1.0.0.js”,
“~/Content/Scripts/knockout-3.0.0.js”)
);
Like StyleBundle, ScriptBundle also features a constructor that accepts an IBundleTransform object as its second argument. This object is expected to bring in some custom logic for minifying script files. The default minifier comes from WebGrease and corresponds to the JsMinify class.

It’s very common today to arrange very complex and graphically rich Web templates that are responsive to changes in the browser’s window size and that update content on the client side through direct access to the local DOM. All this can happen if you have a lot of script files. It’s not, for the most part, JavaScript code that you write yourself. It’s general-purpose JavaScript that forms a framework or a library. In a nutshell, you often end up composing your client-side logic by sewing together multiple pieces, each of which represents a distinct download.

Considering the general recommendation of using as few script endpoints as possible—and bundling does help a lot in that regard—the optimal position of the tags in the body of the HTML page is an open debate. For quite some time, the common practice was to put elements at the end of the document body. This practice was promoted by Yahoo and aimed at avoiding roadblocks during the rendering of the page. By design, in fact, every time the browser encounters a tag, it stops until the script has been downloaded (or recovered from the local cache) and processed.

It’s not mandatory that all script files belong at the bottom. It’s advisable that you distinguish the JavaScript that’s needed for the page to render from the JavaScript that serves other purposes. The second flavor of JavaScript can safely load at the bottom. Well, mostly at the bottom. Consider that as the page renders the user interface in the browser, users may start interacting with it. In doing so, users may trigger events that need some of the other JavaScript placed at the bottom of the page and possibly not yet downloaded and evaluated. If this is your situation, consider keeping input elements that the user can interact with disabled until it’s safe to use them. The ready event of jQuery is an excellent tool to synchronize user interfaces with downloaded scripts. Finally, consider some techniques to load scripts in parallel so that the overall download time becomes the longest of all instead of the sum of all downloads. The simplest way you can do this is through a programmatically created element. You do this using code, as shown below.

var h = document.getElementsByTagName(“HEAD”)[0];
var script = document.createElement(“script”);
script.type = “text/javascript”;
script.onreadystatechange = function() {…};
script.onload = function() {…};
script.onerror = function() {…};
document.src = “…”;
h.appendChild(script)
Script elements are appended to the HEAD element so that parallel download begins as soon as possible. Note that this is the approach that most social Web sites and Google Analytics use internally. The net effect is that all dynamically created elements are processed on different JavaScript threads. This approach is also employed by some popular JavaScript loader frameworks these days.

#5 The Structure of the _Layout File
In ASP.NET MVC, a layout file is what a master page was in classic Web Forms: the blueprint for multiple pages that are ultimately built out of the provided template. What should you have in a master view? And in which order?

With the exceptions and variations mentioned a moment ago for parallelizing the download of multiple scripts, there are two general rules that hold true for the vast majority of websites. The first rule says: Place all of your CSS in the HEAD element. The second rule says: Place all of your script elements right before the closing tag of the element.

There are a few other little things you want to be careful about in the construction of the layout file(s) for your ASP.NET MVC application. First off, you might want to declare explicitly that the document contains HTML5 markup. You achieve this by having the following markup at the very beginning of the layout and subsequently at the beginning of each derived page.

The DOCTYPE instructs older browsers that don’t support specific parts of HTML5 to behave well and correctly interpret the common parts of HTML while ignoring the newest parts. Also, you might want to declare the character set in the HEAD block.

The charset attribute is case-insensitive, meaning that you can indicate the character set name as UTF-8, utf-8 or otherwise. In general, you don’t use other character sets than UTF-8, as it’s the default encoding for Web documents since HTML4, which came out back in 1999. As far as IIS and ASP.NET are concerned, you have other ways to set the character set. For example, you can type it in the section of the web.config file. Having it right in each page just adds clarity. An interesting consequence of clarifying the character set being used is that you can avoid using HTML entities and type special characters directly in the source. Canonical examples are the copyright (©), trademark (®), euro (&euro), dashes (—), and more. The only HTML entities you should use are those that provide the text version of reserved markup characters, such as less-than, greater-than, and ampersand.

Another rather important meta-tag you’ll want to have is the viewport meta-tag whose usage dates back to the early days of smartphones. Most mobile browsers can be assumed to have a rendering area that’s much larger than the physical width of the device. This virtual rendering area is just called the “viewport.” The real size of the internal viewport is browser-specific. However, for most smart phones, it’s around 900 pixels. Having such a large viewport allows browsers to host nearly any Web page, leaving users free to pan and zoom to view content, as illustrated in Figure 5.
Figure 5 : The viewport in a browser
The viewport meta-tag is a way for you to instruct the browser about the expected size of the viewport.

In this example, you tell the browser to define a viewport that is the same width as the actual device. Furthermore, you specify that the page isn’t initially zoomed and worse, users can’t zoom in. Setting the width property to the device’s width is fairly common, but you can also indicate an explicit number of pixels.

In ASP.NET MVC, pay a lot of attention to keeping the layout file as thin as possible. This means that you should avoid referencing from the layout file CSS and script files that are referenced by all pages based on the layout. As developers, we certainly find it easier and quicker to reference resources used by most pages right from the layout file. But that only produces extra traffic and extra latency. Taken individually, these extra delays aren’t significant, except that they sum up and may add one or two extra seconds for the page to show and be usable.

Advertisement

In ASP.NET MVC, a layout page consists of sections. A section is an area that derived pages can override. You might want to use this feature to let each page specify CSS and script (and of course markup) that needs be specific. Each layout must contain at least the section for the body.

@RenderBody()


© @DateTime.Now.Year – ASP.NET QuickUp

The markup above indicates that the entire body of the page replaces @RenderBody. You can define custom sections in a layout file using the following line:

@RenderSection(“CustomScripts”)
The name of the section is unique but arbitrary and you can have as many sections as you need with no significant impact on the rendering performance. You just place a @RenderSection call where you want the derived page to inject ad hoc content. The example above indicates a section where you expect the page to insert custom script blocks. However, there’s nothing that enforces a specific type of content in a section. A section may contain any valid HTML markup. If you want to force users to add, say, script blocks, you can proceed as follows:

@RenderSection(“CustomScripts”)

In this case, overridden sections are expected to contain data that fits in the surrounding markup; otherwise, a parsing error will be raised. In a derived page, you override a section like this:

@section CustomScripts
{
alert(“Hello”);
}
#6 (Don’t) Use Twitter Bootstrap
Twitter Bootstrap is quickly becoming the de-facto standard in modern Web development, especially now that Visual Studio 2013 incorporates it in the default template for ASP.NET MVC applications. Bootstrap essentially consists of a large collection of CSS classes that are applicable directly to HTML elements and in some cases to special chunks of HTML markup. Bootstrap also brings down a few KBs of script code that extends CSS classes to make changes to the current DOM.

As a matter of fact, with Bootstrap, you can easily arrange the user interface of Web pages to be responsive and provide advanced navigation and graphical features.

The use of Bootstrap is becoming common and, as popularity grows, also controversial. There are reasons to go for it and reasons for staying away from it. My gut feeling is that Bootstrap is just perfect for quick projects where aesthetics are important but not fundamental, and where you need to provide pages that can be decently viewed from different devices with the lowest possible costs. Key arguments in favor of Twitter Bootstrap are its native support for responsive Web design (RWD), deep customizability, and the not-secondary fact that it’s extremely fast to learn and use.

Bootstrap was created as an internal project at Twitter and then open-sourced and shared with the community. When things go this way, there are obvious pros and cons. For Web developers, it’s mostly about good things. Bootstrap offers a taxonomy of elements that you want to have in Web pages today: fluid blocks, navigation bars, breadcrumbs, tabs, accordions, rich buttons, composed input fields, badges and bubbles, lists, glyphs, and more advanced things, such as responsive images and media, auto-completion, and modal dialogs. It’s all there and definable through contracted pieces of HTML and CSS classes. Put another way, when you choose Bootstrap, you choose a higher level markup language than HTML. It’s much the same as when you use jQuery and call it JavaScript. The jQuery library is made of JavaScript but extensively using it raises the abstraction level of JavaScript.

By the same token, using Bootstrap extensively raises the abstraction level of the resulting HTML and makes it look like you’re writing Bootstrap pages instead of HTML pages. This is just great for developer-centric Web solutions. It’s not good for Web designers and for more sophisticated projects where Web designers are deeply involved.

When you choose Bootstrap. you choose a higher-level markup language than HTML. It’s much the same as when you use jQuery and call it JavaScript.

From a Web designer’s perspective, Twitter Bootstrap is just a Twitter solution and even theming it differently is perceived like work that takes little creativity. From a pure Web design perspective, Bootstrap violates accepted (best) practices. In particular, Bootstrap overrides the HTML semantic and subsequently, presentation is no longer separate from the content. Not surprisingly, when you change perspective, the same feature may turn from being a major strength to being a major weakness. Just because Bootstrap overrides the HTML semantic, it tends to favor an all-or-nothing approach. This may be problematic for a Web design team that joins an ongoing project where Bootstrap is being used. In a nutshell, Bootstrap is an architectural decision—and one that’s hard to change on the go. So, yes, it makes presentation tightly bound to content. Whether this is really an issue for you can’t be determined from the outside of the project.

Last but not least, the size of Twitter Bootstrap is an issue. Minified, it counts for about 100K of CSS, 29K of JavaScript plus fonts. You can cut this short by picking exactly the items you need. The size is not an issue for sites aimed at powerful devices such as a PC, but Bootstrap for sites aimed at mobile devices may be a bit too much. If you’re going to treat desktop devices differently from mobile devices, you might want to look into the mobile-only version of Bootstrap that you find at .

#7 Keep Controllers Thin
ASP.NET MVC is often demonstrated in the context of CRUD applications. CRUD is a very common typology for applications and it’s a very simple typology indeed. For CRUD applications, a fat controller that serves any request directly is sometimes acceptable. When you combine the controller with a repository class for each specific resource you handle, you get good layering and achieve nifty separation of concerns.

It’s essential to note that the Model-View-Controller pattern alone is not a guarantee of clean code and neatly separated layers. The controller simply ensures that any requests are routed to a specific method that’s responsible for creating the conditions for the response to be generated and returned. In itself, an action method on a controller class is the same as a postback event handler in old-fashioned Web Forms applications. It’s more than OK to keep the controller action method tightly coupled to the surrounding HTTP context and access it from within the controller method intrinsic objects such as Session, Server, and Request. A critical design goal is keeping the controller methods as thin as possible. In this way, the controller action methods implement nearly no logic or very simple workflows (hardly more than one IF or two) and there’s no need to test them.

Advertisement

As each controller method is usually invoked in return to a user’s gesture, there’s some action to be performed. Which part of your code is responsible for that? In general, a user action triggers a possibly complex workflow. It’s only in a basic CRUD, like the very basic Music Store tutorial, that workflow subsequent to user actions consists of one database access that the resource repository carries out. You should consider having an intermediate layer between controllers and repositories. (See Figure 6.)
Figure 6 : A multi-layer architecture for an ASP.NET MVC application
The extra layer is the application layer and it consists of classes that typically map to controllers. For example, if you have HomeController, you might also want to have some HomeService class. Each action in HomeController ends up calling one specific method in HomeService. Listing 1 shows some minimalistic code to illustrate the pattern.

The Index method invokes the associated worker service to execute any logic. The service returns a view model object that is passed down to the view engine for the actual rendering of the selected Razor view. Figure 7 shows instead a modified project structure that reflects worker services and the application layer of the ASP.NET MVC application.
Figure 7 : The new project infrastructure for worker services and view models
#8 Membership and Identity
To authenticate a user, you need some sort of a membership system that supplies methods to manage the account of a user. Building a membership system means writing the software and the related user interface to create a new account and update or delete existing accounts. It also means writing the software for editing any information associated with an account. Over the years, ASP.NET has offered a few different membership systems.

Historically, the first and still largely used membership system is centered on the Membership static class. The class doesn’t directly contain any logic for any of the methods it exposes. The actual logic for creating and editing accounts is supplied by a provider component that manages an internal data store. You select the membership in the configuration file. ASP.NET comes with a couple of predefined providers that use SQL Server or Active Directory as the persistence layer. Using predefined providers is fine, as it binds you to a predefined storage schema and doesn’t allow any reuse of existing membership tables. For this reason, it’s not unusual that you end up creating your own membership provider.

Defining a custom membership provider is not difficult at all. All you do is derive a new class from MembershipProvider and override all abstract methods. At a minimum, you override a few methods such as ValidateUser, GetUser, CreateUser, and ChangePassword. This is where things usually get a bit annoying.

The original interface of the Membership API is way too complicated with too many methods and too many quirks. People demanded a far simpler membership system. Microsoft first provided the SimpleMembership provider and with Visual Studio 2013, what appears to be the definitive solution: ASP.NET Identity.

In the ASP.NET Identity framework, all of the work is coordinated by the authentication manager. It takes the form of the UserManager<T> class, which basically provides a façade for signing users in and out.

public class UserManager<T> where T : IUser
{
:
}
The type T identifies the account class to be managed. The IUser interface contains a very minimal definition of the user, limited to ID and name. The ASP.NET Identity API provides the predefined IdentityUser type that implements the IUser interface and adds a few extra properties such as PasswordHash and Roles. In custom applications, you typically derive your own user type inheriting from IdentityUser. It’s important to notice that getting a new class is not required; you can happily work with native IdentityUser if you find its structure appropriate.

User data storage happens via the UserStore<T> class. The user store class implements the IUserStore interface that summarizes the actions allowed on the user store:

public interface IUserStore<T> : where T:IUser
{
Task CreateAsync(T user);
Task DeleteAsync(T user);
Task<T> FindByIdAsync(string userId);
Task<T> FindByNameAsync(string userName);
Task UpdateAsync(T user);
}
As you can see, the user store interface looks a lot like a canonical repository interface, much like those you might build around a data access layer. The entire infrastructure is glued together in the account controller class. The skeleton of an ASP.NET MVC account controller class that is fully based on the ASP.NET Identity API is shown in Listing 2.

The controller holds a reference to the authentication identity manager. An instance of the authentication identity manager is injected in the controller. The link between the user store and the data store is established in the ApplicationDbContext class. You’ll find this class defined by the ASP.NET MVC 5 wizard if you enable authentication in the Visual Studio 2013 project template.

public class ApplicationDbContext :
IdentityDbContext<IdentityUser>
{
public ApplicationDbContext() :
base(“DefaultConnection”)
{
}
}
The base IdentityDbContextclass inherits from DbContextand is dependent on Entity Framework. The class refers to an entry in the web.config file, where the actual connection string is read. The use of Entity Framework Code First makes the structure of the database a secondary point. You still need a well-known database structure, but you can have the code to create one based on existing classes instead of manual creation in SQL Server Management Studio. In addition, you can use Entity Framework Code First Migration tools to modify a previously created database as you make changes to the classes behind it.

Currently, ASP.NET Identity covers only the basic features of membership but its evolution is not bound to the core ASP.NET Framework. Features that the official interfaces don’t cover yet (such as enumerating users) must be coded manually, which brings you back to the handcrafted implementation of membership.

#9 Expose HTTP Endpoints
An architecture for Web applications that’s becoming increasingly popular is having a single set of HTTP endpoints—collectively known as Web services—consumed by all possible clients. Especially if you have multiple clients (like mobile applications and various Web frontends) a layer of HTTP endpoints is quite helpful to have. Even if you only have a single client frontend, a layer of HTTP endpoints is helpful as it allows you to have a bunch of Ajax-based functionalities integrated in HTML pages. The question is: How would you define such endpoints?

If you need an API—or even a simple set of HTTP endpoints—exposed out of anything but ASP.NET MVC (such as Web Forms or Windows services) using Web API is a no-brainer. But if all you have is an ASP.NET MVC application, and are tied to IIS anyway, you can simply use a separate ASP.NET MVC controller and make it return JSON.

Advertisement

There are many posts out there calling for a logical difference between Web API controllers and ASP.NET MVC controllers. There’s no doubt that a difference exists because overall Web API and ASP.NET MVC have different purposes. Anyway, the difference becomes quite thin and transparent when you consider it from the perspective of an ASP.NET MVC application.

With plain ASP.NET MVC, you can easily build an HTTP façade without learning new things. In ASP.NET MVC, the same controller class can serve JSON data or an HTML view. However, you can easily keep controllers that return HTML separate from controllers that only return data. A common practice consists in having an ApiController class in the project that exposes all endpoints expected to return data. In Web API, you have a system-provided ApiController class at the top of the hierarchy for controllers. From a practical perspective, the difference between ASP.NET MVC controllers and Web API controllers hosted within the same ASP.NET MVC is nearly non-existent. At the same time, as a developer, it’s essential that you reason about having some HTTP endpoints exposed in some way.

Web API and ASP.NET MVC have different purposes.

#10 Use Display Modes
One of the best-selling points of CSS is that it enables designers and developers to keep presentation and content neatly separated. Once the HTML skeleton is provided, the application of different CSS style sheets can produce even radically different results and views. With CSS, you can only hide, resize, and reflow elements. You can’t create new elements and you can add any new logic for new use-cases.

In ASP.NET MVC, a display mode is logically the same as a style sheet except that it deals with HTML views instead of CSS styles. A display mode is a query expression that selects a specific view for a given controller action. In much the same way, the Web browser on the client processes CSS media query expressions and applies the appropriate style sheet; a display mode in server-side ASP.NET MVC processes a context condition and selects the appropriate HTML view for a given controller action.

Display modes are extremely useful in any scenario where multiple views for the same action can be selected based on run-time conditions. The most compelling scenario, however, is associated with server-side device detection and view routing. By default, starting with ASP.NET MVC 4, any Razor view can be associated with a mobile-specific view. The default controller action invoker automatically picks up the mobile-specific view if the user agent of the current request is recognized as the user agent of a mobile device. This means that if you have a pair of Razor views such as index.cshtml and index.mobile.cshtml, the latter will be automatically selected and displayed in lieu of the former if the requesting device is a mobile device. This behavior occurs out of the box and leverages display modes. Display modes can be customized to a large extent. Here’s an example:

var tablet = new DefaultDisplayMode(“tablet”)
{
ContextCondition = (c => IsTablet(c.Request))
};
var desktop = new DefaultDisplayMode(“desktop”)
{
ContextCondition = (c => return true)
};
displayModes.Clear();
displayModes.Add(tablet);
displayModes.Add(desktop);
The preceding code goes in the Application_Start event of global.asax and clears default existing display modes and then adds a couple of user-defined modes. A display mode is associated with a suffix and a context condition. Display modes are evaluated in the order in which they’re added until a match is found. If a match is found—that is, if the context condition holds true—then the suffix is used to complete the name of the view selected. For example, if the user agent identifies a tablet, then index.cshtml becomes index.tablet.cshtml. If no such Razor file exists, the view engine falls back to index.cshtml.

Display modes are an extremely powerful rendering mechanism but all this power fades without a strong mechanism to do good device detection on the server side. ASP.NET lacks such a mechanism. ASP.NET barely contains a method in the folds of the HttpRequest object to detect whether a given device is mobile or not. The method is not known to be reliable and work with just any old device out there. It lacks the ability to distinguish between smartphones, tablets, Google glasses, smart TVs, and legacy cell phones. Whether it works in your case is up to you.

If you’re looking for a really reliable device detection mechanism, I recommend WURFL, which comes through a handy Nuget package. For more information on WURFL, you can check out my article that appeared in the July 2013 issue of CODE Magazine, available at the following URL: .

Display modes are extremely useful in any scenario where multiple views for the same action can be selected based on run time conditions.

Summary
ASP.NET MVC 5 is the latest version of Microsoft’s popular flavor of the ASP.NET platform. It doesn’t come with a full bag of new goodies for developers but it remains a powerful platform for Web applications. ASP.NET is continuously catching up with trends and developments in the Web space and writing a successful ASP.NET MVC application is a moving target. This article presented ten common practices to build ASP.NET MVC applications with comfort and ease.

Domain Model

Unless you are creating a plain CRUD application, the model of business data (also referred to as the domain model) is referenced from a separate assembly and is created and mapped to persistence using any of the known approaches in Entity Framework, whether Database-first, Model-first, or Code-first.

Bundling, Minification, and Debug Mode

Bundling and minification are not a functional feature and are, rather, a form of optimization. For this reason, it makes no sense for you to enable both while in debug mode. For common libraries such as jQuery or Bootstrap, a direct reference to the minified version is acceptable. By default, bundling and minification are disabled until you compile in release mode. The code discussed in this article, therefore, won’t work until you set debug=false in the web.config file. If you only want to check bundling and minification in release mode but leave debug mode on until deployment, you can set the EnableOptimizations property to true on the BundleTable class.

Ratchet 2.0

Recently, the project codenamed Ratchet reached version 2.0 and merged and synced up with Bootstrap. Ratchet can be considered the mobile-only version of Bootstrap. It largely follows the same approach and design and offers the same benefits in terms of raising the abstraction level of the HTML being used. The ideal scenario for Ratchet is mobile sites and HTML5 applications, whether compiled native through Cordova or pinned to the dashboard of mobile operating systems.

Listing 1: A layered controller class
public interface IHomeService
{
IndexViewModel GetModelForIndex();
}

public class HomeController : Controller
{
private readonly IHomeService _service;

public HomeController() : this (new HomeService())
{
}
public HomeController(IHomeService service)
{
_service = service;
}

public ActionResult Index()
{
var model = _service.GetModelForIndex();
return View(model);
}
}

public class ViewModelBase
{
public String Title { get; set; }
}

public class IndexViewModel : ViewModelBase
{
// More members here
}
Listing 2. Sample account controller class
public class AccountController : Controller
{
public UserManager<IdentityUser> UserManager { get; set; }
public AccountController(UserManager<IdentityUser> manager)
{
UserManager = manager;
}
public AccountController() : this(
new UserManager<IdentityUser>(
new UserStore<IdentityUser>(new ApplicationDbContext())))
{
}

// Other members here
}
Table 1: Typical project folders.

Folder name Intended goal
App_Data Contains data used by the application, such as proprietary files (e.g., XML files) or local databases
App_Start Contains initialization code. By default, it simply stores static classes invoked from within global.asax.
Controllers Folder conventionally expected to group all controllers used by the application
Models Folder conventionally expected to contain classes representing the rather nebulous MVC concept of “model”
Views Folder conventionally expected to group all Razor views used by the application. The folder is articulated in subfolders,one per controller

Bootstrap multi column Menu

<!DOCTYPE html>

<html>

<head>

  https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js

  https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js

  <link data-require=”bootstrap-css@3.3.6″ data-semver=”3.3.6″ rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css&#8221; />

  <link rel=”stylesheet” href=”style.css” />

  http://script.js

</head>

<body>

<ul id=”multicol-menu” class=”nav pull-left”>

    <li class=”dropdown”>

        <a href=”#” class=”dropdown-toggle” data-toggle=”dropdown”>MultiCol Menu <b class=”caret”></b></a>

        <ul class=”dropdown-menu”>

            <li>

               

                   

                           

  • test1-1
  •                        

  • test1-2
  •                        

  • test1-3
  •                    

                   

                           

  • test2-1
  •                        

  • test2-2
  •                        

  • test2-3
  •                    

                   

                           

  • test3-1
  •                        

  • test3-2
  •                        

  • test3-3
  •                    

               

            </li>

        </ul>

    </li>

</ul>

</body>

</html>

AngularJS Rest http calls

function rest(request) {

var deferred = $q.defer();
showBusy();
return $http(request).
success(function (data, status, headers, config) {
hideBusy();
deferred.resolve(data);
return deferred.promise;
}).
error(function (data, status, headers, config) {
hideBusy();
console.log(“failure message: ” + JSON.stringify({ data: data }));
deferred.reject();
$location.url(‘/’);
});
}

discountOrder: function (myOrder) {
return rest({ method: ‘POST’, url: websiteUrl.concat(“/api/ShopApi/DiscountCustomerOrder?shopId=”).concat(shopIndaSoftId), data: myOrder, headers: config.headers });
},

Async Programming : Introduction to Async/Await on ASP.NET

https://msdn.microsoft.com/en-us/magazine/dn802603.aspx

 


Async Programming : Introduction to Async/Await on ASP.NET

Stephen Cleary | October 2014

Most online resources around async/await assume you’re developing client applications, but does async have a place on the server? The answer is most definitely “Yes.” This article is a conceptual overview of asynchronous requests on ASP.NET, as well as a reference for the best online resources. I won’t be covering the async or await syntax; I’ve already done that in an introductory blog post (bit.ly/19IkogW) and in an article on async best practices (msdn.microsoft.com/magazine/jj991977). This article focuses specifically on how async works on ASP.NET.

For client applications, such as Windows Store, Windows desktop and Windows Phone apps, the primary benefit of async is responsiveness. These types of apps use async chiefly to keep the UI responsive. For server applications, the primary benefit of async is scalability. The key to the scalability of Node.js is its inherently asynchronous nature; Open Web Interface for .NET (OWIN) was designed from the ground up to be asynchronous; and ASP.NET can also be asynchronous. Async: It’s not just for UI apps!

Synchronous vs. Asynchronous Request Handling

Before diving into asynchronous request handlers, I’d like to briefly review how synchronous request handlers work on ASP.NET. For this example, let’s say the requests in the system depend on some external resource, like a database or Web API. When a request comes in, ASP.NET takes one of its thread pool threads and assigns it to that request. Because it’s written synchronously, the request handler will call that external resource synchronously. This blocks the request thread until the call to the external resource returns. Figure 1 illustrates a thread pool with two threads, one of which is blocked waiting for an external resource.

Waiting Synchronously for an External Resource
Figure 1 Waiting Synchronously for an External Resource

Eventually, that external resource call returns, and the request thread resumes processing that request. When the request is complete and the response is ready to be sent, the request thread is returned to the thread pool.

This is all well and good—until your ASP.NET server gets more requests than it has threads to handle. At this point, the extra requests have to wait for a thread to be available before they can run. Figure 2illustrates the same two-threaded server when it receives three requests.

A Two-Threaded Server Receiving Three Requests
Figure 2 A Two-Threaded Server Receiving Three Requests

In this situation, the first two requests are assigned threads from the thread pool. Each of these requests calls an external resource, blocking their threads. The third request has to wait for an available thread before it can even start processing, but the request is already in the system. Its timer is going, and it’s in danger of an HTTP Error 503 (Service unavailable).

But think about this for a second: That third request is waiting for a thread, when there are two other threads in the system effectively doing nothing. Those threads are just blocked waiting for an external call to return. They’re not doing any real work; they’re not in a running state and are not given any CPU time. Those threads are just being wasted while there’s a request in need. This is the situation addressed by asynchronous requests.

Asynchronous request handlers operate differently. When a request comes in, ASP.NET takes one of its thread pool threads and assigns it to that request. This time the request handler will call that external resource asynchronously. This returns the request thread to the thread pool until the call to the external resource returns. Figure 3 illustrates the thread pool with two threads while the request is asynchronously waiting for the external resource.

Waiting Asynchronously for an External Resource
Figure 3 Waiting Asynchronously for an External Resource

The important difference is that the request thread has been returned to the thread pool while the asynchronous call is in progress. While the thread is in the thread pool, it’s no longer associated with that request. This time, when the external resource call returns, ASP.NET takes one of its thread pool threads and reassigns it to that request. That thread continues processing the request. When the request is completed, that thread is again returned to the thread pool. Note that with synchronous handlers, the same thread is used for the lifetime of the request; with asynchronous handlers, in contrast, different threads may be assigned to the same request (at different times).

Now, if three requests were to come in, the server could cope easily. Because the threads are released to the thread pool whenever the request has asynchronous work it’s waiting for, they’re free to handle new requests, as well as existing ones. Asynchronous requests allow a smaller number of threads to handle a larger number of requests. Hence, the primary benefit of asynchronous code on ASP.NET is scalability.

Why Not Increase the Thread Pool Size?

At this point, a question is always asked: Why not just increase the size of the thread pool? The answer is twofold: Asynchronous code scales both further and faster than blocking thread pool threads.

Asynchronous code can scale further than blocking threads because it uses much less memory; every thread pool thread on a modern OS has a 1MB stack, plus an unpageable kernel stack. That doesn’t sound like a lot until you start getting a whole lot of threads on your server. In contrast, the memory overhead for an asynchronous operation is much smaller. So, a request with an asynchronous operation has much less memory pressure than a request with a blocked thread. Asynchronous code allows you to use more of your memory for other things (caching, for example).

Asynchronous code can scale faster than blocking threads because the thread pool has a limited injection rate. As of this writing, the rate is one thread every two seconds. This injection rate limit is a good thing; it avoids constant thread construction and destruction. However, consider what happens when a sudden flood of requests comes in. Synchronous code can easily get bogged down as the requests use up all available threads and the remaining requests have to wait for the thread pool to inject new threads. On the other hand, asynchronous code doesn’t need a limit like this; it’s “always on,” so to speak. Asynchronous code is more responsive to sudden swings in request volume.

Bear in mind that asynchronous code does not replace the thread pool. This isn’t thread pool or asynchronous code; it’s thread pool and asynchronous code. Asynchronous code allows your application to make optimum use of the thread pool. It takes the existing thread pool and turns it up to 11.

What About the Thread Doing the Asynchronous Work?

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Now, consider the current state of the system. There are various I/O structures that have been allocated (for example, the Task instances and the IRP), and they’re all in a pending/incomplete state. However, there’s no thread that is blocked waiting for that write operation to complete. Neither ASP.NET, nor the BCL, nor the OS, nor the device driver has a thread dedicated to the asynchronous work.

When the disk completes writing the data, it notifies its driver via an interrupt. The driver informs the OS that the IRP has completed, and the OS notifies the BCL via the completion port. A thread pool thread responds to that notification by completing the task that was returned from WriteAsync; this in turn resumes the asynchronous request code. There were a few threads “borrowed” for very short amounts of time during this completion-notification phase, but no thread was actually blocked while the write was in progress.

This example is drastically simplified, but it gets across the primary point: no thread is required for true asynchronous work. No CPU time is necessary to actually push the bytes out. There’s also a secondary lesson to learn. Think about the device driver world, how a device driver must either handle an IRP immediately or asynchronously. Synchronous handling is not an option. At the device driver level, all non-trivial I/O is asynchronous. Many developers have a mental model that treats the “natural API” for I/O operations as synchronous, with the asynchronous API as a layer built on the natural, synchronous API. However, that’s completely backward: in fact, the natural API is asynchronous; and it’s the synchronous APIs that are implemented using asynchronous I/O!

Why Weren’t There Asynchronous Handlers Already?

If asynchronous request handling is so wonderful, why wasn’t it already available? Actually, asynchronous code is so good for scalability that the ASP.NET platform has supported asynchronous handlers and modules since the very beginnings of the Microsoft .NET Framework. Asynchronous Web pages were introduced in ASP.NET 2.0, and MVC got asynchronous controllers in ASP.NET MVC 2.

However, until recently, asynchronous code has always been awkward to write and difficult to maintain. Many companies decided it was easier all around to just develop the code synchronously and pay for larger server farms or more expensive hosting. Now, the tables have turned: in ASP.NET 4.5, asynchronous code using async and await is almost as easy as writing synchronous code. As large systems move into cloud hosting and demand more scale, more and more companies are embracing async and await on ASP.NET.

Asynchronous Code Is Not a Silver Bullet

As wonderful as asynchronous request handling is, it won’t solve all your problems. There are a few common misunderstandings around what async and await can do on ASP.NET.

When some developers learn about async and await, they believe it’s a way for the server code to “yield” to the client (for example, the browser). However, async and await on ASP.NET only “yield” to the ASP.NET runtime; the HTTP protocol remains unchanged, and you still have only one response per request. If you needed SignalR or AJAX or UpdatePanel before async/await, you’ll still need SignalR or AJAX or UpdatePanel after async/await.

Asynchronous request handling with async and await can help your applications scale. However, this is scaling on a single server; you may still need to plan to scale out. If you do need a scale-out architecture, you’ll still need to consider stateless, idempotent requests and reliable queueing. Async and await do help somewhat: they enable you to take full advantage of your server resources, so you won’t have to scale out as often. But if you do need to scale out, you’ll need a proper distributed architecture.

Async and await on ASP.NET are all about I/O. They really excel at reading and writing files, database records, and REST APIs. However, they’re not good for CPU-bound tasks. You can kick off some background work by awaiting Task.Run, but there’s no point in doing so. In fact, that will actually hurt your scalability by interfering with the ASP.NET thread pool heuristics. If you have CPU-bound work to do on ASP.NET, your best bet is to just execute it directly on the request thread. As a general rule, don’t queue work to the thread pool on ASP.NET.

Finally, consider the scalability of your system as a whole. A decade ago, a common architecture was to have one ASP.NET Web server that talked to one SQL Server database back end. In that kind of simple architecture, usually the database server is the scalability bottleneck, not the Web server. Making your database calls asynchronous would probably not help; you could certainly use them to scale the Web server, but the database server will prevent the system as a whole from scaling.

Rick Anderson makes the case against asynchronous database calls in his excellent blog post, “Should My Database Calls Be Asynchronous?” (bit.ly/1rw66UB). There are two arguments that support this: first, asynchronous code is difficult (and therefore expensive in developer time compared to just purchasing larger servers); and second, scaling the Web server makes little sense if the database back end is the bottleneck. Both of those arguments made perfect sense when that post was written, but both arguments have weakened over time. First, asynchronous code is much easier to write with async and await. Second, the data back ends for Web sites are scaling as the world moves to cloud computing. Modern back ends such as Microsoft Azure SQL Database, NoSQL and other APIs can scale much further than a single SQL Server, pushing the bottleneck back to the Web server. In this scenario, async/await can bring a tremendous benefit by scaling ASP.NET.

Before Getting Started

The first thing you need to know is that async and await are only supported on ASP.NET 4.5. There’s a NuGet package called Microsoft.Bcl.Async that enables async and await for the .NET Framework 4, but do not use it; it will not work correctly! The reason is that ASP.NET itself had to change the way it manages its asynchronous request handling to work better with async and await; the NuGet package contains all the types the compiler needs but will not patch the ASP.NET runtime. There is no workaround; you need ASP.NET 4.5 or higher.

Next, be aware that ASP.NET 4.5 introduces a “quirks mode” on the server. If you create a new ASP.NET 4.5 project, you don’t have to worry. However, if you upgrade an existing project to ASP.NET 4.5, the quirks are all turned on. I recommend you turn them all off by editing your web.config and setting httpRuntime.targetFramework to 4.5. If your application fails with this setting (and you don’t want to take the time to fix it), you can at least get async/await working by adding an appSetting key of aspnet:UseTaskFriendlySynchronizationContext with value “true.” The appSetting key is unnecessary if you have httpRuntime.targetFramework set to 4.5. The Web development team has a blog post on the details of this new “quirks mode” at bit.ly/1pbmnzK. Tip: If you’re seeing odd behavior or exceptions, and your call stack includes LegacyAspNetSynchronizationContext, your application is running in this quirk mode. LegacyAspNet­SynchronizationContext isn’t compatible with async; you need the regular AspNetSynchronizationContext on ASP.NET 4.5.

In ASP.NET 4.5, all the ASP.NET settings have good default values for asynchronous requests, but there are a couple of other settings you might want to change. The first is an IIS setting: consider raising the IIS/HTTP.sys queue limit (Application Pools | Advanced Settings | Queue Length) from its default of 1,000 to 5,000. The other is a .NET runtime setting: ServicePointManager.DefaultConnectionLimit, which has a default value of 12 times the number of cores. The DefaultConnectionLimit limits the number of simultaneous outgoing connections to the same hostname.

A Word on Aborting Requests

When ASP.NET processes a request synchronously, it has a very simple mechanism for aborting a request (for example, if the request exceeded its timeout): It will abort the worker thread for that request. This makes sense in the synchronous world, where each request has the same worker thread from beginning to end. Aborting threads isn’t wonderful for long-term stability of the AppDomain, so by default ASP.NET will regularly recycle your application to keep things clean.

With asynchronous requests, ASP.NET won’t abort worker threads if it wants to abort a request. Instead, it will cancel the request using a CancellationToken. Asynchronous request handlers should accept and honor cancellation tokens. Most newer frameworks (including Web API, MVC and SignalR) will construct and pass you a CancellationToken directly; all you have to do is declare it as a parameter. You can also access ASP.NET tokens directly; for example, HttpRequest.TimedOutToken is a CancellationToken that cancels when the request times out.

As applications move into the cloud, aborting requests becomes more important. Cloud-based applications are more dependent on external services that may take arbitrary amounts of time. For example, one standard pattern is to retry external requests with exponential backoff; if your application depends on multiple services like this, it’s a good idea to apply a timeout cap for your request processing as a whole.

Current State of Async Support

Many libraries have been updated for compatibility with async. Async support was added to Entity Framework (in the EntityFramework NuGet package) in version 6. You do have to be careful to avoid lazy loading when working asynchronously, though, because lazy loading is always performed synchronously. HttpClient (in the Microsoft.Net.Http NuGet package) is a modern HTTP client designed with async in mind, ideal for calling external REST APIs; it’s a modern replacement for HttpWebRequest and WebClient. The Microsoft Azure Storage Client Library (in the WindowsAzure.Storage NuGet package) added async support in version 2.1.

Newer frameworks such as Web API and SignalR have full support for async and await. Web API in particular has built its entire pipeline around async support: not only async controllers, but async filters and handlers, too. Web API and SignalR have a very natural async story: you can “just do it” and it “just works.”

This brings us to a sadder story: Today, ASP.NET MVC only partially supports async and await. The basic support is there—async controller actions and cancellation work appropriately. The ASP.NET Web site has an absolutely excellent tutorial on how to use async controller actions in ASP.NET MVC (bit.ly/1m1LXTx); it’s the best resource for getting started with async on MVC. Unfortunately, ASP.NET MVC does not (currently) support async filters (bit.ly/1oAyHLc) or async child actions (bit.ly/1px47RG).

ASP.NET Web Forms is an older framework, but it also has adequate support for async and await. Again, the best resource for getting started is the tutorial on the ASP.NET Web site for async Web Forms (bit.ly/Ydho7W). With Web Forms, async support is opt-in. You have to first set Page.Async to true, then you can use PageAsyncTask to register async work with that page (alternatively, you can use async void event handlers). PageAsyncTask also supports cancellation.

If you have a custom HTTP handler or HTTP module, ASP.NET now supports asynchronous versions of those, as well. HTTP handlers are supported via HttpTaskAsyncHandler (bit.ly/1nWpWFj) and HTTP modules are supported via EventHandlerTaskAsyncHelper (bit.ly/1m1Sn4O).

As of this writing, the ASP.NET team is working on a new project known as ASP.NET vNext. In vNext, the entire pipeline is asynchronous by default. Currently, the plan is to combine MVC and Web API into a single framework that has full support for async/await (including async filters and async view components). Other async-ready frameworks such as SignalR will find a natural home in vNext. Truly, the future is async.

Respect the Safety Nets

ASP.NET 4.5 introduced a couple of new “safety nets” that help you catch asynchronous problems in your application. These are on by default, and should stay on.

When a synchronous handler attempts to perform asynchronous work, you’ll get an InvalidOperationException with the message, “An asynchronous operation cannot be started at this time.” There are two primary causes for this exception. The first is when a Web Forms page has async event handlers, but neglected to set Page.Async to true. The second is when the synchronous code calls an async void method. This is yet another reason to avoid async void.

The other safety net is for asynchronous handlers: When an asynchronous handler completes the request, but ASP.NET detects asynchronous work that hasn’t completed, you get an Invalid­OperationException with the message, “An asynchronous module or handler completed while an asynchronous operation was still pending.” This is usually due to asynchronous code calling an async void method, but it can also be caused by improper use of an Event-based Asynchronous Pattern (EAP) component (bit.ly/19VdUWu).

There’s an option you can use to turn off both safety nets: HttpContext.AllowAsyncDuringSyncStages (it can also be set in web.config). A few pages on the Internet suggest setting this whenever you see these exceptions. I can’t disagree more vehemently. Seriously, I don’t know why this is even possible. Disabling the safety nets is a horrible idea. The only possible reason I can think of is if your code is already doing some extremely advanced asynchronous stuff (beyond anything I’ve ever attempted), and you are a multithreading genius. So, if you’ve read this entire article yawning and thinking, “Please, I’m no n00b,” then I suppose you can consider disabling the safety nets. For the rest of us, this is an extremely dangerous option and should not be set unless you’re fully aware of the ramifications.

Getting Started

Finally! Ready to get started taking advantage of async and await? I appreciate your patience.

First, review the “Asynchronous Code Is Not a Silver Bullet” section in this article to ensure async/await is beneficial to your architecture. Next, update your application to ASP.NET 4.5 and turn off quirks mode (it’s not a bad idea to run it at this point just to make sure nothing breaks). At this point, you’re ready to start true async/await work.

Start at the “leaves.” Think about how your requests are processed and identify any I/O-based operations, especially anything network-based. Common examples are database queries and commands and calls to other Web services and APIs. Choose one to start with, and do a bit of research to find the best option for performing that operation using async/await. Many of the built-in BCL types are now async-ready in the .NET Framework 4.5; for example, SmtpClient has the SendMailAsync methods. Some types have async-ready replacements available; for example, HttpWebRequest and WebClient can be replaced with HttpClient. Upgrade your library versions, if necessary; for example, Entity Framework got async-compatible methods in EF6.

However, avoid “fake asynchrony” in libraries. Fake asynchrony is when a component has an async-ready API, but it’s implemented by just wrapping the synchronous API within a thread pool thread. That is counterproductive to scalability on ASP.NET. One prominent example of fake asynchrony is Newtonsoft JSON.NET, an otherwise excellent library. It’s best to not call the (fake) asynchronous versions for serializing JSON; just call the synchronous versions instead. A trickier example of fake asynchrony is the BCL file streams. When a file stream is opened, it must be explicitly opened for asynchronous access; otherwise, it will use fake asynchrony, synchronously blocking a thread pool thread on the file reads and writes.

Once you’ve chosen a “leaf,” then start with a method in your code that calls into that API, and make it into an async method that calls the async-ready API via await. If the API you’re calling supports CancellationToken, your method should take a CancellationToken and pass it along to the API method.

Whenever you mark a method async, you should change its return type: void becomes Task, and a non-void type T becomes Task<T>. You’ll find that then all the callers of that method need to become async so they can await the task, and so on. Also, append Async to the name of your method, to follow the Task-based Asynchronous Pattern conventions (bit.ly/1uBKGKR).

Allow the async/await pattern to grow up your call stack toward the “trunk.” At the trunk, your code will interface with the ASP.NET framework (MVC, Web Forms, Web API). Read the appropriate tutorial in the “Current State of Async Support” section earlier in this article to integrate your async code with your framework.

Along the way, identify any thread-local state. Because asynchronous requests may change threads, thread-local state such as ThreadStaticAttribute, ThreadLocal<T>, thread data slots and CallContext.GetData/SetData will not work. Replace these with HttpContext.Items, if possible; or you can store immutable data in CallContext.LogicalGetData/LogicalSetData.

Here’s a tip I’ve found useful: you can (temporarily) duplicate your code to create a vertical partition. With this technique, you don’t change your synchronous methods to asynchronous; you copy the entire synchronous method and then change the copy to be asynchronous. You can then keep most of your application using the synchronous methods and just create a small vertical slice of asynchrony. This is great if you want to explore async as a proof-of-concept or do load testing on just part of the application to get a feeling for how your system could scale. You can have one request (or page) that’s fully asynchronous while the rest of your application remains synchronous. Of course, you don’t want to keep duplicates for every one of your methods; eventually, all the I/O-bound code will be async and the synchronous copies can be removed.

Wrapping Up

I hope this article has helped you get a conceptual grounding in asynchronous requests on ASP.NET. Using async and await, it’s easier than ever to write Web applications, services and APIs that make maximum use of their server resources. Async is awesome!


Stephen Cleary is a husband, father and programmer living in northern Michigan. He has worked with multithreading and asynchronous programming for 16 years and has used async support in the Microsoft .NET Framework since the first community technology preview. His homepage, including his blog, is atstephencleary.com.

Thanks to the following Microsoft technical expert for reviewing this article: James McCaffrey

Async and Await

http://blog.stephencleary.com/2012/02/async-and-await.html

 

Most people have already heard about the new “async” and “await” functionality coming in Visual Studio 11. This is Yet Another Introductory Post.

First, the punchline: Async will fundamentally change the way most code is written.

Yup, I believe async/await will have a bigger impact than LINQ. Understanding async will be a basic necessity just a few short years from now.

Introducing the Keywords

Let’s dive right in. I’ll use some concepts that I’ll expound on later on – just hold on for this first part.

Asynchronous methods look something like this:

public async Task DoSomethingAsync()
{
  // In the Real World, we would actually do something...
  // For this example, we're just going to (asynchronously) wait 100ms.
  await Task.Delay(100);
}

The “async” keyword enables the “await” keyword in that method and changes how method results are handled.That’s all the async keyword does! It does not run this method on a thread pool thread, or do any other kind of magic. The async keyword only enables the await keyword (and manages the method results).

The beginning of an async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).

The “await” keyword is where things can get asynchronous. Await is like a unary operator: it takes a single argument, an awaitable (an “awaitable” is an asynchronous operation). Await examines that awaitable to see if it has already completed; if the awaitable has already completed, then the method just continues running (synchronously, just like a regular method).

If “await” sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method.

Later on, when the awaitable completes, it will execute the remainder of the async method. If you’re awaiting a built-in awaitable (such as a task), then the remainder of the async method will execute on a “context” that was captured before the “await” returned.

I like to think of “await” as an “asynchronous wait”. That is to say, the async method pauses until the awaitable is complete (so it waits), but the actual thread is not blocked (so it’s asynchronous).

Awaitables

As I mentioned, “await” takes a single argument – an “awaitable” – which is an asynchronous operation. There are two awaitable types already common in the .NET framework: Task<T> and Task.

There are also other awaitable types: special methods such as “Task.Yield” return awaitables that are not Tasks, and the WinRT runtime (coming in Windows 8) has an unmanaged awaitable type. You can also create your own awaitable (usually for performance reasons), or use extension methods to make a non-awaitable type awaitable.

That’s all I’m going to say about making your own awaitables. I’ve only had to write a couple of awaitables in the entire time I’ve used async/await. If you want to know more about writing your own awaitables, see the Parallel Team Blog or Jon Skeet’s Blog.

One important point about awaitables is this: it is the type that is awaitable, not the method returning the type. In other words, you can await the result of an async method that returns Task … because the method returns Task, not because it’s async. So you can also await the result of a non-async method that returns Task:

public async Task NewStuffAsync()
{
  // Use await and have fun with the new stuff.
  await ...
}

public Task MyOldTaskParallelLibraryCode()
{
  // Note that this is not an async method, so we can't use await in here.
  ...
}

public async Task ComposeAsync()
{
  // We can await Tasks, regardless of where they come from.
  await NewStuffAsync();
  await MyOldTaskParallelLibraryCode();
}

Tip: If you have a very simple asynchronous method, you may be able to write it without using the await keyword (e.g., using Task.FromResult). If you can write it without await, then you should write it without await, and remove the async keyword from the method. A non-async method returning Task.FromResult is more efficient than an async method returning a value.

Return Types

Async methods can return Task<T>, Task, or void. In almost all cases, you want to return Task<T> or Task, and return void only when you have to.

Why return Task<T> or Task? Because they’re awaitable, and void is not. So if you have an async method returning Task<T> or Task, then you can pass the result to await. With a void method, you don’t have anything to pass to await.

You have to return void when you have async event handlers.

You can also use async void for other “top-level” kinds of actions – e.g., a single “static async void MainAsync()” for Console programs. However, this use of async void has its own problem; see Async Console Programs. The primary use case for async void methods is event handlers.

Returning Values

Async methods returning Task or void do not have a return value. Async methods returning Task<T> must return a value of type T:

public async Task<int> CalculateAnswer()
{
  await Task.Delay(100); // (Probably should be longer...)

  // Return a type of "int", not "Task<int>"
  return 42;
}

This is a bit odd to get used to, but there are good reasons behind this design.

Context

In the overview, I mentioned that when you await a built-in awaitable, then the awaitable will capture the current “context” and later apply it to the remainder of the async method. What exactly is that “context”?

Simple answer:

  1. If you’re on a UI thread, then it’s a UI context.
  2. If you’re responding to an ASP.NET request, then it’s an ASP.NET request context.
  3. Otherwise, it’s usually a thread pool context.

Complex answer:

  1. If SynchronizationContext.Current is not null, then it’s the current SynchronizationContext. (UI and ASP.NET request contexts are SynchronizationContext contexts).
  2. Otherwise, it’s the current TaskScheduler (TaskScheduler.Default is the thread pool context).

What does this mean in the real world? For one thing, capturing (and restoring) the UI/ASP.NET context is done transparently:

// WinForms example (it works exactly the same for WPF).
private async void DownloadFileButton_Click(object sender, EventArgs e)
{
  // Since we asynchronously wait, the UI thread is not blocked by the file download.
  await DownloadFileAsync(fileNameTextBox.Text);

  // Since we resume on the UI context, we can directly access UI elements.
  resultTextBox.Text = "File downloaded!";
}

// ASP.NET example
protected async void MyButton_Click(object sender, EventArgs e)
{
  // Since we asynchronously wait, the ASP.NET thread is not blocked by the file download.
  // This allows the thread to handle other requests while we're waiting.
  await DownloadFileAsync(...);

  // Since we resume on the ASP.NET context, we can access the current request.
  // We may actually be on another *thread*, but we have the same ASP.NET request context.
  Response.Write("File downloaded!");
}

This is great for event handlers, but it turns out to not be what you want for most other code (which is, really, most of the async code you’ll be writing).

Avoiding Context

Most of the time, you don’t need to sync back to the “main” context. Most async methods will be designed with composition in mind: they await other operations, and each one represents an asynchronous operation itself (which can be composed by others). In this case, you want to tell the awaiter to not capture the current context by calling ConfigureAwait and passing false, e.g.:

private async Task DownloadFileAsync(string fileName)
{
  // Use HttpClient or whatever to download the file contents.
  var fileContents = await DownloadFileContentsAsync(fileName).ConfigureAwait(false);

  // Note that because of the ConfigureAwait(false), we are not on the original context here.
  // Instead, we're running on the thread pool.

  // Write the file contents out to a disk file.
  await WriteToDiskAsync(fileName, fileContents).ConfigureAwait(false);

  // The second call to ConfigureAwait(false) is not *required*, but it is Good Practice.
}

// WinForms example (it works exactly the same for WPF).
private async void DownloadFileButton_Click(object sender, EventArgs e)
{
  // Since we asynchronously wait, the UI thread is not blocked by the file download.
  await DownloadFileAsync(fileNameTextBox.Text);

  // Since we resume on the UI context, we can directly access UI elements.
  resultTextBox.Text = "File downloaded!";
}

The important thing to note with this example is that each “level” of async method calls has its own context. DownloadFileButton_Click started in the UI context, and called DownloadFileAsync. DownloadFileAsync also started in the UI context, but then stepped out of its context by calling ConfigureAwait(false). The rest of DownloadFileAsync runs in the thread pool context. However, when DownloadFileAsync completes and DownloadFileButton_Click resumes, it does resume in the UI context.

A good rule of thumb is to use ConfigureAwait(false) unless you know you do need the context.

Async Composition

So far, we’ve only considered serial composition: an async method waits for one operation at a time. It’s also possible to start several operations and await for one (or all) of them to complete. You can do this by starting the operations but not awaiting them until later:

public async Task DoOperationsConcurrentlyAsync()
{
  Task[] tasks = new Task[3];
  tasks[0] = DoOperation0Async();
  tasks[1] = DoOperation1Async();
  tasks[2] = DoOperation2Async();

  // At this point, all three tasks are running at the same time.

  // Now, we await them all.
  await Task.WhenAll(tasks);
}

public async Task<int> GetFirstToRespondAsync()
{
  // Call two web services; take the first response.
  Task<int>[] tasks = new[] { WebService1Async(), WebService2Async() };

  // Await for the first one to respond.
  Task<int> firstTask = await Task.WhenAny(tasks);

  // Return the result.
  return await firstTask;
}

By using concurrent composition (Task.WhenAll or Task.WhenAny), you can perform simple concurrent operations. You can also use these methods along with Task.Run to do simple parallel computation. However, this is not a substitute for the Task Parallel Library – any advanced CPU-intensive parallel operations should be done with the TPL.

Guidelines

Read the Task-based Asynchronous Pattern (TAP) document. It is extremely well-written, and includes guidance on API design and the proper use of async/await (including cancellation and progress reporting).

There are many new await-friendly techniques that should be used instead of the old blocking techniques. If you have any of these Old examples in your new async code, you’re Doing It Wrong(TM):

Old New Description
task.Wait await task Wait/await for a task to complete
task.Result await task Get the result of a completed task
Task.WaitAny await Task.WhenAny Wait/await for one of a collection of tasks to complete
Task.WaitAll await Task.WhenAll Wait/await for every one of a collection of tasks to complete
Thread.Sleep await Task.Delay Wait/await for a period of time
Task constructor Task.Run or TaskFactory.StartNew Create a code-based task

Next Steps

I have published an MSDN article Best Practices in Asynchronous Programming, which further explains the “avoid async void”, “async all the way” and “configure context” guidelines.

The official MSDN documentation is quite good; they include an online version of the Task-based Asynchronous Pattern document which is excellent, covering the designs of asynchronous methods.

The async team has published an async/await FAQ that is a great place to continue learning about async. They have pointers to the best blog posts and videos on there. Also, pretty much any blog post by Stephen Toub is instructive!

Of course, another resource is my own blog.