Tuesday, March 31, 2009

Limiting the File Upload Size in ASP.NET

By default, the maximum size of a file to be uploaded to a server using the ASP.NET FileUpload control is 4MB. You cannot upload anything that is larger than this limit.

To change this size limit, you have to make some changes in the application's web.config:    

    

   

maxRequestLength - Attribute limits the file upload size for ASP.NET application. This limit can be used to prevent denial of service attacks (DOS) caused by users posting large files to the server. The size specified is in kilobytes. As mentioned earlier, the default is "4096" (4 MB). Max value is "1048576" (1 GB) for .NET Framework 1.0/1.1 and "2097151" (2 GB) for .NET Framework 2.0.

executionTimeout - Attribute indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by the application. The executionTimeout value should always be longer than the amount of time that the upload process can take. 

Saturday, February 28, 2009

How Get Start and End days of a week/month?

DECLARE @SchDate datetime
SET @SchDate  = getdate()

-- Gets Week Start Day
SELECT  DATEADD(wk, DATEDIFF(wk, 6, @SchDate), 6) AS WeekStart
-- Gets Week End day
SELECT DATEADD(wk, DATEDIFF(wk, 5, @SchDate), 5) AS WeekEnd
-- Gets Month Start Day
SELECT dateadd(m, datediff(m, 0, @SchDate), 0) AS MonthStart
-- Gets Month End Day
SELECT dateadd(m, datediff(m, 0, dateadd(m, 1 ,@SchDate)), -1) AS MonthEnd

Friday, February 27, 2009

TSQL List of table and size in SQL database

I found this on searching for list of tables.

SELECT
X.[name],
REPLACE(CONVERT(varchar, CONVERT(money, X.[rows]), 1), '.00', '') AS [rows],
REPLACE(CONVERT(varchar, CONVERT(money, X.[reserved]), 1), '.00', '') AS [reserved],
REPLACE(CONVERT(varchar, CONVERT(money, X.[data]), 1), '.00', '') AS [data],
REPLACE(CONVERT(varchar, CONVERT(money, X.[index_size]), 1), '.00', '') AS [index_size],
REPLACE(CONVERT(varchar, CONVERT(money, X.[unused]), 1), '.00', '') AS [unused]
FROM
(SELECT
CAST(object_name(id) AS varchar(50)) AS [name],
SUM(CASE WHEN indid < 2 THEN CONVERT(bigint, [rows]) END) AS [rows],
SUM(CONVERT(bigint, reserved)) * 8 AS reserved,
SUM(CONVERT(bigint, dpages)) * 8 AS data,
SUM(CONVERT(bigint, used) - CONVERT(bigint, dpages)) * 8 AS index_size,
SUM(CONVERT(bigint, reserved) - CONVERT(bigint, used)) * 8 AS unused
FROM sysindexes WITH (NOLOCK)
WHERE sysindexes.indid IN (0, 1, 255)
AND sysindexes.id > 100
AND object_name(sysindexes.id) <> 'dtproperties'
GROUP BY sysindexes.id WITH ROLLUP) AS X
ORDER BY X.[name]

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.