Saturday, June 1, 2013

Best Code practice C#

Use int.TryParse( ) to keep away exception .
Convert.Int32 throws an exception of "System.FormatException" when the input parameter is wrong .

Example

If we are converting a QueryString value to integer and the QueryString value is "de8913jhjkdas", then -
int employeeID = 0;
employeeAge = Convert.ToInt32(Request.QueryString.Get("Userid")); //Here it will throw an Exception.

int employeeAge = 0;
int.TryParse(Request.QueryString.Get("Userid");, out employeeAge); //Here it will not throw any Exception.

You can also use bool.TryParse, float.TryParse, double.TryParse, etc for converting into other datatypes.



Convert.ToString() V/S obj.ToString()



Use Convert.ToString(), because if you are using obj.ToString() and the object(obj) value is null it will throw an excetion of type "System.NullReferenceException".
The cause of the exception is null doesn't have a method called ToString().
Response.Write("Name : " + Session["User_Name"].ToString());        //Here it will throw an Exception if Session["User_Name"] is null.
Response.Write("Name : " + Convert.ToString(Session["User_Name"])); //Here it will not throw any Exception.
 String.Empty V/S ""


If you want to check whether a string is empty or not then use String.Empty instead of "", because "" will create a new object in the memory for the checking while String.Empty will not create any object, because Empty is a read-only property of String class.
So its better to use if("Devi" == String.Empty) instead of if("Devi" == "").
You can also use if("Devi".Length == 0) for doing the same thing but if the string is null then it will throw an exception of type "System.NullReferenceException".
 
 String.IsNullorEmpry() V/S ("" || null)


Suppose you want to check a string for both its emptiness and nullability then its better to use String.IsNullOrEmpty() instead of ("" || null). Because "" will create a new object but String.IsNullOrEmpty() will not do so.
So its better to use if(String.IsNullOrEmpty("Devi")) instead of if("Devi" == "" || "Devi" == null)

Wednesday, May 15, 2013

Facebook Login and friend list - Post on User Wall and Friends Wall javascript SDK

 Facebook Login and friend list - Post on User Wall and Friends Wall javascript SDK

<html>
<head>
    <title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

</head>
<body>

<script>

// publish to friend wall
function postonwall(src){
         FB.init({
            appId:'Application ID', cookie:true,
            status:true, xfbml:true
         });
var str=src;
var n=str.split("/");

         FB.ui({ method:'feed',from:'User ID',to:n[3] ,
            message: ''},

function(response) {
    if (response && response.post_id) {
     
    } else {
     
    }
  }
);
}
 

</script>


 <script>

 // Post on User Timeline

 
      FB.init({appId: "Application ID", status: true, cookie: true});

      function postToFeed() {

        // calling the API ...
        var obj = {
          method: 'feed',
          redirect_uri: 'http://localhost',
          link: 'https://developers.facebook.com/docs/reference/dialogs/',
          picture: 'http://fbrell.com/f8.jpg',
          name: 'Facebook Dialogs',
          caption: 'Reference Documentation',
          description: 'Using Dialogs to interact with users.'
        };

        function callback(response) {
          document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
        }

        FB.ui(obj, callback);
      }
  
    </script>


<script>
function publish_to_wall(){
FB.ui({ method: 'stream.publish', message: 'This is a simple post to appshack.tv' });
}
</script>

    <script>
// Load the SDK Asynchronously
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));

// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId: 'Application ID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true  // parse XFBML
});

// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
        FB.api('/me', function(me)
        {
        document.getElementById('Id').innerHTML = me.id;
        document.getElementById('auth-displayname').innerHTML = me.name;
        document.getElementById('Email').innerHTML = me.email;
        document.getElementById('link').innerHTML = me.link;
        document.getElementById('locale').innerHTML=me.locale;
        document.getElementById('DOB').innerHTML = me.birthday;
        document.getElementById('profileImg').src = uid;
        document.getElementById('Gender').innerHTML = me.gender;      
      
      
      
       FB.api('/me/friends', function(response)
       {     
        for(i=0;i<response.data.length;i++)
            {
                $(document.createElement("img")).attr({ src: 'https://graph.facebook.com/'+response.data[i].id+'/picture', title: response.data[i].name,onClick:'postonwall(this.src)'}).appendTo('.divContainer');
            }
        });
      
      
        })
        document.getElementById('auth-loggedout').style.display = 'none';
        document.getElementById('auth-loggedin').style.display = 'block';
        }
        else
        {
            // user has not auth'd your app, or is not logged into Facebook
            document.getElementById('auth-loggedout').style.display = 'block';
            document.getElementById('auth-loggedin').style.display = 'none';
        }});
        $("#auth-logoutlink").click(function() { FB.logout(function() { window.location.reload(); }); });
        }
    
    </script>

    <h1>
        Facebook Login Authentication Example</h1>
    <div id="auth-status">
        <div id="auth-loggedout">
            <div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">
                Login with Facebook</div>
        </div>
        <div id="auth-loggedin" style="display: none; border: solid 1px #000; width: 231px;
            height: auto;">
            <img id="profileImg" width="100px" height="100px" onClick="postToFeed()"  /><a href="#" id="auth-logoutlink"
                style="float: right; font-weight: bold; text-decoration: none;">logout</a>
            <br />
            <b>User-ID :</b><span id="Id"></span>
            <br />
            <b>Name :</b><span id="auth-displayname"></span><br />
            <b>Gender: </b><span id="Gender"></span>
            <br />
            <b>locale: </b><span id="locale"></span>
            <br />
            Your Date of Birth :, <span id="DOB"></span><br/>
            <br />
            <b>Email: </b><span id="Email"></span>
            <br />
            <b>link: </b><span id="link"></span>
            <br />
        </div>
        <div class="divContainer">              
        </div>
    </div>
