Thursday, 24 May 2012

SQL COALESCE‏


Coalesce function is a good feature in SQL to concatenate data from multiple columns of that row and return a single field value. During the concatenation the null value will be ignore and it retrieve non null values.

Consider a scenario you need to retrieve contact number of an employee from an employee table. It is not necessary that all type of contact number is available in the employee table. We need to retrieve the employee contact number. So using the coalesce function we can retrieve the employee contact number.

Employee Table
Name
Business_Phone
Cell_Phone
Home_Phone
Marsh
531-2531
622-7813
565-9901
Don
NULL
772-5588
312-4088
Parker
NULL
NULL
594-7477
and we want to find out the best way to contact each person according to the following rules:
1. If a Employee has a business phone, use the business phone number.
2. If a Employee does not have a business phone and has a cell phone, use the cell phone number.
3. If a Employee does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.
We can use the COALESCE function to achieve our goal:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone 
FROM Contact_Info;
Result:
Name
Contact_Phone
Marsh
531-2531
Don
772-5588
Parker
594-7477

Wednesday, 23 May 2012

ASP.net Copy Files and Folder from source to destination with creating backup folder.


The manual deployment of files is applicable in most of the enhancement or maintenance project. This method is applicable only for certain applications that are developed before 2002 for classic asp and other programming languages with no class libraries. Still it is a part of activity performed by the deployment team to transfer the modified file from staging folder to the production folder. Normally the developers copy the files from the development environment or UAT environment and put it in a staging environment. And then after approval process the deployment team takes the code from staging and deployment in production.  The whole process is so cumbersome and difficult for the developer to copy the files from the development or UAT to staging. So the below code is so self explanatory for creating the files and folders in the staging environment with a deployment instruction in the staging location.

The Code accepts various parameters like source location, destination location, backup folder location, ticket name.
Create deployment instruction and rollback instruction along with the files and folders to be copied in the staging environment with the same structure.

This code can used as a part in a web application for creating deployment instruction.

