private async Task <HttpResponseMessage> PostToApi(dynamic data, string apiUrl) { var client = new HttpClient(); var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)); var content = new ByteArrayContent(byteData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry) ?? Policy.NoOpAsync <HttpResponseMessage>(); var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object> { { PolicyContextItems.Logger, _logger }, { "url", apiUrl } }); var retries = 0; // ReSharper disable once AccessToDisposedClosure var response = await retryPolicy.ExecuteAsync((ctx) => { client.DefaultRequestHeaders.Remove("retries"); client.DefaultRequestHeaders.Add("retries", new [] { retries++.ToString() }); var uri = Request.GetUri(); var baseUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; var isValid = Uri.IsWellFormedUriString(apiUrl, UriKind.Absolute); return(client.PostAsync(isValid ? apiUrl : $"{baseUrl}/api/Face", content)); }, context); content.Dispose(); return(response); }
public Task <TResponse> PostFileWithRequestAsync <TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request, string fieldName = "upload") { var queryString = QueryStringSerializer.SerializeToString(request); var nameValueCollection = PclExportClient.Instance.ParseQueryString(queryString); var content = new MultipartFormDataContent(); foreach (string key in nameValueCollection) { var value = nameValueCollection[key]; content.Add(new StringContent(value), "\"{0}\"".Fmt(key)); } var fileBytes = fileToUpload.ReadFully(); var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeTypes.GetMimeType(fileName)); content.Add(fileContent, "file", fileName); return(SendAsync <TResponse>(HttpMethods.Post, GetBaseUrl(relativeOrAbsoluteUrl), content) .ContinueWith(t => { content.Dispose(); fileContent.Dispose(); return t.Result; }, TaskContinuationOptions.ExecuteSynchronously)); }
/// <summary> /// Sends a PUT type request including the parameters values from /// a byte array object /// </summary> /// <param name="urlBase">Main resource address</param> /// <param name="method">Method resource address part</param> /// <param name="parameters">Parameters to include in request</param> /// <returns>HttpResponseMessage</returns> public async Task <HttpResponseMessage> Put(string urlBase, string method, byte[] parameters) { //Verify http request integrity if (!urlBase.IsWebDirectory(out Uri uri) || method.IsNotValid() || parameters.IsNotValid()) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } HttpResponseMessage response; try { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(urlBase); AddHeaders(client); using (HttpContent content = new ByteArrayContent(parameters)) { response = await client.PutAsync(method, content); content.Dispose(); } client.Dispose(); } } catch (Exception ex) { response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(JsonConvert.SerializeObject(ex)) }; } return(response); }
private async Task <List <ImageUpload> > BatchUploadAsync(IAsyncEnumerable <ImageData> images) { var uploads = new List <ImageUpload>(); await foreach (var image in images) { using var stream = image.Stream; stream.Position = 0; var bytes = new byte[stream.Length]; await stream.ReadAsync(bytes); var content = new ByteArrayContent(bytes); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Headers.Add("X-Goog-Upload-Content-Type", image.ContentType); content.Headers.Add("X-Goog-Upload-Protocol", "raw"); var response = await googleHttpClient.PostAsync( "https://photoslibrary.googleapis.com/v1/uploads", content ); response.EnsureSuccessStatusCode(); var uploadToken = await response.Content.ReadAsStringAsync(); uploads.Add(new ImageUpload { UploadToken = uploadToken, Description = image.Description, }); content.Dispose(); stream.Dispose(); } return(uploads); }
public async Task <byte[]> GetPDF() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:8000/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); ByteArrayContent postContent = new ByteArrayContent(GetPostContent()); postContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json"); try { HttpResponseMessage response = await client.PostAsync("/", postContent); postContent.Dispose(); if (response.IsSuccessStatusCode) { foreach (var header in response.Content.Headers) { System.Console.Write("{0}:", header.Key); foreach (var v in header.Value) { System.Console.Write("{0}, ", v); } System.Console.WriteLine(); } return(await response.Content.ReadAsByteArrayAsync()); } } catch (AggregateException ex) { Console.Error.WriteLine(ex.StackTrace); } return(null); } }
private async Task <HttpResponseMessage> PostToApi(dynamic data, string apiUrl) { var client = new HttpClient(); var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)); var content = new ByteArrayContent(byteData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry) ?? Policy.NoOpAsync <HttpResponseMessage>(); var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object> { { PolicyContextItems.Logger, _logger } }); var retries = 0; // ReSharper disable once AccessToDisposedClosure var response = await retryPolicy.ExecuteAsync((ctx) => { client.DefaultRequestHeaders.Remove("retries"); client.DefaultRequestHeaders.Add("retries", new [] { retries++.ToString() }); return(client.PostAsync(apiUrl, content)); }, context); content.Dispose(); return(response); }
private static string UploadToDPSR(FileInfo fi, string URI) { string fileName = fi.Name; byte[] fileContents = File.ReadAllBytes(fi.FullName); const int tentatives = 5; string res = "Upload process failed"; for (int i = 0; i < tentatives; i++) { var webService = new Uri(@URI); var requestMessage = new HttpRequestMessage(HttpMethod.Post, webService); requestMessage.Headers.ExpectContinue = false; var multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); var byteArrayContent = new ByteArrayContent(fileContents); byteArrayContent.Headers.Add("Content-Type", "application/octet-stream"); multiPartContent.Add(byteArrayContent, "file", fileName); //multiPartContent.Add(new StringContent("generator=ei"), "gen", "ei"); requestMessage.Content = multiPartContent; var httpClient = new HttpClient(); try { Task <HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None); HttpResponseMessage httpResponse = httpRequest.Result; HttpStatusCode statusCode = httpResponse.StatusCode; HttpContent responseContent = httpResponse.Content; if (responseContent != null) { Task <string> stringContentsTask = responseContent.ReadAsStringAsync(); string stringContents = stringContentsTask.Result; int first = stringContents.IndexOf('{'); int length = stringContents.LastIndexOf('}') - first + 1; string JSONFormat = stringContents.Substring(first, length); DPSReportsResponseItem item = JsonConvert.DeserializeObject <DPSReportsResponseItem>(JSONFormat, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() } }); return(item.Permalink); } } catch (Exception e) { res = e.GetFinalException().Message; } finally { byteArrayContent.Dispose(); httpClient.Dispose(); requestMessage.Dispose(); } } return(res); }
public async Task <string> AddSimple(IFormFile file, string id) { if (file == null || file.Length <= 0) { return(null); } if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentException("message", nameof(id)); } using var form = new MultipartFormDataContent(); var method = new StringContent("pwg.images.addSimple"); form.Add(method, "method"); var name = new StringContent(id); form.Add(name, "name"); byte[] fileBytes; using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { Name = "image", FileName = file.FileName }; form.Add(fileContent, "image"); try { using var response = await _client.PostAsync("?format=json", form).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var pwg = response.Content.ReadAsStringAsync().Result; var one = pwg.IndexOf("/upload", StringComparison.InvariantCulture); var two = pwg.LastIndexOf("\"", StringComparison.InvariantCulture) - one; var result = pwg.Substring(one, two).Replace("\\", "", StringComparison.InvariantCulture); result = result.Insert(result.LastIndexOf(".", StringComparison.InvariantCulture), "-sq"); return(result); } catch (Exception) { throw; } finally { fileContent.Dispose(); name.Dispose(); method.Dispose(); } }
private static async Task Handle(Message message, CancellationToken arg2) { Console.WriteLine($"message Label: {message.Label}"); Console.WriteLine($"message CorrelationId: {message.CorrelationId}"); var newOrderString = Encoding.UTF8.GetString(message.Body); var order = JsonConvert.DeserializeObject <NewOrderMessage>(newOrderString); var _orderToUpsert = new OrderToUpsert(); _orderToUpsert.OrderId = order.OrderId; _orderToUpsert.Products = order.Products; _orderToUpsert.Productions = order.ProductionIds; Console.WriteLine("Message Received"); Console.WriteLine(newOrderString); //Thread.Sleep(40000); var client = new HttpClient(); var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_orderToUpsert)); var content = new ByteArrayContent(byteData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var _policyRegistry = new PolicyRegistry(); var apiUrl = "/api/order"; var _baseUri = "http://localhost:5009/"; var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("basic-retry") ?? Policy.NoOpAsync <HttpResponseMessage>(); var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object> { { "url", apiUrl } }); var retries = 0; // ReSharper disable once AccessToDisposedClosure var response = await retryPolicy.ExecuteAsync((ctx) => { client.DefaultRequestHeaders.Remove("retries"); client.DefaultRequestHeaders.Add("retries", new[] { retries++.ToString() }); var baseUrl = _baseUri; var isValid = Uri.IsWellFormedUriString(apiUrl, UriKind.Absolute); return(client.PostAsync(isValid ? $"{baseUrl}{apiUrl}" : $"{baseUrl}/api/Order", content)); }, context); content.Dispose(); return; }
/// <summary> /// Upload media data to WeChat. /// </summary> /// <typeparam name="T">The upload result type.</typeparam> /// <param name="attachmentData">The attachment data need to be uploaded.</param> /// <param name="url">The endpoint when upload the data.</param> /// <param name="isTemporaryMedia">If upload media as a temporary media.</param> /// <param name="timeout">Upload media timeout.</param> /// <returns>Uploaded result from WeChat.</returns> private async Task <UploadMediaResult> UploadMediaAsync(AttachmentData attachmentData, string url, bool isTemporaryMedia, int timeout = 30000) { try { // Border break var boundary = "---------------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture); using (var mutipartDataContent = new MultipartFormDataContent(boundary)) { mutipartDataContent.Headers.Remove("Content-Type"); mutipartDataContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary); // Add attachment content. var contentByte = new ByteArrayContent(attachmentData.OriginalBase64); contentByte.Headers.Remove("Content-Disposition"); var ext = GetMediaExtension(attachmentData.Name, attachmentData.Type); contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{attachmentData.Name + ext}\""); contentByte.Headers.Remove("Content-Type"); contentByte.Headers.TryAddWithoutValidation("Content-Type", attachmentData.Type); mutipartDataContent.Add(contentByte); // Additional form is required when upload a forever video. StringContent stringContent = null; if (isTemporaryMedia == false && attachmentData.Type.Contains(MediaTypes.Video)) { var additionalForm = string.Format(CultureInfo.InvariantCulture, "{{\"title\":\"{0}\", \"introduction\":\"introduction\"}}", attachmentData.Name); // Important! name must be "description" stringContent = new StringContent(additionalForm); mutipartDataContent.Add(stringContent, "\"description\""); } _logger.LogInformation($"Upload {attachmentData.Type} to WeChat", Severity.Information); var response = await SendHttpRequestAsync(HttpMethod.Post, url, mutipartDataContent, null, timeout).ConfigureAwait(false); // Disponse all http content in mutipart form data content before return. contentByte.Dispose(); if (stringContent != null) { stringContent.Dispose(); } if (isTemporaryMedia) { return(ConvertBytesToType <UploadTemporaryMediaResult>(response)); } return(ConvertBytesToType <UploadPersistentMediaResult>(response)); } } catch (Exception ex) { _logger.LogError(ex, $"Failed To Upload Media, Type: {attachmentData.Type}"); throw; } }
private async Task <string> MakeOCRRequest(byte[] imageBytes) { _log.Info("Making OCR request"); var licensePlate = string.Empty; // Request parameters. const string requestParameters = "language=unk&detectOrientation=true"; // Get the API URL and the API key from settings. // TODO 2: Populate the below two variables with the correct AppSettings properties. var uriBase = ConfigurationManager.AppSettings["computerVisionApiUrl"]; var apiKey = ConfigurationManager.AppSettings["computerVisionApiKey"]; var resiliencyStrategy = DefineAndRetrieveResiliencyStrategy(); // Configure the HttpClient request headers. _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Assemble the URI for the REST API Call. var uri = uriBase + "?" + requestParameters; var content = new ByteArrayContent(imageBytes); try { // Add application/octet-stream header for the content. content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // Execute the REST API call, implementing our resiliency strategy. HttpResponseMessage response = await resiliencyStrategy.ExecuteAsync(() => _client.PostAsync(uri, content)); // Get the JSON response. var result = await response.Content.ReadAsAsync <OCRResult>(); licensePlate = GetLicensePlateTextFromResult(result); content.Dispose(); } catch (BrokenCircuitException bce) { _log.Error($"Could not contact the Computer Vision API service due to the following error: {bce.Message}"); } catch (Exception e) { _log.Error($"Critical error: {e.Message}", e); } _log.Info($"Finished OCR request. Result: {licensePlate}"); return(licensePlate); }
public static async Task <HttpResponseMessage> PostAsync(Uri uri, string jsonSerializedStrategy, IEnumerable <string> libraries) { if (libraries == null) { throw new ArgumentNullException(nameof(libraries)); } var stringContent = new StringContent(jsonSerializedStrategy, Encoding.UTF8, "application/json"); var byteArrayContents = new List <ByteArrayContent>(); try { using (var client = new HttpClient()) { using (var multipartFormDataContent = new MultipartFormDataContent()) { multipartFormDataContent.Add(stringContent, "strategy"); foreach (var file in libraries) { var fileInfo = new FileInfo(file); using (var fileStream = File.OpenRead(file)) { using (var br = new BinaryReader(fileStream)) { var byteArrayContent = new ByteArrayContent(br.ReadBytes((int)fileStream.Length)); multipartFormDataContent.Add(byteArrayContent, fileInfo.Name, fileInfo.FullName); byteArrayContents.Add(byteArrayContent); } } } return(await client.PostAsync(uri, multipartFormDataContent).ConfigureAwait(false)); } } } finally { foreach (var byteArrayContent in byteArrayContents) { byteArrayContent.Dispose(); } stringContent.Dispose(); } }
public Task <TResponse> PostFileAsync <TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType = null) { var content = new MultipartFormDataContent(); var fileBytes = fileToUpload.ReadFully(); var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType ?? MimeTypes.GetMimeType(fileName)); content.Add(fileContent, "file", fileName); return(SendAsync <TResponse>(HttpMethods.Post, GetBaseUrl(relativeOrAbsoluteUrl), content) .ContinueWith(t => { content.Dispose(); fileContent.Dispose(); return t.Result; }, TaskContinuationOptions.ExecuteSynchronously)); }
internal async Task <bool> UploadFileToApiAsync(byte[] bytes, string fileName, string token) { var content = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(bytes); var client = new HttpClient(); try { var apiUrlPath = cs.GetAppSetting(c.FileUploadApiUrlKey); var bearerToken = $"Bearer {token}"; client.DefaultRequestHeaders.Add("Authorization", bearerToken); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; content.Add(fileContent); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); var result = await client.PostAsync($"{_apiHostName}{apiUrlPath}", content).ConfigureAwait(false); var retVal = result.IsSuccessStatusCode; if (!cs.AppIsInDebugMode) { return(retVal); } var methodName = MethodBase.GetCurrentMethod().Name; var now = DateTime.Now.ToString("G"); Logger.Info(retVal ? $"Successfully uploaded file {fileName} from method {methodName} on {now}." : $"Failed to upload file {fileName} to server from method {methodName} on {now}."); return(retVal); } catch (Exception ex) { Logger.Error(ex); throw; } finally { content.Dispose(); fileContent.Dispose(); client.Dispose(); } }
public static async Task UpdatePassword(byte[] currentPassword, byte[] newPassword, byte[] confirmPassword) { byte[] currentPasswordVariable = Encoding.UTF8.GetBytes("CurrentPassword="******"&NewPassword="******"&ConfirmPassword="******"An error occurred"); } } }
public static async Task Login(string username, byte[] password) { byte[] bytes = Encoding.UTF8.GetBytes("Username="******"&Password="******"CurrentUsername", username); } else if (status == 400) { throw new LoginException(); } else if (status == 401) { throw new LoginException(); } else if (status == 500) { throw new ServerException(); } else { //Uncaught status code throw new Exception("An unknown error occurred"); } } }
private async void Upload(ByteArrayContent ba, string LabelName) { ba.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); ba.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "fileUpload", FileName = LabelName + ".jpg" }; string boundary = "---8393774hhy37373773"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary); multipartContent.Add(ba); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.PostAsync("http://www.theplacetobe.ovh/admin/upload.php", multipartContent); string responseString = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); ba.Dispose(); }
/// <summary> /// Отправка изображения на сервер /// </summary> /// <param name="image">Изображение, которое следует отправить.</param> /// <returns>Ответ от сервера</returns> public static async Task <json_st.ResponsePost> SendScreen(byte[] image) { // Создание контейнера для отправки var requ = new MultipartFormDataContent(); // Конвектируем массив байтов в контент HTTP протокола var ImContent = new ByteArrayContent(image); // Указываем тип конента ImContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); // Добавление сведений о контенте в контейнере requ.Add(ImContent, "up_image", "image.png"); // Отправка изображения HttpResponseMessage response = await cl.PostAsync(Settings.UPLOAD, requ); // Уничтожение контейнера requ.Dispose(); // Уничтожение контента HTTP ImContent.Dispose(); // Конвектирование ответа JSON в структуру C# return(await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync <json_st.ResponsePost> (await response.Content.ReadAsStringAsync())); }
public async Task <Emotion[]> RecognizeEmotionsAsync(byte[] imageBytes) { var content = new ByteArrayContent(imageBytes); await content.LoadIntoBufferAsync(); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await EmotionServiceHttpClient.PostAsync("", content); Debug.WriteLine("Response Is" + response); var resultContent = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return(null); } Debug.WriteLine("Content Is" + resultContent); var emotions = JsonConvert.DeserializeObject <Emotion[]>(resultContent); content.Dispose(); return(emotions); }
// Background uploader private void _WorkerThreadFunc() { _Log("[Worker] Up and running"); //_IsWorkerActive = true; while (!_WorkerThreadStopped) { //if (_WorkerStopWatch != null) // _WorkerStopWatch.Stop(); // Wait for activation _WorkerWakeup.WaitOne(); _WorkerWakeup.Reset(); //_WorkerStopWatch = _Stopwatch.StartNew(); if (_WorkerThreadStopped) { _Debug("[Worker] Received STOP"); break; } _Debug("[Worker] Peeking for data avail ..."); byte[] data = null; lock (_UploadQueue) { if (_UploadQueue.Count > 0) { data = _UploadQueue.Peek(); } } if (data == null) { _Debug("[Worker] ... none avail, going back to sleep"); continue; // Cease work for now } if (data.Length == 0) { _Debug("[Worker] ... skipping empty data, going back to sleep"); continue; // Cease work for now } _Log("[Worker] Trying to send a {0} of data", data.Length); HttpContent content = null; Task <HttpResponseMessage> post = null; HttpResponseMessage result = null; Task <string> response = null; try { while (true) { content = new ByteArrayContent(data); _Debug("[Worker] POSTing ..."); post = _Client.PostAsync(_Url, content); while (!post.IsCompleted) { post.Wait(100); if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { break; } } if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { _Debug("[Worker] Received STOP in middle of operation (Post)"); break; } result = post.Result; #if DEBUG StringBuilder sb = new StringBuilder(); sb.Append("[Worker] ... result header:"); foreach (var h in result.Headers) { string vals; if (h.Value != null) { vals = "'" + string.Join("' | '", h.Value) + "'"; } else { vals = "n/a"; } sb.AppendFormat("\n- {0}: {1}", h.Key, vals); } _Debug(sb.ToString()); #endif response = result.Content.ReadAsStringAsync(); while (!response.IsCompleted) { response.Wait(100); if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { break; } } if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { _Debug("[Worker] Received STOP in middle of operation (Response)"); break; } if (!result.IsSuccessStatusCode) { _Error("[Worker] ... failed -> {0} | {1}", result.StatusCode, response.Result); //TODO: What to do in case of failure? } else { // Done our job w/o any issues #if DEBUG _Debug("[Worker] ... success -> {0} | {1}", result.StatusCode, response.Result); #else _Log("[Worker] ... success"); #endif lock (_UploadQueue) _UploadQueue.Dequeue(); } break; } if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { _Debug("[Worker] Received STOP in middle of operation, killing pending requests"); _Client.CancelPendingRequests(); } } catch (Exception exc) { _Error("[Worker] ... failed with exception!", exc); //TODO: What to do in case of failure? _Client.CancelPendingRequests(); } finally { // Cleanup if (post != null) { post.Dispose(); } if (result != null) { result.Dispose(); } if (response != null) { response.Dispose(); } if (content != null) { content.Dispose(); } } _Debug("[Worker] Going back to sleep"); } if (_WorkerThreadStopped || _WorkerCancelWork.WaitOne(0)) { _Client.CancelPendingRequests(); } if (_WorkerCancelWork.WaitOne(0)) { _WorkerCancelWork.Reset(); } //if (_WorkerStopWatch != null) // _WorkerStopWatch.Stop(); // End of thread _Log("[Worker] Is down"); //_IsWorkerActive = false; }
// BUTTON RETOUR private void GoBack(object sender, EventArgs e, ByteArrayContent ba) { ba.Dispose(); // Cancel the scan this.Navigation.PopAsync(); }
private static string UploadToDPSR(FileInfo fi, string URI, OperationController operation) { string fileName = fi.Name; byte[] fileContents = File.ReadAllBytes(fi.FullName); const int tentatives = 5; string res = "Upload process failed"; for (int i = 0; i < tentatives; i++) { operation.UpdateProgressWithCancellationCheck("Upload tentative"); var webService = new Uri(@URI); var requestMessage = new HttpRequestMessage(HttpMethod.Post, webService); requestMessage.Headers.ExpectContinue = false; var multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); var byteArrayContent = new ByteArrayContent(fileContents); byteArrayContent.Headers.Add("Content-Type", "application/octet-stream"); multiPartContent.Add(byteArrayContent, "file", fileName); //multiPartContent.Add(new StringContent("generator=ei"), "gen", "ei"); requestMessage.Content = multiPartContent; var httpClient = new HttpClient(); try { Task <HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None); HttpResponseMessage httpResponse = httpRequest.Result; HttpStatusCode statusCode = httpResponse.StatusCode; HttpContent responseContent = httpResponse.Content; if (statusCode != HttpStatusCode.OK) { throw new HttpRequestException(statusCode.ToString()); } if (responseContent != null) { Task <string> stringContentsTask = responseContent.ReadAsStringAsync(); string stringContents = stringContentsTask.Result; DPSReportsResponseItem item = JsonConvert.DeserializeObject <DPSReportsResponseItem>(stringContents, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() } }); if (item.Error != null) { throw new InvalidOperationException(item.Error); } operation.UpdateProgressWithCancellationCheck("Upload tentative successful"); return(item.Permalink); } } catch (Exception e) { res = e.GetFinalException().Message; operation.UpdateProgressWithCancellationCheck("Upload tentative failed: " + res); } finally { byteArrayContent.Dispose(); httpClient.Dispose(); requestMessage.Dispose(); } } return(res); }
/// <summary> /// Pushes the file to amazon aws. /// </summary> /// <param name="request">The request.</param> /// <param name="fileUploadResponse">The file upload response.</param> /// <exception cref="System.Exception"></exception> private void PushFileToAmazonAWS(PushFileRequest request, FileUploadResponse fileUploadResponse) { StringContent awsaccesskeyidContent = null; StringContent aclContent = null; StringContent keyContent = null; StringContent signatureContent = null; StringContent policyContent = null; StringContent contentTypeContent = null; StringContent cacheControlContent = null; ByteArrayContent fileContent = null; try { using (var multiPartCont = new MultipartFormDataContent()) { awsaccesskeyidContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.AWSAccessKeyId, fileUploadResponse.Data.AWSAccessKeyId); aclContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Acl, fileUploadResponse.Data.Acl); keyContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Key, fileUploadResponse.Data.Key); signatureContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Signature, fileUploadResponse.Data.Signature); policyContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Policy, fileUploadResponse.Data.Policy); contentTypeContent = CreateStringContentFromNameValue(PushbulletConstants.AmazonHeaders.ContentType, fileUploadResponse.FileType); multiPartCont.Add(awsaccesskeyidContent); multiPartCont.Add(aclContent); multiPartCont.Add(keyContent); multiPartCont.Add(signatureContent); multiPartCont.Add(policyContent); multiPartCont.Add(contentTypeContent); using (var memoryStream = new MemoryStream()) { request.FileStream.CopyTo(memoryStream); fileContent = new ByteArrayContent(memoryStream.ToArray()); } fileContent.Headers.Add(PushbulletConstants.AmazonHeaders.ContentType, PushbulletConstants.MimeTypes.OctetStream); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = string.Format("\"{0}\"", "file"), FileName = string.Format("\"{0}\"", request.FileName) }; multiPartCont.Add(fileContent); using (var httpClient = new HttpClient()) { Task <HttpResponseMessage> httpRequest = httpClient.PostAsync(fileUploadResponse.UploadUrl, multiPartCont); HttpResponseMessage httpResponse = httpRequest.Result; Task <string> xmlContentResponse = httpResponse.Content.ReadAsStringAsync(); if (!string.IsNullOrWhiteSpace(xmlContentResponse.Result)) { throw new Exception(xmlContentResponse.Result); } } } } catch (Exception) { throw; } finally { if (awsaccesskeyidContent != null) { awsaccesskeyidContent.Dispose(); } if (aclContent != null) { aclContent.Dispose(); } if (keyContent != null) { keyContent.Dispose(); } if (signatureContent != null) { signatureContent.Dispose(); } if (policyContent != null) { policyContent.Dispose(); } if (contentTypeContent != null) { contentTypeContent.Dispose(); } if (cacheControlContent != null) { cacheControlContent.Dispose(); } if (fileContent != null) { fileContent.Dispose(); } } }
private static async Task RegisterAsync(string lastName, string firstName, string username, byte[] password, Role role) { byte[] bytes = Encoding.UTF8.GetBytes("LastName=" + lastName + "&FirstName=" + firstName + "&Username="******"&Password="******"Role error"); } Array.Clear(bytes, 0, bytes.Length); Array.Clear(parameters, 0, parameters.Length); content.Dispose(); if (status == 200) { if (!String.Equals(body, "Success")) { if (body.Contains("exists")) { throw new UserExistsException(body); } else { throw new Exception("Message contents could not be parsed."); } } } else if (status == 400) { throw new Exception(body); } else if (status == 500) { throw new ServerException(); } else { throw new Exception("An error occurred"); } }