Chapter 1

Migrating from ASP.NET to ASP.NET MVC 4

CONCEPTS

IN THIS CHAPTER

  • Knowing what you need to start
  • Understanding the difference between ASP.NET and ASP.NET MVC
  • Seeing the differences between ADO.NET and NHibernate
  • Exploring the improvements from IIS 7.0/7.5/8 to IIS 6
  • Understanding Team Foundation Server
  • Using Test Driven Development in ASP.NET MVC

Deciding to take the leap from one technology to another is a difficult one. You face the risk of improper implementation of the technology, which can cause performance issues. You also face possible impact to business logic, which can produce disruption to your customers and partners. Many core business processes were written many years ago and live on legacy environments; although the developers who wrote them are long gone, and the support teams who run the operations likely are offshore and have a high resource turnover rate. Over time, the cost of maintaining these legacy systems will increase, and the knowledge of how they work will continue to dwindle.

Although change from legacy systems to more robust platforms and newer technologies is difficult, the rewards in the form of cheaper operations cost and increased customer loyalty, as well as avoidance of risks, likely setbacks, and wrong turns are worth the effort. Not only that, but your employees will stay around longer and your developers will be happier because they get exposure to and are working on the newest technologies.

After you decided to migrate for all those good reasons, you can move to the following section, which discusses some of the differences between ASP.NET, ASP.NET MVC, ADO.NET, and NHibernate.


NOTE This chapter contains key migration concepts. To learn how to create an actual project, see Chapter 2.

GETTING STARTED

When I first started migrating the sample ASP.NET blog website I planned on maintaining the same look and feel in the new ASP.NET MVC 4 website. A few web pages into the migration I started thinking, “Why am I changing technologies when, in the end, I will have the same website?” Most visitors to a website do not know what technology runs it. Customers or visitors know only if the website looks and performs well. So I decided to not only change the technology that produces my website, but also to give it a new look and feel. Improvements to your website keep your customers interested and coming back. So when you change, make sure the customer can easily notice the innovation.

This chapter discusses some important migration topics, which you will see in action in Chapter 2, such as:

  • ASP/COM versus ASP.NET versus ASP.NET MVC
  • ADO.NET versus NHibernate (Object Relational Mapping)
  • IIS 6 versus IIS 8
  • Team Foundation Server
  • Test Driven Development in an ASP.NET MVC 4 application

NOTE You should have a good understanding of ASP.NET, ADO.NET, and IIS. It should be clear to you that ASP.NET web forms dynamically present content based on user input, that ADO.NET is a framework for data retrieval and manipulation, and lastly, that IIS is the web server, which answers HTTP requests. An in-depth understanding of these technologies and their dependencies is expected. A deep comprehension of NHibernate, TFS, or development approaches is not as critical.

COMPARING ASP.NET TO ASP.NET MVC

The choice to move away from ASP.NET web forms to a new technology, such as ASP.NET MVC 4, is not an easy one, and you may not even have the opportunity to make it; many companies have invested a lot into their ASP.NET web forms platform, enduring complexities and hard-fought challenges to get their system to where it is now, and they will likely meet the prospect of change with resistance. At the same time, some of these ASP.NET web form systems are simply old; some may even be ASP/COM, with the costs for supporting them likely to increase in the near future. Therefore, some actions in the short term must be made. While making such decisions and having discussions with managers and development teams, consider the concepts, technologies, and tools discussed in this section and chapter.

A starting point is to discuss the advantages and disadvantages of both ASP.NET and ASP.NET MVC 4. The following four sections provide a brief overview. The following are the advantages of ASP.NET web forms over previously existing technology (ASP/COM):

  • A lot of rich user controls that boost Rapid Application Development (RAD)
  • Familiar model for Windows Forms developers
  • Compatibility with any .NET language such as C# and VB.NET
  • Support for object-oriented programming (OOP)
  • Separation of presentation and business logic code
  • Web Service capabilities

