Post message with image on twitter using C#

Sheonarayan
Posted by in C# category on for Advance level | Points: 250 | Views : 5836 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we shall learn how to automate the twitter posting using C#. In this example we will know how to post a message along with an image on twitter website from C# code within our application.


 Download source code for Post message with image on twitter using C#

Recommendation
Read Password generator in C# before this article.

Introduction

While working on applications, sometimes we came across requirement where we need to automate any news posting on twitter using our code in C#. Here we are going to learn how to create a method in ASP.NET that will actually write a message with an image to twitter website.


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 as shown above.

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.

Registering our app to Twitter

Go to https://apps.twitter.com/ and create your app. After creation of app, you will be taken to App management web page where click on Keys and Access Tokens tab and generate token. After generating the token, the twitter web page should look like this.



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

Using C# Code to Tweet


Now write following code in .aspx page that will create a user interface as shown below.

<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>

Clicking on the button, calls following method of the code behind page.

    protected void btnTwit_Click(object sender, EventArgs e)
    {
        string key = "acb";
        string secret = "dec";
        string token = "12-ghk";
        string tokenSecret = "klm";

        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 wtih 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> { { "john", 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 kyes 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.

Reference

TweetSharp

Recommendation
Read Simple controller dependency injection in ASP.NET MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Rajayadav on: 12/24/2015 | Points: 25
Nice Sir, Thanks for sharing
Posted by: Priyankak on: 5/19/2016 | Points: 25
above code giving following\ error
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Posted by: Amatya on: 5/19/2016 | Points: 25
Are you following the above steps? @Priyankak

Login to post response

Comment using Facebook(Author doesn't get notification)