Sunday, April 27, 2014

SQL Server 2008 MERGE statement

One Statement for INSERT, UPDATE, DELETE


In earlier versions of SQL Server we had to write separate statements for Insert,update and Delete based on certain conditions but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it.

One of the most important advantage of MERGE statement is all the data is read and processed only once. In previous versions three different statement has to be written to process three different activity (INSERT, UPDATE or DELETE), however using MERGE statement all update activity can be done in one pass of database table. This is quite an improvement in performance of database query.

Syntax of MERGE statement is as following:

MERGE
[ TOP ( expression ) [ PERCENT ] ]
[ INTO ] target_table [ WITH ( ) ] [ [ AS ] table_alias]
USING
ON
[ WHEN MATCHED [ AND ]
THEN ]
[ WHEN NOT MATCHED [ BY TARGET ] [ AND ]
THEN ]
[ WHEN NOT MATCHED BY SOURCE [ AND ]
THEN ]
[ ]
[ OPTION ( [ ,...n ] ) ];


Example:
Let’s create Student Details and StudentTotalMarks and inserted some records.


Student Details:

USE TestDataBase
GO
CREATE TABLE StudentDetails
(
StudentID INTEGER PRIMARY KEY,
StudentName VARCHAR(15)
)
GO
INSERT INTO StudentDetails
VALUES(1,'Aditya')
INSERT INTO StudentDetails
VALUES(2,'MARK')
INSERT INTO StudentDetails
VALUES(3,'SAM')
INSERT INTO StudentDetails
VALUES(4,'JOHN')
INSERT INTO StudentDetails
VALUES(5,'GARY')
GO

StudentTotalMarks:

CREATE TABLE StudentTotalMarks
(
StudentID INTEGER REFERENCES StudentDetails,
StudentMarks INTEGER
)
GO
INSERT INTO StudentTotalMarks
VALUES(1,230)
INSERT INTO StudentTotalMarks
VALUES(2,255)
INSERT INTO StudentTotalMarks
VALUES(3,200)
GO

In our example we will consider three main conditions while we merge this two tables.

Delete the records whose marks are more than 250.
Update marks and add 25 to each as internals if records exist.
Insert the records if record does not exists.
Now we will write MERGE process for tables created earlier. We will make sure that we will have our three conditions discussed above are satisfied.



MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);
GO

There are two very important points to remember while using MERGE statement. 
  •  Semicolon is mandatory after the merge statement. 
  • When there is a MATCH clause used along with some condition, it has to be specified first among all other WHEN MATCH clause.
AS we can see there are 5 rows updated. StudentID 2 is deleted as it is more than 250, 25 marks have been added to all records that exists i.e StudentID 1,3 and the records that did not exists i.e. 4 and 5 are now inserted in StudentTotalMarks.

MERGE statement is very handy improvement for T-SQL developers who have to update database tables with complicated logic. MERGE statement also improves the performance of database as it passes through data only once.

Facebook, Twitter and Google Plus shortcuts keys

Facebook

Facebook shortcut keys are based on browser. Shortcuts for Facebook will vary from browser to browser.
In Firefox, you will need to add a Shift key before the key combinations given below, whereas in Internet Explorer, you need to hit Enter after the combination. Same goes for a Mac, except that for Firefox, you need to press Ctrl instead of Shift. Rest of the keys should be same.
Facebook key combinations

Key     Function

Alt + M Compose new message
Alt + /    Main site search
Alt + 1   Go to home page
Alt + 2   Go to Timeline
Alt + 3   See friends requests
Alt + 4   Go to message inbox
Alt + 5   See all notifications
Alt + 6   Go to Account Settings
Alt + 7   Go to Privacy Settings
Alt + 8   Go to Facebook's Profile Page
Alt + 9   Go to Facebook's Terms of Service
Alt + 0   Go to Facebook Help Center

Twitter

Twitter shortcuts are the easiest to use. Twitter also displays the whole list of shortcuts in a pop-up so you can easily look for the action you want. To bring up this pop-up, simply press the ? key (Shift + /). Here is the list of Twitter shortcuts.

Key     Function

Actions

F              Favorite
R             Reply
T              Retweet
M            New direct message
N             New Tweet
Enter     Open Tweet Details
L              Close all open Tweets

Navigation

?              List of all shortcuts
J              Next Tweet
K             Previous Tweet
Space    Page down
/              Search
.               Go to top and load new Tweets

Timelines

G + H     Go Home
G + C     Go to Connect
G + A     Activity
G + D     Discover
G + R     Mentions
G + L      Lists
G + P     Profiles
G + F      Favorites
G + M    Messages
G + S      Settings
G + U     Go to user

Google Plus

Google Plus also has its share of shortcuts, but they are relatively fewer, and they can only be activated in certain instances, such as when a post or a particular section of the website is in focus. Here are the most commonly used shortcuts for Google plus.

Key     Function

K             Go to previous item in the stream (feed)
J              Go to next item in the stream
Q             Search for people to chat with (when chat windows is active)
Space    Scroll down
Shift + Space      Scroll up
Enter     Start new comment (when focused on a post)
Enter + Tab         End comment
@ or +   Tag someone (start typing a name)


Saturday, April 26, 2014

IPL 2014 live streaming

Watch your favorite teams playing....

Just put the below code in your blog or website

  

Thursday, April 24, 2014

App_Offline.htm feature in ASP.NET 2.0

"App_Offline.htm" feature in ASP.NET 2.0 provides a super convenient way to bring down an ASP.NET application while you make changes to it (for example: updating a lot of content or making big changes to the site where you want to ensure that no users are accessing the application until all changes are done).
  • This is very handy when we do deployments manually.
  • This allows you to remove the locks from those files and replace them, without the need to do a full IISRESET, taking down other sites on the server


How this is implemented?

We just need to put App_Offline.htmfile in root directory of web application and the ASP.NET runtime will detect the existence of  App_Offline.htm, if it exists, then the ASP.NET runtime will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

When all Web site files have been copied, you can delete the App_offline.htm. Once removed, the next request into the application will cause ASP.NET to load the application and app-domain again, and all things will continue to work as normal.

Important points to be considered while implementing “App_offline.htm”

Ø  Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.

Ø  Also ensure that the file is named exactly as it should be. "app_offline.htm" 


  So if you use the app_offline.htm feature, you should make sure you have at least 512 bytes of content within it to make sure that your HTML (instead of IE's friendly status message) shows up to your users.  If you don't want to have a lot of text show-up on the page, one trick you can use is to just add an html client-side comment with some bogus content to push it over 512 bytes. 
 For example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Site Under Construction</title>
</head>
<body>
    <h1>
Under Construction</h1>
<h2>
Gone to Florida for the sun...</h2>
<!--       
    Adding additional hidden content so that IE Friendly Errors don't prevent
    this message from displaying (note: it will show a "friendly" 404
    error if the content isn't of a certain size).
   
    <h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
<h2>
Gone to Florida for the sun...</h2>
-->
</body>
</html>




Parallel programming in c# 4.0

In our daily programming routine we use thread mechanism to parallelize your code to distribute work across multiple processorsTo take advantage of the hardware of today and tomorrow Visual Studio 2010 and the .NET Framework 4 enhance support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools.

Let’s start with a simple concept in parallel programming.

Data Parallelism (Task Parallel Library)

Data Parallelism describes how to create parallel for and foreach loops. In this article we will look into simple for loop in parallel programming world.
In this application I wrote a simple method to calculate the Root of a given number. Let’s look into the executing time of for and Parallel.For loop methods.

The below code took me 16 seconds to execute. I am using 2.8-Ghz dual core 64 bit processor with 4 GB of RAM.

for (int i = 2; i < 20; i++)
            {
                var result = SumRootN(i);
                Console.WriteLine("root {0} : {1} ", i, result);
            }
Instead of a regular for loop I used Parallel.For method and now the execution time got decreased from 16 to 5 seconds

Parallel.For(2, 20, (i) =>
            {
                var result = SumRootN(i);
                Console.WriteLine("root {0} : {1} ", i, result);
            });


When you use the Parallel.For method, the .NET Framework automatically manages the threads that service the loop, so you don’t need to do this yourself. But remember that running code in parallel on two processors does not guarantee that the code will run exactly twice as fast. Nothing comes for free; although you don’t need to manage threads yourself, the .NET Framework still uses them behind the scenes. And of course this leads to some overhead. In fact, if your operation is simple and fast and you run a lot of short parallel cycles, you may get much less benefit from parallelization than you might expect.

Source Code:

namespace ParallelProgramming
{
    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;

    class Program
    {

        static void Main(string[] args)
        {
            var watch = Stopwatch.StartNew();
            
            //
            for (int i = 2; i < 20; i++)
            {
                var result = SumRootN(i);
                Console.WriteLine("root {0} : {1} ", i, result);
            }

            Parallel.For(2, 20, (i) =>
            {
                var result = SumRootN(i);
                Console.WriteLine("root {0} : {1} ", i, result);
            });

            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.ReadLine();
        }

        public static double SumRootN(int root)
        {
            double result = 0;
            for (int i = 1; i < 10000000; i++)
            {
                result += Math.Exp(Math.Log(i) / root);
            }
            return result;
        }
    }