Public Shared Sub CreateFileFolder(ByVal srcFullPath As String, ByVal srcPath As String, ByVal dstPath AsString, ByVal fileName As String, ByVal ticketNo As String, ByVal lastFldr As Boolean, ByVal bkpFolder AsString)
        Dim dstDir, backupDir As DirectoryInfo
        Dim tmpPath As String
        ‘Create instr if it is the last folder 
        If lastFldr = True Then
            If File.Exists(DeployInstrPath & "Instr.txt") Then File.Delete(DeployInstrPath & "Instr.txt")
            WriteFile(DeployInstr, DeployInstrPath & "Instr.txt")
            If File.Exists(DeployInstrPath & "RollbackInstr.txt") Then File.Delete(DeployInstrPath &"RollbackInstr.txt")
            WriteFile(RollbackInstr, DeployInstrPath & "RollbackInstr.txt")
            Exit Sub
        End If

        Try
            If (srcPath.Contains("\")) Then
                tmpPath = srcPath.Substring(0, srcPath.IndexOf("\"))
                srcPath = srcPath.Substring(srcPath.IndexOf("\") + 1)
                lastFldr = False
            Else
                tmpPath = srcPath
                lastFldr = True
            End If
            If ticketNo.Length <> 0 Then
                dstPath += "\" + tmpPath + "\" + ticketNo
                backupDir = New DirectoryInfo(dstPath + "\Backup")
              ‘Create backupFolder 
                backupDir.Create()
                bkpFolder = dstPath + "\Backup"
            Else
                dstPath += "\" + tmpPath
                bkpFolder += "\" + tmpPath
              ‘Create folder inside the structure
                backupDir = New DirectoryInfo(bkpFolder)
                If (Not backupDir.Exists) Then backupDir.Create()
            End If
             ‘Create Main Folder
            dstDir = New DirectoryInfo(dstPath)
            If (Not dstDir.Exists) Then dstDir.Create()
            If lastFldr = True Then
                CopyFiles(srcFullPath, dstPath + "\" + fileName)
                WriteDeployInstruction(fileName, srcPath, bkpFolder & "\", dstPath & "\")
                WriteRollbackInstruction(fileName, srcPath, bkpFolder & "\")
            End If
            CreateFileFolder(srcFullPath, srcPath, dstPath, fileName, String.Empty, lastFldr, bkpFolder)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Tuesday, 22 May 2012

ASP.net to write simple log file in VB.net language

In many applications we may came across lot logging techniques. Like writing log files in text file, some custom log file, log in event viewer, logging information in Databases etc.,

Here we are going to see a simple code in VB.net programming language that will help in logging information for any applications.

1. Use a system.IO namespace for any file handling operations.
2. When a variable is considered as a shared object, it means there is no need for object creation in the instantiation class.
3. The  System.Windows.Forms.Application.StartupPath is a application running folder path
4. Check to see the log folder and log file already exists. If not exist then create one or else concatenate with the existing content in the log file.
5. Create a filestream object and using streamwriter write the content to the log file.



Imports System
Imports System.IO
Public Class Log
    Private Shared LogPath As String = System.Windows.Forms.Application.StartupPath + "\Log\"
    Private Shared fs As FileStream
    Private Shared sw As StreamWriter
    ''' <summary>
    ''' Log result in the log file
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub Log(ByVal logStr As String)
        Dim logDir As DirectoryInfo
        Dim logFileName As String = LogPath + "Log.txt"
        logDir = New DirectoryInfo(LogPath)
        If (Not logDir.Exists) Then logDir.Create()
        If (Not File.Exists(logFileName)) Then File.Create(logFileName)
        If File.Exists(logFileName) Then
            sw = File.AppendText(logFileName)
            sw.WriteLine(logStr.ToString())
            sw.Close()
        Else
            fs = New FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
            sw = New StreamWriter(fs)
            sw.WriteLine()
            sw.WriteLine(logStr.ToString())
            sw.Close()
        End If
    End Sub
End Class

Sunday, 20 May 2012

SQL 2008 Transaction

What Is a Transaction?
A transaction may be a single operation or collection of different operations that succeed or fail together as a whole, thereby ensuring consistency of data should unexpected situation arise. One scenario might be a financial transaction. For example, let's say you buy a car. The single transaction of purchasing item from online store a consists of distinct operations as below:
1.       Select a product.
2.       Select the payment mode.
3.       Enter credential for payment.
4.       Payment transferred
5.       Product ship to customer address.
Skipping any of these steps could cause major angst to one or more of the parties involved. This is a simple example of a set of steps that must always occur together in a consistent manner.
Transactions allow us to ensure consistency in our data through four basic principles. These principles provide a set of rules that must be followed for our transaction to succeed. The four principles help ensure that the state of our data is atomic, consistent, isolated, and durable, regardless of the success or failure of the transaction.

Acid Property

Consider the transaction of purchasing product using debit card to purchase a product worth $200. The data for this transaction can be easily represented in a database as a table with two columns, one holding your AccountID and the other holding your AccountBalance.
To begin with, consider your account balance is $200, so after withdrawing $200, your updated balance should be zero. Also, it makes logical sense that the system must ensure that you have the funds available in your account before the cash can be dispensed. What this means in database terms is that two database queries must be run in this transaction. The first query checks the account balance, as shown here:

SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

If the query returns an AccountBalance value greater than or equal to the requested withdrawal, you can withdraw the cash.
After withdrawing the cash, you must update the account record with the updated balance. To do so, you run an UPDATE query:


UPDATE Account
 SET AccountBalance = AccountBalance – 100
 WHERE AccountID = @AccountID

The two distinct operations in this transaction are the two database queries that support the one operation of withdrawing cash. Both must succeed or fail together in an atomic manner, or the transaction should not be considered complete. Atomicity is the first ACID property.
Now let's change the nature of the transaction a bit. Let's say that the original account balance is $250 and that within the same transaction, the user requests to withdraw $200 and to purchase another product worth $75 to a second account. The first update query will succeed, changing the account balance to $250 – $200 = $50. But the second operation will fail because there won't be enough money left in the account to purhcaser the $75. You therefore need a way to undo the cash withdrawal and return the database to its original state. You cannot leave the database midway through a transaction because it is in an inconsistent state. In a real-world scenario, you would not normally wrap a withdrawal and a transfer in the same transaction, but the point here is to show how data can end up in an inconsistent state between multiple operations. Rolling back operations that cannot be completed in this manner demonstrates the second ACID property, consistency.
Let's say now that the withdrawal and transfer operations are separated into two distinct transactions instead of one but that they happen to run simultaneously. Each transaction will have to check the current balance by attempting to execute a query like this:


SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

Unless your system has explicit checks blocking concurrent reads, both transactions will get the same result: $250. Thus they will both assume that the account has enough funds for the transaction. One transaction will disburse $200, and the other will transfer $75. The result will be an overall deduction of $200 + $75 = $275, even though the account actually has only $250 available. In many systems, especially financial applications, such transactions must be isolated from each other to prevent what is known as a "dirty read." A dirty read happens when data is read at one point in a transition state and the result of the query doesn't reflect the data's true state at the end of the current operation. This brings us to the third ACID property, isolation.
Isolation means that other transactions attempting to request a common resource will be blocked. Blocking, in turn, seriously affects the response times of your application. As it turns out, you'll often want to relax this blocking behavior to suit your application architecture. You can do that by using isolation levels, which we'll discuss later in this chapter.
Last, when you have successfully completed all your operations within a transaction, you don't want to lose the changes made. In other words, system failures must not affect the transactional integrity of your operations. This brings us to the fourth ACID property, durability. Durability means that the systems involved with the transaction will faithfully retain the correct transacted state even if the system sustains catastrophic failure nanoseconds after the transaction completes. Conversely, if the transaction isn't completed because of system failure, it won't be allowed to complete (or be undone) until the system is reset and the application restarted. Transacted steps are retained, and the application can resume operations where it left off with no ill effects (at least from a data consistency perspective).
Let's summarize the four ACID properties before we continue:
  • Atomicity Operations succeed or fail together. Unless all steps succeed, the transaction cannot be considered complete.
  • Consistency Operations leave the database in a consistent state. The transaction takes the underlying database from one stable state to another, with no rules violated before the beginning or after the end of the transaction.
  • Isolation Every transaction is an independent entity. One transaction will not affect any other transaction that is running at the same time.
  • Durability Every transaction is persisted to a reliable medium that cannot be undone by system failures. Furthermore, if a system failure does occur in the middle of a transaction, either the completed steps must be undone or the uncompleted steps must be executed to finish the transaction. This typically happens by use of a log that can be played back to return the system to a consistent state.

Tuesday, 15 May 2012

jQuery Effects And Animation


The jQuery library provides several techniques for adding animation to a web page.
These include simple, standard animations that are frequently used, and the ability to craft sophisticated custom effects.

.hide() Hide the matched elements.
$('#book').hide();
.show() Display the matched elements.
$('#book').show();
$('#clickme').click(function() {
                 $('#book').show('slow', function() {
                                 // Animation complete.
                });
});

.fadeIn() .fadeOut() Display the matched elements by fading them to opaque and back respectively.
$("div").fadeIn(“slow”);
$("div").fadeIn(3000, function () { 
});

.toggle() Display or hide the matched elements.
<p>Hello</p> 
$("p").toggle(); 
$("p").toggle("slow"); 

jQuery Event Handling

Jquery provides methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.



.bind() Attach a handler to an event for the elements.


<input type=“button” id=“myButton” value=“GO”/>
$(‘#myButton').bind('click', function() {
                alert('User clicked on "foo."');
});


Bind Multiple Events
$(‘#myButton').bind('mouseenter mouseleave', function() {
                alert(‘Action Performed');
});


.unbind() Remove a previously-attached event handler from the elements.
$(‘#myButton').unbind('click');

Events


event.preventDefault() If this method is called, the default action of the event will not be triggered.
<a href="http://jquery.com">jquery home page</a> 
$("a").click(function(event) {   
                event.preventDefault(); 
                alert(“default prevented”);
});


.trigger() Execute all handlers and behaviors attached to the matched elements for the given event type.
$('#myButton').bind('click', function() {
                alert($(this).text());
});
$('#myButton').trigger('click');

.live() Attach a handler to the event for all elements which match the current selector, now and in the future.
<span class=“clickme”> CLICK ME</span>
$('.clickme').live('click', function() {
                 // Live handler called.
});
$('body').append('<div class="clickme">Another target</div>');


.die() Remove all event handlers previously attached using .live() from the elements.
$('.clickme').die('click‘);

Few event methods available in jquery
.blur()
.change()
.click()
.dblclick()
.keydown()
.keypress()
.keyup()
.mousedown()
.mouseenter()
.mousemove()
.mouseout()
.mouseover()
.mouseup()

Usage:
$('#myButton').dblclick(function() {
                alert('Handler for .mousedown() called.');
});

jQuery DOM Manipulation

.html() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").html();  //Output <b>Demonstration Box</b>

.text() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").text();  //Output Demonstration Box

.val() Get the current value of the first element in the set of matched elements
Ex: <input type=“text” id=“uname” value=“Johnny”/>

$(“uname").val();  //Output Johnny

.append() Insert content, specified by the parameter, to the end of each element in the set of matched elements.

<p>I would like to say: </p>

<script>$("p").append("<strong>Hello</strong>");</script>

Output : <p>I would like to say: <strong>Hello</strong></p>

.prepend() Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

<p>I would like to say: </p>
<script>$("p").prepend("<strong>Hello</strong>");</script>
Output : <p><strong>Hello</strong> I would like to say:</p>

<div>
                <span>One</span>
                <p>Two</p>
                <span>Three</span>
</div>
.remove() Remove the set of matched elements from the DOM.
$(“div”).remove(“p”);
Output:
<div>
                <span>One</span>
                <span>Three</span>
</div>
.empty() Remove all child nodes of the set of matched elements from the DOM.
$(“div”).empty();
<div>
</div>

<input type=“text” id=“mydata” style=“font-size:10px;”/>

.attr() Get or Set the value of an attribute for the first element in the set of matched elements.
$(“#mydata”).attr(“style”)  // Output : font-size:10px;
$(“#mydata”).attr(“name”,”mynode”) 
// Output : <input type=“text” id=“mydata” name=“mynode” style=“font-size:10px;”/>


 .removeAttr() Remove an attribute from each element in the set of matched elements.
$(“#mydata”).removeAttr(“style”)
//Output : <input type=“text” id=“mydata” />

Dom nodes can be created in Jquery using the $ or jquery()
$(“<div>This is a div element</div>”)
$(“<input></input>”).attr(“type”,”text”).attr(“name”,”mydata”)
The above is equivalent to <input type=“text” name=“mydata”/>
$(“<span><b>Hello world</b></span>”)