Monthly Archives: August 2013

MVC 4.0: The Role of the View

The views in your ASP.NET MVC application are what a user sees. Views are the window into your application, and so is one of the most important parts of the application…along with all the rest of it!

Views provide one of the biggest reasons to use MVC instead of Web Forms. Unlike Web Forms, you have complete control over the HTML that the application generates. There are no server controls as there are in Web Forms that spew HTML, which you have little control over or that are hard to use with CSS and client-side JavaScript.

Having complete control over HTML sounds great in theory, but it could also mean that you’d have to write a lot more HTML by hand. One of the big selling points of Web Forms is that you can do drag and drop development, using server controls that generate massive amounts of HTML based on the properties you set and the data you bind to the controls.

But MVC has a lot of features built in that make the job of writing HTML and other code simpler and more manageable, while letting you retain control over most of the generated HTML. And when you need complete control, you can bypass the MVC features and write all the beautiful HTML you care to write.

The trick to writing good views in MVC is to keep the view focused on the user interface only. This means that there should be no code that directly reads or writes to a data store, no business rule implementations, nothing that isn’t directly related to interacting with the user. The ideal view should consist of a lot of HTML, maybe some client-side JavaScript (perhaps including Ajax), and a little code that reads data from the model or ViewData for the purpose of displaying data to the user. It might be appropriate to put some logic in a view, but it should only be presentation logic needed to dynamically interact with the user. Anything else you should rip out and put in the controller or model. Make that your solemn goal.

The purest way to think about views is that the controller hands a model to the view, and the view converts it into something that is presented to the user. We’ve found this way of thinking to be a helpful context for understanding what views do and how to create them, as well as where to implement different kinds of logic.

In this chapter, you’ll learn about how views work, how you can add dynamic data to the view, how you can bundle and minify files, a little bit about the view engine that makes it all work, and ways to adhere to MVC’s DRY—Don’t Repeat Yourself—principle by creating reusable controls that you can use in multiple views.

The Figure below shows a graphic view of the interactions of the components of an MVC application. In order to handle a user request, the controller interacts with the model in whatever way is necessary to respond to the request. The controller then selects a view and passes it whatever data the view requires to generate a page. The view engine then reads the view template and dynamically generates the HTML that is sent to the user.

MVC4 Views
The Figure above. Anatomy of an MVC request and response.

In this chapter, you’ll learn some of the many features you can use to build views that provide a robust user interface for your applications. The MVC framework has a rich infrastructure for creating responsive and attractive web sites for your users.

 

ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Views and Models course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

C# 2012: Anatomy of an Async Method

There are two new keywords added to C# for asynchronous programming: async and await. The async keyword is a modifier for methods, delegates, and lambdas to indicate to the C# compiler that a method might contain async code. It also allows other code to call this method asynchronously. 

If a method doesn’t contain async code, it executes synchronously, but you will receive a warning message from the C# compiler. To run code asynchronously, use the await modifier when executing a method, anonymous method, or lambda. Here’s an example of using async and await keywords to implement an async method:

The async modifier indicates that StartAsync can contain async code. The await modifier calls the DoNetworkCommunicationsAsync method and waits for it to complete. In other words, it awaits the method.

Notice the suffix to the StartAsync method is Async. You aren’t required to add the Async suffix to the method name, but it’s a convention that Microsoft recommends and most developers follow in practice. Another tip on naming conventions refers to methods in earlier versions of .NET that implement EAP and already have the Async suffix—you would name them with the TaskAsync suffix.

To make the example simpler, the return type in the previous example is void, but async methods do have return types other than void. For now, let’s defer discussion of the return type until later, which is an important subject of its own.

The previous example doesn’t have any parameters by design in order to keep it simple. However, async methods can have parameters, but none of the parameters can be ref or out.

As in APM and EAP, as soon as the code calls an async method, with the await modifier, control returns to the caller while the method executes asynchronously. Expanding on the previous method, the following code demonstrates a basic example of how async methods work:

Let’s look at what this code shows in terms of control or what is running when. The specific threading model is defined separately for each .NET technology by a type derived from SynchronizationContext, but this is beyond the scope of this course.

