Wednesday, 7 September 2011

how to post on user's wall in facebook

for posting on users wall we have to give publish_stream in scope.for all scope and permission in facebook you can follow the link:
http://developers.facebook.com/docs/reference/api/permissions/


callback.aspx.cs:
--------------------------------------------------
oAuthFacebook oAuth = new oAuthFacebook();
if (Request["code"] != null)
        {
            try
            {
                oAuth.AccessTokenGet(Request["code"]);
                Api api = new Api(oAuth.Token);
                User u = api.GetUser();
                api.PostFeed("Message", "Picture Path on web", "Link", "Name", "Caption", "Description");
              }
             catch
            {

             }
    }


Retrieving facebook contacts

First you need to create an app on facebook app from following url  http://developers.facebook.com/
 

Click on app option and you will get following window from where you can create new application on facebook by clicking on create new app button.


after cliccking on create new app button you will get following window 

 

Give your app name and check the checkbox for terms and conditions of facebook. after that click on continue button.

by that your app will be created on facebook and you will get app id and secret which we have to use in our code.



I am using facebook graph api  to import facebook contacts in our asp.net application. we need to include facebookGraphApi.dll and Newtonsoft.json.dll in your project. after that you need to add config section in web.config file.

<configuration>
 <configSections>
    <section name="FacebookGraphToolkitConfiguration" type="Facebook_Graph_Toolkit.FacebookGraphToolkitConfiguration"/>
  </configSections>
  <FacebookGraphToolkitConfiguration FacebookAppID="yourAppKey" FacebookAppSecret="YourAppSecret"/>

</configuration>

add oAuthFacebook.cs file in your project which contains:
-------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.IO;
using System.Net;

public class oAuthFacebook
{
    public enum Method { GET, POST };
    public const string AUTHORIZE = "https://graph.facebook.com/oauth/authorize";
    public const string ACCESS_TOKEN = "https://graph.facebook.com/oauth/access_token";
    public const string CALLBACK_URL = "http://www.yourSite.com/CallBack.aspx";

    private string _consumerKey = "";
    private string _consumerSecret = "";
    private string _token = "";

    public oAuthFacebook()
    {
    }

    #region Properties

    public string ConsumerKey
    {
        get
        {
            if (_consumerKey.Length == 0)
            {
                _consumerKey = "xxxxxxxx"; //Your application ID
            }
            return _consumerKey;
        }
        set { _consumerKey = value; }
    }

    public string ConsumerSecret
    {
        get
        {
            if (_consumerSecret.Length == 0)
            {
                _consumerSecret = "xxxxxxxxxxxxxxxxxxxxxxx";//Your application secret
            }
            return _consumerSecret;
        }
        set { _consumerSecret = value; }
    }

    public string Token { get { return _token; } set { _token = value; } }

    #endregion

    /// <summary>
    /// Get the link to Facebook's authorization page for this application.
    /// </summary>
    /// <returns>The url with a valid request token, or a null string.</returns>
    public string AuthorizationLinkGet(string url)
    {
        return string.Format("{0}?client_id={1}&redirect_uri={2}", AUTHORIZE, this.ConsumerKey, url);
    }

  
    public void GetAccessToken(string authToken,string url)
    {
        this.Token = authToken;
        string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}",
        ACCESS_TOKEN, this.ConsumerKey, url, this.ConsumerSecret, authToken);

        string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);

        if (response.Length > 0)
        {
            //Store the returned access_token
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs["access_token"] != null)
            {
                this.Token = qs["access_token"];
            }
        }
    }

    public void AccessTokenGet(string authToken)
    {
        this.Token = authToken;
        string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}",
        ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);

        string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);

        if (response.Length > 0)
        {
            //Store the returned access_token
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs["access_token"] != null)
            {
                this.Token = qs["access_token"];
            }
        }
    }

    /// <summary>
    /// Web Request Wrapper
    /// </summary>
    /// <param name="method">Http Method</param>
    /// <param name="url">Full url to the web resource</param>
    /// <param name="postData">Data to post in querystring format</param>
    /// <returns>The web server response.</returns>
    public string WebRequest(Method method, string url, string postData)
    {

        HttpWebRequest webRequest = null;
        StreamWriter requestWriter = null;
        string responseData = "";

        webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = method.ToString();
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.UserAgent = "[You user agent]";
        webRequest.Timeout = 20000;

        if (method == Method.POST)
        {
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //POST the data.
            requestWriter = new StreamWriter(webRequest.GetRequestStream());

            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }

            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }
        }

        responseData = WebResponseGet(webRequest);
        webRequest = null;
        return responseData;
    }

    /// <summary>
    /// Process the web response.
    /// </summary>
    /// <param name="webRequest">The request object.</param>
    /// <returns>The response data.</returns>
    public string WebResponseGet(HttpWebRequest webRequest)
    {
        StreamReader responseReader = null;
        string responseData = "";

        try
        {
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }

        return responseData;
    }
}

