Friday, December 11, 2009

How to recover lost files in windows 7 and Vista?

Have you ever deleted a file or folder from the desktop and emptied the recycle bin only to realize, seconds later, that you deleted the wrong one? Or have you ever edited a document, saved it, and then wanted to undo those changes?

Luckily, both Windows Vista and Windows 7 include a build-in feature called Shadow Copy that can solve this exact problem without you having to do anything. As you work with the files, Shadow Copy will automatically save incremental backups of your files in the background so if you accidentally delete or change a file, you can revert to the previous version with a simple right-click.

The Shadow Copy feature is available in all editions of Windows 7 but only in the Business and Ultimate editions of Vista. However, if your computer is running Vista Home Basic or Home Premium editions, you can still enjoy the Shadow Copy feature without upgrading your OS.

The feature may also come in handy if your document gets damaged or you want to bring back the files that were deleted by a virus.

Tuesday, November 17, 2009

Visual Studio 2005/2008 tips & tricks

Check this URL for tricks and tips by which you can enhance your productivity and efficiency

Microsoft Code Analysis Tool .NET (CAT.NET)

CAT.NET is a snap-in to the Visual Studio IDE that helps you identify security flaws within a managed code (C#, Visual Basic .NET, J#) application you are developing. It does so by scanning the binary and/or assembly of the application, and tracing the data flow among its statements, methods, and assemblies. This includes indirect data types such as property assignments and instance tainting operations. The engine works by reading the target assembly and all reference assemblies used in the application -- module-by-module -- and then analyzing all of the methods contained within each. It finally displays the issues its finds in a list that you can use to jump directly to the places in your application's source code where those issues were found. The following rules are currently support by this version of the tool. - Cross Site Scripting - SQL Injection - Process Command Injection - File Canonicalization - Exception Information - LDAP Injection - XPATH Injection - Redirection to User Controlled Site

Click here to Download

Saturday, October 24, 2009

Windows 7 Upgrade Advisor

Download and run the Windows 7 Upgrade Advisor to see if your PC is ready for Windows 7.
Click here to Download Advisor

Saturday, October 03, 2009

Doloto – Download time optimizer for web 2.0 apps

Doloto is an AJAX application optimization tool, useful for large and complex Web 2.0 applications that contain a lot of code. Doloto analyzes AJAX application workloads and automatically performs code splitting of existing large Web 2.0 applications. After being processed by Doloto, an application will initially transfer only the portion of code necessary for application initialization.

Requirements

  • Minimum: .NET Framework 3.5 (in US English only)

Doloto reduced the amount of initial downloaded JavaScript code by over 40%, or hundreds of kilobytes resulting in startup often faster by 30-40%, depending on network conditions

Download and Install Doloto.

Walkthrough Doloto

Thursday, October 01, 2009

Microsoft Security Essentials (MSE), its free!!

Microsoft today officially announced Microsoft Security Essentials (MSE), its free, real-time consumer antimalware solution for fighting viruses, spyware, rootkits, and trojans. Currently being tested by Microsoft employees and a select few testers, MSE is Microsoft's latest offering intended to help users fight the threats that plague Windows PCs.

Its absolutely free and can be used in Windows XP, Vista and 7. Both 32 and 64-bit versions are available.

Features:

  • Remove most-prevalent malware
  • Remove known viruses
  • Real-time anti-virus protection
  • Remove known spyware
  • Real-time anti-spyware protection

Minimum system requirements:

Operating System: Genuine Windows XP (Service Pack 2 or Service Pack 3); Windows Vista (Gold, Service Pack 1, or Service Pack 2); Windows 7

  • For Windows XP, a PC with a CPU clock speed of 500 MHz or higher, and 1 GB RAM or higher.
  • For Windows Vista and Windows 7, a PC with a CPU clock speed of 1.0 GHz or higher, and 1 GB RAM or higher.
  • VGA display of 800 × 600 or higher.
  • 140 MB of available hard disk space.
  • An Internet connection is required for installation and to download the latest virus and spyware definitions for Microsoft Security Essentials.
  • Internet Browser:
    • Windows Internet Explorer 6.0 or later.
    • Mozilla Firefox 2.0 or later.
  • Microsoft Security Essentials also supports Windows XP Mode in Windows 7. For more information see the system requirements for Windows XP Mode in Windows 7

Download Microsoft Security Essentials (MSE)

Sunday, September 20, 2009

Force Validation Using ASP.NET Validation Controls

ASP.NET comes in with a set of validation controls that automatically validate the data entered by a user. Though this validation controls are very powerful and easy to use, they have a small draw back in the sense that they require the entire page to be valid before it's submitted back to the server. There is no direct way to validate only a particular section of the page. This article will explain some circumstances where validating a particular section of page will be required and how to accomplish it.
While validation controls is a great tool for validating user input before data is being submitted there are some situations where we might either want the data to be submitted without validation or we want to validate only particular fields in the form.
A typical example for when we may want the data to be passed through without validation is when a page has both submit and cancels server buttons. When the user clicks the submit button the data has to be validated whereas when the user clicks the cancel post back has to happen without any validation.

The solution for by passing validation on server button click is fairly easy. All we have to do is set the CausesValidation property of the button control to false. Once the CausesValidation property is set to false no validation will happen both on the client side and server side.
The syntax for doing it in the design time is
<asp:button id="cmdCancel" runat="server" Text="Cancel" CausesValidation="False"></asp:button>
This can also be done in runtime using the following code
cmdCancel.CausesValidation = false;

To disable a particular validation control we can use the ValidatorEnable function as shown in the script below
<script language="javascript">
ValidatorEnable(nameofvlaidationcontrol, false)
</script>
To disable all the validation control we need to loop through Page_Validators array and disable each validator as shown in script below
<script language="javascript">
for(i=0;i< Page_Validators.length;i++)
{    ValidatorEnable(Page_Validators[i], false);
}
</script>
In order to enable validation only for particular set of controls when a submit button is clicked we need to combine the above two scripts and call it from the client click event of the button as shown in sample below
<script language="javascript">
function enableValidators()
{
  for(i=0;i< Page_Validators.length;i++)
  {

    ValidatorEnable(Page_Validators[i], false)
  }
  ValidatorEnable(rvState, true);
}
</script>
Attaching the function to the client click event of a submit button
cmdSave.Attributes.Add("onclick","enableValidators();");
When the cmdSave submit button is clicked all the other validators will be disabled and only the validator named rvState will be enabled. If the validation of rvState is successful then the page will be submitted. The code we have used so far will disable the validatiors only on the client side, so the validation will still happen on the server side and error messages will be shown. To disable particular validators on the server side the following code has to be added to the button click event
validationcontrolname.IsValid=true;

Tuesday, September 15, 2009

IE 8: Developer Tools

We definitely start loving IE 8 a lot more than we expected and as we discover newer features in it.

IE 8 includes a add-in called Developer Tools, which will allow you to analyze websites much more better than earlier versions of the browser.

These developer tools can be accessed by going to Tools –> Developer Tools or simply pressing F12 key.

Here are few built in developer tools that are available,

  • Debugging of HTML & CSS
  • Code Search
  • Source viewing
  • Outline elements on screen
  • Controlling caching and cookies
  • Browser Modes.

More information watch this webcast

File Monitoring in .NET

File monitoring applications can be easily developed in .NET using the FileSystemWatcher class. This class listens to changes in files system and raises events whenever changes happen. This article explains how to monitor changes in files and subdirectories of a directory using the FileSystemWatcher class.
The FileSystemWatcher is available within the System.IO namespace. We need to include the System.IO namespace for accessing the FileSystemWatcher class. In order to specify the folder to monitor we have to set the Path property of the FileSystemWatcher as shown below:

FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = "c:\\fileWatcher";
If you want to monitor changes to a specific file then the Filter property should be used along with the Path property. The Filter property should be set to file name and the Path property should be set to the path of the folder as shown below
fsw.Path = "c:\\fileWatcher ";
fsw.Filter = "TestWatchFile.txt";
Wild card characters can also be used to specify set of files as shown below
fsw.Filter = "*.txt";
The FileSystemWatcher to begin monitoring we have to set the EnableRaisingEvents property to true
fsw.EnableRaisingEvents = true;

As mentioned before the FileSystemWatcher raises events whenever changes like creation, deletion etc happens to the specific folder or file. The events that are raised by FileSystemWatcher are Changed, Created, Deleted, Error and Renamed.

We need to write appropriate event handlers to handle these events. The FileSystemEventHandler has an argument named FileSystemEventArgs, which provides useful event data. The data provided by the FileSystemEventArgs are ChangeType which gives the type of change that occurred and Path which gives the full path of the affected file or folder.

A sample Changed event handler is given below
fsw.Changed += new FileSystemEventHandler(fsw_changed);
fsw.Deleted += new FileSystemEventHandler(fsw_changed);
fsw.Created += new FileSystemEventHandler(fsw_changed);
private void fsw_changed(object Sender,FileSystemEventArgs e)
{
MessageBox.Show("The file" + e.FullPath+ " was " + e.ChangeType.ToString() + " on " + System.DateTime.Now.ToString());
}

FileSystemObject class can be used to monitor files or folders by setting appropriate properties and handling the events raised by the class.

Monday, September 14, 2009

Executing ASP Page in ASP.NET

When migrating applications from ASP to ASP.NET there may be situations where you would like to use some of the existing ASP code within ASP.NET pages. This how can we achieve to do so.

We can embed ASP pages within ASP.Net pages by suing screen-scraping mechanisms provided by the WebRequest and WebResponse classes, which are within the System.Net namespace. These two classes provide a request/response model for accessing data from Internet. Using the WebRequest class we can create a request to the asp page, which you need to embed within ASP.NET page. The WebResponse class is used to receive the response generated by the request. We then use the StreamReader class to get the contents of the response and display it on the screen.
All this functionality is encapsulated within a static method of a class as given in the code below. This static function accepts the name of the ASP page to be embedded. It gets response from the ASP page and returns the response content as a string.
public class ASPWithInASPNet
{
public static void GetASPResults(string AspPage)
{
try
{
//CHECK IF THE GIVEN PAGE NAME IS A URL
Regex objRegex = new Regex(@"^http\://[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}(/\S*)?$");
string StrPath;
//IF THE PAGE NAME IS URL
if(objRegex.IsMatch(AspPage))
{
StrPath = AspPage;
}
//IF THE PAGE NAME IS NOT A URL
else
{
Uri RequestURI = HttpContext.Current.Request.Url;
StrPath = RequestURI.Scheme+ "://" + RequestURI.Host +
HttpContext.Current.Request.ApplicationPath + "/";
StrPath = StrPath + AspPage;
}
//CREATE A REQUEST TO THE ASP PAGE
HttpWebRequest WebReq =
(HttpWebRequest)WebRequest.Create(StrPath);
// GET THE RESPONSE
WebResponse WebRes = WebReq.GetResponse();
StreamReader SR = new StreamReader(WebRes.GetResponseStream());
HttpContext.Current.Response.Write(SR.ReadToEnd());
}
catch(WebException Ex)
{
HttpContext.Current.Response.Write( Ex.Message);
}
}
}
This class can be used in any of you ASP.Net pages as shown in the sample below.
private void Page_Load(object sender, System.EventArgs e)
{
   ASPWithInASPNet.GetASPResults("http://localhost/aspconvertProj/default.asp");
}
Note: This functionality can be used to embed not only ASP pages but also any web page like JSP, HTML etc.

Friday, September 04, 2009

Build the Newest Silverlight 3 Applications with Expression

Silverlight 3 and Expression Studio 3 help you create and deploy Web sites and rich Internet applications more easily than ever. Download Silverlight 3 and the Expression Studio 3 60-day trial today.

View article...

Wednesday, September 02, 2009

HTML 5

HTML 5 is the next major revision of HTML (Hypertext Markup Language), the core markup language of the World Wide Web.

HTML 5 is the proposed next standard for both HTML 4.01 and XHTML 1.0, as development on the next version of the latter has stopped. HTML 5 was initially said to become a game-changer in Web application development, making obsolete such plug-in-based rich Internet application (RIA) technologies as Adobe Flash, Microsoft Silverlight, and Sun JavaFX. Such applications would be made obsolete by specifying a standard video codec for all browsers to use. However, in December 2007, the editor of the burgeoning draft specification dropped the recommendation of the free software Theora and Vorbis codecs, after opposition from Apple and Nokia. This means HTML 5 does not currently specify a common video codec for Web development.

The ideas behind HTML 5, originally referred to as Web Applications 1.0, were pioneered in 2004 by the Web Hypertext Application Technology Working Group (WHATWG); HTML 5 incorporates Web Forms 2.0, another WHATWG specification. The HTML 5 specification was adopted as the starting point of the work of the new HTML working group of the W3C in 2007.

Difference between HTML4 and HTML5

Click Here for more.

Friday, August 28, 2009

How to Change Font-Size, Font-Family,Font-Style at RunTime

Label lblCarrier = new Label();

lblCarrier.Text = "Carrier Name:"
lblCarrier.AutoSize = true;
Font font = new Font("Arial", 9, FontStyle.Bold);
lblCarrier.Font = font;

Hope this helps :-)

