Tuesday, 21 March 2017

Twitter Integration with Application

Twitter Integration with Application

Dependencies:
Ø  To achieve automation of twitter, we will use a third party component called TweetSharp that can also be integrated to our application using Manage NuGet Packages from Visual Studio.
Ø  Once we have installed the TweetSharp in our project, we need to follow one more step and that is to register our app to Twitter.
Register your Website on Twitter.com:
Everything you need to know can be found on the Twitter Developers Portal (Of Course you need a Twitter Account)
Ø  After Login to your Twitter account follow below process:-

Step-1:

Step-2:


After clicking above link it will take you to the below page:


















Step-3:

Click on "Create New App" which will open like this below:
































Step-4:

Completely Fill Out the "Application Details" Form. The Callback URL field, you can leave it blank.












Step-5:

After filling the “Application Details” accept the agreement and click on “Create your Twitter Application” button which will create your twitter application.






















Step-6:

After your Application is created your Consumer Key/Secret are created, which are needed for authorization. So note it for future use.






























Step-7:

In the Application Settings the Application Type needs to be set to "Read and Write". You can change the type by clicking “Permissions” tab like below.



























Step-8:

After creation of application, you will be taken to “App management” web page where click on “Keys and Access Tokens tab. Here you can see “Consumer Key”, “Consumer Secret” and you can generate “Access Token” also.



































Step-9:

Here you can generate Access Token by clicking “Create my access token” button it will generate your “Access Token” and “Access Token Secret” like below.





















Step-10:

Now copy following from the above page
·         Consumer Key
·         Consumer Secret
·         Access Token
·         Access Token Secret

Step-10:

Using C# code to Tweet:
Ø  First add a new web form page in your Solution named it as MessagePosting.aspx
Ø  Now write HTML markup in MessagePosting.aspx page that will create a user interface.
HTML Markup:
<body>
    <form id="form1" runat="server">
    <div>
        <p>Twitter message:<br />
 <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="5"     Columns="50" /></p>
        <p>Twitter Image:<br />
        <asp:FileUpload runat="server" id="FileUpload1" /></p>
 <asp:Button ID="btnTwit" runat="server" Text="Tweet" OnClick="btnTwit_Click"   /><hr />
        <asp:Label ID="lblResult" runat="server" EnableViewState="false" />
    </div>
    </form>
</body>

Ø  Your User Interface look like this:






















Clicking on the Tweet button, will call following method of the code behind page.

Step-11:

Write code on code behind page i.e. MessagePosting.cs
C# Code:
Ø  Now import these two namespaces:
    using TweetSharp;
    using TwitterOAuth;
Ø  Write c# code in button’s OnClick event i.e.- OnClick="btnTwit_Click"
protected void btnTwit_Click(object sender, EventArgs e)
        {
            string key = "T0CQ6WQ9ITAjwzhfeHWpOUOFM";
            string secret = "
9x09s4PN1NzjWx6XkTKZIICTLKqjLF0Zze5QdqIz9HPT86r1pW
";
            string token = "
836141164331950080-6h5bdSPg6ZpJYyNeT5AlmCZxjKTUGFT";
            string tokenSecret = "
6FHUXMAZD8a042VqRblPrRNKRfvxa5VC9sjkR8nsFbjPf
";
string message = txtMessage.Text.Trim();
             //check if file is there, upload it
            string imagePath = string.Empty;
            if (FileUpload1.HasFile)
            {
                string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                imagePath = Server.MapPath("~/Images/" + fileName);
                FileUpload1.SaveAs(imagePath);
            }

            var service = new TweetSharp.TwitterService(key, secret);
            service.AuthenticateWith(token, tokenSecret);

            //Tweet with image
            if (imagePath.Length > 0)
            {
                 using (var stream = new FileStream(imagePath, FileMode.Open))
                {
                    var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
                    {
                        Status = message,
                        Images = new Dictionary<string, Stream> { { "Images", stream } }

                    });
                    lblResult.Text = result.Text.ToString();
                }
            }
            else // just message
            {
                var result = service.SendTweet(new SendTweetOptions
                {
                    Status = message
                });
                lblResult.Text = result.Text.ToString();
     }
       }
Ø  In the above code, first we are creating variables for keys and secrets to be used from twitter app registrations page. Then we are checking if the user is uploading the file to tweet, if yes then uploading the file into "Image" folder otherwise simply authenticating to Twitter service using keys and secrets.
Ø  If image is being uploaded, we are calling SendTweetWithMedia() method to send the message as well as image as stream to the twitter otherwise we are calling SendTweet() method that simply sends the plain text message to the twitter to tweet.
Ø  Now once you go to your twitter account, you can cross check that all your tweets are available on twitter website.
Conclusion:
Even if Twitter has its own API that can be consumed directly to tweet however using TweetSharp makes it easy for us to call methods and pass necessary arguments. TweetSharp is a wrapper around Twitter API that exposes methods and property to simplify tweeting.


No comments:

Post a Comment