Thursday 29 December 2011

How to Tweet on user Profile from asp.net website


Before we start  add Your application  to  twitter and get consumer ids

First Download Twitterizer from http://www.twitterizer.net/
and add that dlls to Your Project

Now place Two buttons  say authorization and Tweet buttons  and  text box say tweet text on web form
 Now in Authorization Button click event use this method
  protected void btnauthorize_Click(object sender, EventArgs e)
        {
           


            var consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
            var consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];
            string callbackadress = "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + HttpContext.Current.Request.Url.PathAndQuery;

            //If User is not valid user
            if (Request.QueryString["oauth_token"] == null)
            {
                //Step 1: Get Request Token
                OAuthTokenResponse RequestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callbackadress);

                //Step 2: Redirect User to Requested Token
                Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" + RequestToken.Token);
            }
        
        }
After authenticating that user
 we will be redirected To our url and place this code on page load vent to read user information


 protected void Page_Load(object sender, EventArgs e)
        {
          
            if (!string.IsNullOrEmpty(Request["oauth_verifier"]) && !Page.IsPostBack)
            {
                Readuserinformation();
            }
        }
        public void Readuserinformation()
        {
         
            var consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            var consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];
            string Oauth_Token = Request.QueryString["oauth_token"].ToString();
            var accessToken = OAuthUtility.GetAccessToken(consumerKey,
                                                  consumerSecret,
                                                  Oauth_Token, "");
          //Save this tokens For Tweeting

            string Token: = accessToken.Token;
            string TokenSecrt= accessToken.TokenSecret;
            string userid= accessToken.UserId;

        }
Now in tweetbutton click event call this method


  protected void btnTweet_Click(object sender, EventArgs e)
        {
         
            try
            {

                var consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
                var consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];

                OAuthTokens accessToken = new OAuthTokens();
//Use the access token we got  after Reading user information
                accessToken.AccessToken = "xxxxxxx";
                accessToken.AccessTokenSecret = "xxxxxx";
                accessToken.ConsumerKey = consumerKey;
                accessToken.ConsumerSecret = consumerSecret;

                 

                Twitterizer.TwitterStatus.Update(accessToken, tbxTweet.Text);
            }
            catch (Exception ex)
            {


            }


        }
Happy coding

Monday 26 December 2011

How to find nodes on tree view and expand them


Place searchtextbox,Button on webform which contains Treeview



In the search button click event call this method


 private void FindInTreeView(TreeNodeCollection tncoll, string strNode)
       {
         foreach (TreeNode tnode in tncoll)
    {
        if (tnode.Text.ToLower() == strNode.ToLower())
        {
            tnode.Selected = true;
         
                tnode.Expand();
                tnode.ExpandAll();
                if (tnode.Selected == true)
                {
                    searchtextbox.Text = null;
                }
          
           
         
        }
        else
        {
            tnode.Selected = false;
          
          
        }
        FindInTreeView(tnode.ChildNodes,strNode);
    }

import Excel data to Gridview in c#

Place one file upload control and grid view on webform
In file upload click event place the below code
        protected void btnUpload_Click(object sender, EventArgs e)
        {
          if (FileUpload1.HasFile)
            {
                string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                //string FolderPath = ConfigurationManager.AppSettings["FolderPath"] + "\\";
                string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
                string path = Path.GetFullPath(FileName);
               //string FilePath = Server.MapPath(FolderPath + FileName);
               // string FilePath = Server.MapPath(("App_Data/" + Extension));
               string SaveLocation = FolderPath + "ExcelUpload4";
               FileUpload1.SaveAs(SaveLocation);
               if (grdbom_detail.Rows.Count == 0)
               {
                   Import_To_Grid(SaveLocation, Extension);
               }
            

        }

//Method to return data to gridview
     private void Import_To_Grid(string FilePath, string Extension)
    {
       
        string conStr="";

       
             if (Extension == ".xls" || Extension == ".xlsx")
        {
            switch (Extension)
            {
                case ".xls": //Excel 97-03
                    conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";;Extended Properties=Excel 8.0;";
                    break;
                case ".xlsx": //Excel 07
                    conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";;Extended Properties=Excel 8.0;";
                    break;

            }
            //string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";;Extended Properties=Excel 8.0;";
            //conStr = String.Format(conStr, FilePath);


            OleDbConnection connExcel = new OleDbConnection(conStr);
            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt1 = new DataTable();
            cmdExcel.Connection = connExcel;

            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
          
            int y = dtExcelSchema.Rows.Count;

            connExcel.Close();
          
            {
                //Read Data from First Sheet
                connExcel.Open();
                cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
                oda.SelectCommand = cmdExcel;
                oda.Fill(dt1);
              
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                   
                   
                   //Loop throgh elements and add to list
                }
                connExcel.Close();

                //Bind Data to GridView
                // GridView1.Caption = Path.GetFileName(FilePath);
                grd_detail.DataSource = list;
                grd_detail.DataBind();
                SaveToSession("Ex_object", er);
            }
           
        }
        else
        {
            string sMessage = " Please Load .xls and .xslx type Files";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + sMessage + "')</script>", false);
        }
    }