-------------------------------------------------------------------------------------

Default.aspx:

now create a signIn button like:
<body>
<input id="btnFBSignIn" type="button" value="Facebook SignIn" onclick="javascript:FBSignIn();"/>
</body>

<script type="text/javascript">
        function FBSignIn() {
            top.location.href = "https://graph.facebook.com/oauth/authorize?client_id=YOURCLIENTID&redirect_uri=YOURREDIRECTURL&scope=publish_stream,email,offline_access";
        }
 </script>

NOTE: your YOURREDIRECTURL must be same as which you have specified while creating app in facebook and OAuthFacebook.cs file.

After that when you will click on this sign in button it will redirect to facebook login and then it will ask for the permissions which you have specified in scope in script if user allow the permission it will redirect to that page which you have specified in your script as well as in OAuthFacebook.cs file.In my case it is callback.aspx.
-----------------------------------------------------------------------------
callback.aspc.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook_Graph_Toolkit.GraphApi;----dont forget to include it.


protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["code"] != null)
        {
            getFacebookProfile();
        }
    }

private void getFacebookProfile()
    {      
    string fullName, facebookId, email, photoPath = "", friendId, friendName;

        oAuthFacebook oAuth = new oAuthFacebook();

        if (Request["code"] == null)
        {

            oAuth.AccessTokenGet(Request["code"]);

        }
        else
        {
            try
            {
                oAuth.AccessTokenGet(Request["code"]);
                Api api = new Api(oAuth.Token);
-------------------------------------------------------
You can get user profile with this user object :

                User u = api.GetUser();
                facebookId = api.UserID;
                fullName = u.first_name + " " + u.last_name;
                email = u.email;
                photoPath = api.GetPictureURL(u.id);
----------------------------------------------------------
user friend list

                IList friends = (IList)api.GetFriends();
                int k = 1;
                foreach (Facebook_Graph_Toolkit.FacebookObjects.NameIDPair pair in friends)
                {
                    friendId = pair.id;
                    friendName = pair.name;
                }
-------------------------------------------------------              
            }
            catch
            {
            }
        }
    }

Sunday, 29 May 2011

Creating Pie-Chart From Telerik RadChart In Wpf



Drag and Drop A radChart Control in your Xaml file
 <telerik:RadChart Name="radChartDemo" Width="400" Height="400" HorizontalAlignment="Left" VerticalAlignment="Top" />

In Xamal.cs Create User defined method LoadChart() like this-

        private void loadChart()
        {
            DataTable tbl = new DataTable();
            DataColumn col = new DataColumn("Value");
            col.DataType = typeof(int);
            tbl.Columns.Add(col);
            col = new DataColumn("ExcerciseType");
            col.DataType = typeof(string);
            tbl.Columns.Add(col);

            tbl.Rows.Add(new object[] { 30, "ExerciseA" });
            tbl.Rows.Add(new object[] { 60, "ExerciseB" });
            tbl.Rows.Add(new object[] { 10, "ExerciseC" });


            SeriesMapping seriesMapping = new SeriesMapping();
            seriesMapping.SeriesDefinition = new PieSeriesDefinition();

            ItemMapping itemMapping = new ItemMapping();
            itemMapping.DataPointMember = DataPointMember.YValue;
            itemMapping.FieldName = "Value";
            seriesMapping.ItemMappings.Add(itemMapping);

            itemMapping = new ItemMapping();
            itemMapping.DataPointMember = DataPointMember.LegendLabel;
            itemMapping.FieldName = "ExcerciseType";
            seriesMapping.ItemMappings.Add(itemMapping);

            radChartDemo.SeriesMappings.Add(seriesMapping);

            //RadChart1.DefaultSeriesDefinition = new PieSeriesDefinition();
            radChartDemo.ItemsSource = tbl;

        }