The best approach for understanding the advantages of a new technology is to analyze the technology the new one replaces. ASP.NET replaced or maybe, enhanced in many aspects, the ASP/COM platforms. If you recall, ASP/COM exposed only a number of built-in objects such as Request, Response, Application, and Session. These objects still exist and are useful in even the most sophisticated of systems. However, they had some problems, such as using the Session object in a web farm, some challenges with the Response Buffering implementations, and the ominous regsrv32.

Although some features found in these technologies were non-optimal, they were ground-breaking at the time. The release of ASP.NET resolved many of these sub optimal features. One such feature enabled the separation of your presentation layer from your business logic layer using the code-behind concept. A reference to the code-behind is made in the ASP.NET file (*.aspx), as shown in the following snippet, which tells the compiler where to reference the method and properties.

<%@ Page Title="As keyword in C#" Language="C#" 
    CodeFile="As-keyword.aspx.cs" ... %>

The snippet identifies a number of things, but the important attribute is the language of the code-behind and the name of the file, that is, *.aspx.cs or *.aspx.vb.

Overtime, as ASP.NET was implemented into highly scaled and highly trafficked websites, it became apparent that the state-full nature as well as the heaviness of the ASP.NET user controls and VIEWSTATE needed some additional attention and optimization. Some of these optimization techniques are discussed in Chapter 3, and some examples are implemented in Chapter 4.

In addition, the migration from ASP/COM to ASP.NET (which generally was created by those who wrote the more process-oriented ASP/COM code) was not designed from a model/object-oriented perspective. At that time, many C++ coders with strong OOP skills still focused mainly on client-server or Windows services development. So they delivered more process-oriented code on the ASP.NET platform.

Potential disadvantages of ASP.NET web forms include:

  • Support for a single <form> tag.
  • By default, the VIEWSTATE is enabled and web pages can become bloated.
  • Difficult source code manageability of very large websites and teams.

There may be more, but the point of this discussion is not to find fault with ASP.NET; most developers would agree that, based on the alternative, ASP.NET is a useful and feature-rich technology.

It’s not correct to say that ASP.NET MVC is a replacement for ASP.NET. Rather, it is an alternative. You can fuse together ASP.NET MVC and ASP.NET to create a hybrid web-based application. Many enhancements are still being made to the ASP.NET features. An example of this is Web Tools 2012.2 and the .NET Framework, which is the platform on which you can create code customizations and innovations.

This book, and specifically this chapter, focuses on migrating a blog website using ASP.NET to an ASP.NET MVC 4 project, which is ultimately deployed as a Windows Azure Web Role/Cloud Service. Figure 1-1 shows the available features on the current ASP.NET website.

Although Figure 1-1 shows a relatively simple blog website, you can learn many of the important and challenging features in MVC by migrating this site to MVC. Chapter 2 provides many examples and exercises required to complete this migration, so you can get a better understanding of MVC concepts.

Understanding the Model–View–Controller

A basic, but fundamental, concept in ASP.NET MVC is the MVC part. MVC stands for Model–View–Controller and is a pattern that helps designers and developers separate the system between input logic, business logic, and user interface (UI) logic. Figure 1-2 illustrates the MVC pattern, which consists of:

  • Model: This is the class used to store, manipulate, and retrieve information from a database.
  • View: Typically created from the model data, this is the application’s user interface, displays the data, and supports the manipulation of it.
  • Controller: Selects the view to display the data existing in the model and handles the interaction with the application user. Controls the interaction between the model and the view.

Having a global template for the website greatly reduces the amount of effort when you implement changes to the look and feel of your website. ASP.NET has Master Pages, which you create with the <%@ Master tag at the beginning of the page. You then place a <asp:ContentPlaceHolder tag in the master page where you want to display content. Although Master Pages are supported in an ASP.NET MVC system, you may want to consider using a layout page.

Using Master Pages versus Shared Views

