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;
        }
    }

Wednesday, April 23, 2014

Decorating code snippets in blogger

Follow the below steps to highlight you content (code) in blogger posts.

Step 1:

Go to Blogger Dashboard -> Template ->Edit Html
Paste the below code into your Blogger Template inside the <head> </head> tag

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 



Step2:
Use the <pre> tag to highlight your code snippet
Example:
<pre class="brush: csharp">
RequestToken GetRequesttoken()
        {
            var requestToken = (RequestToken)Session["RequestToken"];
            Session.Remove("RequestToken");
            return requestToken;
        }
</pre>
 output looks like:
RequestToken GetRequesttoken()
        {
            var requestToken = (RequestToken)Session["RequestToken"];
            Session.Remove("RequestToken");
            return requestToken;
        }

Google Authentication with ASP.Net

Code download available at the bottom of the post

In this post i would like to share my experience with Google Authentication with Asp.net membership (Forms Authentication)
High level google authentication work flow with ASP.NET membership
1.            Your application requests access and gets an unauthorized request token from Google's authorization server.
2.            Google asks the user to grant you access to the required data.
3.            Your application gets an authorized request token from the authorization server.
4.            You exchange the authorized request token for an access token.

5.            You use the access token to request data from Google's service access servers.

Step 1:
I am using forms authentication for my application. When the user tries to access the application, system will check whether the user is authenticated or not. If the user is unauthenticated he will be redirected to the login screen as shown below. 


 
      
    
    
      
      
    

Step 2:
When your application initially requests access to a user's data, Google issues an unauthorized request token to your application.
If the user is not already logged in, Google prompts the user to log in. Google then displays an authorization page that allows the user to see what Google service data your application is requesting access to.


        /// Step 1: Get a Request Token
        private void MakeRequestForToken()        {
            string consumerKey = "anonymous";
            string consumerSecret = "anonymous";
            // Google requires an additional "scope" parameter that identifies one of the google applications
            string requestTokenEndpoint = "https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/userinfo#email";
            string requestTokenCallback = GetRouteableUrlFromRelativeUrl("GoogleAuth/oAuth/GoogleValidation.aspx/authorizeToken/google/");
            string authorizeTokenUrl = "https://www.google.com/accounts/OAuthAuthorizeToken";

            // Step 1: Make the call to request a token
            var oAuthConsumer = new OAuthConsumer();
            var requestToken = oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint, realm, consumerKey, consumerSecret, requestTokenCallback);
            PersistRequestToken(requestToken);

            // Step 2: Make a the call to authorize the request token
            Response.Redirect(authorizeTokenUrl + "?oauth_token=" + requestToken.Token);
        }
Step 3:
If the user approves your application's access request, Google issues an authorized request token. Each request token is valid for only one hour. Only an authorized request token can be exchanged for an access token, and this exchange can be done only once per authorized request token.


 private void HandleAuthorizeTokenResponse()
        {
            string consumerKey = "anonymous";
            string consumerSecret = "anonymous";
            string token = Request.QueryString["oauth_token"];
            string verifier = Request.QueryString["oauth_verifier"];
            string accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";

            // Exchange the Request Token for an Access Token
            var oAuthConsumer = new OAuthConsumer();

            var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);

            // Google Only - This method will get the email of the authenticated user
            var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/userinfo/email", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
            
            NameValueCollection nvc = StringToNameValueCollection(responseText);

            if (nvc["email"] != "")
            {
                FormsAuthentication.RedirectFromLoginPage(nvc["email"].ToString(), false);
            }

        }
Step 4:
By default, access tokens are long-lived. Each access token is specific to the user account specified in the original request for authorization, and grants access only to the services specified in that request. Your application should store the access token securely, because it's required for all access to a user's data.

Sunday, April 20, 2014

HTML5 Geolocation

Code download available at the bottom of the post

In this tutorial we will use Jquery,Goople Api and HTML5 to capture geolocation
Browser used:Google Chrome

Step 1:
Include the Jquery and Goople maps API as shown below
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>

Step 2:
Add a place holder for the Map
<div id="map"> </div>
Using HTML5 feature we will display the latitude and longitude, so add placeholders for latitude and longitude.
 <div id="lat"></div>
<div id="long"></div>

Step 3:
 Start writing code to capture the Geolocation
<script>
//using navigator (Html 5 feature) to get the Geolocation
x = navigator.geolocation;
x.getCurrentPosition(sucess,failure);

'getCurrentPosition' method has 2 argument, one when the function success and other for failure

If the browser supports HTML5 success method is invoked else the failure method is invoked.
In the failure method we will show a warning message to user as shown below..

function failure()
{
        //Using Jquery we will display the warning message in the lat DIV element.
$('#lat').html("<p>It din't work, co-ordinated not available</p>")
}

Step 4:
We will implement the Success method to display the Geolocation
We use the position variable in the success method to get the latitude and longitude
//Fetch the co-ordinates 
var mylat=position.coords.latitude;
var mylong = position.coords.longitude;
//Display the co-ordinates in the mylat and mylong DIV elements respectively
$('#lat').html(mylat)
$('#long').html(mylong)

Open up Google chrome, you will see the longitude and latitude if successful or the error message in case of unsupported browsers.

Step 5:
Now using the google API we will display the map
//Declare the coords variable to hold the co-ordinates
var coords = new google.maps.LatLng(mylat,mylong);

//Setting up our Google Map
We are going to specify three different parameters
i. Zoom,
ii.Co-ordinates
iii.Type of map (In this case we will define a road map)

var mapOptions = {zoom:16,
center:coords,

mapTypeId:google.maps.MapTypeId.ROADMAP}

//Creating a map
We will feed in 2 arguments, one the element which we want to override and fill our Map div element
Argument 1: document.getElementById("map") //get the div map element
Argument 2: Map settings which we defined earlier

var map=new google.maps.Map(document.getElementById("map"),mapOptions);

Step 6: 
Add some styles to the div element to view the map properly
<style type="text/css">
#map
{
height: 400px;width: 400px;
}
</style>

Step 7:
Add marker to specify the exact location
 //Create a marker
           var marker = new google.maps.Marker({ map: map, position: coords });





Save and open the page in Google Chrome



Note: Please change the browser setting to allow the application to access the geolocations
Browser Setting -> Advance Settings -> Privacy Settings -> Content settings -> Location ........

Download Code




Thursday, April 17, 2014

How to find a column reference in a given database schema

Run the below query
SELECT T.NAME AS TABLE_NAME,SCHEMA_NAME(SCHEMA_ID) AS SCHEMA_NAME,C.NAME AS COLUMN_NAME
FROM SYS.TABLES AS T
INNER JOIN SYS.COLUMNS C ON T.OBJECT_ID = C.OBJECT_ID
WHERE C.NAME LIKE '%User%'
ORDER BY SCHEMA_NAME, TABLE_NAME;

Output:



Wednesday, April 16, 2014

Change default browser in visual studio

Step 1: Right-click on an ASPX page within a Web Project and click "Browse With..."
Step 2: From this dialog you can click Set Default
Step 3: You can add other browsers, like Google Chrome to this dialog via Add

Jquery not working

6 steps to take if your jQuery is not working

1. The file is not there or does not exist

People tend to become upset and/or frustrated (Including me) when something simple doesn’t work, such as jQuery not working. Before you do anything, navigate to your jQuery file and check that it is exactly where it should be.

Also make sure that you have the correct html file open – I have actually tried to load files using the incorrect html, so the path would have been correct if I had the correct html file open. Don’t ever be too proud to check the absolute basics.

2. Incorrect File Path

This is a common problem and it is the first thing I check when I’m having a javascript problem (I actually do step 1 and 2 with my style.css as well). After checking that the file path is correct, I double check by viewing the page source using Firefox, I then click on the .js link. If it opens up the jQuery file (Double check it is opening the correct file) then the destination is correct. If it does not, or it opens a page-not-found, then I know I have a problem with my file path.

3. Script load order

Help! jQuery not working, however it is loading perfectly!!!
Make sure that it is the first script loaded on your page. This is very easy to overlook. The problem exists because browsers understand javascript and not stand alone jQuery snippets. jQuery turns our code into normal javascript code, so that the browsers can interpret what we are saying. Javascript libraries are shortcuts.
If you were to load a library plugin before the library itself has been loaded, the plugin would be seen as bunch of mumbo-jumbo by the browser. This snippet of code means absolute nothing before the library has been loaded.

4. Plugin not working

Plugins malfunction sometimes, for whatever reason; And people sometimes tend to think that jQuery is not working, which isn’t always the case. When it gets this far I think to myself, “Lets get out the big guns”.
Note: Step 1 and 2 can also be applied to CSS problems.
Even though I have tried step 1, step 2 and step 3, I do ANOTHER test to make 100% sure that it is loading properly. 99.999% of the time this is the final test.
Firstly, I make sure there are absolutely NO plugins, other libraries or anything javascript related on my page, except for the jQuery library and a little script I write beneath it.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript">
$(document).ready(function(){ 
         
 $("div").css("border", "3px solid red");
 
});
</script>
This adds a 3px red border to every single div on the page.
If this works, which it really should, the library is loading correctly. You then know that there is something wrong with the plugin(s) and that it is time for more troubleshooting. If you have more than one plugin, try switching the plugin order (This has worked for me on a few occasions), if it is still unsuccessful then remove each plugin and test until something works. Once you find the problem plugin, download it’s latest available version and see if it works.
If the 3px red border does not show up, then it’s time to jump to the next step.

5. Javascript library issues

Do not use multiple javascript libraries simultaneously! There are a few reasons to avoid this even besides the conflicts that could occur. More .js libraries means more html requests and more things to load. It doesn’t matter what .js library you use, use which ever you prefer more but stick with it throughout your project. There are thousands of jQuery plugins, I would say that 99% of the time there is no need for multiple libraries anyway.

6. Javascript disabled/not supported by browser

Make sure you are using a modern browser, and not IE 5.5 or something old and outdated.
It is possible to turn off the javascript support within a browser, and I have had this problem before (I actually turned off javascript support and forgot to turn it back on).
jQuery not working by this point? Try viewing the page with a different modern browser and see if there is any difference or make sure that javascript is enabled within the browser. This is a last resort.

Tips

  • Don’t load two different javascript library versions, only one is ever needed.
  • I have started loading jquery through Google at all times:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
The only downside to doing this that I can think of is if you are working offline (Obviously it won’t load) or if Google goes down for whatever reason.
  • Step 1, 2 and 3 can be applied to CSS files too. The Step 3 load order could refer to the IE specific stylesheets loading before the main one.
  • jQuery not working? Then follow the 6 steps again :)
  • Feel free to comment and ask for help if any is needed.

Friday, April 11, 2014

Difference between HTTP Post and HTTP Get

In an HTTP GET request, key/value pairs are specified in the URL:  

http://Aditya/PageName?value1=foo&value2=bar 

In an HTTP POST request, key/value pairs are sent as part of the HTTP request after the headers.
For example: 

 POST /something HTTP/1.1  Host: server  Content-Length: 21  Content-Type: application/x-www-form-urlencoded 


It's hard to really describe one as being more or less secure than the other, but HTTP POST data is not visible in the URL, and when submitting data to a website, an HTTP POST can usually only be performed as a result of user interaction (for example clicking on a "Submit" button). 

This means a user can't be tricked into visiting a URL like http://Aditya/update_profile?name=I_Test and sensitive data is not exposed in the URL. 

You can also use nonces and other anti-forgery tokens with html forms (which use POST) to prevent other forms of cross-site request forgeries. 

In general, POST should be used for requests that potentially modify state on the server, and GET should be used for read-only operations. 

Thursday, April 10, 2014

Break points in SQL Server

TOGGLE A BREAK POINT
Press F9.

To open the breakpoints window
Press CTRL+ALT_B

To RUN the query/execute the store procedure
Press ALT+F5

Sample break point example below:


Move from one break point to another: Right click on the query window and select ‘Run To Cursor’