Thursday, February 19, 2009

Transactions in ASP.NET

What are Transactions? 

A transaction symbolizes code or a set of components or procedures which must be executed as a unit. All the methods must execute successfully or the complete unit fails. A transaction can be described to cover the ACID properties for mission critical applications.

What are the ACID Properties?

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability

Transfer Funds Sample 

We will build a sample ASP.NET web form for a fictitious bank which will transfer a specified amount from one account to another - if the  balance in the first account is sufficient to cover the transfer.

First we need to create the database we will using in the example.

I used an MS Access database containing only one table : tblAccount.
 

Field Name

Field Type

AccNumber

Text

dBalance

Double

Listing 1 displays the code for the web page. Save the web page as Test.aspx.

First include the Namespaces required for accessing the data. 

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %>

Here is the function which processes the transaction for transferring the data.

For this example we assume that the transaction should be rolled back (Cancelled) if :

  1. There are insufficient funds in the From Account to cover the transfer. 
  2. Either of the SQL statements for marking credit or debit in the To and From accounts results in an error. 

We create the Connection needed to connect to our database.

OleDbConnection Conn = newOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:\\inetpub\\wwwroot\\dotnet\\test.mdb;");

In real life we would use Server.MapPath to map to the location of the database.

We use the Data Reader oReader to check the validity of the amount in the From Account. The crux of the function is to execute the two SQL queries one to subtract the amount from the From Account and one to add the same amount to the balance in the To Account.

We start the transaction after we have created the data objects .The transaction should be kept as short as possible to avoid concurrency issues and to enable maximum number of positive commits. 

Create the transaction and associate the transaction with the OleDbCommand as follows: 

OleDbTransaction Trans = Conn.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = Trans;

Within the Try block run the transaction and Commit the transaction if everything proceeds smoothly. Committing a transaction will write the changes to the database.

If there is an exception we will Roll Back the transaction. This will cancel any changes that have been carried out as a part of the transaction. This is how we maintain the integrity of our transaction.

try

{

    oReader = cmd.ExecuteReader();

    oReader.Read();

    dCurrBalance = oReader.GetDouble(0);

    oReader.Close();

    if (dCurrBalance < Convert.ToDouble(txtAmt.Text))

    {

        throw (new Exception("Insufficient funds for transfer"));

    }

    strSQL = "Update tblAccount set dbalance =  dBalance - " + txtAmt.Text + " where AccNumber = '" +

    txtFrom.Text + "'";

    cmd.CommandText = strSQL;

    cmd.ExecuteNonQuery();

    strSQL = "Update tblAccount set dbalance =  dBalance + " + txtAmt.Text + " where AccNumber = '" +

    txtTo.Text + "'";

    cmd.CommandText = strSQL;

    cmd.ExecuteNonQuery();

    Trans.Commit();

    lbl.Text = "true";

}

catch (Exception ex)

{

    Trans.Rollback();

    lbl.Text = "Error: " + ex.Message;

}

finally

{

    Conn.Close();
}

Note how we Throw an exception if the balance in the From Account is less than the transfer amount.

throw (new Exception("Insufficient funds for transfer")); 

The string passed in the constructor of the Exception object initializes the message for the Exception that will be raised.

Finally we indicate the results of the transfer activity to the user .

lbl.Text = "Fund Transfer of Amount " + txtAmt.Text + " from Account " + txtFrom.Text + " to Account " + txtTo.Text + " was executed successfully.";
OR
lbl.Text = "Error: " + ex.Message; 

In real life, we would have converted the error message to a more meaningful and user friendly message.

Here is the complete code listing for the web form. 

Listing 1: Test.aspx : Transfer Funds Web Page.

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %>

<html>

<head>

    <title>Transfer Funds</< span>title>

 

    <script language="C#" runat="server">

        protected void TransferFund(Object Sender, EventArgs e)

        {

            String strSQL = "Select dBalance FROM tblAccount where AccNumber='" + txtFrom.Text + "'";

            double dCurrBalance;

            OleDbConnection Conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA

            SOURCE=c:\\inetpub\\wwwroot\\dotnet\\test.mdb;");

            Conn.Open();

            OleDbDataReader oReader;

            OleDbCommand cmd = new OleDbCommand(strSQL, Conn);

            OleDbTransaction Trans = Conn.BeginTransaction(IsolationLevel.ReadCommitted);

            cmd.Transaction = Trans;

            try

            {

                oReader = cmd.ExecuteReader();

                oReader.Read();

                dCurrBalance = oReader.GetDouble(0);

                oReader.Close();

                if (dCurrBalance < Convert.ToDouble(txtAmt.Text))

                {

                    throw (new Exception("Insufficient funds for transfer"));

                }

                strSQL = "Update tblAccount set dbalance =  dBalance - " + txtAmt.Text + " where AccNumber = '"

                + txtFrom.Text + "'";

                cmd.CommandText = strSQL;

                cmd.ExecuteNonQuery();

                strSQL = "Update tblAccount set dbalance =  dBalance + " + txtAmt.Text + " where AccNumber = '"

                + txtTo.Text + "'";

                cmd.CommandText = strSQL;

                cmd.ExecuteNonQuery();

                Trans.Commit();

                lbl.Text = "true";

            }

            catch (Exception ex)

            {

                Trans.Rollback();

                lbl.Text = "Error: " + ex.Message;

            }

            finally

            {

                Conn.Close();

            } 

        }

 

    </< span>script>

 

</< span>head>