posting on facebook wall from asp.net website

iam assuming You have already  Registered Your Application  with facebook and got client id
First place Two buttons For Authorization and Posting on webform with labels on web form
In authorization button click Event Write the following code
We set Offline access ,Publish stream Permission   of users to post on walls.
protected void Authorization_Click(object sender, EventArgs e)
        {
          
       //     Your Website Url which needs to Redirected
            string callbackUrl = "xxxxxxx";
         
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope=offline_access,publish_stream,read_stream,publish_actions", ConfigurationManager.AppSettings["FacebookClientId"], callbackUrl));
          

        }
After user Authorizes  U will Receive Oauth code.use the below  code to get  Access token For that user

           https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
     client_secret=YOUR_APP_SECRET&code=The code U got from face book after Redirecting

        
This will Return Access token save it For Further use
Now its time For posting .place the below code in  post button click event


//Paste the Following variables
            public string Message = "";

        public string AccessToken = "";


        public string FacebookProfileID = "";

        public string ErrorMessage { get; private set; }

        public string PostID { get; private set; }

           protected void BtnPublish_Click(object sender, EventArgs e)
        {
postonwall();
}

//Method   used To post Feed

   public static string Append(string key, string value)
        {
            return string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));
        }

     

 

            public void Post()
            {

               

                var url = "https://graph.facebook.com/me/feed?" +
                    Append("access_token", this.AccessToken);

            

                var parameters = ""

                    + Append("name", "name")

                    + Append("link", "http://link.com")

                    + Append("caption", "a test caption")

                    + Append("description", "a test description")

                 

                    + Append("privacy", "{\"value\": \"EVERYONE\"}")

                    + Append("message", this.Message);

          
                var webRequest = WebRequest.Create(url);

                webRequest.ContentType = "application/x-www-form-urlencoded";

                webRequest.Method = "POST";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);

                webRequest.ContentLength = bytes.Length;

                System.IO.Stream os = webRequest.GetRequestStream();

                os.Write(bytes, 0, bytes.Length);

                os.Close();

                // Send the request to Facebook, and query the result to get the confirmation code

                try
                {

                    var webResponse = webRequest.GetResponse();

                    StreamReader sr = null;

                    try
                    {

                        sr = new StreamReader(webResponse.GetResponseStream());

                        this.PostID = sr.ReadToEnd();

                    }

                    finally
                    {

                        if (sr != null) sr.Close();

                    }

                }
                catch (WebException ex)
                {

                   

                    StreamReader errorStream = null;

                    try
                    {

                        errorStream = new StreamReader(ex.Response.GetResponseStream());

                        this.ErrorMessage = errorStream.ReadToEnd();

                    }
                    finally
                    {

                        if (errorStream != null) errorStream.Close();

                    }

                }

            }
            public void postonwall()
            {
            

                this.Message = "Test message ";

                this.ArticleTitle = "New Arcticle";

                this.AccessToken = "xxxxxxxx";

                this.Post();

               

            }




The above code Returns post id if posted successfully.
Note: Access tokens are different For Different users
That’s it We posted a new post on users wall
Happy coding



Sharing on facebook,Twitter,Linkedin using Customized url

Sharing on facebook,Twitter,Linkedin  using  Customized url

To Accomplish this place three buttons on Webform  called Twitter,facebook,Linkedin buttons

In the Twitter button click event

Protected void Twitter_click(object sender, EventArgs e)

{

//path of custimized url

string Customizedurl="";

 string twitterUrl = string.Format("http://www.twitter.com/share?url={0}", Customizedurl);

Response.Redirect(twitterUrl );

}

In the  facebook button click event

Protected void facebook_click(object sender, EventArgs e)

{

//path of custimized url

string Customizedurl="";

   string facebookurl = string.Format("http://www.facebook.com/share.php?url={0}", Customizedurl);

Response.Redirect(facebookurl );

}



In the Linkedin button click event

Protected void linkedin_click(object sender, EventArgs e)

{

//path of custimized url

string Customizedurl="";

   string linkedinurl = string.Format("http://www.linkedin.com/shareArticle?url={0}", Customizedurl);

Response.Redirect(linkedinurl);

}

open new window in asp.net website

How to open new window in asp.net website

Use this code to open new window

 const string windowName = "";
            //params for a window

            const string windowParams = "height=760,width=760,status=yes,toolbar=no,menubar=no,location=no,resizable,name=Notes";
 private void OpenNewWindow(string url, string windowName, string windowParams)
        {
            if (url == null)
                throw new ArgumentNullException("url");
            if (windowName == null)
                windowName = "";
            if (windowParams == null)
                windowParams = "";
            string scriptCode =
                string.Format(
                    "<script>window.open('{0}','{1}','{2}');</script>",
                    url, windowName, windowParams);
            //write the script out to HTTP Response stream
            Response.Write(scriptCode);
        }
after pasting this code in Your webform  call this method  to open new window
like  below


  OpenNewWindow(url, windowName, windowParams);