Error 401 Unauthorized

dotnet
oauth
linqtotwitter

#1

My code is generated in C #, and do everything they ask me, and checked the parameters sent in Aout console and are very similar to those sent from my system, but the answer I returned: Error on remote server (401) Not authorized. Nose that I may be missing or I’m doing wrong. If someone could help me I would appreciate very much. Here I have the complete code for my project:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using Newtonsoft.Json.Linq;
using System.Globalization;
using LinqToTwitter;
using System.Security.Policy;
using System.Security.Cryptography;

namespace TWITER
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnEnviarPost_Click(object sender, EventArgs e)
        {
            m_EnviaMensajeUsuario("Send Message", "UsuarioPruebas");
        }

        public void m_EnviaMensajeUsuario(string sMsg, string sScreenName)
        {
            var oauth_consumer_key = "DC0sePOBbasdC8r4Smg";
            var oauth_signature_method = "HMAC-SHA1";
            var oauth_timestamp = GenerateTimeStamp();
            var oauth_nonce = GenerateNonce();
            var oauth_version = "1.0";
            var oauth_token = "3xxxxxxxxxxxJqUxzHoC59wy";
            var oauth_consumer_secret = "IhqbdxxxxxxxukA3l49UzpvxGM52";
            var oauth_token_secret = "ZO1zxxxxxxxxWSRjrb1zF";

            string surl = "https://api.twitter.com/1.1/direct_messages/new.json";
            var postBody = "text=" + Uri.EscapeDataString(sMsg) + "&screen_name=" + Uri.EscapeDataString(sScreenName);

            string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&{6}";
            string baseString = string.Format(
                baseFormat,
                oauth_consumer_key,
                oauth_nonce,
                oauth_signature_method,
                oauth_timestamp, oauth_token,
                oauth_version,
                Uri.EscapeDataString(postBody)
            );

            var oauth_signature = CalculateSignature(oauth_consumer_secret, oauth_token_secret, surl, baseString);

            var headerFormat = "OAuth oauth_consumer_key=\"{0}\",oauth_signature_method=\"{1}\"," +
                               "oauth_timestamp=\"{2}\",oauth_nonce=\"{3}\"," +
                               "oauth_version=\"{4}\",oauth_token=\"{5}\"," +
                               "oauth_signature=\"{6}\"";
            var authHeader = string.Format(headerFormat,
                                    Uri.EscapeDataString(oauth_consumer_key),
                                    Uri.EscapeDataString(oauth_signature_method),
                                    Uri.EscapeDataString(oauth_timestamp),
                                    Uri.EscapeDataString(oauth_nonce),
                                    Uri.EscapeDataString(oauth_version),
                                    Uri.EscapeDataString(oauth_token),
                                    Uri.EscapeDataString(oauth_signature)
                            );


            HttpWebRequest objHttpWebRequest = (HttpWebRequest)WebRequest.Create(surl + "?" + postBody);
            objHttpWebRequest.Headers.Add("Authorization", authHeader);
            objHttpWebRequest.Method = "POST";
            objHttpWebRequest.ContentType = "application/x-www-form-urlencoded;";

            var responseResult = "";
            try
            {
                //success posting
                WebResponse objWebResponse = objHttpWebRequest.GetResponse();
                StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
                responseResult = objStreamReader.ReadToEnd().ToString();
            }
            catch (Exception ex)
            {
                //throw exception error
                responseResult = "Twitter Post Error: " + ex.Message.ToString() + ", authHeader: " + authHeader;
            }
        }

        internal string CalculateSignature(string oauth_consumer_secret, string oauth_token_secret, string sURL, string sBaseString)
        {
            string oauth_signature = null;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Uri.EscapeDataString(oauth_consumer_secret) + "&" + Uri.EscapeDataString(oauth_token_secret))))
            {
                oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes("POST&" + Uri.EscapeDataString(sURL) + "&" + Uri.EscapeDataString(sBaseString))));
            }
            return oauth_signature;
        }

        const long UnixEpocTicks = 621355968000000000L;
        internal string GenerateTimeStamp()
        {
            long ticksSinceUnixEpoc = DateTime.UtcNow.Ticks - UnixEpocTicks;
            double secondsSinceUnixEpoc = new TimeSpan(ticksSinceUnixEpoc).TotalSeconds;
            return Math.Floor(secondsSinceUnixEpoc).ToString(CultureInfo.InvariantCulture);
        }

        internal virtual string GenerateNonce()
        {
            Random _random = new Random();
            var sb = new System.Text.StringBuilder();
            for (int i = 0; i < 8; i++)
            {
                int g = _random.Next(3);
                switch (g)
                {
                    case 0:
                        // lowercase alpha
                        sb.Append((char)(_random.Next(26) + 97), 1);
                        break;
                    default:
                        // numeric digits
                        sb.Append((char)(_random.Next(10) + 48), 1);
                        break;
                }
            }
            return sb.ToString();
        }
    }
}