<body>

    <form id="frmTransfer" runat="server">

        <asp:Label ID="lblFrom" runat="server">Enter the account number from which to transfer

          funds</< span>asp:Label>

        <asp:TextBox ID="txtFrom" runat="server"></< span>asp:TextBox><br />

        <asp:Label ID="lblTo" runat="server">Enter the account number to which to transfer funds</< span>asp:Label>

        <asp:TextBox ID="txtTo" runat="server"></< span>asp:TextBox><br />

        <asp:Label ID="lblAmount" runat="server">Enter the amount to transfer</< span>asp:Label>

        <asp:TextBox ID="txtAmt" runat="server"></< span>asp:TextBox><br />

        <asp:Button ID="Button1" OnClick="TransferFund" runat="server" Text="Start Transfer">

        </< span>asp:Button><br />

        <asp:Label ID="lbl" runat="server"></< span>asp:Label>

    </< span>form>

</< span>body>

</< span>html>

Figure 1 : Front end web page for the transaction example.

Figure 2 : Successfully Committed Transactions.

Figure 3: Insufficient Funds RollBack !  

Note:  When the transaction is rolled back (Insufficient funds or an error in the SQL statements) the Balance field in both the From Account and To Account in the database is not updated.

Tuesday, February 17, 2009

JavaScript - Confirm OK Cancel - Yes No

just cam across a post, brilliant way to change the confirm box from ok / cancel to yes / no.

Well it doesn't work in Mozilla though, it returns ok / cancel only

http://www.delphifaq.com/faq/javascript/f1172.shtml

<script language=javascript>

/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)

function window.confirm(str)
{
execScript('n = msgbox("'+str+'","4132")', "vbscript");
return(n == 6);
}

@end @*/
var r = confirm("Can you do it?");
alert(r);
</script>

Monday, October 20, 2008

Microsoft .NET Framework 3.0 (Brief Overview)

 

What is the Microsoft .NET Framework 3.0?
The Microsoft .NET Framework 3.0 (formerly WinFX), is the new managed code programming model for Windows.

It combines the power of the .NET Framework 2.0 with four new technologies:
Windows Presentation Foundation (WPF),
Windows Communication Foundation (WCF),
Windows Workflow Foundation (WF), and
Windows CardSpace (WCS, formerly “InfoCard”).

Use the .NET Framework 3.0 today to build applications that have visually compelling user experiences, seamless communication across technology boundaries, the ability to support a wide range of business processes, and an easier way to manage your personal information online. This is the same great WinFX technology you know and love, now with a new name that identifies it for exactly what it is – the next version of Microsoft’s development framework.

What is Windows Communication Foundation ?
The Windows Communication Foundation (previously codenamed "Indigo") is Microsoft's unified framework for building
secure, reliable, transacted, and interoperable distributed applications.

What is Windows Presentation Foundation ?

Windows Presentation Foundation (WPF) is the next-generation presentation sub-system for Windows.

It provides developers and designers with a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents.

What is Windows Workflow Foundation?

Windows Workflow Foundation (WF) is the programming model, engine and tools for quickly building workflow enabled applications.

WF radically enhances a developer’s ability to model and support business processes.

Windows Workflow Foundation is a part of the .NET Framework 3.0 that enables developers to create workflow enabled applications. It consists of the following parts:

Activity Model:
Activities are the building blocks of workflow, think of them as a unit of work that needs to be executed.

Activities are easy to create, either from writing code or by composing them from other activities. Out of the box, there are a set of activities provided that mainly provide structure, such as parallel execution, if/else, call web service.

Workflow Designer:
This is the design surface that you see within Visual Studio, and it allows for the graphical composition of workflows, by placing activities within the workflow model.
One interesting feature of the designer is that it can be re-hosted within any Windows Forms application.

Workflow Runtime:
Our runtime is a light-weight and extensible engine that executes the activities which make up a workflow.

The runtime is hosted within any .NET process, enabling developers to bring workflow to anything from a Windows Forms application to an ASP.NET web site or a Windows Service.

Rules Engine:
Windows Workflow Foundation has a rules engine which enables declarative, rule-based development for workflows and any .NET application to use.

Windows Workflow Foundation will be released as part of the .NET Framework 3.0 which is part of the Windows Vista release. The .NET Framework 3.0 will be available for Windows XP as well as Windows Server 2003

What is Windows Card Space ?
Windows CardSpace enables users to provide their digital identities in a familiar, secure and easy way.

In the physical world we use business cards, credit cards and membership cards.

Online with CardSpace we use a variety of virtual cards to identify ourselves, each retrieving data from an identity provider. Don't struggle with usernames and passwords, just choose an information card!

Thursday, October 16, 2008

Microsoft Expression Blend

Expression Blend 2 SP1 (which is an evolution of the Blend 2.5 previews) provides rich authoring support for Silverlight 2. Building on the earlier Blend 2.5 releases, this Service Pack provides designers with even more control over the visual and interaction design for rich interactive web applications.

New platform functionality exposed:
  • Control Skinning offers designers the ability to edit templates for customizing controls, or to create new templates from scratch for complete expressive freedom and component reusability.
  • Visual State Manager gives designers the power to precisely specify how each element of a control looks and behaves in each state of the interaction model, including transitions.
  • Font Embedding and Subsetting provides designers an easy way to present text consistently to users.

Download Microsoft Expression Blend™ 2 Service Pack 1

Microsoft® Expression Blend™ 2 is the professional design tool used to create engaging Web-connected experiences for Microsoft® Windows®. The Expression Blend 2.5 June 2008 Preview allows you to create Microsoft® Silverlight™ 2-based applications

Download Microsoft Expression Blend 2.5 June 2008

Microsoft Silverlight Tools Beta 2 for Visual Studio 2008

Silverlight Tools Beta 2 has been updated to support Visual Studio 2008 and Visual Studio 2008 SP1. Visual Studio 2008 SP1 Beta is no longer supported.

Click here to download