public static JObject GetUserInfo(WebConsumer consumer, int userid, String screenName, string accessToken) { var baseUri = "https://api.twitter.com/1.1/users/show.json"; String uri = String.Empty; if (userid > 0 && String.IsNullOrEmpty(screenName)) { uri = String.Concat(baseUri, "?user_id=", userid); } if (userid == 0 && !String.IsNullOrEmpty(screenName)) { uri = String.Concat(baseUri, "?screen_name=", screenName); } var endpoint = new MessageReceivingEndpoint(uri, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JObject.Parse(result)); } }
public static JArray GetUserTimeLine(WebConsumer consumer, String accessToken, int userId, String screenName, bool includeRetweets, int count) { var parameters = new Dictionary <String, string>(); parameters.Add("count", count.ToString(CultureInfo.InvariantCulture)); parameters.Add("include_rts", includeRetweets.ToString()); if (!String.IsNullOrEmpty(screenName)) { parameters.Add("screen_name", screenName); } if (userId > 0) { parameters.Add("user_id", userId.ToString(CultureInfo.InvariantCulture)); } HttpWebRequest request = consumer.PrepareAuthorizedRequest(GetUserTimeLineEndPoint, accessToken, parameters); IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JArray.Parse(result)); } }
public static XDocument GetUserInfo(int userid, string accessToken) { var endpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/users/show.xml?user_id=" + userid, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); IncomingWebResponse response = TwitterSignIn.PrepareAuthorizedRequestAndSend(endpoint, accessToken); var doc = XDocument.Load(XmlReader.Create(response.GetResponseReader())); return(doc); }
public static string Tweet(ConsumerBase twitter, string accessToken, string status) { Dictionary <string, string> extraData = new Dictionary <string, string>(); extraData.Add("status", status); HttpWebRequest request = twitter.PrepareAuthorizedRequest(TweetEndpoint, accessToken, extraData); IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); return(response.GetResponseReader().ReadToEnd()); }
public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, Stream image, string contentType) { var parts = new[] { MultipartPostPart.CreateFormFilePart("image", "twitterPhoto", contentType, image), }; HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileImageEndpoint, accessToken, parts); IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); string responseString = response.GetResponseReader().ReadToEnd(); return(XDocument.Parse(responseString)); }
private void beginButton_Click(object sender, RoutedEventArgs e) { try { var service = new ServiceProviderDescription { RequestTokenEndpoint = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest), AccessTokenEndpoint = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, ProtocolVersion = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a, }; var tokenManager = new InMemoryTokenManager(); tokenManager.ConsumerKey = this.consumerKeyBox.Text; tokenManager.ConsumerSecret = this.consumerSecretBox.Text; var consumer = new DesktopConsumer(service, tokenManager); string accessToken; if (service.ProtocolVersion == ProtocolVersion.V10) { string requestToken; Uri authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken); Process.Start(authorizeUrl.AbsoluteUri); MessageBox.Show(this, "Click OK when you've authorized the app."); var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null); accessToken = authorizationResponse.AccessToken; } else { var authorizePopup = new Authorize( consumer, (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken)); authorizePopup.Owner = this; bool?result = authorizePopup.ShowDialog(); if (result.HasValue && result.Value) { accessToken = authorizePopup.AccessToken; } else { return; } } HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest; if (this.resourceHttpMethodList.SelectedIndex == 1) { resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest; } var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod); using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) { this.resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd(); } } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { MessageBox.Show(this, ex.Message); } }
public static JArray SearchUsers(WebConsumer consumer, String search, string accessToken) { var endpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/users/search.json?q=" + search, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JArray.Parse(result)); } }
public static XDocument UpdateProfileBackgroundImage(ConsumerBase twitter, string accessToken, string image, bool tile) { var parts = new[] { MultipartPostPart.CreateFormFilePart("image", image, "image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()), MultipartPostPart.CreateFormPart("tile", tile.ToString().ToLowerInvariant()), }; HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileBackgroundImageEndpoint, accessToken, parts); request.ServicePoint.Expect100Continue = false; IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); string responseString = response.GetResponseReader().ReadToEnd(); return(XDocument.Parse(responseString)); }
/// <summary> /// Updates the authenticating user's status, also known as tweeting. /// </summary> /// <param name="twitter"></param> /// <param name="accessToken"></param> /// <param name="status">The text of your status update, typically up to 140 characters. URL encode as necessary. t.co link wrapping may effect character counts.</param> /// <param name="includeEntities">When set to either true, t or 1, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See Tweet Entities for more detail on entities. /// </param> /// <returns></returns> public static JObject UpdateStatus(ConsumerBase twitter, string accessToken, String status, bool includeEntities) { var parts = new[] { MultipartPostPart.CreateFormPart("status", status), MultipartPostPart.CreateFormPart("include_entities", includeEntities.ToString()), }; HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateStatusEndpoint, accessToken, parts); IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JObject.Parse(result)); } }
public static JArray GetHomeTimeLine(WebConsumer consumer, String accessToken, bool includeRetweets, int count) { var parameters = new Dictionary <String, string>(); parameters.Add("count", count.ToString()); parameters.Add("include_rts", includeRetweets.ToString()); HttpWebRequest request = consumer.PrepareAuthorizedRequest(GetHomeTimeLineEndpoint, accessToken, parameters); IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JArray.Parse(result)); } }
/// <summary> /// Gets the protocol message that may be in the given HTTP response. /// </summary> /// <param name="response">The response that is anticipated to contain an protocol message.</param> /// <returns> /// The deserialized message parts, if found. Null otherwise. /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response) { // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain // Others return text/javascript. Again bad. string body = response.GetResponseReader().ReadToEnd(); if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded) { return(this.DeserializeFromJson(body)); } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) { return(HttpUtility.ParseQueryString(body).ToDictionary()); } else { throw ErrorUtilities.ThrowProtocol(ClientStrings.UnexpectedResponseContentType, response.ContentType.MediaType); } }
public static XDocument VerifyCredentials(ConsumerBase twitter, string accessToken) { IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(VerifyCredentialsEndpoint, accessToken); return(XDocument.Load(XmlReader.Create(response.GetResponseReader()))); }
public static XDocument GetUpdates(ConsumerBase twitter, string accessToken) { IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFriendTimelineStatusEndpoint, accessToken); return(XDocument.Load(XmlReader.Create(response.GetResponseReader()))); }
public XPathNavigator DoRequest(MessageReceivingEndpoint message, List <MultipartPostPart> parameters) { // Initialize the response XML document XDocument responseDocument = null; // Perform the request based on the authentication if (_oAuthConsumer == null) { // Multipart requests are only available to authenticated API accesses at the moment if (parameters != null) { throw new NotImplementedException(); } // Construct the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(message.Location); if ((message.AllowedMethods & HttpDeliveryMethods.PostRequest) == HttpDeliveryMethods.PostRequest) { request.Method = "POST"; } if (_proxy != null) { request.Proxy = _proxy; } // Get and parse the response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new MalformedRequest(new StreamReader(response.GetResponseStream()).ReadToEnd()); } responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseStream(), new XmlReaderSettings())); } else { // Verify authentication if (_accessToken == null) { AuthorizedTokenResponse accessTokenResponse = _oAuthConsumer.ProcessUserAuthorization(); if (accessTokenResponse != null) { _accessToken = accessTokenResponse.AccessToken; } else if (_accessToken == null) { _oAuthConsumer.Channel.Send(_oAuthConsumer.PrepareRequestUserAuthorization()); } } // Construct the request HttpWebRequest request = (parameters == null ? _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken) : _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken, parameters)); if (_proxy != null) { request.Proxy = _proxy; } IncomingWebResponse response = _oAuthConsumer.Channel.WebRequestHandler.GetResponse(request); if (response.Status != HttpStatusCode.OK) { throw new MalformedRequest(new StreamReader(response.ResponseStream).ReadToEnd()); } // Parse the response responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseReader())); } // Establish navigator and validate response XPathNavigator responseNavigation = responseDocument.CreateNavigator(); XPathNodeIterator responseCheckIterator = responseNavigation.Select("/response"); if (responseCheckIterator.Count == 0) { throw new MalformedRequest(responseDocument.ToString()); } while (responseCheckIterator.MoveNext()) { if (responseCheckIterator.Current == null) { return(null); } if (responseCheckIterator.Current.GetAttribute("status", "") != "ok") { string code = responseCheckIterator.Current.GetAttribute("code", ""); string msg = responseCheckIterator.Current.GetAttribute("message", ""); switch (code) { default: throw new MalformedRequest(msg); case "invalid_oauth_site": case "invalid_oauth_user": case "invalid_signature": case "token_required": throw new InvalidCredentials(msg); case "permission_denied": throw new PermissionDenied(msg); } } } // All should be good, return the document return(responseNavigation); }
/// <summary> /// Gets the protocol message that may be in the given HTTP response. /// </summary> /// <param name="response">The response that is anticipated to contain an protocol message.</param> /// <returns> /// The deserialized message parts, if found. Null otherwise. /// </returns> protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response) { string body = response.GetResponseReader().ReadToEnd(); return(HttpUtility.ParseQueryString(body).ToDictionary()); }
public static XDocument GetAuthToken(ConsumerBase flickr, string accessToken) { IncomingWebResponse response = flickr.PrepareAuthorizedRequestAndSend(ServiceDescription.AccessTokenEndpoint, accessToken); return(XDocument.Load(XmlReader.Create(response.GetResponseReader()))); }