When you create an ASP.NET MVC 4 project (a sample is shown in Figure 1-3), a view called _Layout.cshtml is generated in the ViewShared directory. The _Layout.cshtml file contains the <head>, <body>, <header>, and <footer>. Nonetheless, the Layout property of the System.Web.WebPages.StartPage class is set to _Layout.cshtml in the Views\_ViewStart.cshtml, and is loaded with each rendering of a page. This is similar behavior of the ASP.NET master page.


NOTE If you haven’t used HTML in some time, you might find a short refresher will be of benefit. For a refresher, you might consider reading Beginning HTML and CSS, (Wiley, 2013).
Also, take a look at the Razor View Engine and learn what it is and how to use it in ASP.NET MVC applications. The *.cshtml file extensions mean C# Razor.

When you make a request, using the following code snippet for example, the content loads along with the Index.cshtml view located in the ViewsCSharpFundamentals directory and the Index method in the ControllerCSharpFundamentalsController.cs file is called.

@Html.ActionLink("C# Fundamentals", "Index", "CSharpFundamentals")

In Chapter 2, you’ll find that the @RenderBody() in the _Layout.cshtml file is responsible for rendering the content in the ViewsCSharpFundamentalsIndex.html file.

When to Use User Controls versus Partial Views

Other useful features in ASP.NET are user controls (that is, *.ascx files), which enable you to group capabilities or content together and reference them from other files. For example, in the ASP.NET and ASP.NET MVC 4 code for this book, you’ll find a Blog Navigation Bar that contains a translator, comment information, blog information, tag cloud, and blog archive. This Blog Navigation Bar is referenced from all the blogs and also in some of the other pages on the sample blog website. Instead of adding the code for this Blog Navigation Bar to each page, the page is referenced from each ASP.NET page using a code snippet similar to the following:

<%@ Register TagPrefix="NAVBAR" TagName="BlogBar" 
    Src="~/include/BlogRightColumn.ascx" %>
...
<NAVBAR:BlogBar ID="NAV1" runat="server" />

Again, user controls are supported in an ASP.NET MVC 4 application. An alternative, and the one used for an exercise in Chapter 2, is the @Html.Partial() method. The view, which is a parameter of the @Html.Partial() method, is used like a control in the ASP.NET MVC 4 application and is created in the ViewShared directory. The file is called BlogNarBar.cshtml and contains all the code and content required to render the same information as rendered in the ASP.NET user control. The following code snippet demonstrates how to imbed the partial view into another page:

@Html.Partial("_BlogNavBar", ViewData["blognavbar"])

There are a number of different overloads for the Html.Partial() method. The one used here is the Partial(HtmlHelper, String), where HtmlHelp is the name of the view to be rendered and the String is a dictionary called ViewData, which contains data and passes that data between a controller and a view.

Understanding the Statelessness of ASP.NET MVC

VIEWSTATE is a useful but often overused feature in ASP.NET, which can cause some serious performance issues. VIEWSTATE saves the state of the data in controls across page post backs. For example, you can store a drop-down list on the ASP.NET page that is populated by a database query in the VIEWSTATE and pass it between pages without having to re-query the database for its content.

VIEWSTATE is not supported in ASP.NET MVC. The reason for this might be for the reason just stated — that it’s heavy and often overused. In addition, there’s a move towards a more stateless architecture, enhanced integration with testing, and better alignment with the separation of concerns (SoC) concept.

Understanding Strongly Typed Class References

Another nice feature of ASP.NET MVC 4 is strongly bound type references between the view and the model. The Razor View Engine provides the capability for displaying the data in the model using a strong reference. The Razor View Engine was introduced in MVC 3 to simplify the presentation of data in the view. For example, Listing 1-1 shows the @model List<MVC.Models.BlogList> collection being referenced in a .cshtml file using a foreach statement.

LISTING 1-1: Using Razor to Display a Strongly Typed Class

@foreach (var item in Model)
{
  <tr><th>@item.Title</th></tr>
  <tr><td>@item.Description</td></tr>
  <tr><td><a href="@item.Url">More...>>></a></td></tr>
}