The Main method calls the StartAsync method. Because StartAsync is modified as async, the code will run synchronously until it encounters a call to an async method with the await modifier. As soon as the code calls the method with await, control returns to the calling code Main. So you have two methods running at the same time—Main and StartAsync.

StartAsync continues by calling the DoNetworkCommunicationsAsync method. However, the await modifier makes StartAsync wait until DoNetworkCommunicationsAsync completes. When DoNetworkCommunicationsAsync completes, StartAsync ends. Control was already returned to Main when it encountered the await call to DoNetworkCommunicationsAsync, so StartAsync does not return at the end of the method, it just stops running.

That means that inside of StartAsync, all the code above the awaited method will run synchronously. At the same time, the async method runs. When
DoNetworkCommunicationsAsync completes, control returns to StartAsync and any code following StartAsync executes.

 

JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Asynchronous Programming course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

C# 2012: Debugging Tips

For effective debugging, you need to be able to set a breakpoint. The easiest way to set a breakpoint is to click your mouse in the gutter, which is the vertical space to the left of the editor window, shown in the Figure below.

cswhatsnew

 

The Figure above. Click in the gutter to create a breakpoint.

After setting a breakpoint, you can start debugging by selecting DEBUG|Start Debugging or by pressing the F5 key. This will run the program until it reaches the breakpoint and then stop.

You can customize an individual breakpoint with conditions. Right-click on the red dot in the gutter and you’ll see options for Conditions, Hit Count, and more. You can use Hit Count to stop on the breakpoint after it executes a specified number of times, such as in a loop. Condition, shown in the Figure below, lets you define an expression that will make the code hit a breakpoint on that line when the expression is true.

CS What's New 2

 

The Figure above. You can set conditions on a breakpoint.

After setting a number of breakpoints, you’ll want to organize and keep track of them. You can open the Breakpoints window where you manage breakpoints, shown in the Figure above, by selecting DEBUG|Windows|Breakpoints.

CS What's New 3

 

The Figure above. The Breakpoints window lets you manage breakpoints. From the Breakpoints window, you can create new breakpoints, specify columns to view, and filter the list with Search. You can organize the breakpoints by right-clicking on a breakpoint and selecting Edit labels. Then you can search on labels and perform actions on the entire group of breakpoints as a whole.

When the program stops, you can inspect its state by hovering over variables with a mouse or viewing debugger windows.

 

JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Language Changes and Updates course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

Business Connectivity Services

While the lists, libraries, and other features of SharePoint provide a useful platform for collaboration, SharePoint doesn’t operate in a vacuum. Users will frequently interact with external applications, such as line-of-business applications, alongside their regular use of SharePoint. At some point users may express a desire to have SharePoint integrate with external systems. It could be as simple as a desire to do everything possible within SharePoint; or, it may be a need to integrate data from an external source into a SharePoint list or library in order to enforce a business rule or to avoid duplicating data in
multiple sources.

Business Connectivity Services, or BCS, exists to connect to external data. BCS represents a significant upgrade to the Business Data Catalog offered in SharePoint 2007. Specific improvements include:

  • Simple support for Write operations (no coding required).
  • Excellent tool support with SharePoint Designer 2010 and Visual Studio 2010.
  • External Lists for surfacing BCS data as a SharePoint list.
  • Support for both server object model and client object model.
  • Integration with Microsoft Office client applications.

NOTE Microsoft made an unfortunate choice when it comes to the use of the acronym BDC. In SharePoint 2007 BDC refers to Business Data Catalog; in SharePoint 2010 BDC refers to the Business Data Connectivity service, which is a subsystem of Business Connectivity Services. For the remainder of this chapter, BDC refers to SharePoint 2010 Business Data Connectivity service unless otherwise noted.

BCS Architecture

There are several key components that make up the BCS architecture. These components work together to provide a complete solution for integrating external data.

BDC Metadata Store

The BDC Metadata Store is responsible for storing External Content Types. As you will see in a later section of the chapter, External Content Types provide metadata and connectivity information for external sources of data. The BDC Metadata Store may be updated via SharePoint Designer when creating or updating external types.

BDC Server Runtime

The BDC Server Runtime uses the contents of the BDC Metadata Store to reach into external systems and perform operations such as reading or writing data. These read/write operations are carried out without the need for custom code.

