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…

Using RegisterStartupScript in ASP.NET

The RegisterStartupScript method is similar to the RegisterClientScriptBlock method. The major difference is that the RegisterStartupScript puts the script at the foot of the ASP.NET page as opposed to the top. The RegisterStartupScript method uses the same constructors as the RegisterClientScriptBlock method:

  • RegisterStartupScript (type, key, script)
  • RegisterStartupScript (type, key, script, script tag specification)

So what difference does it make to register the script at the foot of the page as opposed to the top? A lot, is the answer!
If you have JavaScript working with one of the controls on your page, you will not want your Javascript function to fire before the control is placed on the screen if it requires that control, therefore you should use the RegisterStartupScript method instead of RegisterClientScriptBlock.


For example, the below code listing creates a page that includes a simple control which contains a default value of    ASP.NET 101.

 <asp:TextBox ID="txtBox1" Runat="server">Hello ASP.NET</asp:TextBox>

Therefore use RegisterStartupScript to place a script on the page which uses the value in the txtBox1 control, as shown below:

protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"alert(document.forms[0][’txtBox1’].value);";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"MyScript", myScript, true);
}

This puts the JavaScript function at the foot of the ASP.NET page, so when the JavaScript actually starts, it can find the txtBox1 control and works as planned.

Using RegisterClientScriptInclude in ASP.NET

The final method for registering Javascript in an ASP.NET page is the RegisterClientScriptInclude method. Most developers place JavaScript inside a .js file, which is considered best practice because it makes it simple to make global JavaScript changes to the app and .js pages are cached. You can register the script files on your ASP.NET pages using the ClientScriptInclude method as shown below:

string myJavaScript = "myJsCode.js";
Page.ClientScript.RegisterClientScriptInclude("myKey", myJavaScript);

This creates the following tag in your ASP.NET page:

Using XML with DataSets

The disconnected data access model of ADO.NET is centered on DataSets. DataSets are the core of ADO.NET architecture and represent an in memory representation of the database. They can be used with a wide variety of data sources and contain one or more DataTable objects. These DataTable objects in turn comprise of one or more DataRows and DataColumns. While the DataTable object represents every table within a DataSet; the DataColumn and the DataRow objects represent the columns and rows within a DataTable. The DataSet class provides a seamless support for XML. Using XML, we can use the DataSet class in ADO.NET to perform the CRUD (Create, Read, Update and Delete) operations without an underlying database to store the data. This article discusses how we can use DataSets and XML – considered by many as a perfect combination to perform the CRUD operations devoid of any underlying database to hold data.

What are DataSets?

A DataSet is in effect an in-memory representation of cached, disconnected data that is available as a as a collection of tables, relationships, constraints, etc. In other words, a DataSet is actually an in-memory representation of the entire database along with its tables and relationships.

Continues…

The DataSet class is contained in the System.Data namespace in ADO.NET. The DataSet class has the ability to represent itself as XML upon request or when you pass it through the tiers or components of an application.

The primary advantage in using DataSets in applications is its disconnected approach that enables data to be transferred across application boundaries. The primary disadvantage of using DataSets however that is it consumes large amount of memory that is particularly a nightmare if your DataSet contains high volume of data. Hence, it becomes detrimental to the application’s performance when the DataSet contains large amount of data due to excessive consumption of memory.

DataSet and XML – A perfect match

Before we delve deep any further, let us have a recap of XML. What is XML and why is it so useful? Extensible Markup Language (XML) is a simple, platform independent, flexible meta-markup language that provides a format for storing structured data and is great for efficient exchange of data across the internet. XML has rapidly gained wide popularity and the enterprise applications the world over are using XML as the primary format for data exchange across the globe.

The salient features of this language are:–

  • Robust
  • Support for UNICODE
  • Hierarchical structure
  • Platform Independent
  • Present in human readable format
  • Can support even complex data structures

Now that we have had a quick tour of XML, let us discuss the support for XML provided by the DataSet class in ADO.NET.

The DataSet class in ADO.NET contains a lot of methods that provide XML support. The following are some of the most important methods of this class:–

  • The ReadXml Method
  • The ReadXmlSchema Method
  • The GetXml Method
  • The GetXmlSchema Method
  • The WriteXml Method
  • The WriteXmlSchema Method

While the ReadXML, GetXML and WriteXML methods deal with the data as XML representation devoid of any schema, the ReadXMlSchema, WriteXMLSchema and the GetXMLSchema methods represent the schema only. These methods would become much clear as we move on to the next section where working (for CRUD operations) with DataSet instances and XML has been illustrated. //break//

Working with DataSet and XML

This section discusses how we can perform the CRUD operations using DataSet and XML as the database to store the data.
Continues…