call LoadChart() method in Class constructor and you will see a pie chart at runtime.



Creating A Window Service in C#

To Create A window Service Just Go To Your Visual Studio Click On New projects Select Windows Option from Left Side and select Window Service from Right side window

When You will Go to Code View You will Find The Code window like

Create A new Class in coding called Window Service which will inherite installer class.

 [RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {

        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;

            //# Service Information
            serviceInstaller.DisplayName = "Your Service Name";
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            // This must be identical to the WindowsService.ServiceBase name
            // set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "Your Service Name";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }

Create Your user defined method MyMethod() do your stuff there and call it from OnStart() Method.
Now For Installing the service open VS Command Prompt.and go to path where this service exe file is present.it will be in bin\debug folder.
Write The command for Installing InstallUtil /i yourServiceName.exe 
when you will execte this command you will find window like
Now Your Service will be created you can see from service Command from RUN
command for Uninstalling The service InstallUtil /u YourServiceName.exe
 

How To Make a Job In sql Server

Go To Sql serever 2008. For Creating a new job Go to Sql Server Agent and Job folder Right Click on that Click on New job

When You Will Click On New Job You Will Find A window Like-
Give The name of job and description of Job.Then Click On Steps Option on left Side Window
Click On New Button.You Will find This Window
Just Give Step name.Choose Database From Drop Down Write Your Querry In the command Multiline textbox or call sp From there and ckick on ok.After Clicking On Ok Just select Schedules option from left side you will find this window. click on new.
you will find this window
Just Set Time And day to run the Job.and click on ok.Your Job Is Completed





 

How To Send EMail From Sql Server

exec msdb.dbo.sp_send_dbmail @profile_name='Profile From which U want To send Mail',
@recipients='Email Id To Which U Want To Send Email',
@subject= 'Your Subject',
@body='Your Message'

Monday, 2 May 2011

Order Of Elements in Hash Table

Remember that a Hashtable represents a collection of key/value pairs that are organized based on the hash code of the key, and when a element is added to the Hashtable it's stored based on the hash code of the key, and the elements don't preserves the order based in their insertion to the Hashtable's "bag".
As we Know that when an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. We can get the Hash Code with GetHashCode() method.
If you want that the items contained in a collection always be "sorted" you need to use a SortedList instead a HashTable. If you don need the items sorted then use a HashTable, beacuse it's more faster than a SortedList obtaining a value from their "bag". For ex-


class Program
    {
        static void Main(string[] args)
        {

            Hashtable ht = new Hashtable();
         
            ht.Add("ht01", "DotNetGuts");
            ht.Add("ht02", "EasyTutor.2ya.com");
            ht.Add("ht03", "DailyFreeCode.com");
            Console.WriteLine("\nht01 hash code= " + "ht01".GetHashCode().ToString() + "\n\n" +
                "ht02 hash code= " + "ht02".GetHashCode().ToString() +
                "\n\n" + "ht01 hash code= " + "ht03".GetHashCode().ToString() + "\n\n");
            Console.WriteLine("..........Hash Table Items..............\n");
            foreach (DictionaryEntry entry in ht)
            {
                Console.WriteLine("{0}\t{1}\n", entry.Key, entry.Value);
            }

            Console.ReadKey();
            Console.ReadLine();
        }
}

So If you want that the items contained in a collection always be "sorted" you need to use a SortedList instead a HashTable.

Diffrent Algorithams are used to generate the hash code one of the algorithim is MD5 Hash.


        public static string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }