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.