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.

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!