ASP.NET MVC 3 First Look

ASP.NET MVC 3 Preview 1 has just been released and is now available for download here. Microsoft is now using Preview as the name for its early releases which roughly corresponds with the old CTP release type.

The first thing to not is that MVC 3 is backwards compatible with MVC  2, and can be installed side-by-side with MVC 2 – so you can use the current distribution for testing without impacting your current MVC 2 projects.

MVC 3 View Enhancements

MVC 3 introduces two improvements to the MVC view engine:

  • Ability to select the view engine to use. MVC 3 allows you to select from any of your  installed view engines from Visual Studio by selecting Add > View (including the newly introduced ASP.NET “Razor” engine”):
    MVC 3
  • Support for the next ASP.NET “Razor” syntax. The newly previewed Razor syntax is a concise lightweight syntax.

MVC 3 Control Enhancements

  • Global Filters : ASP.NET MVC 3  allows you to specify that a filter which applies globally to all Controllers within an app by adding it to the GlobalFilters collection.  The RegisterGlobalFilters() method is now included in the default Global.asax class template and so provides a convenient place to do this since is will then be called by the Application_Start() method:
    void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
    filters.Add(new HandleLoggingAttribute());
    filters.Add(new HandleErrorAttribute());
    }
    void Application_Start()
    {
    RegisterGlobalFilters (GlobalFilters.Filters);
    }
  • Dynamic ViewModel Property : MVC 3 augments the ViewData API with a new “ViewModel” property on Controller which is of type “dynamic” – and therefore enables you to use the new dynamic language support in C# and VB pass ViewData items using a cleaner syntax than the current dictionary API.
    Public ActionResult Index()
    {
    ViewModel.Message = "Hello World";
    return View();
    }
  • New ActionResult Types : MVC 3 includes three new ActionResult types and helper methods:
    1. HttpNotFoundResult – indicates that a resource which was requested by the current URL was not found. HttpNotFoundResult will return a 404 HTTP status code to the calling client.
    2. PermanentRedirects – The HttpRedirectResult class contains a new Boolean “Permanent” property which is used to indicate that a permanent redirect should be done. Permanent redirects use a HTTP 301 status code.  The Controller class  includes three new methods for performing these permanent redirects: RedirectPermanent()RedirectToRoutePermanent(), andRedirectToActionPermanent(). All  of these methods will return an instance of the HttpRedirectResult object with the Permanent property set to true.
    3. HttpStatusCodeResult – used for setting an explicit response status code and its associated description.

MVC 3 AJAX and JavaScript Enhancements

MVC 3 ships with built-in JSON binding support which enables action methods to receive JSON-encoded data and then model-bind it to action method parameters.
For example a jQuery client-side JavaScript could define a “save” event handler which will be invoked when the save button is clicked on the client. The code in the event handler then constructs a client-side JavaScript “product” object with 3 fields with their values retrieved from HTML input elements. Finally, it uses jQuery’s .ajax() method to POST a JSON based request which contains the product to a /theStore/UpdateProduct URL on the server:

$('#save').click(function () {
var product = {
ProdName: $('#Name').val()
Price: $('#Price').val(),
}

$.ajax({
url: '/theStore/UpdateProduct',
type: "POST";
data: JSON.stringify(widget),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#message').html('Saved').fadeIn(),
},
error: function () {
$('#message').html('Error').fadeIn(),
}
});
return false;
});

MVC will allow you to implement the /theStore/UpdateProduct URL on the server by using an action method as below. The UpdateProduct() action method will accept a strongly-typed Product object for a parameter. MVC 3 can now automatically bind an incoming JSON post value to the .NET Product type on the server without having to write any custom binding.

[HttpPost]
public ActionResult UpdateProduct(Product product) {
// save logic here
return null
}

MVC 3 Model Validation Enhancements

MVC 3 builds on the MVC 2 model validation improvements by adding   support for several of the new validation features within the System.ComponentModel.DataAnnotations namespace in .NET 4.0:
Continues…

Using Custom Data Types in ASP.NET Profiles

ASP.NET Profile can also accept custom data types and they are relatively easy to implement

The first step is to create a class which wraps the information you require. In the class, you may use public member variables, but the preferred choice is full-fledged property procedures which will allow the  class to support data binding or other complex logic.

For example, the below code shows an  Address class which should be placed in the App_Code directory of the web app:

[Serializable()]
public class Address
{
private string fullName;
public string FullName {...}
private string streetNumber;
public string StreetNumber {...}
private string cityCode;
public string CityCode {...}
private string zip;
public string Zip  {...}
private string stateCode;
public string StateCode {...}
private string countryCode;
public string CountryCode {...}
public Address(string nameCode, string streetCode, string cityCode,
string zip, string stateCode, string countryCode)
{
NameCode = nameCode;
StreetCode = streeCodet;
CityCode = cityCode;
Zip= zip;
StateCode = stateCode;
CountryCode = countrCode;
}
public Address()
{ }
}

Next add a property in the web.config to declare it:

<properties>
<add name="CutomerAddress" type="Address" />
</properties>

Now you can use the Profile in your code.


To assign values to the Profile:

Profile.CutomerAddress.Zip = txtZip.Text;

To access the Profile data:

string zipStr;
zipStr = Profile.CutomerAddress.Zip;

Automatic Saves

The ASP.NET Profiles feature cannot detect changes in complex data types (ie anything other than strings, Boolean values, simple numeric types etc). So the Profile includes complex data types, ASP.NET will save the complete profile info at the end of every request which accesses the Profile. The behavior has an obvious performance cost. Therefore to optimize Profile performance when using  complex types, you can  set the profile property to be read-only (in the event it never changes).

Alternatively, you can disable the autosave behavior by using  the automaticSaveEnabled attribute in the <profile> element and setting this to  false. If you do this you will need to use Profile.Save() to explicitly save changes to the Profile. This approach is normally preferred as the parts of code which modify a Profile are easy to spot and you can easily add  Profile.Save() to the end of the code block:

Profile.CustomerAddress = new Address(txtName1.Text, txtStreet1.Text, txtCity1.Text,

txtZip1.Text, txtState1.Text, txtCountry1.Text);

Profile.Save();

Optimizing ASP.NET Profiles Performance

ASP.NET Profiles were introduced to assist developers in persisting user information. Previous methods of persistence all had limitations in how they stored user data, Session state would only be held in memory and lost once the user’s session ended, a query-string would only be useful for that particular page and had to be recreated on each new page, cookies are only available on a single user machine. Profiles addressed all these difficulties by providing a simple persistent store which plugs into ASP.NET Membership. Profiles are ideal for storing user info such as preferences for a web app, besides being convenient they are very simple to use – just create them in the web.config file and access them anywhere in the application using Profile.ProfileName.

But with the convenience and power of Profiles comes a price – performance. Profiles are stored in a database, and therefore if used without caution can have a major performance cost.

To understand how best to use Profiles, first we will look at how they work under the hood. Profiles plug into the life-cycle of the page at two points:

  • The first time the Profile object is accessed in your code ASP.NET retrieves all the  profile data for the current user from the   database. If   the profile data is used more  than once in the same request ASP.NET reads it only once and then reuses it.
  • If profile data is updated, that update is deferred until the page has finished processing( ie after the PreRender, PreRenderComplete, and Unload events have completed). At that point the profile data  is written   to the database, thus  multiple changes are updated in batch.

Thus, using Profiles can result in an extra two database hits  per  request (if Profile data is read and then updated) or one extra database hit  (for simply reading the Profile data). It should be noted that Profiles do not have a caching mechanism so so every request for Profile data or update of Profile data  requires a database connection.

Thus from a performance viewpoint, Profiles are best when:

  • There are a relatively small number of pages which access the Profile data.
  • Profiles only store small amounts of data (since accessing Profiles always results in the retrieval of all the Profile data for that user it can be quite result in large payloads).

Therefore to optimize performance when using ASP.NET Profiles it is best to combine  

Profiles with other methods of  state management. For example,   a web app could first check if there was a cookie stored on the user’s machine for the user’s date format preference and if not available  this data could be retrieved from the Profile (which would then then add a cookie) this will save a database round trip each time to check the preferences (session state could also be used for this).

Getting Started Using ASP.NET Profiles

ASP.NET Profiles are a very useful tool for  persisting user data. Most other methods of state management do not easily persist the data across user visits, but Profiles plug seamlessly into the ASP.NET Membership database to provide a convenient persistent store.

Defining Profile Properties

The first step to using Profiles is to defining them in the web.config file.  This is done by adding the <profile> section to the web.config file and the adding each property using a  <add> element nested inside the <properties> element:

<configuration>
<system.web>
...
<profile>
<properties>
<add name="Language"/>
<add name="NumberFormat"/>
<add name="JoinedDate"/>
</properties>
</profile>
</system.web>
...
</configuration>

In addition to name the <add> element accepts several attributes which should be used. By default the format of the Profile is set to String but can be set to any datatype, for example the above JoinedDate profile should have a attribute of type added with the associated data type:

<add name="JoinedDate" type="System.DateTime" />

defaultValue is another useful attribute which sets the default of the Profile. For example, this could be used the set the initial language a user’s preferences is set to:

<add name="Language" defaultValue="en" />

There are several additional attributes, namely:

  • serializeAs : The format to use for serializing this Profile (String, CML, Binary, or ProviderSpecific)
  • readOnly : This is a boolean which sets if the Profile can be updated.
  • allowAnonymous : A boolean which sets if the Profile can be used with anonymous profiles.
  • provider : The profile provider that is used to manage this property.

Access Profiles

Profile access is very simple. Just use Profile.ProfileName anywhere in an app to get the profile value for the user. For example:

String langStr = Profile.Language

Update Profiles

Updating ASP.NET  Profiles is also a simple procedure, just assign the value to the Profile and it will be stored:

Profile.Language  = langTxtBox.Text

Note that the Profile will not actually be written to the database (and therefore not stored) until the page life-cycle is complete. Therefore after updating a Profile, avoid accessing it unless the page has finished processing (as only the old value will be stored).

Be aware that Profiles do not come without issues. There is a performance cost to using Profiles inappropriately see ASP.NET Profile Performance for more details.

Run External Applications From ASP.NET

To run an external application from your ASP.NET web application use the System.Diagnostics.Process.Start method for calling the  application.

The first step for  running an external application from an ASP.NET app is to create a ProcessStartInfo object, and then pass  the name of the application to run as well as  command-line parameters it might require. In the sample code below, we use the Java runtime to execute a Java program named ExternalJavaProgram, in this case the name of the application to run is java and the only command-line parameter required is  the name of the Java program - ExternalJavaProgram.

In the page’s code-behind class :

  1. Import the System.Diagnostics namespace.
  2. Create a ProcessStartInfo object and then pass the name of the external app to run as well as all required command-line parameters.
  3. Set the working directory to the external app’s location.
  4. Start the external app process by calling the Start method of the Process class  and pass the ProcessStartInfo object.


Code Example

private void Page_Load(object sender, System.EventArgs e)

  {

  Process proc = null;
  ProcessStartInfo si = null;

  // create a new start info object with the program to execute
 // and the required command line parameters
  si = new ProcessStartInfo("java",  "ExternalJavaProgram");

  // set the working directory to the location of the the legacy program
  si.WorkingDirectory = Server.MapPath(".");

  // start a new process using the start info object
  proc = Process.Start(si);

  // wait for the process to complete before continuing
  proc.WaitForExit( );

  }  // Page_Load

Working with ADO.NET Transactions

A transaction is a group of operations combined into a logical unit of work that is either guaranteed to be executed as a whole or rolled back. Transactions help the database in satisfying all the ACID (Atomic, Consistent, Isolated, and Durable). Transaction processing is an indispensible part of ADO.NET. It guarantees that a block of statements will either be executed in its entirety or rolled back,( i.e., none of the statements will be executed). Transaction processing has improved a lot in ADO.NET 2.0. This article discusses how we can work with transactions in both ADO.NET 1.1 and 2.0.

Implementing Transactions in ADO.NET

Note that in ADO.NET, the transactions are started by calling the BeginTransaction method of the connection class. This method returns an object of type SqlTransaction.
Other ADO.NET connection classes like OleDbConnection, OracleConnection also have similar methods. Once you are done executing the necessary statements within the transaction unit/block, make a call to the Commit method of the given SqlTransaction object, or you can roll back the transaction using the Rollback method, depending on your requirements (if any error occurs when the transaction unit/block was executed).
To work with transactions in ADO.NET, you require an open connection instance and a transaction instance. Then you need to invoke the necessary methods as stated later in this article.  Transactions are supported in ADO.NET by the SqlTransaction class that belongs to the System.Data.SqlClient namespace.

The two main properties of this class are as follows:

  • Connection: This indicates the SqlConnection instance that the transaction instance is associated with
  • IsolationLevel: This specifies the IsolationLevel of the transaction

The following are the methods of this class that are noteworthy:
Commit()   This method is called to commit the transaction
Rollback()  This method can be invoked to roll back a transaction. Note that a transaction can only be rolled back after it has been committed.
Save()       This method creates a save point in the transaction. This save point can be used to rollback a portion of the transaction at a later point in time. The following are the steps to implement transaction processing in ADO.NET.

  • Connect to the database
  • Create a SqlCommand instance with the necessary parameters
  • Open the database connection using the connection instance
  • Call the BeginTransaction method of the Connection object to mark the beginning of the transaction
  • Execute the sql statements using the command instance
  • Call the Commit method of the Transaction object to complete the
    transaction, or the Rollback method to cancel or abort the transaction
  • Close the connection to the database