BCS Security

BCS Security provides authentication and authorization for browser-based clients as well as Microsoft Office clients. It is capable of passing the user’s credentials through to the external system, or impersonating a dedicated account to the external system on behalf of the user. BCS Security also supports claims-based authentication.

SharePoint User Interface

BCS continues the SharePoint 2007 model of exposing external data via web parts. However, it also provides the new External List to present external data to the user via the SharePoint browser-based user interface. The presentation of these External Lists are seamlessly integrated with other lists on a particular SharePoint site.

Design Tools

SharePoint Designer 2010 provides full support for creating BCS solutions, including the creation of External Content Types, the definition of External Lists, and the definition of InfoPath for presenting external data. Visual Studio 2010 builds upon this foundation and allows developers to further extend BCS capabilities, such as a scenario where significant transformation of the external data is necessary.

 

John.UnderwoodThis post is an excerpt from the online courseware for our Microsoft SharePoint 2010: Enterprise Content Management course written by expert John Underwood.

John Underwood is a technical evangelist for a SharePoint consulting company, with 30 years of programming experience, including 20 years on the Microsoft platform and 10 years with .NET. John also has extensive experience using, configuring, and programming SharePoint.

 

User Profiles and My Sites

Although you can view and modify a user’s profile properties in Shared Services Administration, your users cannot, and they need a way to update their information. SharePoint Server provides this functionality with My Sites. However, My Sites have much more functionality than the basic ability to work with profile properties.

A My Site is a self-service personalized site that contains private pages that are visible only to the owner of the site. A My Site allows consumption and manipulation of data of interest to the owner—a private dashboard. It also contains pages that are visible to the public and/or the site owner’s colleagues.

My Sites also serve an important role in creating a unified experience between SharePoint and the Office client applications and in targeting links to specific audiences based on profile data.

Configuring My Sites

You configure My Sites by using SharePoint Central Administration and The User Profile Service Application page you used earlier in the chapter. A My Site uses a normal site definition. The site definition specifies a dependency that requires you to create My Site instances only within a specialized site collection based on the My Site Host site definition. You can create a My Site Host by using either the standard Create Site Collection page or by specifying that SharePoint create one automatically when you create a new User Profile
Service Application.

A single instance of the User Profile Service Application supports exactly one My Site Host. However, it is possible to have more than one instance of the User Profile Service Application in an environment, and therefore more than one My Sites host. This is common in large portals that span multiple geographic locations. The My Sites Settings configuration includes:

  • Setup My Sites: Specifies the location of the My Site Host as well as the managed path for My Sites.
  • Configure Trusted Host Locations: Connects multiple instances of the User Profile Service Application.
  • Configure Personalization Site: Adds personalization site navigation links to the My Site left navigation.
  • Publish Links to Office Client Applications: Publishes links to SharePoint sites and lists when opening and saving documents from Office client applications.
  • Manage Social Tags and Notes: Finds, manages, and deletes social tags.

Linking to Office Client Applications

You can cause a user’s My Site to associate specific document libraries with their local machine profile. These libraries will appear in the Save dialog box when users work with Microsoft Office applications. This important functionality can encourage users to save public documents to appropriate libraries. Without this functionality, they are much less likely to put their documents in appropriate locations because they must manually add the
locations.

You can target links to users with simple rules based on information found in their profile or by their group memberships.

Personalization Links

You can also target links to appear on a My Site’s Quick Launch menu by creating personalization links. Personalization links, like links to Office client applications, are an invaluable way to direct users to content without a lot of effort or training.

As with links to Office applications, you can target personalization links to users with simple rules based on information within their profiles or by their group memberships.

 

John.UnderwoodThis post is an excerpt from the online courseware for our Microsoft SharePoint 2010: Enterprise Content Management course written by expert John Underwood.

John Underwood is a technical evangelist for a SharePoint consulting company, with 30 years of programming experience, including 20 years on the Microsoft platform and 10 years with .NET. John also has extensive experience using, configuring, and programming SharePoint.

Introduction to Stored Procedures