When you add the items to the foreach statement, IntelliSense is also supported.


NOTE For more information about the Razor View Engine consider purchasing a book focused specifically on ASP.NET MVC 3 or 4. A good start is Professional ASP.NET MVC 4 (Wiley, 2012).

ASP.NET, ASP.NET MVC, or Both?

Some additional advantages of ASP.NET MVC 4 for further consideration are:

  • The separation of content from presentation (SoC)
  • Better support for Test Driven Development
  • URL’s optimized for SEO and REST integrated with MapRoutes
  • No server-based forms
  • Good ALM and TFS integration for use with large development teams

The decision whether to use ASP.NET or ASP.NET MVC is a difficult one. You should review the previous section and utilize other resources (such as consultants or online forums for posting any question you have) to make the decision best for your situation. It is common to have hybrid systems that use both ASP.NET web forms together with ASP.NET MVC, Model–View–Controller capabilities. Taking the best parts of each and building a most optimal solution may be the way to go for you.

WHAT ARE THE DIFFERENCES BETWEEN ADO.NET AND NHIBERNATE?

You’ll encounter a number of differences between an ADO.NET data access layer and Object Relational Mapping (ORM)–like NHibernate. The main difference is the focus on design first versus model first. Before the creation or existance of ORMs software, development was usually driven by a relational-database. This caused some problems when the ASP.NET developer attempted to map the code to the database which could and often did change. The ORM concept approaches the design of software development from a code first, object-oriented perspective. All changes made to the design of a database happen from the source code and you execute commands on data table structures.

Therefore, it is recommended that where a system already has an existing relational-database that you not attempt to rewrite the system using the model-first capabilites. Instead, either use an alternative library for accessing the data, such as ADO.NET or use the manual mapping methods available in either the NHibernate or the ADO.NET Entitiy Framework.


NOTE For deeper analysis and review of NHibernate and the differences it has with ADO.NET you might consider reading Working with NHibernate 3.0 (Wiley, 2011).

From a code perspective, the following sections discuss how you’d implement an ADO.NET data access layer versus a similar situation for an NHibernate ORM structure. These sections compare and contrast these concepts to give you a better understanding of the differences.

Understanding the Data Access Layer

A significant migration opportunity has to do with the data access layer. A data access layer is typically a group of methods that manage the access to the database, the execution of SQL queries, and the storage of that data used for rendering to the client. Objects such as result sets, connection, and command objects should sound familiar as should the following code snippet:

set conn=Server.CreateObject("ADODB.Connection")

In the programming world, there’s been a lot of progress since this set of ADODB COM objects was first created. For example, its successor, ADO.NET, is a feature-rich set of classes available in the .NET Framework, which you access using the System.Data directive.

The data access layer provided in the sample ASP.NET website uses a common data access pattern. All the code making the connection executes queries and returns the results, storing them in the App_CodeDataAccess directory. This directory has a class called ConnectionManager that is used for all the methods, which make connections and execute queries against the database. Listing 1-2 is an example of an ADO.NET ConnectionManager.

LISTING 1-2: ADO.NET ConnectionManager

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
 
