Wednesday, 19 June 2013

Twitter API Authentication -- OAuth v 1.1

You can use following class to get the Tweets from from Twitter API v 1.1 using the oAuth.  you should perform following steps.

 Step1:

Login your Developer account on twitter website by using following link.

https://dev.twitter.com/user/login

Step2:

Click on the My Applications on the user profile as shown in following pic.

 



Step3:

Click on the Create New Application button. Fill the form and save the information as shown in following figure

 



Step4:

It will display the list of your created applications as shown in following figure.. so select your application so select your application , it will show the consumer key and consumer secret as shown in following figure.




Step5:

 Use following code to get tweets.

Twitter OAuth is based on four tokens generally referred to as consumer key and consumer secret



public class ManageTweets
    {
        public string OAuthConsumerKey { get; set; }
        public string OAuthConsumerSecret { get; set; }
        public string OAuthUrl { get; set; }
                     
        public DataTable GetTweetsListFromTwitter()
        {

            DataTable dataTable =TweetsDataTable();
            var timeLineJson = string.Empty;
            var oAuthConsumerKey = OAuthConsumerKey;
            var oAuthConsumerSecret = OAuthConsumerSecret;
            var oAuthUrl = OAuthUrl;
           
          
            //var screenname = "yourscreenname";
            // Do the Authenticate
            var authHeaderFormat = "Basic {0}";

            var authHeader = string.Format(authHeaderFormat,
                 Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
                        Uri.EscapeDataString((oAuthConsumerSecret)))
                        ));

            var postBody = "grant_type=client_credentials";

            System.Net.HttpWebRequest authRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(oAuthUrl);
                        authRequest.Headers.Add("Authorization", authHeader);
            authRequest.Method = "POST";
            authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            authRequest.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;

            using (System.IO.Stream stream = authRequest.GetRequestStream())
            {
                byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
                stream.Write(content, 0, content.Length);
            }

            authRequest.Headers.Add("Accept-Encoding", "gzip");

            System.Net.WebResponse authResponse = authRequest.GetResponse();
            // // deserialize into an object
            TwitAuthenticateResponse twitAuthResponse;
            using (authResponse)
            {
                using (var reader = new System.IO.StreamReader(authResponse.GetResponseStream()))
                {
                    var objectText = reader.ReadToEnd();
                    //objectText = objectText.Replace("{\"","");
                    //string[] arr = objectText.Split(':');
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    twitAuthResponse = js.Deserialize<TwitAuthenticateResponse>(objectText);
                }
            }

            // Do the timeline
            var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
            timelineUrl = string.Format(timelineFormat, screenname);

          

            System.Net.HttpWebRequest timeLineRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(
timelineUrl );
            if (!string.IsNullOrEmpty(ProxyURL))
            {
                timeLineRequest.Proxy = webproxy;
            }
            var timelineHeaderFormat = "{0} {1}";
            timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
            timeLineRequest.Method = "Get";
            System.Net.WebResponse timeLineResponse = timeLineRequest.GetResponse();

            using (authResponse)
            {
                using (var reader = new System.IO.StreamReader(timeLineResponse.GetResponseStream()))
                {
                    timeLineJson = reader.ReadToEnd();
                }

                Newtonsoft.Json.Linq.JArray jsonDat = Newtonsoft.Json.Linq.JArray.Parse(timeLineJson);

                for (int x = 0; x < jsonDat.Count(); x++)
                {
                    Newtonsoft.Json.Linq.JObject tweet = Newtonsoft.Json.Linq.JObject.Parse(jsonDat[x].ToString());
                    string created_at = tweet["created_at"].ToString();
                    string tweettext = tweet["text"].ToString();
                    string profile_image_url_https = tweet["user"]["profile_image_url_https"].ToString() ;
                    dataTable.Rows.Add(tweettext.Replace("\"", ""), profile_image_url_https.Replace("\"", ""), created_at.Replace("\"", ""));
                    //whatever else you want to look up
                }

            }
            return dataTable;
        }
      
        private DataTable TweetsDataTable()
        {
            DataTable tweetsTable = new DataTable();
            tweetsTable.Columns.Add("Tweet_Text", typeof(string));
            tweetsTable.Columns.Add("Department_Logo", typeof(string));
            tweetsTable.Columns.Add("createdAt", typeof(string));
            return tweetsTable;
        }

        public class TwitAuthenticateResponse
        {
            public string token_type { get; set; }
            public string access_token { get; set; }
        }
    }





 

Friday, 19 October 2012

enable versioning to sharepoint list


The following is the code snippet which is used to do the versioning settings.
        ///Enable Versioning to lists
        SPContext.Current.Web.AllowUnsafeUpdates = true;
        SPList objList = SPContext.Current.Web.Lists["TestList"];

        //EnableVersioning:- True if versioning is enabled for the document library; Otherwise false.
        objList.EnableVersioning = true;
        //EnableMinorVersions:- true if minor versions are enabled when versioning is enabled for the document library; otherwise false.
        objList.EnableMinorVersions = true;
        //EnableModeration: property is true if Content Approval is enabled; otherwise, false
        objList.EnableModeration = true;
        //ForceCheckout:- This property is true if Forced checkout is enabled for the document library; otherwise false
        objList.ForceCheckout = true;
        //DraftVersionVisibility:- Set the accessibilty of the minor versions of document drafts within the list.
        objList.DraftVersionVisibility = DraftVisibilityType.Author;
        objList.Update();
  SPContext.Current.Web.AllowUnsafeUpdates = false;
       

Sunday, 27 March 2011

Retriving SharePoint WSP Files from Config DB using SharePoint Object Model

WSP files are the preferred way of deploying the new functionlaity in SharePoint. WSP files are stored in the Config DB. If you need to extract these files you can do that by using the SharePoint Object Model Code. The following code snippet will retrive all the solutions from the config DB and will place them in the specified location:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace Retrive_Solutions
{ 
    class SolutionBackup
    {
        static void Main(string[] args)
        {
            SPSolutionCollection AllSolutions = SPFarm.Local.Solutions;
            foreach (SPSolution Solution in AllSolutions)
            {
                SPPersistedFile wspFile = Solution.SolutionFile;
                wspFile.SaveAs("C:\\Solutions\\" + Solution.Name);
            }
        }
    }
}