A stored procedure is a batch of Transact-SQL (T-SQL) code that is saved internally in SQL Server as a database object. You can use stored procedures to mask complex SQL tasks from clients, improve the performance of your application, enforce data and business rules, increase multi-user concurrency, and reduce locking and blocking conflicts. It is a module of T-SQL code that can perform just about any task in SQL Server, accessing data as well as
resources outside of SQL Server. A stored procedure is the workhorse of SQL coding, and in this chapter you’ll learn about how to use this important database feature.

Stored Procedure Features

Unlike scripts, which are saved outside your database as text files, stored procedures are saved as objects inside your database. You can execute a stored procedure from a client application, a batch or script, or from other stored procedures. Stored procedures are parsed and syntax-checked when you create them and are compiled on first execution. SQL Server caches the execution plan and shares it among all users of the database. Subsequent calls to the stored procedure can reuse the cached plan, even if different users call the stored procedure. This compilation, caching, and sharing of execution plans gives stored procedures a significant performance advantage over running ad hoc T-SQL statements. You can also lock down the security of your database by revoking permissions on database objects and only granting access to data and objects through a stored procedure.

Unlike views, which are also saved as database objects, stored procedures support the full capabilities of Transact-SQL. A single stored procedure can contain up to 250 megabytes of text, a limit you won’t encounter anytime soon (or, if you do, you should seriously consider refactoring your code!) Stored procedures can accept input parameters and can return more than one result set, and they can also return data in the form of output parameters and a return value. Stored procedures are as close as you can come to functions or methods that you’ll find in full-featured, object-oriented programming languages.

TIP: SQL Server uses stored procedures in most of its internal operations. System stored procedures have a schema name of sys and an sp_ prefix. You can read the Transact-SQL definitions of these stored procedures by running the sp_helptext system stored procedure and supplying the stored procedure name(for example, sp_helptext ‘sys.sp_tables’). You’ll find that most contain explanatory comments as well. Exploring system stored procedures is a great way to learn advanced T-SQL programming techniques once you’ve mastered
the basics.

The only tasks that you cannot complete with a stored procedure are the creation of triggers, defaults, rules, other stored procedures, and views. A stored procedure can do everything from executing a basic SELECT statement to enforcing complex business logic and explicit transactions, as well as modifying data and other database and system objects.

 

ldn-expertdkielyThis post is an excerpt from the online courseware for our SQL Server 2012: Stored Procedures course written by expert Don Kiely.Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

Using Reflection

Reflection gives you the ability to inspect the code of a .NET application and execute that code dynamically. Various tools, such as VS 2012 Web Services and unit testing use reflection to perform actions based on the code you’ve written. When building a Web Service, VS 2012 uses reflection to inspect the attributes applied to classes and then read the method names, parameters, and return types of those methods to build an XML contract for clients to consume.The Unit Test runner uses reflection to find classes that contain tests and execute the methods decorated with test attributes.

Getting Type and TypeInfo

The first step in using reflection is to obtain a Type type or a TypeInfo type. A type is a class, struct, interface, or delegate that you write in order to inspect and learn more about the type. TheType andTypeInfo types let you furtherdelve into the internals of a type, using reflection, to learn about the membersof a type. The Type type has been part of .NET since v1.0. Microsoft introduced the TypInfo type in .NET v4.5, which also supports Windows 8
applications. The difference between Type and TypeInfo in .NET 4.5 is that Type provides reference support and TypeInfo is intended for execution.

If you already have an instance of an object, you can get its Type through the System.Object’s GetType method, like this:

In this example, the code has an instance of Program, prog, making it possible to call GetType to obtain the Type object. TheType object has manymethods for inspecting the type and it contains assembly information. This example prints the Name property, which is Program

Another way to obtain a Type is via the typeof operator. This is a C# operatorfrom basic C# syntax, but now you understand its true purpose and how to use it. Here’s an example:

You give the name of the type to the typeof operator and it returns a Type instance for that type. This example uses the AssemblyQualifiedName, whichgives the fully qualified name of the assembly, as follows:

With a Type, you can get a TypeInfo. Here’s an example:

The example above shows that you must first have a Type, which is testType in this case. With that Type , you can call GetTypeInfo to obtain a TypeInfo .


JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Attributes, Reflections and Dynamic
course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

Choosing the Right Actions