</body>
</html>

Tuesday, April 30, 2013

Google page rank class C#

Add this Class in project

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for GooglePR
/// </summary>
public class GooglePR
{
    public GooglePR()
    {

    }
    private const UInt32 myConst = 0xE6359A60;
    private static void Hashing(ref UInt32 a, ref UInt32 b, ref UInt32 c)
    {
        a -= b; a -= c; a ^= c >> 13;
        b -= c; b -= a; b ^= a << 8;
        c -= a; c -= b; c ^= b >> 13;
        a -= b; a -= c; a ^= c >> 12;
        b -= c; b -= a; b ^= a << 16;
        c -= a; c -= b; c ^= b >> 5;
        a -= b; a -= c; a ^= c >> 3;
        b -= c; b -= a; b ^= a << 10;
        c -= a; c -= b; c ^= b >> 15;
    }
    public static string PerfectHash(string theURL)
    {
        string url = string.Format("info:{0}", theURL);
        int length = url.Length;
        UInt32 a, b;
        UInt32 c = myConst;
        int k = 0;
        int len = length;
        a = b = 0x9E3779B9;
        while (len >= 12)
        {
            a += (UInt32)(url[k + 0] + (url[k + 1] << 8) +
                 (url[k + 2] << 16) + (url[k + 3] << 24));
            b += (UInt32)(url[k + 4] + (url[k + 5] << 8) +
                 (url[k + 6] << 16) + (url[k + 7] << 24));
            c += (UInt32)(url[k + 8] + (url[k + 9] << 8) +
                 (url[k + 10] << 16) + (url[k + 11] << 24));
            Hashing(ref a, ref b, ref c);
            k += 12;
            len -= 12;
        }
        c += (UInt32)length;
        switch (len)
        {
            case 11:
                c += (UInt32)(url[k + 10] << 24);
                goto case 10;
            case 10:
                c += (UInt32)(url[k + 9] << 16);
                goto case 9;
            case 9:
                c += (UInt32)(url[k + 8] << 8);
                goto case 8;
            case 8:
                b += (UInt32)(url[k + 7] << 24);
                goto case 7;
            case 7:
                b += (UInt32)(url[k + 6] << 16);
                goto case 6;
            case 6:
                b += (UInt32)(url[k + 5] << 8);
                goto case 5;
            case 5:
                b += (UInt32)(url[k + 4]);
                goto case 4;
            case 4:
                a += (UInt32)(url[k + 3] << 24);
                goto case 3;
            case 3:
                a += (UInt32)(url[k + 2] << 16);
                goto case 2;
            case 2:
                a += (UInt32)(url[k + 1] << 8);
                goto case 1;
            case 1:
                a += (UInt32)(url[k + 0]);
                break;
            default:
                break;
        }
        Hashing(ref a, ref b, ref c);
        return string.Format("6{0}", c);
    }
    public int MyPageRank(string MyUrl)
    {
        string HashDomain = PerfectHash(MyUrl);
        string RequestedURL = string.Format("http://toolbarqueries.google.com/" +
               "tbr?client=navclient-auto&ch={0}&features=Rank&q=info:{1}",
               HashDomain, MyUrl);
        try
        {
            HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(RequestedURL);
            string GetResponse = new StreamReader(
                   HttpRequest.GetResponse().GetResponseStream()).ReadToEnd();
            if (GetResponse.Length == 0)
                return 0;
            else
                return int.Parse(Regex.Match(GetResponse,
                       "Rank_1:[0-9]:([0-9]+)").Groups[1].Value);
        }
        catch (Exception)
        {
            return -1;
        }
    }
}



and on code behind page
 protected void Page_Load(object sender, EventArgs e)
    {
GooglePR Gpr = new GooglePR();
Response.write(Gpr.MyPageRank(val));
}

Count GetAlexa Rank

Count GetAlexa Rank

Storing  Alexa value in viewstate and using that viestate as per requirement.

private int GetAlexaRank(string domain)
    {
        var alexaRank = 0;
        try
        {
            var url = string.Format("http://data.alexa.com/data?cli=10&dat=snbamz&url={0}", domain);
            var doc = XDocument.Load(url);
            var rank = doc.Descendants("POPULARITY")
            .Select(node => node.Attribute("TEXT").Value)
            .FirstOrDefault();

            if (!int.TryParse(rank, out alexaRank))
                alexaRank = -1;

        }
        catch (Exception e)
        {
            return -1;
        }
        ViewState["alaska"] = Convert.ToString(alexaRank);
        return alexaRank;

    }

Count google indexed page C#

To perform this task we need htmlagility pack click here and download

Count Google indexed page : -

public void getindexedcount(string url)
    {

        HtmlWeb hw = new HtmlWeb();
        HtmlDocument doc = hw.Load("https://www.google.co.in/search?hl=en&noj=1&q=site:" + url + "");
        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//div[@id='resultStats']"))
        {
            getindex.Text = "Indexes pages Count is :" + link.OuterHtml;
        }
    }