public static bool FollowAccount(string AccessToken, string AccessTokenSecret, string Screen_name, string user_id) { bool IsFollowed = false; oAuthTwitter oauth = new oAuthTwitter(); oauth.AccessToken = AccessToken; oauth.AccessTokenSecret = AccessTokenSecret; oauth.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; oauth.ConsumerKeySecret = ConfigurationManager.AppSettings["consumerSecret"]; string RequestUrl = "https://api.twitter.com/1.1/friendships/create.json"; SortedDictionary <string, string> strdic = new SortedDictionary <string, string>(); if (!string.IsNullOrEmpty(Screen_name)) { strdic.Add("screen_name", Screen_name); } else if (!string.IsNullOrEmpty(user_id)) { strdic.Add("user_id", user_id); } else { return(false); } strdic.Add("follow", "true"); string response = oauth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!string.IsNullOrEmpty(response)) { IsFollowed = true; } return(IsFollowed); }
public static string ComposeTwitterMessage(string message, string profileid, long userid, string picurl, bool isScheduled, DatabaseRepository dbr, Domain.Socioboard.Models.TwitterAccount TwitterAccount, Domain.Socioboard.Models.ScheduledMessage schmessage) { bool rt = false; string ret = ""; string str = "Message posted"; if (message.Length > 140) { message = message.Substring(0, 135); } Domain.Socioboard.Models.TwitterAccount objTwitterAccount = TwitterAccount; // oAuthTwitter OAuthTwt = new oAuthTwitter("MbOQl85ZcvRGvp3kkOOJBlbFS", "GF0UIXnTAX28hFhN1ISNf3tURHARZdKWlZrsY4PlHm9A4llYjZ", "http://serv1.socioboard.com/TwitterManager/Twitter"); oAuthTwitter OAuthTwt = new oAuthTwitter("h4FT0oJ46KBBMwbcifqZMw", "yfowGI2g21E2mQHjtHjUvGqkfbI7x26WDCvjiSZOjas", "https://www.socioboard.com/TwitterManager/Twitter"); OAuthTwt.AccessToken = objTwitterAccount.oAuthToken; OAuthTwt.AccessTokenSecret = objTwitterAccount.oAuthSecret; OAuthTwt.TwitterScreenName = objTwitterAccount.twitterScreenName; OAuthTwt.TwitterUserId = objTwitterAccount.twitterUserId; Tweet twt = new Tweet(); if (!string.IsNullOrEmpty(picurl)) { try { PhotoUpload ph = new PhotoUpload(); string res = string.Empty; rt = ph.NewTweet(picurl, message, OAuthTwt, ref res); } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; } } else { try { JArray post = twt.Post_Statuses_Update(OAuthTwt, message); ret = post[0]["id_str"].ToString(); } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; } } if (!string.IsNullOrEmpty(ret) || rt == true) { schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; schmessage.url = ret; dbr.Update <ScheduledMessage>(schmessage); } else { str = "Message not posted"; } return(str); }
private void AuthenticateWithTwitter(string returnUrl) { string url = ""; string xml = ""; var oAuth = new oAuthTwitter(); if (Request["oauth_token"] == null) { //Redirect the user to Twitter for authorization. //Using oauth_callback for local testing. oAuth.CallBackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/AuthenticatedWithTwitter?state=" + Request["ReturnUrl"]; Response.Redirect(oAuth.AuthorizationLinkGet(), true); } else { //Get the access token and secret. oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]); if (oAuth.TokenSecret.Length > 0) { //We now have the credentials, so make a call to the Twitter API. url = "http://twitter.com/account/verify_credentials.xml"; xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty); var response = Server.HtmlEncode(xml); //POST Test //url = "http://twitter.com/statuses/update.xml"; //xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API")); //apiResponse.InnerHtml = Server.HtmlEncode(xml); } } }
/// <summary> /// This method Will Check Rate Limit Of Account Using OAUTH /// </summary> /// <param name="OAuth">OAuth Keys Token, TokenSecret, ConsumerKey, ConsumerSecret</param> /// <returns>Return Xml Text With User Details</returns> public XmlDocument Rate_Limit_Status(oAuthTwitter OAuth) { string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, Globals.RateLimitStatusUrl, String.Empty); xmlResult.Load(new StringReader(response)); return(xmlResult); }
/// <summary> /// This Method Will Check That User is Authenticated Or Not Using OAUTH /// </summary> /// <param name="OAuth">OAuth Keys Token, TokenSecret, ConsumerKey, ConsumerSecret</param> /// <returns>Return Xml Text With User Details</returns> public XmlDocument Verify_Credentials(oAuthTwitter OAuth) { string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, Globals.VerifyCredentialsUrl, String.Empty); xmlResult.Load(new StringReader(response)); return(xmlResult); }
protected void FirstPos() { string url = ""; string xml = ""; oAuthTwitter oAuth = new oAuthTwitter(); oAuth.ConsumerKey = System.Configuration.ConfigurationManager.AppSettings["consumerkey"]; oAuth.ConsumerSecret = System.Configuration.ConfigurationManager.AppSettings["consumersecret"]; oAuth.CallBackUrl = SessionState.WebsiteURL + "twitter.aspx"; if (Request["oauth_token"] == null) { Response.Redirect(oAuth.AuthorizationLinkGet()); } else { //Get the access token and secret. oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]); verifier = Request["oauth_verifier"]; token = Request["oauth_token"]; if ((oAuth.TokenSecret.Length > 0)) { //We now have the credentials, so make a call to the Twitter API. url = "https://api.twitter.com/1.1/account/verify_credentials.json?test=test&include_entities=true&skip_status=true"; // url = "https://api.twitter.com/1.1/search/tweets.json"; xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, string.Empty); CheckAndRegister(xml); } } }
protected void Page_Load(object sender, EventArgs e) { // if this is a callback that is providing the twitter access token, then update with the token. if (!String.IsNullOrEmpty(Request["oauth_token"]) && Page.User.Identity.IsAuthenticated) { if (String.IsNullOrEmpty(Request["oauth_verifier"])) { throw new MyFlightbookException("oauth token passed but no oauth_verifier along with it."); } oAuthTwitter oAuth = new oAuthTwitter(); oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]); mfbTwitter.SetUserTwitterToken(Page.User.Identity.Name, oAuth); } if (util.GetStringParam(Request, "oauth_token").Length > 0) { LogbookEntry le = mfbTwitter.PendingFlightToPost; if (le != null) { mfbTwitter.PostFlight(le); mfbTwitter.PendingFlightToPost = null; // clear it } } Response.Redirect(SocialNetworkAuthorization.PopRedirect(Master.IsMobileSession() ? SocialNetworkAuthorization.DefaultRedirPageMini : SocialNetworkAuthorization.DefaultRedirPage)); }
public static string ComposeTwitterMessage(string message, string profileid, long userid, string picurl, bool isScheduled, DatabaseRepository dbr, Domain.Socioboard.Models.TwitterAccount TwitterAccount, Domain.Socioboard.Models.ScheduledMessage schmessage) { bool rt = false; string ret = ""; string str = "Message posted"; if (message.Length > 140) { message = message.Substring(0, 135); } Domain.Socioboard.Models.TwitterAccount objTwitterAccount = TwitterAccount; oAuthTwitter OAuthTwt = new oAuthTwitter(Helper.AppSettings.twitterConsumerKey, Helper.AppSettings.twitterConsumerScreatKey, Helper.AppSettings.twitterRedirectionUrl); OAuthTwt.AccessToken = objTwitterAccount.oAuthToken; OAuthTwt.AccessTokenSecret = objTwitterAccount.oAuthSecret; OAuthTwt.TwitterScreenName = objTwitterAccount.twitterScreenName; OAuthTwt.TwitterUserId = objTwitterAccount.twitterUserId; Tweet twt = new Tweet(); if (!string.IsNullOrEmpty(picurl)) { try { PhotoUpload ph = new PhotoUpload(); string res = string.Empty; rt = ph.NewTweet(picurl, message, OAuthTwt, ref res); } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; } } else { try { JArray post = twt.Post_Statuses_Update(OAuthTwt, message); ret = post[0]["id_str"].ToString(); } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; } } if (!string.IsNullOrEmpty(ret) || rt == true) { schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; schmessage.url = ret; dbr.Update <ScheduledMessage>(schmessage); } else { str = "Message not posted"; } return(str); }
public bool Tweet(string imageFile, string message, oAuthTwitter oAuth) { bool bupdated = false; try { //HttpContext.Current.Response.Write("<script>alert(\""+imageFile+"\")</script>"); oauth["consumer_key"] = oAuth.ConsumerKey; oauth["consumer_secret"] = oAuth.ConsumerKeySecret; oauth["token"] = oAuth.AccessToken; oauth["token_secret"] = oAuth.AccessTokenSecret; var url = GetTwitterUpdateUrl(imageFile, message); if (url == twitterUrl1) { strdic.Add("status", message); } 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); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; 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(message); 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()) { // HttpContext.Current.Response.Write("<script>alert(\"" + response.StatusCode + "\")</script>"); if (response.StatusCode == HttpStatusCode.OK) { bupdated = true; } } } catch (Exception ex) { Console.WriteLine(ex.Message); logger.Error(ex.Message); //using (StreamWriter _testData = new StreamWriter(HttpContext.Current.Server.MapPath("~/log.txt"), true)) //{ // _testData.WriteLine("Error on PhotoUpload : " + ex.Message); // Write the file. //} } return bupdated; }
public bool NewTweet(string imageFile, string message, oAuthTwitter oAuth, ref string myfunctioncalled) { bool bupdated = false; try { //HttpContext.Current.Response.Write("<script>alert(\""+imageFile+"\")</script>"); #region For Loacl Testing //oauth["consumer_key"] = "udiFfPxtCcwXWl05wTgx6w";//oAuth.ConsumerKey; //oauth["consumer_secret"] = "jutnq6N32Rb7cgbDSgfsrUVgRQKMbUB34yuvAfCqTI";//oAuth.ConsumerKeySecret; //oauth["token"] = "1904022338-Ao9chvPouIU8ejE1HMG4yJsP3hOgEoXJoNRYUF7";//oAuth.AccessToken; //oauth["token_secret"] = "Wj93a8csVFfaFS1MnHjbmbPD3V6DJbhEIf4lgSAefORZ5";//oAuth.AccessTokenSecret; #endregion #region For Post data Reference /* Url Link : https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media // Post data: * POST /1.1/statuses/update_with_media.json HTTP/1.1 Host: api.twitter.com User-Agent: Go http package Content-Length: 15532 Authorization: OAuth oauth_consumer_key="...", oauth_nonce="...", oauth_signature="...", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1347058301", oauth_token="...", oauth_version="1.0" Content-Type: multipart/form-data;boundary=cce6735153bf14e47e999e68bb183e70a1fa7fc89722fc1efdf03a917340 Accept-Encoding: gzip --cce6735153bf14e47e999e68bb183e70a1fa7fc89722fc1efdf03a917340 Content-Disposition: form-data; name="status" Hello 2012-09-07 15:51:41.375247 -0700 PDT! --cce6735153bf14e47e999e68bb183e70a1fa7fc89722fc1efdf03a917340 Content-Type: application/octet-stream Content-Disposition: form-data; name="media[]"; filename="media.png" ... --cce6735153bf14e47e999e68bb183e70a1fa7fc89722fc1efdf03a917340-- */ #endregion #region For Online oauth["consumer_key"] = oAuth.ConsumerKey; oauth["consumer_secret"] = oAuth.ConsumerKeySecret; oauth["token"] = oAuth.AccessToken; oauth["token_secret"] = oAuth.AccessTokenSecret; #endregion var url = GetTwitterUpdateUrl(imageFile, message); if (url == twitterUrl1) { strdic.Add("status", message); } //url = "https://upload.twitter.com/1/statuses/update_with_media.json"; var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.PreAuthenticate = true; request.AllowWriteStreamBuffering = true; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0"; request.Headers.Add("Authorization", authzHeader); request.AutomaticDecompression = DecompressionMethods.GZip; if (imageFile != null) { string boundary = Guid.NewGuid().ToString().Replace("-", ""); var separator = "--" + boundary; var footer = "\r\n" + separator + "--\r\n"; request.ServicePoint.Expect100Continue = false; request.ContentType = "multipart/form-data; boundary=" + boundary; string shortFileName = Path.GetFileName(imageFile); string fileHeader = string.Format("Content-Disposition: file; " + "name=\"media[]\"; filename=\"{0}\"", shortFileName); var encoding = System.Text.Encoding.GetEncoding("iso-8859-1"); using (Stream rs = request.GetRequestStream()) { string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; string formitem = string.Empty; byte[] firstboundarybytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); rs.Write(firstboundarybytes, 0, firstboundarybytes.Length);//rs.Write(boundarybytes, 0, boundarybytes.Length); formitem = string.Format(formdataTemplate, "status", message); byte[] formitembytes1 = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes1, 0, formitembytes1.Length); rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "media[]", shortFileName, "application/octet-stream"); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read)) { //FileStream fileStream = new FileStream(localImagePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } //fileStream.Close(); } byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");//System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); } } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // HttpContext.Current.Response.Write("<script>alert(\"" + response.StatusCode + "\")</script>"); if (response.StatusCode == HttpStatusCode.OK) { bupdated = true; } myfunctioncalled = myfunctioncalled + "myfunctioncalled: " + response.ToString(); } } catch (Exception ex) { myfunctioncalled = myfunctioncalled + "myfunctioncalled: " + ex.Message + ">>> " + ex.StackTrace; Console.WriteLine(ex.Message); logger.Error(ex.Message); } return bupdated; }
//************************************************************************* // Method: GetXmlDocument() // /// <summary> /// Gets an XML document from an URL. /// </summary> /// /// <param name="sUrl"> /// The URL to get the document from. /// </param> /// /// <param name="oRequestStatistics"> /// A <see cref="RequestStatistics" /> object that is keeping track of /// requests made while getting the network. /// </param> /// /// <returns> /// The XmlDocument from the URL. /// </returns> /// /// <remarks> /// If an error occurs, an exception is thrown. /// </remarks> //************************************************************************* protected XmlDocument GetXmlDocument( String sUrl, RequestStatistics oRequestStatistics ) { Debug.Assert( !String.IsNullOrEmpty(sUrl) ); Debug.Assert(oRequestStatistics != null); AssertValid(); Debug.Assert(m_oTwitterAccessToken != null); // Has the user authorized NodeXL to use her Twitter account? String sToken, sSecret; if ( m_oTwitterAccessToken.TryLoad(out sToken, out sSecret) ) { // Yes. Add the required authorization information to the URL. oAuthTwitter oAuthTwitter = new oAuthTwitter(); oAuthTwitter.Token = sToken; oAuthTwitter.TokenSecret = sSecret; String sAuthorizedUrl, sAuthorizedPostData; oAuthTwitter.ConstructAuthWebRequest(oAuthTwitter.Method.GET, sUrl, String.Empty, out sAuthorizedUrl, out sAuthorizedPostData); sUrl = sAuthorizedUrl; } Int32 iRateLimitPauses = 0; while (true) { try { return ( GetXmlDocumentWithRetries(sUrl, HttpStatusCodesToFailImmediately, oRequestStatistics, null) ); } catch (WebException oWebException) { if (!WebExceptionIsDueToRateLimit(oWebException) || iRateLimitPauses > 0) { throw; } // Twitter rate limits have kicked in. Pause and try again. iRateLimitPauses++; Int32 iRateLimitPauseMs = GetRateLimitPauseMs(oWebException); DateTime oWakeUpTime = DateTime.Now.AddMilliseconds( iRateLimitPauseMs); ReportProgress( String.Format( "Reached Twitter rate limits. Pausing until {0}." , oWakeUpTime.ToLongTimeString() ) ); // Don't pause in one large interval, which would prevent // cancellation. const Int32 SleepCycleDurationMs = 1000; Int32 iSleepCycles = (Int32)Math.Ceiling( (Double)iRateLimitPauseMs / SleepCycleDurationMs) ; for (Int32 i = 0; i < iSleepCycles; i++) { CheckCancellationPending(); System.Threading.Thread.Sleep(SleepCycleDurationMs); } } } }