The job of the action invoker to select the appropriate action method is more complicated than may appear on the surface. There could be multiple overloaded methods with the same name in a controller, they may be decorated with different attributes that make their selection appropriate in some scenarios and not others, their action method name may be different from their class method name, and other complications. Designing an effective controller requires that you understand how the selection process works.

The first thing that the action invoker does is to look for the action portion of the route definition for the request. Using the default route defined in a new MVC application shown below, it is the name at the second position.

Even if the current URL doesn’t include the action portion of the route, the default route definition defines it to be the “Index” action.

Once the action invoker has the name of the action, it needs to map that action name to a method of the controller. The simplest case occurs when there is a single method in the controller class with a name that matches the action name. For example, in a new MVC application the Index action of the Home controller maps to the single Index method in that controller.

But what qualifies as an action method? Is every method defined in the controller a potential action method? Not at all. There are a few requirements that a method must meet for the action invoker to consider it to be an action method candidate:

  • It must be a public method and not marked as static.
  • It cannot be a method defined on System.Object or the Controller base class. In other words, it must be defined within your custom controller object, not inherited from another object. So ToString could not be an action method because it is defined on System.Object.
  • It cannot be a special method, such as a constructor, property accessor, or event accessor.
  • It cannot have the NonActionAttribute decoration. This attribute is handy if you want to include a public method in a controller but don’t want to use it as an action method.

Taking all these restrictions into consideration, the action invoker uses reflection to find all methods in the controller with the same action name as the action name specified in the URL and meet the previous requirements.

But here is where things get a bit murky. Through the use of attributes on the controller’s methods, there could be multiple methods with the same name, the action name could be different from the method name, and there may be a selector attribute that restricts which requests an action method can respond to. This can create a bit of a gauntlet that the action invoker must navigate in order to find the correct action method.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Controllers course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

MVC Project Template

ASP.NET MVC 4 is available in Visual Studio 2012 without any additional
installs. MVC 4 can easily be used in older versions of Visual Studio, but it
requires a separate installation. In Visual Studio 2012, there are two, basic
Project Templates: ASP.NET MVC 3 Web Application and ASP.NET MVC 4
Web Application. The MVC 3 template is included because of the relative
newness of MVC 4. The templates are available for both Visual Basic and C#;
other than la nguage, the templates are identical. You can access the templates

from the New Project dialog box that opens when you select File|New|Project

from the Visual Studio menu.

When you select the ASP.NET MVC 4 Web Application template, you have
the choice of several, specific project templates. The Internet Application

template creates a basic but fully functional MVC application, complete with a
model, a couple of controllers, and a few views. It uses best practice HTML
with a CSS (Cascading Style Sheet) file to format the views. It also includes
support for forms authentication and authorization, using the built-in features

of ASP.NET. (This is one of many ways that you can see how MVC is built on
top of ASP.NET, rather than being an alternative to it.) This template gives
you the option of creating a test project in addition to the main application
project, so that you can write unit tests.

The Intr anet Application template builds virtually the same project as the

Internet Application template, but uses Windows forms authentication. It also
gives you the option of creating a test project in the solution.

The Empty template sets up the project structure, including folders for models,
views, and controllers, and sets references to use the MVC framework, but no
default con trollers or models. It provides a great starting point for a new

application that you’ll develop from scratch, including building your own CSS
styles for views. If you want to create a unit test project with a project created
from this template, you’ll need to add that manually after you create the empty
web application.

The Basic template is very similar to the Empty template but includes common
Content an d Scripts that are useful to most MVC applications.

The Mobile Application template is almost exactly the same as the Internet
Application template except it incorporates jQuery.mobile to adjust the
application for delivery to mobile devices and does not use the built-in
authentication mechanisms for .NET applications.

The Web API Application is significantly different from the others in the sense
that it isn’t intended to produce a web site. Rather, it sets up a web services
application that runs according to RESTful URLs. The processing model is
very similar, but Web API Applications are used primarily to serve up data to
other applic ations. This template has no visual component to it.

With the exception of the Web API Application, it really doesn’t matter which
template you use. All provide support for MVC applications, and all are much
simpler than starting with a completely blank solution. In the following
sections, you’ll use the Internet Application template in order to explore the
structure of an MVC application.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Views and Models course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.