401 unauthorized When sending a direct message using api 1.1


#1

I am getting an error “401 unauthorized” al the settings are fine in the https://dev.twitter.com/‎, any help it would be welcome thanks in advance! here is my code:

using System;
using System.IO; 
using System.Net; 
using System.Text; 
using System.Diagnostics; 
using System.Collections.Generic; 
using System.Security.Cryptography;
using oAuthTwitterWrapper.TwitterDatabaseDataSetTableAdapters;
using System.Globalization;
 

namespace oAuthTwitterWrapper
{
    public class Utility2
    {
        public string ConsumerKey = "";
        public string ConsumerKeySecret = "";
        public string OauthToken = "";
        public string OauthTokenSecret = "";
        public string UserNameToBeFollowed = "";
        public string strMessage = "";
        public Utility2(String IdTwitter)
        {

            TwitterAccountsTableAdapter inputDB = new TwitterAccountsTableAdapter();
            TwitterDatabaseDataSet.TwitterAccountsDataTable reponse = inputDB.GetDataByID(IdTwitter);
            ConsumerKey = reponse[0].oAuthConsumerKey;
            ConsumerKeySecret = reponse[0].oAuthConsumerSecret;
            OauthToken = reponse[0].OauthToken.Trim();
            OauthTokenSecret = reponse[0].OauthTokenSecret;
        }
        public string Generate_Nonce()
        {
            return new Random().Next(123400, int.MaxValue).ToString("X", CultureInfo.InvariantCulture);
        }

        public string Generate_TimeStamp()
        {
            return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture);
        }

        public string EncodeString(string value)
        {

            if (value == null)
                return null;

            StringBuilder stringBuilder = new StringBuilder();
            string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
            string str1 = value;
            int num = 0;
            int length = str1.Length;
            while (num < length)
            {
                char chr = str1[num];
                if (str.IndexOf(chr) == -1)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(chr.ToString());
                    byte[] numArray = bytes;
                    for (int i = 0; i <= Convert.ToInt32(numArray.Length) - 1; i++)
                    {
                        byte num1 = numArray[i];
                        stringBuilder.AppendFormat("%{0:X2}", num1);
                    }
                }
                else
                {
                    stringBuilder.Append(chr);
                }
                num += 1;
            }

            return stringBuilder.ToString();

        }
        private string GenerateHeader1()
        {

            return string.Concat("OAuth ",
                                              string.Format("oauth_consumer_key=\"{0}\", ", EncodeString(ConsumerKey)),
                                              string.Format("oauth_nonce=\"{0}\", ", EncodeString(Generate_Nonce())),
                                              string.Format("oauth_signature=\"{0}\", ", EncodeString(this.GenerateSignature1())),
                                              string.Format("oauth_signature_method=\"{0}\", ", EncodeString("HMAC-SHA1")),
                                              string.Format("oauth_timestamp=\"{0}\", ", EncodeString(Generate_TimeStamp())),
                                              string.Format("oauth_token=\"{0}\", ", EncodeString(OauthToken)),
                                              string.Format("oauth_version=\"{0}\"", "1.0"));

        }

        private string GenerateSignature1()
        {


            string basestring = string.Concat(string.Format("&oauth_consumer_key={0}", ConsumerKey),
                                              string.Format("&oauth_nonce={0}", Generate_Nonce()),
                                              string.Format("&oauth_signature_method={0}", "HMAC-SHA1"),
                                              string.Format("&oauth_timestamp={0}", Generate_TimeStamp()),
                                              string.Format("&oauth_token={0}", OauthToken), "",
                                              string.Format("&oauth_version={0}", "1.0"),
                                              string.Format("&text={0}", strMessage),
                                              string.Format("&screen_name={0}", UserNameToBeFollowed)
                                              );

            basestring = string.Concat("POST", "&", Uri.EscapeDataString("https://api.twitter.com/1.1/direct_messages/new.json"), "&", Uri.EscapeDataString(basestring.TrimStart('&')));

            // Console.WriteLine(basestring);

            string compositeString = string.Concat(EncodeString(ConsumerKeySecret), "&", EncodeString(OauthTokenSecret));

            return Convert.ToBase64String((new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(compositeString)).ComputeHash(Encoding.ASCII.GetBytes(basestring))));

        }

        public Boolean sendMessage()
        {
            Boolean responseSuccessful = false;
            string postBody = string.Concat(string.Format("screen_name={0}", EncodeString(UserNameToBeFollowed)), "&", string.Format("text={0}", EncodeString(strMessage)));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/1.1/direct_messages/new.json");
            request.Headers.Add("Authorization", GenerateHeader1());
            request.ContentType = "application/x-www-form-urlencoded";
            request.ServicePoint.Expect100Continue = false;
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            request.Method = "POST";

            try
            {



                using (System.IO.Stream stream = request.GetRequestStream())
                {

                    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);

                    stream.Write(content, 0, content.Length);

                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Close();
                responseSuccessful = true;

            }

            catch (Exception ex)
            {
                // Console.WriteLine(ex.Message);

            }


            request = null;

            return responseSuccessful;

        }

    }
    


}