private static void Delete(string postId) { // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath(postId) .Method("DELETE") .QueryStrings(qs => qs.Add("access_token", AccessToken)) .Headers(h => h.Add("User-Agent", "FluentHttp")) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)); // Execute the request. Call EndRequest immediately so it behaves synchronously. var ar = request.Execute(); // seek the save stream to beginning. responseSaveStream.Seek(0, SeekOrigin.Begin); // Print the response Console.WriteLine("Delete: "); Console.WriteLine(FluentHttpRequest.ToString(responseSaveStream)); }
public void BaseUrlShouldBeSameAsOringialBaseUrl() { var originalBaseUrl = "https://graph.facebook.com"; var request = new FluentHttpRequest(originalBaseUrl); Assert.Equal(originalBaseUrl, request.GetBaseUrl()); }
public string SendGist(string fileName, string content, string description, bool isPublic, GitHubCredentials credentials) { var gistAsJson = new CreatesGistMessages().CreateMessage(fileName, content, description, isPublic); using (var stream = new MemoryStream()) { var request = new FluentHttpRequest() .BaseUrl("https://api.github.com") .ResourcePath("/gists") .Method("POST") .Headers(h => h.Add("User-Agent", "Gister")) .Headers(h => h.Add("Content-Type", "application/json")) .Body(x => x.Append(gistAsJson)) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(stream)); AppliesGitHubCredentialsToFluentHttpRequest.ApplyCredentials(credentials, request); var response = request .Execute(); if (response.Response.HttpWebResponse.StatusCode != HttpStatusCode.Created) throw new GitHubUnauthorizedException(response.Response.HttpWebResponse.StatusDescription); return PeelOutGistHtmlUrl(response); } }
public async Task <FluentHttpResponse> Invoke(FluentHttpRequest request) { request.Items["request"] = "item"; var response = await _next(request); return(response); }
public string SendGist(string fileName, string content, string description, bool isPublic, GitHubCredentials credentials) { var gistAsJson = new CreatesGistMessages().CreateMessage(fileName, content, description, isPublic); using (var stream = new MemoryStream()) { var request = new FluentHttpRequest() .BaseUrl("https://api.github.com") .ResourcePath("/gists") .Method("POST") .Headers(h => h.Add("User-Agent", "Gister")) .Headers(h => h.Add("Content-Type", "application/json")) .Body(x => x.Append(gistAsJson)) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(stream)); AppliesGitHubCredentialsToFluentHttpRequest.ApplyCredentials(credentials, request); var response = request .Execute(); if (response.Response.HttpWebResponse.StatusCode != HttpStatusCode.Created) { throw new GitHubUnauthorizedException(response.Response.HttpWebResponse.StatusDescription); } return(PeelOutGistHtmlUrl(response)); } }
/// <inheritdoc /> public async Task <FluentHttpResponse> Invoke(FluentHttpRequest request) { if (!_logger.IsEnabled(LogLevel.Information)) { return(await _next(request)); } var options = request.GetLoggingOptions(_options); if (request.Message.Content == null || !options.ShouldLogDetailedRequest.GetValueOrDefault(false)) { _logger.LogInformation("Pre-request... {request}", request); } else { var requestContent = await request.Message.Content.ReadAsStringAsync(); _logger.LogInformation("Pre-request... {request}\nContent: {requestContent}", request, requestContent); } var response = await _next(request); if (response.Content == null || !options.ShouldLogDetailedResponse.GetValueOrDefault(false)) { _logger.LogInformation("Post-request... {response}", response); return(response); } var responseContent = await response.Content.ReadAsStringAsync(); _logger.LogInformation("Post-request... {response}\nContent: {responseContent}", response, responseContent); return(response); }
private static void GetAsync() { // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/4") .Method("GET") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(q => q .Add("fields", "name,first_name,last_name") .Add("format", "json")) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)); request.ExecuteAsync(ar => { var response = ar.Response; // seek the save stream to beginning. response.SaveStream.Seek(0, SeekOrigin.Begin); // Print the response Console.WriteLine("GetAsync: "); Console.WriteLine(FluentHttpRequest.ToString(response.SaveStream)); }, null); }
/// <inheritdoc /> public async Task <FluentHttpResponse> Invoke(FluentHttpRequest request) { var watch = Stopwatch.StartNew(); FluentHttpResponse response; try { response = await _next(request); } finally { var threshold = request.GetTimerWarnThreshold() .GetValueOrDefault(_options.WarnThreshold); if (_logger.IsEnabled(LogLevel.Warning) && watch.Elapsed > threshold) { _logger.LogWarning(TimeTakenMessage, request, watch.Elapsed.TotalMilliseconds); } else if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation(TimeTakenMessage, request, watch.Elapsed.TotalMilliseconds); } } return(response.SetTimeTaken(watch.Elapsed)); }
public virtual Uri GetLoginUrl(IDictionary<string, object> parameters) { var defaultParameters = new Dictionary<string, object>(); defaultParameters["client_id"] = ClientId; defaultParameters["redirect_uri"] = RedirectUri; var mergedParameters = FluentHttpRequest.Merge(defaultParameters, parameters); // check if client_id and redirect_uri is not null or empty. if (mergedParameters["client_id"] == null || string.IsNullOrEmpty(mergedParameters["client_id"].ToString())) throw new ArgumentNullException("parameters", "client_id requried."); if (mergedParameters["redirect_uri"] == null || string.IsNullOrEmpty(mergedParameters["redirect_uri"].ToString())) throw new ArgumentNullException("parameters", "redirect_uri requried."); // seems like if we don't do this and rather pass the original uri object, // it seems to have http://localhost:80/ instead of // http://localhost/ // notice the port number, that shouldn't be there. // this seems to happen for iis hosted apps. mergedParameters["redirect_uri"] = mergedParameters["redirect_uri"].ToString(); var request = new FluentHttpRequest() .BaseUrl("https://github.com/login/oauth/authorize") .QueryStrings(qs => qs.Add(mergedParameters)); return new Uri(request.BuildRequestUrl()); }
public void ResourcePathShouldBeSlash() { var request = new FluentHttpRequest("https://graph.facebook.com").ResourcePath("/"); var resourcePath = request.GetResourcePath(); Assert.Equal("/", resourcePath); }
public void ItShouldReturnTheOriginalMethod(string originalMethod) { var request = new FluentHttpRequest("https://graph.facebook.com").Method(originalMethod); var method = request.GetMethod(); Assert.Equal(originalMethod, method); }
public void ItShouldStartWithSlash(string originalResourcePath) { var request = new FluentHttpRequest("https://www.facebook.com") .ResourcePath(originalResourcePath); var resourcePath = request.GetResourcePath(); Assert.True(resourcePath.StartsWith("/")); }
public void ItShouldSetItCorrectly() { var request = new FluentHttpRequest("https://graph.facebook.com"); request.BufferSize(10); var bufferSize = request.GetBufferSize(); Assert.Equal(10, bufferSize); }
private static string PeelOutGistHtmlUrl(FluentHttpAsyncResult response) { response.Response.SaveStream.Seek(0, SeekOrigin.Begin); var gistJson = FluentHttpRequest.ToString(response.Response.SaveStream); dynamic gist = JObject.Parse(gistJson); return((string)gist.html_url); }
/// <summary> /// Authenticates the fluent http request using http basic authentication. /// </summary> /// <param name="fluentHttpRequest"> /// The fluent http request. /// </param> public void Authenticate(FluentHttpRequest fluentHttpRequest) { fluentHttpRequest.Headers( headers => headers.Add( "Authorization", string.Concat("Basic ", Convert.ToBase64String( Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Username, Password)))))); }
public void ItShouldSetTheTimeout() { var request = new FluentHttpRequest("https://graph.facebook.com"); request.Timeout(100); var timeout = request.GetTimeout(); Assert.Equal(100, timeout); }
public void ItResourcePathShouldBeEmptyString() { var request = new FluentHttpRequest("https://graph.facebook.com").ResourcePath("/me"); request.ResourcePath(null); var result = request.GetResourcePath(); Assert.Equal(string.Empty, result); }
public void ItShouldStartWithSlashFollowedByTheOriginalResourcePath(string originalResourcePath) { var expcetedResourcePath = string.Concat("/", originalResourcePath); var request = new FluentHttpRequest("https://www.facebook.com") .ResourcePath(originalResourcePath); var resourcePath = request.GetResourcePath(); Assert.Equal(expcetedResourcePath, resourcePath); }
/// <summary> /// Initializes a new instance of the <see cref="FluentHttpAsyncResult"/> class. /// </summary> /// <param name="request">The <see cref="FluentHttpRequest"/>.</param> /// <param name="response">The <see cref="FluentHttpResponse"/>.</param> /// <param name="asyncState">The async state.</param> /// <param name="asyncWaitHandle">The async wait handle.</param> /// <param name="completedSynchronously">Indicates whether the async operation completed synchronously.</param> /// <param name="isCompleted">Indicates whether the async operation completed.</param> /// <param name="isCancelled">Indicates whether the async operation was cancelled.</param> /// <param name="exception">The exception during the http web request.</param> /// <param name="innerException">The inner exception during the http web request.</param> public FluentHttpAsyncResult(FluentHttpRequest request, FluentHttpResponse response, object asyncState, WaitHandle asyncWaitHandle, bool completedSynchronously, bool isCompleted, bool isCancelled, Exception exception, Exception innerException) { _request = request; _response = response; _asyncState = asyncState; _asyncWaitHandle = asyncWaitHandle; _completedSynchronously = completedSynchronously; _isCompleted = isCompleted; _isCancelled = isCancelled; _exception = exception; _innerException = innerException; }
public static void ApplyCredentials(GitHubCredentials credentials, FluentHttpRequest request) { var map = new Dictionary <Type, CredentialVisitor>() { { typeof(AnonymousGitHubCredentials), new AnonymousGitHubCredentialsForFluentHttp() }, { typeof(GitHubUserCredentials), new GitHubUserCredentialsForFluentHttp() } }; var credentialApplier = (from item in map where item.Key == credentials.GetType() select item.Value).First(); credentialApplier.Apply(request, credentials); }
public static void ApplyCredentials(GitHubCredentials credentials, FluentHttpRequest request) { var map = new Dictionary<Type, CredentialVisitor>() { {typeof (AnonymousGitHubCredentials), new AnonymousGitHubCredentialsForFluentHttp()}, {typeof (GitHubUserCredentials), new GitHubUserCredentialsForFluentHttp()} }; var credentialApplier = (from item in map where item.Key == credentials.GetType() select item.Value).First(); credentialApplier.Apply(request, credentials); }
public static string UploadPhoto(string path, string filename, string contentType, string message) { var parameters = new Dictionary <string, object>(); parameters["message"] = message; parameters["file1"] = new MediaObject { ContentType = contentType, FileName = Path.GetFileName(filename) } .SetValue(File.ReadAllBytes(path)); // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/me/photos") .Method("POST") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(qs => qs.Add("access_token", AccessToken)) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)) .Body(body => AttachRequestBodyAndUpdateHeader(body.Request, parameters, null)); // Execute the request. Call EndRequest immediately so it behaves synchronously. var ar = request.Execute(); // seek the save stream to beginning. responseSaveStream.Seek(0, SeekOrigin.Begin); var responseResult = FluentHttpRequest.ToString(responseSaveStream); // Convert to json var json = (IDictionary <string, object>)SimpleJson.SimpleJson.DeserializeObject(responseResult); if (ar.Exception != null) { throw ar.Exception; } // Print the response Console.WriteLine("Upload photo: "); Console.WriteLine(responseResult); if (ar.InnerException != null) { throw ar.InnerException; } return((string)json["id"]); }
public static string UploadPhoto(string path, string filename, string contentType, string message) { var parameters = new Dictionary<string, object>(); parameters["message"] = message; parameters["file1"] = new MediaObject { ContentType = contentType, FileName = Path.GetFileName(filename) } .SetValue(File.ReadAllBytes(path)); // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/me/photos") .Method("POST") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(qs => qs.Add("access_token", AccessToken)) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)) .Body(body => AttachRequestBodyAndUpdateHeader(body.Request, parameters, null)); // Execute the request. Call EndRequest immediately so it behaves synchronously. var ar = request.Execute(); // seek the save stream to beginning. responseSaveStream.Seek(0, SeekOrigin.Begin); var responseResult = FluentHttpRequest.ToString(responseSaveStream); // Convert to json var json = (IDictionary<string, object>)SimpleJson.SimpleJson.DeserializeObject(responseResult); if (ar.Exception != null) { throw ar.Exception; } // Print the response Console.WriteLine("Upload photo: "); Console.WriteLine(responseResult); if (ar.InnerException != null) { throw ar.InnerException; } return (string)json["id"]; }
private string GetFacebookToken() { var oauthuri = Consts.BASE_URI + "/oauth/access_token?client_id=******&client_secret=****&grant_type=client_credentials"; using (var responseSaveStream = new MemoryStream()) { var request = new FluentHttpRequest() .BaseUrl(oauthuri) .Method("GET") .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)); var ar = request.Execute(); var response = ar.Response; // seek the save stream to beginning. response.SaveStream.Seek(0, SeekOrigin.Begin); var token = FluentHttpRequest.ToString(response.SaveStream); return token.Split('=')[1]; } }
private static string Post(string message) { // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/me/feed") .Method("POST") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(q => q .Add("format", "json") .Add("access_token", AccessToken)) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)) .Body(body => { var parameters = new Dictionary <string, object>(); parameters["message"] = message; AttachRequestBodyAndUpdateHeader(body.Request, parameters, null); }); // Execute the request. var ar = request.Execute(); // seek the save stream to beginning. responseSaveStream.Seek(0, SeekOrigin.Begin); var responseResult = FluentHttpRequest.ToString(responseSaveStream); // Convert to json var json = (IDictionary <string, object>)SimpleJson.SimpleJson.DeserializeObject(responseResult); // Print the response Console.WriteLine("Post: "); Console.WriteLine(responseResult); return((string)json["id"]); }
public void GivenANewFluentHttpRequest() { _fluentHttpRequest = new FluentHttpRequest("https://graph.facebook.com"); }
/// <summary> /// Authenticates the fluent http request using OAuth2. /// </summary> /// <param name="fluentHttpRequest">The fluent http request.</param> public abstract void Authenticate(FluentHttpRequest fluentHttpRequest);
/// <summary> /// Initializes a new instance of the <see cref="FluentHttpRequestBody"/> class. /// </summary> public FluentHttpRequestBody(FluentHttpRequest request) { _request = request; _streams = new List<Stream>(); }
internal static void AttachRequestBodyAndUpdateHeader(FluentHttpRequest request, IDictionary<string, object> parameters, string boundary) { if (request == null) throw new ArgumentNullException("request"); if (parameters == null) return; if (string.IsNullOrEmpty(boundary)) boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture); var mediaObjects = ExtractMediaObjects(parameters); if (mediaObjects.Count == 0) { request.Headers(h => h.Add("Content-Type", "application/x-www-form-urlencoded")); var sb = new StringBuilder(); bool isFirst = true; foreach (var key in parameters.Keys) { if (isFirst) isFirst = false; else sb.Append("&"); if (parameters[key] != null) { // Format Object As Json And Remove leading and trailing parenthesis string jsonValue = SimpleJson.SimpleJson.SerializeObject(parameters[key]); jsonValue = SimpleJson.SimpleJson.EscapeToJavascriptString(jsonValue); if (jsonValue.StartsWith("\"", StringComparison.Ordinal)) jsonValue = jsonValue.Substring(1, jsonValue.Length - 1); if (jsonValue.EndsWith("\"", StringComparison.Ordinal)) jsonValue = jsonValue.Substring(0, jsonValue.Length - 1); if (!string.IsNullOrEmpty(jsonValue)) sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", FluentHttpRequest.UrlEncode(key), FluentHttpRequest.UrlEncode(jsonValue)); } else { sb.Append(FluentHttpRequest.UrlEncode(key)); } request.Body(body => body.Append(sb.ToString())); } } else { request.Headers(h => h.Add("Content-Type", string.Concat("multipart/form-data; boundary=", boundary))); // Build up the post message header var sb = new StringBuilder(); foreach (var kvp in parameters) { sb.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine); sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", kvp.Key); sb.AppendFormat("{0}{0}{1}{0}", MultiPartNewLine, kvp.Value); } request.Body(b => b.Append(sb.ToString())); var newLine = Encoding.UTF8.GetBytes(MultiPartNewLine); foreach (var kvp in mediaObjects) { var sbMediaObject = new StringBuilder(); var mediaObject = kvp.Value; if (mediaObject.ContentType == null || mediaObject.GetValue() == null || string.IsNullOrEmpty(mediaObject.FileName)) throw new InvalidOperationException("The media object must have a content type, file name, and value set."); sbMediaObject.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine); sbMediaObject.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", kvp.Key, mediaObject.FileName, MultiPartNewLine); sbMediaObject.AppendFormat("Content-Type: {0}{1}{1}", mediaObject.ContentType, MultiPartNewLine); byte[] fileData = mediaObject.GetValue(); Debug.Assert(fileData != null, "The value of MediaObject is null."); request.Body(b => b .Append(sbMediaObject.ToString()) .Append(fileData) .Append(newLine)); } request.Body(body => body.Append(Encoding.UTF8.GetBytes(string.Concat(MultiPartNewLine, MultiPartFormPrefix, boundary, MultiPartFormPrefix, MultiPartNewLine)))); } }
/// <summary> /// Authenticate the fluent http request using OAuth2 uri querystring parameter bearer_token. /// </summary> /// <param name="fluentHttpRequest">The fluent http request.</param> public override void Authenticate(FluentHttpRequest fluentHttpRequest) { fluentHttpRequest.QueryStrings(qs => qs.Add("bearer_token", BearerToken)); }
private static string Post(string message) { // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/me/feed") .Method("POST") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(q => q .Add("format", "json") .Add("access_token", AccessToken)) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)) .Body(body => { var parameters = new Dictionary<string, object>(); parameters["message"] = message; AttachRequestBodyAndUpdateHeader(body.Request, parameters, null); }); // Execute the request. var ar = request.Execute(); // seek the save stream to beginning. responseSaveStream.Seek(0, SeekOrigin.Begin); var responseResult = FluentHttpRequest.ToString(responseSaveStream); // Convert to json var json = (IDictionary<string, object>)SimpleJson.SimpleJson.DeserializeObject(responseResult); // Print the response Console.WriteLine("Post: "); Console.WriteLine(responseResult); return (string)json["id"]; }
internal FluentHttpRequest PrepareRequest(string method, string url, IDictionary<string, object> parameters, Stream responseStream) { /* if (!method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException("method", "Only POST http method supported."); } */ var request = new FluentHttpRequest() .BaseUrl(url) .Method(method) .Headers(h => h.Add("Content-Type", "application/x-www-form-urlencoded")) .Body(b => b.Append(parameters)) .Proxy(Proxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseStream)); ; return request; }
private static void GetAsyncWithTask() { // Stream to save the response to var responseSaveStream = new MemoryStream(); // Prepare the request. var request = new FluentHttpRequest() .BaseUrl("https://graph.facebook.com") .ResourcePath("/4") .Method("GET") .Headers(h => h.Add("User-Agent", "FluentHttp")) .QueryStrings(q => q .Add("fields", "name,first_name,last_name") .Add("format", "json")) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)); var task = request.ExecuteTaskAsync(); task.ContinueWith( t => { var ar = t.Result; // seek the save stream to beginning. ar.Response.SaveStream.Seek(0, SeekOrigin.Begin); // Print the response Console.WriteLine("GetAsyncWithTask: "); Console.WriteLine(FluentHttpRequest.ToString(ar.Response.SaveStream)); }); }
public GivenABaseUrlThen() { request = new FluentHttpRequest("https://graph.facebook.com"); }
public void Apply(FluentHttpRequest request, GitHubCredentials credentials) { }
public void Apply(FluentHttpRequest request, GitHubCredentials credentials) { var userCreds = (GitHubUserCredentials)credentials; request.AuthenticateUsing(new HttpBasicAuthenticator(userCreds.Username, userCreds.Password)); }
/// <summary> /// Initializes a new instance of the <see cref="FluentHttpResponse"/> class. /// </summary> /// <param name="request"> /// The fluent http web request. /// </param> /// <param name="httpWebResponse"> /// The http web response. /// </param> public FluentHttpResponse(FluentHttpRequest request, IHttpWebResponse httpWebResponse) : this() { _request = request; _httpWebResponse = httpWebResponse; }
/// <inheritdoc /> public async Task <FluentHttpResponse> Run(FluentHttpRequest request, Func <Task <FluentHttpResponse> > action) => await _middleware.Invoke(new FluentHttpMiddlewareContext { Func = action, Request = request }).ConfigureAwait(false);
internal static void AttachRequestBodyAndUpdateHeader(FluentHttpRequest request, IDictionary <string, object> parameters, string boundary) { if (request == null) { throw new ArgumentNullException("request"); } if (parameters == null) { return; } if (string.IsNullOrEmpty(boundary)) { boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture); } var mediaObjects = ExtractMediaObjects(parameters); if (mediaObjects.Count == 0) { request.Headers(h => h.Add("Content-Type", "application/x-www-form-urlencoded")); var sb = new StringBuilder(); bool isFirst = true; foreach (var key in parameters.Keys) { if (isFirst) { isFirst = false; } else { sb.Append("&"); } if (parameters[key] != null) { // Format Object As Json And Remove leading and trailing parenthesis string jsonValue = SimpleJson.SimpleJson.SerializeObject(parameters[key]); jsonValue = SimpleJson.SimpleJson.EscapeToJavascriptString(jsonValue); if (jsonValue.StartsWith("\"", StringComparison.Ordinal)) { jsonValue = jsonValue.Substring(1, jsonValue.Length - 1); } if (jsonValue.EndsWith("\"", StringComparison.Ordinal)) { jsonValue = jsonValue.Substring(0, jsonValue.Length - 1); } if (!string.IsNullOrEmpty(jsonValue)) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", FluentHttpRequest.UrlEncode(key), FluentHttpRequest.UrlEncode(jsonValue)); } } else { sb.Append(FluentHttpRequest.UrlEncode(key)); } request.Body(body => body.Append(sb.ToString())); } } else { request.Headers(h => h.Add("Content-Type", string.Concat("multipart/form-data; boundary=", boundary))); // Build up the post message header var sb = new StringBuilder(); foreach (var kvp in parameters) { sb.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine); sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", kvp.Key); sb.AppendFormat("{0}{0}{1}{0}", MultiPartNewLine, kvp.Value); } request.Body(b => b.Append(sb.ToString())); var newLine = Encoding.UTF8.GetBytes(MultiPartNewLine); foreach (var kvp in mediaObjects) { var sbMediaObject = new StringBuilder(); var mediaObject = kvp.Value; if (mediaObject.ContentType == null || mediaObject.GetValue() == null || string.IsNullOrEmpty(mediaObject.FileName)) { throw new InvalidOperationException("The media object must have a content type, file name, and value set."); } sbMediaObject.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine); sbMediaObject.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", kvp.Key, mediaObject.FileName, MultiPartNewLine); sbMediaObject.AppendFormat("Content-Type: {0}{1}{1}", mediaObject.ContentType, MultiPartNewLine); byte[] fileData = mediaObject.GetValue(); Debug.Assert(fileData != null, "The value of MediaObject is null."); request.Body(b => b .Append(sbMediaObject.ToString()) .Append(fileData) .Append(newLine)); } request.Body(body => body.Append(Encoding.UTF8.GetBytes(string.Concat(MultiPartNewLine, MultiPartFormPrefix, boundary, MultiPartFormPrefix, MultiPartNewLine)))); } }
private void GetAllResultsRecursive(string uri, IDictionary<string, object> query, List<string> results, IDictionary<string, object> projectparameters) { if (!IsStarted) return; string json = string.Empty; try { using (var responseSaveStream = new MemoryStream()) { var request = new FluentHttpRequest() .BaseUrl(uri) .Method("GET") .QueryStrings(q => q .Add(query) //add all query strings ) .Proxy(WebRequest.DefaultWebProxy) .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseSaveStream)); request.AuthenticateUsing(new OAuth2AuthorizationRequestHeaderBearerAuthenticator(GetFacebookToken())); var ar = request.Execute(); var response = ar.Response; // seek the save stream to beginning. response.SaveStream.Seek(0, SeekOrigin.Begin); json = FluentHttpRequest.ToString(response.SaveStream); Dictionary<string, object> responseobject = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); if (responseobject.ContainsKey(Consts.DATA_KEY) && responseobject[Consts.DATA_KEY].HasValue()) { IList<object> datas = JsonConvert.DeserializeObject<IList<object>>(responseobject[Consts.DATA_KEY].ToString()); if (datas.Count > 0) { for (int i = 0; i < datas.Count; i++) { IDictionary<string, object> resultdic = JsonConvert.DeserializeObject<Dictionary<string, object>>(datas[i].ToString()); //resultdic.Add(Consts.WORDS_KEY, projectparameters); //resultdic.Add(Consts.PROVIDER_KEY, "FaceBook"); if (resultdic.ContainsKey(Consts.DESCRIPTION)) { var message = HttpUtility.HtmlDecode(resultdic[Consts.DESCRIPTION].ToString()); results.Add(message.Substring(0, message.Length < 140 ? message.Length : 140)); } //else if (resultdic.ContainsKey(Consts.MESSAGE)) //{ // var message = HttpUtility.HtmlDecode(resultdic[Consts.MESSAGE].ToString()); // results.Add(message.Substring(0, message.Length < 140 ? message.Length : 140)); // } //results.Add(JsonConvert.SerializeObject(resultdic)); resultdic = null; } foreach (var post in results) { if (!IsStarted) return; string p = string.Empty; if (!string.IsNullOrEmpty(additionalString)) { if (140 - post.Length > additionalString.Length + 1) p = post + " " + additionalString; else p = post.Substring(0, post.Length - additionalString.Length + 1) + " " + additionalString; } _twitterService.SendTweet(new SendTweetOptions { Status = p }); _form.Log(post); System.Threading.Thread.Sleep(2000);//twitter kızmasın } if (responseobject.ContainsKey(Consts.PAGING_KEY) && responseobject[Consts.PAGING_KEY].HasValue()) { IDictionary<string, string> nextprevuri = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseobject[Consts.PAGING_KEY].ToString()); if (nextprevuri.ContainsKey(Consts.NEXT_PAGE_KEY) && nextprevuri[Consts.NEXT_PAGE_KEY].HasValue()) { Uri urim = new Uri(nextprevuri[Consts.NEXT_PAGE_KEY].ToString()); var querystrings = ToDictionary(HttpUtility.ParseQueryString(urim.Query)); urim = null; GetAllResultsRecursive(m_baseUrl, querystrings, results, projectparameters); if (string.IsNullOrEmpty(m_untilValue) && querystrings[Consts.UNTIL_KEY].HasValue()) { m_untilValue = querystrings[Consts.UNTIL_KEY].ToString(); WriteSince(querystrings[Consts.QUERY_KEY].ToString(), m_untilValue); } } } } } request = null; GC.Collect(); } } catch (Exception ex) { throw; } }
/// <summary> /// Authenticate the fluent http request using OAuth2 authorization header bearer_token. /// </summary> /// <param name="fluentHttpRequest">The fluent http request.</param> public override void Authenticate(FluentHttpRequest fluentHttpRequest) { fluentHttpRequest.Headers(h => h.Add("Authorization", string.Concat("Bearer ", BearerToken))); }
/// <summary> /// Run specified middleware, and finally send the given request. /// </summary> /// <param name="middlewareCollection">Middleware to pipe.</param> /// <param name="request">Request to send.</param> /// <param name="send">Actual send function.</param> /// <returns>Returns response.</returns> public async Task <FluentHttpResponse> Run(IList <MiddlewareConfig> middlewareCollection, FluentHttpRequest request, FluentHttpRequestDelegate send) { if (middlewareCollection.Count == 0) { return(await send(request)); } FluentHttpResponse httpResult = null; IFluentHttpMiddleware previousMiddleware = null; for (int i = middlewareCollection.Count; i-- > 0;) { request.CancellationToken.ThrowIfCancellationRequested(); var middlewareOptions = middlewareCollection[i]; var isLast = middlewareCollection.Count - 1 == i; var isFirst = i == 0; var next = isLast ? send : previousMiddleware.Invoke; object[] ctor; if (middlewareOptions.Args == null) { ctor = new object[] { next } } ; else { ctor = new object[middlewareOptions.Args.Length + 1]; ctor[0] = next; Array.Copy(middlewareOptions.Args, 0, ctor, 1, middlewareOptions.Args.Length); } var instance = (IFluentHttpMiddleware)ActivatorUtilities.CreateInstance(_serviceProvider, middlewareOptions.Type, ctor); if (isFirst) { httpResult = await instance.Invoke(request); } else { previousMiddleware = instance; } } return(httpResult); }