Tweet using c#

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using OAuth;

namespace TwitterLogin
{
    public partial class OAuthResponse : System.Web.UI.Page
    {
        private string _accessToken = string.Empty;
        private string _accessTokenSecreate = string.Empty;
        string twitterUrl1 = "https://api.twitter.com/1.1/statuses/update.json?status=";
        string twitterUrl2 = "https://api.twitter.com/1.1/statuses/update_with_media.json";


        private string imageFile;

        protected void Page_Load(object sender, EventArgs e)
        {

            if ((Session["twtoken"] == null) && (Session["twsecret"] == null))
            {
                if (Request.QueryString["oauth_token"] != null && Request.QueryString["oauth_verifier"] != null)
                {
                    string oauth_token = Request.QueryString["oauth_token"];
                    string oauth_verifier = Request.QueryString["oauth_verifier"];

                    OAuthHelper oauthhelper = new OAuthHelper();

                    oauthhelper.GetUserTwAccessToken(oauth_token, oauth_verifier);

                    if (string.IsNullOrEmpty(oauthhelper.oauth_error))
                    {
                        _accessToken = oauthhelper.oauth_access_token;
                        _accessTokenSecreate = oauthhelper.oauth_access_token_secret;
                    }
                    else
                    {
                        Response.Write(oauthhelper.oauth_error);
                    }
                    ProcessRequest();

                }
            }
            else
            {
              
                ProcessRequest();
            }

        }

        public void ProcessRequest()
        {
            // _accessToken = "240116438-yr0kEvFUfZYtSx5YS2pKhdLqZe6kgFHYTrXkStqE";
            //_accessTokenSecreate = "";
            //string customerkey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            //string customerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];


            //string nostring = "";
            //string nnString = "";
            //OAuthBase oauth = new OAuthBase();

            ////Twitter
            //Uri t = new Uri("http://api.twitter.com/1.1/statuses/home_timeline.json");
            //string u = oauth.GenerateSignature(t, customerkey, customerSecret, _accessToken, _accessTokenSecreate, "GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(), out nostring, out nnString);

            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(nostring);
            //request.Method = "GET";


            //string realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath;

            //OAuthUtils util = new OAuthUtils();
            //AuthorizeHeader h = util.GetUserInfoAuthorizationHeader(t.ToString(), realm, customerkey, customerSecret, _accessToken, _accessTokenSecreate, SignatureMethod.HMACSHA1, "GET");
            //request.Headers.Add("Authorization", h.ToString());
            //Response.Write(request.Headers["Authorization"].ToString() + "<br />");


            //WebResponse response = request.GetResponse();
            //StreamReader reader = new StreamReader(response.GetResponseStream());
            //string responseString = reader.ReadToEnd();
            //reader.Close();
            ////Response.Write(responseString);

            //hdfJsonData.Value = responseString;

            //ClientScript.RegisterStartupScript(this.GetType(), "SetContent", "javascript:SetTwitterFeed();", true);

            Tweet();
        }



        private string GetTwitterUpdateUrl()
        {
            imageFile = Server.MapPath("~/style/logo.png");
            return (imageFile == null) ?
                twitterUrl1 + "hi" : twitterUrl2;
        }

        private static string GetMimeType(String filename)
        {
            var extension = System.IO.Path.GetExtension(filename).ToLower();
            var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension);

            string result =
                ((regKey != null) && (regKey.GetValue("Content Type") != null))
                ? regKey.GetValue("Content Type").ToString()
                : "image/unknown";
            return result;
        }

        private void Tweet()
        {
            var oauth = new OAuth.Manager();
            oauth["consumer_key"] = "YOUR CONSUMER KEY";
            oauth["consumer_secret"] = "YOUR CONSUMER SECRET";
            oauth["token"] = _accessToken;
            oauth["token_secret"] = _accessTokenSecreate;



            var url = GetTwitterUpdateUrl();
            var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";
            request.PreAuthenticate = true;
            request.AllowWriteStreamBuffering = true;
            request.Headers.Add("Authorization", authzHeader);

            if (imageFile != null)
            {
                string boundary = "======" +
                              Guid.NewGuid().ToString().Substring(18).Replace("-", "") +
                              "======";

                var separator = "--" + boundary;
                var footer = "\r\n" + separator + "--\r\n";

                string shortFileName = Path.GetFileName(imageFile);
                string fileContentType = GetMimeType(shortFileName);
                string fileHeader = string.Format("Content-Disposition: file; " +
                                                  "name=\"media\"; filename=\"{0}\"",
                                                  shortFileName);
                var encoding = System.Text.Encoding.GetEncoding("iso-8859-1");

                var contents = new System.Text.StringBuilder();
                contents.AppendLine(separator);
                contents.AppendLine("Content-Disposition: form-data; name=\"status\"");
                contents.AppendLine();
                contents.AppendLine("hi");
                contents.AppendLine(separator);
                contents.AppendLine(fileHeader);
                contents.AppendLine(string.Format("Content-Type: {0}", fileContentType));
                contents.AppendLine();

                request.ServicePoint.Expect100Continue = false;
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                // actually send the request
                using (var s = request.GetRequestStream())
                {
                    byte[] bytes = encoding.GetBytes(contents.ToString());
                    s.Write(bytes, 0, bytes.Length);
                    bytes = File.ReadAllBytes(imageFile);
                    s.Write(bytes, 0, bytes.Length);
                    bytes = encoding.GetBytes(footer);
                    s.Write(bytes, 0, bytes.Length);
                }
            }


            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                }
            }

        }
    }
}

Comments