The following code snippet shows how we can implement transaction processing using ADO.NET in our applications.

string connectionString = ...; //Some connection string
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();

SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();

SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Transaction = sqlTransaction;

try
{
sqlCommand.CommandText = "Insert into Employee (EmpCode, EmpName) VALUES (1, 'Joydip')";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "Insert into Dept (DeptCode, DeptName, EmpCode) VALUES (9, 'Software', 1)";
sqlCommand.ExecuteNonQuery();
sqlTransaction.Commit();
//Usual code
}

catch(Exception e)
{
sqlTransaction.Rollback();
//Usual code
}

finally
{
sqlConnection.Close();
}

The next piece of code illustrates how we can use the “using” statement for the above code. According to MSDN, the “using” statement, “defines a scope, outside of which an object or objects will be disposed.
Continues…

Add Custom Application Settings to web.config

ASP.NET provides for adding and then accessing configuration info specific to your app to the web.config file by using the <appSettings> element. Application configuration information is added by adding an child element to each parameter. Set the key attribute to the configuration parameter name, and then set the value attribute to the configuration parameter value:

 <appSettings> 
<add key="allowDataAccess" value="1" />
<add key="defaultDataOrder" value="Ascending" />
</appSettings>

When the ASP.NET app is started, ASP.NET creates a NameValueCollection from the key/value pairs in the  <appSettings> section. You can access the NameValueCollection anywhere in your app by using  the ConfigurationSettings object. Any data which can be represented as a string can be stored in the <appSettings> section, but note that data type other than a string will first need to be cast to from a string to that data type before being used  your app, for this reason your code should also incorporate exception handling for invalid data casts when the data is being accessed.


The below code demonstrates how to access the allowDataAccess configuration setting for the app. This is a boolean type (which is saved as a string):

Try

Dim allowDataBool as Boolean = ConfigurationSettings.AppSettings("allowDataAccess")

  If  allowDataBool Then
  '//Perform Data Access tasks
  End If

Catch ex As Exception

'//Perform error handling in the event that the allowDataAccess setting cannot be cast to a Boolean

End Try

Note that these settings are application wide and should not be used to set user specific settings, for this task consider either the Profile setting of ASP.NET Membership (for persistent information storage) or the Session object to store temporary information. Also be aware that changing the configuration settings in the web.config file will cause a restart of the application which will log out any current users.

Scalability and Load Testing in ASP.NET using Visual Studio

Load testing   an ASP.NET web app under different loads can be done using the Application Center Test (ACT) which is included in both the Enterprise Architect and Enterprise Developer editions of Visual Studio. ACT simulates a large number of users by opening multiple connections to the server and then rapidly sending multiple HTTP requests. The simplest way to do this is to first record a test script and subsequently modify the test properties to match the load test that you want to simulate. For example, in the case of a web service, you would record the steps that you would take to manually enter settings on the web service’s test page, and then let the ACT tool automatically replay the test script simulate a large number of users who are simultaneously accessing the service.

To do this, follow the below steps:

  1. Add an  Application Center Test project to the Solution Explorer (ACT projects are under Other Projects in the Project Types listing).
  2. Click   the  ACT project in Solution Explorer, and then select File Add New Item from the menu, and select “Browser Recorded Test (.vbs)” from   the template listing.
  3. Start Browser Record mode and then when the browser opens, navigate to the ASMX page for the web service, select a method to stress test, enter the test  values and then invoke the method.
  4. When  the XML is  returned from the web service, click Stop in the recorder dialog box.

You will then be presented with the contents of the .vbs script which was generated by the ACT. You can then edit  the commands as necessary. The Properties window can be used to set the number of simultaneous browser connections (ie the “stress level”), the iterations and the time in seconds to run the test, the test warm-up time, etc. The test can be started by right-clicking the .vbs file in Solution Explorer and then selecting “Start Test.” which will start the load testing.

A load test can recorded and run within Visual Studio but there are some big  advantages to using ACT’s standalone   interface instead. The ACT standalone interface is  easier to work with and also provides more in-depth reports info and graphs. For example using the ACT interface allows for  adding additional performance counters to a report.

ACT tests can be set to  run for either a  time period or a fixed number of script iterations. When you are  setting the number of iterations, be mindful how this relates to the number of simultaneous browser connections. The number of requests  issued for the test is a product of the two settings. For example, if you set the number of simultaneous browser connections is set to 20 and the number of iterations is set to 20, the web service which is being tested will actually receive 400 requests before the test is complete.
Continues…

WebMatrix Tutorial – Working with Data

In this tutorial we will focus on working with the inbuilt database (SQL Server CE 4) in WebMatrix. If you are new to WebMatrix please check out Part 1 of the WebMatrix Tutorial which deals with installing WebMatrix and working with the new ASP.NET Pages code files.

Working with the Database in WebMatrix

SQL Server CE is deeply integrated into WebMatrix, select Databases on the menu at bottom left of the interface and if you do not currently have an associated database you will be confronted with the below screen:

WebMatrix SQL Server Database

Click Add a Database to your site , then right-click Tables and select New Table.

WebMatrix SQL Server Database

You will then be able to add columns to your table (just click New Column on the ribbon for add the additional columns). You can specify the column details in the Column Properties settings list:

WebMatrix Database

You can edit or add data by clicking Data in the ribbon, which will take you to the existing data in the database presented as an editable grid:

WebMatrix SQL Server Database

Of course you would not normally add data using this method but it is convenient for a quick edit or to add some dummy data.

Note that using WebMatrix does not mean that you are tied to using the inbuilt SQL Server CE, you can interact with any version of SQL Server or other databases supported by the .NET framework such as MySQL.

Accessing the Database using ASP.NET Pages in WebMatrix

The database can be easily accessed using the new database API – primarily using the Open, Query and Execute commands.

The Open command combined with the Query command can be used to access the data in the database:

WebMatrix Databases

You can use queries in parameters to generate dynamic pages. Note the syntax of the Query command of the database API, which can accept numbered parameters:

WebMatrix

Updating the Database using ASP.NET Pages in WebMatrix

The Execute command of the Database object can be used to insert, update or delete data from the database. The first paramater of the Execute command accepts the SQL string for the database operation and the subsequent parameters are for the parameters to be inserted into the SQL string.
Continues…

WebMatrix Tutorial – Getting Started

In this WebMatrix Tutorial we will look at getting started with using WebMatrix and look at the new ASP.NET Pages coding method.

Introduction to WebMatrix

WebMatrix is a fully integrated development environment for building ASP.NET web apps. Currently developing an ASP.NET web will require using Visual Studio, IIS and SQL Server Management Studio all of which complicated tools in their own right. WebMatrix is Microsoft’s attempt to integrate a coding tool, database development tool and web server admin tool in one simple application for rapid application development.

WebMatrix incorporates several new technologies and tools from Microsoft which should make development faster and more simple. First is IIS Express, Visual Studio ships with an inbuilt  web server which is very convenient for testing during development but it is not 100% compatible with IIS 7 or 7.5 and so issues often arise when running the app in production. IIS Express which is incorporated into WebMatrix is a fully compatible but scaled down version of IIS meaning that developers can safely deploy apps that are only tested using the development environment. SQL Server Compact Edition 4 is the database incorporated into WebMatrix, the major innovation in SQL Server CE 4 is that it does not require any database server to run, you  simply build the tables etc in WebMatrix and just ftp the binaries created and the database will run (even on shared servers without admin privileges). Finally the web coding  itself features a simpler interface and the new lean ASP.NET Web pages  ”Razor” syntax syntax. The Razor syntax allows you to easily embed anywhere code in your page using the @ character and is definitely leaner and quicker to work with that the previous model of strictly separating code and markup (although this may not be as suitable for very large projects).

Getting Started with WebMatrix

Currently WebMatrix is in Beta (although it is still robust for  developing apps) and can be downloaded here.

Installation is a simple process (although you will be prompted to download and install Web Platform Installer 3.0 and ASP.NET 4.0 if you do not already have them). On your first run WebMatrix will present you with the below page:

WebMatrix Tutorial

You are presented with four options :

  • My Sites – which is the sites you previously used on WebMatrix
  • Site From Web Gallery – this is a similar listing of open source web-app projects as provided in the Web Platform Installer. Selecting a project such as Umbraco will install it as well as create and configure any associated databases.
  • Site From Template – WebMatrix ships with a limited number of pre-built site templates, none of which are especially useful for any purposes other than training.
  • Site From Folder – Allows you to open sites which were not previously opened with WebMatrix.

It isn’t immediately obvious from this list how to create a new site, but click Site From Web Gallery, then select Empty Site and click OK:

WebMatrix Tutorial

Continues…