Thursday, August 27, 2009

Visual Studio 2010 and .NET Framework 4 Beta 1 Are Here

Check out Visual Studio 2010 and the .NET Framework 4 Beta 1 for the next generation of developer tools from Microsoft.

View article...

Windows 7 Training Kit for Developers Now Available

Download the new Windows 7 Training Kit for Developers. The kit includes code, videos, and labs for both native Win32 C++ developers and .NET developers covering the new features available in Windows 7.

Click here for more Info...

Wednesday, August 05, 2009

Get Process Status using C#

The following code snippet can be used to get the status of any process or an application given its name or PID (Process ID).

using System.Diagnostics;
private void GetProcessStatus()
{
try
{
//If you know the name of the process
Process[] myProcess = Process.GetProcessesByName("notepad");
//If you know the PID of the process use the commented line below
//Process[] myProcess = Process.GetProcessById("1983");
//Check to see if the process array length is greater than 0
if(myProcess.Length > 0)
{
MessageBox.Show("The Process Notepad is currently running.", "Process Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The Process Notepad is currently not running.", "Process Status", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch(Exception ex)
{
MessageBox.Show("An Exception Occoured: " + ex.Message, "Process Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Monday, July 27, 2009

What is AutoEventWireup?

ASP.NET page framework also supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true (or if it is missing, since by default it is true), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers. Therefore, in Visual Studio, the AutoEventWireup attribute is set to false by default and the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

For more information Click here

Wednesday, July 15, 2009

asp:Menu Server Control - Cross Browser Compatibility (Safari/Chrome)

 

Cross browser compatibility is upsetting while working with asp:Menu Server Control, and It was not rendering/working well with Safari and Chrome.

After bit of googling... :-) and found a solution for this.

Approach 1:

I have added below small piece of code snippet in my MasterPage's Page_Load event

        if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
        {
            Request.Browser.Adapters.Clear();
        }

This will tell asp.net not to use an adapter when rendering the menu control. This will work for both Safari and chrome as well because they both use webkit which is how asp.net identifies.

Approach 2:

You can force the menu to work by overwrite the Page_PreInit method on the page and telling the page that the client target is a modern “uplevel” browser:-

protected void Page_PreInit(object sender, EventArgs e)
{
if (Page.Request.ServerVariables["http_user_agent"].ToLower().Contains("safari"))
{
Page.ClientTarget = "uplevel";
}
}

Unfortunately, you can't just add the fix to your Master Page, it doesn't contain a PreInit method as it's a web control not a web page.

Please note that you have to do this in the page class file, and not in the master page class file. Obviously this means you have to do it for every page – which is not ideal.

Wednesday, May 20, 2009

Date Formats in SQL Server

---Yesterday 
select dateadd(d,-1,getdate()) as yesterday

--First Day of Current Week
select dateadd(wk,datediff(wk,0,getdate()),0) as [First Day of Current Week]

--Last Day of Current Week
select dateadd(wk,datediff(wk,0,getdate()),6) as [Last Day of Current Week]

--First Day of Last Week
select dateadd(wk,datediff(wk,7,getdate()),0) as [First Day of Last Week]

--Last Day of Last Week
select dateadd(wk,datediff(wk,7,getdate()),6) as [Last Day of Last Week]

--First Day of Current Month
select dateadd(mm,datediff(mm,0,getdate()),0) as [First Day of Current Month]

--Last Day of Current Month
select dateadd(ms,- 3,dateadd(mm,0,dateadd(mm,datediff(mm,0,getdate())+1,0))) as [Last Day of Current Month]

--First Day of Last Month
select dateadd(mm,-1,dateadd(mm,datediff(mm,0,getdate()),0)) as [First Day of Last Month]

-- First day of next month
SELECT dateadd(m, datediff(m, 0,getdate())+1, 0) AS MonthStart

-- Last day of next month
SELECT dateadd(m,datediff(m, 0, dateadd(m, +2 ,getdate()))+1, -1) AS MonthEnd

--Last Day of Last Month
select dateadd(ms,-3,dateadd(mm,0,dateadd(mm,datediff(mm,0,getdate()),0))) as [Last Day of Last Month]

--First Day of Current Year
select dateadd(yy,datediff(yy,0,getdate()),0) as [First Day of Current Year]

--Last Day of Current Year
select dateadd(ms,-3,dateadd(yy,0,dateadd(yy,datediff(yy,0,getdate())+1,0))) as [Last Day of Current Year]

--First Day of Last Year
select dateadd(yy,-1,dateadd(yy,datediff(yy,0,getdate()),0)) as [First Day of Last Year]

--Last Day of Last Year
select dateadd(ms,-3,dateadd(yy,0,dateadd(yy,datediff(yy,0,getdate()),0))) as [Last Day of Last Year]

select month('09/06/2008')
select year('09/06/2008')
select getutcdate()
select getdate()
select day('09/06/2008')
select datepart(dd,'09/06/2008')
select datename(yyyy,'09/06/2008')
select datediff(dd,'09/06/2008','09/18/2008')
select dateadd(dd,60,'09/06/2008')

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.

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>