internal sealed class ConnectionManager
{
  public static SqlConnection GetConnection()
  {
    // Build the connection string from Web.Config file
    try
    {       
       string connectionString = ConfigurationManager
              .ConnectionStrings["tbcspitw-pro"].ConnectionString;
 
       SqlConnection connection = new SqlConnection(connectionString);
       connection.Open();
       return connection;
    catch(ConfigurationErrorsException)
    {
       //log the exception
    }
  }
}

Notice that the ConnectionString is stored in the web.config file. You can pass the connection string as a string directly into the SqlConnection object; however, if you do this and you need to change the password or server name, a code change and code migration are required. Saving the connection string in the web.config file enables you to make changes like this without the need to modifiy, test, and deploy new source code.

Using the GetConnection() method in the ConnectionManager class is typically done in a using{} statement, as shown in Listing 1-3.

LISTING 1-3: Using the GetConnection() Method of the ConnectionManager Class

using System.Data.SqlClient;
using System.Data;
 
public static int PostTotalCount()
{
  int count = 0;
  string sql = 
        "SELECT COUNT(DISTINCT POSTID) FROM POSTS WHERE TYPE ='blogs'";
 
  using (SqlCommand command = 
        new SqlCommand(sql, ConnectionManager.GetConnection()))
  {
    command.CommandType = CommandType.Text;
    count = (int)command.ExecuteScalar();
  }
  return count;
}

This is a relatively common ADO.NET data access layer implementation. Since the ADO.NET data access layer concepts were first implemented, the introduction of LINQ, repositories, and data models have greatly enhanced this piece of functionaity. ADO.NET is still a very valid and proven data access solution. The driving factor for change to an ORM is a much tighter coupling between the code and the database. Notice that in Listing 1-3 the SQL Query is hard-coded and string-based. This is prone to problems when columns and or tables change on the database. For that reason, in ADO.NET the binding between the code and the database is much weaker.

Understanding the Object Relational Mapping

An Object Relational Mapping (ORM) is an object-oriented approach for designing, creating, and retrieving data from a data source. Two of the most popular ORM’s are NHibernate and the ADO.NET Entity Framework. Some advantages of an ORM follow:

  • Development is faster because ORM reduces repetative code resulting in reduced costs and time.
  • It’s not dependent on a single database vendor (excluding EF).
  • When properly implemented, ORMs have solid caching and pooling capabilities.

Some disadvantages of an ORM follow:

  • The learning curve can be steep.
  • It’s challenging to write complex SQL queries.
  • It can be a little slower than non-ORM solutions.

NOTE This chapter and Chapter 2 focus on the transition from ADO.NET to NHibernate. However, the ADO.NET Entity Framework, which is Microsoft’s equiviliant to NHibernate. Both do similiar things. Therefore, you should look at both to determine which one best meets your needs.

Regarding the learning curve, a disadvantage of NHibernate, when compared to ADO.NET Entity Framework, is the setup complexity. However, after it is performed a few times, the process is relatively straightforward, whereas the ADO.NET Entity Framework is ready to go out-of-the-box.

The setup of NHibernate in a web-based scenerio is generally done in the Global.asax.cs file. An example of the configuration is shown in Listing 1-4. You do need to install the NHibernate binaries prior to using this code.

LISTING 1-4: NHibernate Setup Configuration Example

protected void Application_Start()
{
  ...
  var configuration = ConfigureNHibernate();
  configuration.CurrentSessionContext<WebSessionContext>();
  HbmMapping mapping = GetMappings();
  configuration.AddDeserializedMapping(mapping, "ASP.NET.MVC.4");
  SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
  SessionFactory = configuration.BuildSessionFactory();
  try
  {
    new SchemaExport(configuration).Drop(false, true);
    new SchemaExport(configuration).Create(false, true);
    SchemaValidator schemaValidator = 
                    new SchemaValidator(configuration);
    schemaValidator.Validate();
  }
  catch (HibernateException e)
  {
    //Log the error in the Event Viewer using 
    //the System Diagnostics library
  }
  ...
}

In Chapter 2, you are guided through the configuration and implementation of NHibernate. Therefore, all the methods are not displayed here. Even so, it is important to call attention to a few methods, for example the CurrentSessionContext type. In the sample solution the WebSessionContext context is chosen, but you need to understand the following as well:

  • NHibernate.Context.ManagedWebSessionContext: This session is tracked by the HttpContext object. You are responsible for binding and unbinding the Session methods to the class.
  • NHibernate.Context.CallSessionContext: The session is tracked by the CallContext. You are responsible for binding and unbinding the Session methods to the static methods of the CurrentSessionContext class.
  • NHibernate.Context.ThreadStaticSessionContext: The session is stored as a static thread variable and supports a single session factory. You are responsible for binding and unbinding the Session methods to the static methods of the CurrentSessionContext class.
  • NHibernate.Context.WebSessionContext: This is the same as ManagedWebSessionContext.

The context type is an important factor to investigate further when you plan on implementing any type of level 1 or level 2 caching. The chosen implementation for this sample creates a Session per database transaction, and there is no caching or lazy loading happening with this approach. If you need either of these capabilities in your ASP.NET MVC 4 web solution, choose another context and configure it appropriately.


NOTE In Listing 1-4, it is important that you comment out the SchemaExport.Drop() and Create() methods after the application is run once. As coded, each time the application is started, the database will be dropped and re-created. You will lose all data.

Understanding Mapping by Code

Another “newer” feature in NHibernate 3.0 is mapping by code. The approach originally required (and still supports) mapping files based on XML, which provide information about each column type and the relationship between other entities. These XML mapping files are no longer required; instead, you can perform mapping in a C# class file. Listing 1-5 provides an illustration of an NHibernate entity mapped by code.

LISTING 1-5: NHibernate — Mapping by Code

using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
namespace MVC.Models
{
  public class Blog
  {
    public Blog() 
    {
       comments = new List<Comments>();
    }
 
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Type { get; set; }
    ...
    public virtual IList<Comments> comments { get; set; }
 
  }
 
  public class BlogMap : ClassMapping<Blog>
  {
   public BlogMap()
   {
      Id<int>(x => x.Id);
      Property<string>(x => x.Title);
      Property<string>(x => x.Type);
      ...
 
      Bag<Comments>(x => x.comments, cp => {}, 
                    cr => cr.OneToMany(x => x.Class(typeof(Comments))));
    }
  }
}

Notice that the columns and their types are identified in the class. In addition, the relationships between the Blog class and the Comments class are created in the mapping class. When the SchemaExport.Create() method is run, the columns and primary and foreign keys are created.

Accessing Data from the Database

After the configuration of NHibernate is complete and the associated database schemas exist on the database, the next phase in a migration from an ADO.NET data access layer to NHibernate is to retrieve data from the database. NHibernate has a LINQ data access provider, referred to as LINQ to NHibernate. There are a number of different LINQ providers:

  • LINQ to NHibernate
  • LINQ ro Entities (ADO.NET Entity Framework)
  • LINQ to SQL
  • LINQ to XML

NHibernate has other interfaces such as IQuery and ICriteria that give you different capabilites and options for accessing your data. An example of a LINQ to NHibernate query is shown in Listing 1-6.

LISTING 1-6: LINQ to NHibernate Example

public IList<Blog> GetAdvancedBlogs()
{
  using (ISession session = MvcApplication.SessionFactory.OpenSession())
  using (ITransaction transaction = session.BeginTransaction())
  {
    IList<Blog> blogs = (from b in session.Query<Blog>()
                         where b.Advanced == 1 
                         select b).ToList<Blog>();
 
    return blogs;
  }
}

Choosing to implement an ORM is not only a change in technology but also a change in the approach used to create and design your application. In many cases the database design and the relationships between the tables dictate or drive the capabilities of an application. However, using an ORM, the tables (image) are turned, and the objected-oriented design of your application drives the database and its relationships.

EXAMINING INNOVATIONS FROM IIS 6 TO IIS 7.0/7.5/8

Internet information Service (IIS) has been around for many years and during that time has matured greatly. One of its only significant competitors is Apache, which usually runs on a Linux machine. IIS acts as a web server that responds to HTTP requests using verbs such as GET, POST, HEAD, and PUT.

If you review IIS versions 6 and IIS 7+, you’ll find a lot of differences and particularly new capabilities and enhancements. This section summarizes two of the most important enhancements from a migration perspective.


NOTE For more information on the various IIS 7+ capabilities, consider doing an Internet search or purchasing a book specifically about IIS. A good start is Professional IIS 7, (Wiley, 2008) or the Professional IIS 8, (Wiley, 2012).

Before discussing the differences between the IIS versions, you should know that when you create a Windows Azure Cloud Service, you can choose from a number of different Windows Server versions, as shown in Figure 1-4. The choices and the associated IIS versions as displayed as follows:

  • Windows Server 2008 SP2: IIS 7
  • Windows Server 2008 R2: IIS 7.5
  • Windows Server 2012: IIS 8

One significant difference between IIS 6 and IIS 7+ is the processing of these HTTP requests through what is known as the request pipeline. The request pipeline is a set of ordered native and managed modules that review or react to an HTTP request running through it. Some native modules are:

  • AnonymousAuthenticationModule
  • WindowsAuthenticationModule
  • HTTPCacheModule
  • TracingModule

Some examples of managed modules are:

  • FileAuthorization
  • Session
  • UrlMappingsModule

The type of module you use (that is, native versus managed) is important because it’s version-specific due to the integrated pipeline. For example, in IIS 6 when you request a managed resource, the authentication process happens in both the ASP.NET pipeline and the IIS pipeline, which is not optimal. In IIS 7+, the appropriate authentication modules (managed or native) are used and authentication is performed only once.

IIS 7+ still supports processing of a request as it happens in IIS 6. Some systems have been developed and are dependent on this mode and would not work in IIS 7+. To have your application run in IIS 6 mode, set your application pool to run in Classic mode, as shown in Figure 1-5.

To have your system run in the new unified pipeline mode, leave the application running in Integrated mode, which is the default. The second important difference is the change in built-in user and groups accounts. Table 1-1 describes the IIS 6 and IIS 7+ user group equivalents.

TABLE 1-1: Built-in IIS User and Group Accounts

IIS 6 IIS 7+
IUSR_MachineName IUSR
IIS_WPG IIS_IUSRS

The IIS 6 account and group are both local accounts, and when created, are associated to a security identifies (SID) — a unique number that identifies it from other accounts. A problem with IIS 6 is that this SID is stored in the metabase.xml file, and when you attempt to copy your configuration between one server and another, it does not work because the account and group on the new server has a different SID.

You can work around this by creating a domain account under which your application pool is run, and add this to the IIS_WPG groups. However, this means you need to add an Active Directory (AD) to your architecture. In cases in which a web farm or web server exists in a neutral zone or DMZ, this creates a significant overhead, which increases support and maintenance efforts.

The IUSR is an anonymous account that works similar to the LOCAL SERVICE account and that has no access to resources on the network. This account is used to execute requests running under the Anonymous Authentication provider. Every request needs to run under an identity.

The IIS_IUSRS group in IIS 7+ will have the same SID on Windows Server 2008. Therefore, when you attempt to copy your configuration from one server to the next, you should have no problems with the ACL on the file and system resources.

As mentioned, there are numerous differences between IIS 6 and IIS 7+. When making the jump, you need to choose the newest version of IIS because it has the most current capabilities and features. In addition, you should purchase an IIS book that covers these differences in more details.

INTRODUCING TEAM FOUNDATION SERVER

For many developers, the memories of Visual Source Safe (VSS) are burned into our brains like the theme song from your favorite television or radio episode. In the early days of software development activities, there were not so many source code repositories and VSS performed a key role, not only by keeping a company’s most valuable intellectual property safe, but also by being the basis of the entire release management process.

The Waterfall development process was one of the only methods in existence for moving code from thought to production. You could check code in and out, making a branch to fix bugs, releasing a new bug fix version on a monthly schedule, and releasing new features on a quarterly schedule. However, merging the code back together after releases was truly an art form, especially when there was overlap.

Today, you have many types of development processes, such as Agile, Extreme Programming, Continuous Integration, and so on. The list goes on but the goal is the same: To get the code checked in, tested on the different environments, such as system tests and integration tests, and then get code into production as fast as possible.

Visual Source Safe is no longer. It has been replaced by a very feature-rich and flexible solution called Team Foundation Server (TFS). This tool provides much more than a source code repository for managing the version of your source code. It provides features such as the following:

  • Grouping activities into Team Projects
  • Building management and testing capabilities
  • Using project management tools and work items
  • Using project reporting and metrics
  • Integrating with Windows Azure

Team Foundation Server is coupled somewhat to Application Lifecycle Management (ALM), which governs the life of an application from requirements gathering to maintenance. The concept of Continuous Integration is a focal point of both these solutions, and gets the code through the cycles and into production as fast as they are coded.

Setting up the link between Windows Azure and TFS is relatively straightforward. Simply follow these steps:

1. Access your Windows Azure account.
2. Select the Cloud Service where you want to publish your code.
3. Select the Set Up TFS Publishing link, as illustrated in Figure 1-6.
4. Follow the steps provided in the Setup Wizard.

After you connect Team Foundation Server and the Windows Azure Web Site or Cloud Service together in Visual Studio 2012, you check out a piece of code, modify it, test it, and check it back in, and the application will automatically build and publish.

Figure 1-7 shows the source code Explorer view of a sample project that’s being managed. The code, work items, builds, and testing can also be managed in the web component of TFS. For example, after you set up your TFS account, you can access your TFS at http://uniqueName.visualstudio.com. There you’ll see the windows illustrated in Figure 1-8.

The Team Foundation Service has everything you need to manage your projects, report the status, and manage the source code and deployment onto the Windows Azure platform. There is no doubt that using these tools can result in getting the code into production faster than ever before.

USING TEST DRIVEN DEVELOPMENT WITHIN ASP.NET MVC

ASP.NET MVC solutions are tightly connected to the Test Driven Development (TDD) model. Notice, as shown with Figure 1-9, that when you choose to create a new ASP.NET MVC Project, a generated unit test project is bound to the application by default.

Test Driven Development is focused on writing the least amount of code necessary to meet the requirement. Common practice is to write the test case first and then write the code, which ultimately makes the test case a success. In many cases, development is done the other way around, that is, develop the code and then create the case to test it.

Listing 1-7 illustrates a test case that checks if there are any blogs written in December 2014.

LISTING 1-7: Archive List for December 2014 — TDD

[TestMethod]
public void ArchiveList()
{
  BlogsController bController = new BlogsController();
  var result = bController.ArchiveList("2014", "DEC");
  Assert.IsNotNull(result);
}

After the test method code is implemented, you press CTRL+R, A to execute the test. You can expect the test to fail with the result shown in Figure 1-10.

The process now is to create an ArchiveList() method that accepts a Year and a Month as parameters where blogs are known to exist. You then select the parameters from the data source. When the method is completed, you can re-execute the tests that is, CTRL with the expected outcome, as shown in Figure 1-11.

SUMMARY

This chapter discussed the importance of innovation and change as well as the complexities and challenges you are likely to confront in the coming years due to retirement of Windows Server 2003, Windows XP, and IIS 6. Understanding the importance of the right platform for your application, as well as the opportunities posed by advancement in technologies, require your serious review and consideration. The recommendation of this chapter is that you not only change platforms (which brings more system stability, maintainability, and supportability), but also orient the culture and mentality of your development team to the new approaches and technologies.

Instead of simply moving your ASP.NET 2.0 application from IIS 6 to IIS 7, change where it makes sense! Use Windows Azure, use an ORM, use a development life cycle such as Agile or Continuous Integration, and use the tools that link all these things together, such as TFS and Visual Studio 2012. Innovate and create new value for your company and for your customers.

The next chapter has exercises that walk you through the migration from ASP.NET to ASP.NET MVC 4 and ADO.NET to NHibernate. After you complete this chapter’s exercises, you should have a nice web application that you can then optimize for performance, deploy to the Windows Azure platform, and then monitor to ensure visitors have a pleasant visit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.206.162