public async Task Serialize_StringContent_Success() { var content = new MultipartFormDataContent("test_boundary"); content.Add(new StringContent("Hello World")); var output = new MemoryStream(); await content.CopyToAsync(output); output.Seek(0, SeekOrigin.Begin); string result = new StreamReader(output).ReadToEnd(); Assert.Equal( "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n" + "Content-Disposition: form-data\r\n\r\nHello World\r\n--test_boundary--\r\n", result); }
public async Task Serialize_EmptyList_Success() { var content = new MultipartFormDataContent("test_boundary"); var output = new MemoryStream(); await content.CopyToAsync(output); output.Seek(0, SeekOrigin.Begin); string result = new StreamReader(output).ReadToEnd(); Assert.Equal("--test_boundary\r\n\r\n--test_boundary--\r\n", result); }
public void Add_NullContent_ThrowsArgumentNullException() { var content = new MultipartFormDataContent(); Assert.Throws<ArgumentNullException>(() => content.Add(null)); }
public async Task ReadAsStreamAsync_LargeContent_AllBytesRead() { var form = new MultipartFormDataContent(); const long PerContent = 1024 * 1024; const long ContentCount = 2048; var bytes = new byte[PerContent]; for (int i = 0; i < ContentCount; i++) { form.Add(new ByteArrayContent(bytes), "file", Guid.NewGuid().ToString()); } long totalAsyncRead = 0, totalSyncRead = 0; int bytesRead; using (Stream s = await form.ReadAsStreamAsync()) { s.Position = 0; while ((bytesRead = await s.ReadAsync(bytes, 0, bytes.Length)) > 0) { totalAsyncRead += bytesRead; } s.Position = 0; while ((bytesRead = s.Read(bytes, 0, bytes.Length)) > 0) { totalSyncRead += bytesRead; } } Assert.Equal(totalAsyncRead, totalSyncRead); Assert.InRange(totalAsyncRead, PerContent * ContentCount, long.MaxValue); }
public async Task Serialize_InvalidQuotedName_Encoded() { var content = new MultipartFormDataContent("test_boundary"); content.Add(new StringContent("Hello World"), "\"testク\r\n namé\""); var output = new MemoryStream(); await content.CopyToAsync(output); output.Seek(0, SeekOrigin.Begin); string result = new StreamReader(output).ReadToEnd(); Assert.Equal( "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n" + "Content-Disposition: form-data; name=\"=?utf-8?B?dGVzdOOCrw0KIG5hbcOp?=\"" + "\r\n\r\nHello World\r\n--test_boundary--\r\n", result); }
public ITestBuilder Send(MultipartFormDataContent content) { request.Content = content; return(this); }
private async Task <HttpResponseMessage> DoPostPutAsyncV1(HttpMethod method, string uri, MultipartFormDataContent item) { if (method != HttpMethod.Post && method != HttpMethod.Put) { throw new ArgumentException("Value must be either post or put.", nameof(method)); } // a new StringContent must be created for each retry // as it is disposed after each call var requestMessage = new HttpRequestMessage(method, uri); requestMessage.Content = item; var response = await _client.SendAsync(requestMessage); // raise exception if HttpResponseCode 500 // needed for circuit breaker to track fails if (response.StatusCode == HttpStatusCode.InternalServerError) { throw new HttpRequestException(); } return(response); }
//private async Task<Dictionary<string, Tuple<int, double, string>>> getExplanationFromBackend() private async Task <List <Tuple <int, double, BitmapImage> > > getExplanationFromBackend() { try { var base64 = System.Convert.ToBase64String(this.img); var content = new MultipartFormDataContent { { new StringContent(modelPath), "model_path" }, { new StringContent(base64), "image" } }; topLablesV = Int32.Parse(topLabels.Text); numSamplesV = Int32.Parse(numSamples.Text); numFeaturesV = Int32.Parse(numFeatures.Text); hideRestV = hideRest.IsChecked.Value.ToString(); hideColorV = hideColor.IsChecked.Value.ToString(); positiveOnlyV = positiveOnly.IsChecked.Value.ToString(); string url = "http://localhost:5000/lime?toplabels=" + topLablesV + "&hidecolor=" + hideColorV + "&numsamples=" + numSamplesV + "&positiveonly=" + positiveOnlyV + "&numfeatures=" + numFeaturesV + "&hiderest=" + hideRestV; var response = await client.PostAsync(url, content); var responseString = await response.Content.ReadAsStringAsync(); var explanationDic = (JObject)JsonConvert.DeserializeObject(responseString); if (explanationDic["success"].Value <string>() == "failed") { return(null); } JArray explanations = JArray.Parse(explanationDic["explanations"].Value <object>().ToString()); List <Tuple <int, double, BitmapImage> > explanationData = new List <Tuple <int, double, BitmapImage> >(); foreach (var item in explanations) { var temp = item.ToArray(); int cl = (int)temp[0]; double cl_score = (double)temp[1]; string explanation_img64 = (string)temp[2]; byte[] explanation = System.Convert.FromBase64String(explanation_img64); BitmapImage explanation_bitmap = new BitmapImage(); explanation_bitmap.BeginInit(); explanation_bitmap.StreamSource = new System.IO.MemoryStream(explanation); explanation_bitmap.EndInit(); explanation_bitmap.Freeze(); Tuple <int, double, BitmapImage> tuple = new Tuple <int, double, BitmapImage>(cl, cl_score, explanation_bitmap); explanationData.Add(tuple); } return(explanationData); } catch (Exception e) { return(null); } }
Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(RestMethodInfo restMethod, string basePath, bool paramsContainsCancellationToken) { return(paramList => { // make sure we strip out any cancelation tokens if (paramsContainsCancellationToken) { paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); } var ret = new HttpRequestMessage { Method = restMethod.HttpMethod }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } var urlTarget = (basePath == "/" ? string.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new List <KeyValuePair <string, string> >(); var headersToAdd = new Dictionary <string, string>(restMethod.Headers); for (var i = 0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", Uri.EscapeDataString(settings.UrlParameterFormatter .Format(paramList[i], restMethod.ParameterInfoMap[i])), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item3 == i) { if (paramList[i] is HttpContent httpContentParam) { ret.Content = httpContentParam; } else if (paramList[i] is Stream streamParam) { ret.Content = new StreamContent(streamParam); } // Default sends raw strings else if (restMethod.BodyParameterInfo.Item1 == BodySerializationMethod.Default && paramList[i] is string stringParam) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = paramList[i] is string str ? (HttpContent) new StringContent(Uri.EscapeDataString(str), Encoding.UTF8, "application/x-www-form-urlencoded") : new FormUrlEncodedContent(new FormValueDictionary(paramList[i], settings)); break; case BodySerializationMethod.Default: case BodySerializationMethod.Json: var param = paramList[i]; switch (restMethod.BodyParameterInfo.Item2) { case false: ret.Content = new PushStreamContent((stream, _, __) => { using (var writer = new JsonTextWriter(new StreamWriter(stream))) { serializer.Serialize(writer, param); } }, new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }); break; case true: ret.Content = new StringContent( JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i]?.ToString(); continue; } // ignore nulls if (paramList[i] == null) { continue; } // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { var attr = restMethod.ParameterInfoMap[i].GetCustomAttribute <QueryAttribute>() ?? new QueryAttribute(); if (DoNotConvertToQueryMap(paramList[i])) { queryParamsToAdd.Add(new KeyValuePair <string, string>(restMethod.QueryParameterMap[i], settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]))); } else { foreach (var kvp in BuildQueryMap(paramList[i], attr.Delimiter)) { var path = !string.IsNullOrWhiteSpace(attr.Prefix) ? $"{attr.Prefix}{attr.Delimiter}{kvp.Key}" : kvp.Key; queryParamsToAdd.Add(new KeyValuePair <string, string>(path, settings.UrlParameterFormatter.Format(kvp.Value, restMethod.ParameterInfoMap[i]))); } } continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; string parameterName; if (!restMethod.AttachmentNameMap.TryGetValue(i, out var attachment)) { itemName = restMethod.QueryParameterMap[i]; parameterName = itemName; } else { itemName = attachment.Item1; parameterName = attachment.Item2; } // Check to see if it's an IEnumerable var itemValue = paramList[i]; var enumerable = itemValue as IEnumerable <object>; var typeIsCollection = false; if (enumerable != null) { typeIsCollection = true; } if (typeIsCollection) { foreach (var item in enumerable) { AddMultipartItem(multiPartContent, itemName, parameterName, item); } } else { AddMultipartItem(multiPartContent, itemName, parameterName, itemValue); } } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. if (headersToAdd.Count > 0) { // We could have content headers, so we need to make // sure we have an HttpContent object to add them to, // provided the HttpClient will allow it for the method if (ret.Content == null && !bodylessMethods.Contains(ret.Method)) { ret.Content = new ByteArrayContent(new byte[0]); } foreach (var header in headersToAdd) { SetHeader(ret, header.Key, header.Value); } } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach (var key in query.AllKeys) { queryParamsToAdd.Insert(0, new KeyValuePair <string, string>(key, query[key])); } if (queryParamsToAdd.Any()) { var pairs = queryParamsToAdd.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)); uri.Query = string.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }); }
/// <summary> /// Sends a POST message, returns the reply object /// </summary> /// <param name="postURL"></param> /// <returns></returns> public static async System.Threading.Tasks.Task <JObject> sendPOST(String postURL, NameValueCollection pairs, Stream image = null, string fileName = null, string fileContentType = null) { var uri = new Uri(postURL); string logtxt = ""; string responseObject = ""; using (var client = new HttpClient()) { try { HttpResponseMessage response; using (var form = new MultipartFormDataContent()) { foreach (string itemKey in pairs) { form.Add(ConvertParameterValue(pairs[itemKey]), itemKey); logtxt += itemKey + " = " + pairs[itemKey] + ". "; } if (image != null) { image.Seek(0, SeekOrigin.Begin); HttpContent c = new StreamContent(image); logtxt += "Image " + fileName + "added. "; form.Add(c, "photo", fileName); } Roboto.log.log("Sending Message: " + postURL + "\n\r" + logtxt, logging.loglevel.low); response = await client.PostAsync(uri, form).ConfigureAwait(false); } responseObject = await response.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { Roboto.log.log("Unable to send Message due to HttpRequestException error:\n\r" + e.ToString(), logging.loglevel.high); } catch (Exception e) { Roboto.log.log("Unable to send Message due to unknown error:\n\r" + e.ToString(), logging.loglevel.critical); } if (responseObject == null || responseObject == "") { Roboto.log.log("Sent message but received blank reply confirmation", logging.loglevel.critical); return(null); } try { Roboto.log.log("Result: " + responseObject, logging.loglevel.verbose); JObject jo = JObject.Parse(responseObject); if (jo != null) { return(jo); } else { Roboto.log.log("JObject response object was null!", logging.loglevel.critical); return(null); } } catch (Exception e) { Roboto.log.log("Couldnt parse response from Telegram when sending message" + e.ToString(), logging.loglevel.critical); Roboto.log.log("Response was: " + responseObject, logging.loglevel.critical); return(null); } } }
private async void ConfirmButton_Clicked(object sender, EventArgs e) { if (String.IsNullOrEmpty(HotelNameEntry.Text)) { await DisplayAlert("Error", "Enter Hotel Name!", "Ok"); return; } var HotelName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(HotelNameEntry.Text); var Registrat = String.Empty; var Contact = String.Empty; var Remar = String.Empty; if (!String.IsNullOrEmpty(GSTEntry.Text)) { Registrat = GSTEntry.Text; } if (String.IsNullOrEmpty(ContactEntry.Text)) { await DisplayAlert("Error", "Enter Contact Number!", "Ok"); return; } else { Contact = ContactEntry.Text; } if (!String.IsNullOrEmpty(RemarksEntry.Text)) { Remar = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(RemarksEntry.Text); } var amtEntry = AmountEntry; if (String.IsNullOrEmpty(amtEntry.Text) || amtEntry.Text == "") { amtEntry.Text = String.Empty; amtEntry.Placeholder = "0.0"; Amount = 0.0; } else { if (double.TryParse(amtEntry.Text, out double temp) && temp > 1) { Amount = temp; } else { amtEntry.Text = String.Empty; amtEntry.Placeholder = "0.0"; Amount = 0.0; await DisplayAlert("Error", "Enter valid amount or no amount!", "Ok"); return; } } var current = Connectivity.NetworkAccess; if (current == NetworkAccess.Internet) { MainFrame.IsVisible = false; LoadingOverlay.IsVisible = true; LoadingIndicatorText.Text = "Checking Out"; var ckoutPlace = String.Empty; try { var request = new GeolocationRequest(GeolocationAccuracy.High, TimeSpan.FromSeconds(10)); var location = await Geolocation.GetLocationAsync(request); if (location == null) { location = await Geolocation.GetLastKnownLocationAsync(); } if (location != null) { if (location.IsFromMockProvider) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Your device is set to use mock location.Please disable it and try again!", "OK"); return; } try { var lat = location.Latitude; var lon = location.Longitude; var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon); var placemark = placemarks?.FirstOrDefault(); if (placemark != null) { var PlaceDetails = String.Empty; if (!String.IsNullOrEmpty(placemark.SubThoroughfare)) { PlaceDetails = placemark.SubThoroughfare; } if (!String.IsNullOrEmpty(placemark.Thoroughfare)) { PlaceDetails = $"{PlaceDetails}, {placemark.Thoroughfare}"; } if (!String.IsNullOrEmpty(placemark.SubLocality)) { PlaceDetails = $"{PlaceDetails}, {placemark.SubLocality}"; } if (!String.IsNullOrEmpty(placemark.Locality)) { PlaceDetails = $"{PlaceDetails}, {placemark.Locality}"; } if (!String.IsNullOrEmpty(placemark.SubAdminArea)) { PlaceDetails = $"{PlaceDetails}, {placemark.SubAdminArea}"; } if (!String.IsNullOrEmpty(placemark.AdminArea)) { PlaceDetails = $"{PlaceDetails}, {placemark.AdminArea}"; } if (!String.IsNullOrEmpty(PlaceDetails)) { if (PlaceDetails.Length > 0) { if (PlaceDetails[0] == ',') { PlaceDetails = PlaceDetails.Remove(0, 1); } } } ckoutPlace = PlaceDetails; } else { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Can not connect to location server. Try after some time!", "OK"); return; } } catch (FeatureNotSupportedException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Location feature not supported on your device!", "OK"); return; } catch (Exception) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Can not connect to location server. Try after some time!", "OK"); return; } } } catch (FeatureNotSupportedException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Location feature not supported on your device!", "OK"); return; } catch (FeatureNotEnabledException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Enable location access on your device!", "OK"); return; } catch (PermissionException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Location permission not granted. Go to app setting and grant location permission!", "OK"); return; } catch (Exception) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Can not connect to location server. Try after some time!", "OK"); return; } try { var statime = $"{DateTime.Now.ToLongDateString()} {String.Format("{0:hh:mm tt}", DateTime.Now)}"; await Task.Run(async() => { if (upfilebytes != null) { using (var httpClient = new HttpClient()) { try { var fname = $"{Guid.NewGuid().ToString()}.jpg"; string IUrl = DifferentUrls.UploadBillUrl; MultipartFormDataContent content = new MultipartFormDataContent(); ByteArrayContent baContent = new ByteArrayContent(upfilebytes); content.Add(baContent, "file", fname); var response = await httpClient.PostAsync(IUrl, content); if (!response.IsSuccessStatusCode) { Device.BeginInvokeOnMainThread(async() => { var Message = "Server Is Down. Try Again After Some Time"; await DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; return; }); return; } var responsestr = response.Content.ReadAsStringAsync().Result; if (responsestr == "False") { Device.BeginInvokeOnMainThread(async() => { var Message = "Unable to upload Bill. Try After Some time!!!"; await DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; return; }); return; } else { ImageUrl = responsestr; } } catch (Exception) { Device.BeginInvokeOnMainThread(() => { var Message = "Check Your Internet Connection and Try Again"; DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; return; }); return; } } } else { ImageUrl = String.Empty; } string url = DifferentUrls.AddHotelUrl; HttpContent q1 = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("Username", Application.Current.Properties["Username"].ToString()), new KeyValuePair <string, string>("Password", Application.Current.Properties["Password"].ToString()), new KeyValuePair <string, string>("InLocation", Application.Current.Properties["CINPlace"].ToString()), new KeyValuePair <string, string>("OutLocation", ckoutPlace), new KeyValuePair <string, string>("Timestamp", Application.Current.Properties["CINTime"].ToString()), new KeyValuePair <string, string>("JID", Application.Current.Properties["JID"].ToString()), new KeyValuePair <string, string>("TimestampOut", statime), new KeyValuePair <string, string>("HotelName", HotelName), new KeyValuePair <string, string>("HotelGST", Registrat), new KeyValuePair <string, string>("HotelContact", Contact), new KeyValuePair <string, string>("HotelRemark", Remar), new KeyValuePair <string, string>("BillLink", ImageUrl), new KeyValuePair <string, string>("BillAmt", Amount.ToString()) }); using (var httpClient = new HttpClient()) { try { Task <HttpResponseMessage> getResponse = httpClient.PostAsync(url, q1); HttpResponseMessage response = await getResponse; if (response.IsSuccessStatusCode) { var myContent = await response.Content.ReadAsStringAsync(); if (myContent == "False") { Device.BeginInvokeOnMainThread(async() => { var Message = "Something Went Wrong.Sign In Again!!!"; await DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; Application.Current.Properties["Username"] = string.Empty; await Application.Current.SavePropertiesAsync(); await Navigation.PopToRootAsync(); Application.Current.MainPage = new NavigationPage(new MainPage()); return; }); } else { Device.BeginInvokeOnMainThread(async() => { Application.Current.Properties["CINTime"] = string.Empty; Application.Current.Properties["CINPlace"] = string.Empty; await Application.Current.SavePropertiesAsync(); var Message = $"Checked Out at {statime}!!"; await DisplayAlert("Success", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; await Navigation.PopToRootAsync(); Application.Current.MainPage = new NavigationPage(new HomePage()); return; }); } } else { Device.BeginInvokeOnMainThread(() => { var Message = "Server Is Down. Try Again After Some Time"; DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; return; }); } } catch (Exception) { Device.BeginInvokeOnMainThread(() => { var Message = "Check Your Internet Connection and Try Again"; DisplayAlert("Error", Message, "OK"); MainFrame.IsVisible = true; LoadingOverlay.IsVisible = false; return; }); } } }); } catch (FeatureNotSupportedException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Location feature not supported on your device!", "OK"); return; } catch (FeatureNotEnabledException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Enable location access on your device!", "OK"); return; } catch (PermissionException) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Location permission not granted. Go to app setting and grant location permission!", "OK"); return; } catch (Exception) { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "Can not connect to location server. Try after some time!", "OK"); return; } } else { LoadingOverlay.IsVisible = false; MainFrame.IsVisible = true; await DisplayAlert("Error", "No Internet Connection", "OK"); return; } }
private Task <HttpResponseMessage> DoPostPutAsync(HttpMethod method, string uri, MultipartFormDataContent content) { if (method != HttpMethod.Post && method != HttpMethod.Put) { throw new ArgumentException("Value must be either post or put.", nameof(method)); } // a new StringContent must be created for each retry // as it is disposed after each call var origin = GetOriginFromUri(uri); return(HttpInvoker(origin, async() => { var requestMessage = new HttpRequestMessage(method, uri) { Content = content }; var response = await _client.SendAsync(requestMessage); if (response.StatusCode == HttpStatusCode.InternalServerError) { throw new HttpRequestException(); } return response; })); }
public Task <HttpResponseMessage> PostAsync(string uri, MultipartFormDataContent content) { return(DoPostPutAsync(HttpMethod.Post, uri, content)); }
/// <summary> /// 设置请求内容 /// </summary> /// <param name="request">请求对象</param> /// <param name="param">请求参数</param> private void SetHttpContent(HttpRequestMessage request, IDictionary <string, object>?param) { string contentType; if (!_headerItem.ContainsKey("Content-Type")) { contentType = "text/plain; charset=utf-8"; } else { contentType = _headerItem["Content-Type"]; } HttpContent?content = null; if (param != null) { if (contentType.Contains("form-data")) { var data = new MultipartFormDataContent(); foreach (KeyValuePair <string, object> pair in param) { if (pair.Key.ToLower().Contains("file")) { string fileName = Path.GetFileName(pair.Value.ToString()) !; // 读文件流 data.Add(new ByteArrayContent(File.ReadAllBytes(pair.Value.ToString() !)), pair.Key, fileName); } else { data.Add(new StringContent(pair.Value.ToString() !)); } } content = data; } else if (contentType.Contains("stream")) { HttpContent?data = null; foreach (KeyValuePair <string, object> pair in param) { if (pair.Key.ToLower().Contains("file")) { // 读文件流 FileStream fs = new FileStream(pair.Value.ToString() !, FileMode.Open, FileAccess.Read, FileShare.Read); data = new StreamContent(fs); //为文件流提供的HTTP容器 data.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); //设置媒体类型 } } content = data; } else if (contentType.Contains("json")) { var value = System.Text.Json.JsonSerializer.Serialize(param); var data = new StringContent(value); content = data; data.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); } else if (contentType.Contains("xml")) { var value = new XElement("xml", from keyValue in param select new XElement(keyValue.Key, keyValue.Value) ).ToString(); var data = new StringContent(value); content = data; } else { IEnumerable <KeyValuePair <string, string> > dic = param.Select(kv => new KeyValuePair <string, string>(kv.Key, kv.Value.ToString() !)); var data = new FormUrlEncodedContent(dic); content = data; } } request.Content = content; }
private void SetRequestContent(HttpMethod RequestMethod) { List <KeyValuePair <string, string> > KeyValues = new List <KeyValuePair <string, string> >(); if ((RequestMethod.ToString() == ApplicationAPIUtils.eRequestType.GET.ToString())) { if (eContentType == ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded) { string GetRequest = "?"; if (mAct.RequestKeyValues.Count() > 0) { for (int i = 0; i < mAct.RequestKeyValues.Count(); i++) { GetRequest += mAct.RequestKeyValues[i].ItemName.ToString() + "=" + mAct.RequestKeyValues[i].ValueForDriver + "&"; } } string ValuesURL = mAct.GetInputParamCalculatedValue(ActWebAPIBase.Fields.EndPointURL) + GetRequest.Substring(0, GetRequest.Length - 1); Client.BaseAddress = new Uri(ValuesURL); } else { Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", ContentType); } } else { if ((eContentType != ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded) && (eContentType != ApplicationAPIUtils.eContentType.FormData)) { string RequestBodyType = mAct.GetInputParamValue(ActWebAPIBase.Fields.RequestBodyTypeRadioButton); if (RequestBodyType == ApplicationAPIUtils.eRequestBodyType.FreeText.ToString()) { string RequestBodyWithDynamicParameters = mAct.GetInputParamCalculatedValue(ActWebAPIBase.Fields.RequestBody).ToString(); BodyString = SetDynamicValues(RequestBodyWithDynamicParameters); } else if (RequestBodyType == ApplicationAPIUtils.eRequestBodyType.TemplateFile.ToString()) { BodyString = SetDynamicValues(GetStringBodyFromFile()); } } switch (eContentType) { case ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded: if (mAct.RequestKeyValues.Count() > 0) { KeyValues = ConstructURLEncoded((ActWebAPIRest)mAct); RequestMessage.Content = new FormUrlEncodedContent(KeyValues); } break; case ApplicationAPIUtils.eContentType.FormData: if (mAct.RequestKeyValues.Count() > 0) { MultipartFormDataContent requestContent = new MultipartFormDataContent(); List <KeyValuePair <string, string> > FormDataKeyValues = new List <KeyValuePair <string, string> >(); for (int i = 0; i < mAct.RequestKeyValues.Count(); i++) { if (mAct.RequestKeyValues[i].ValueType == WebAPIKeyBodyValues.eValueType.Text) { FormDataKeyValues.Add(new KeyValuePair <string, string>(mAct.RequestKeyValues[i].ItemName.ToString(), mAct.RequestKeyValues[i].ValueForDriver)); requestContent.Add(new StringContent(mAct.RequestKeyValues[i].ValueForDriver), mAct.RequestKeyValues[i].ItemName.ToString()); } if (mAct.RequestKeyValues[i].ValueType == WebAPIKeyBodyValues.eValueType.File) { string path = mAct.RequestKeyValues[i].ValueForDriver; //string FullPath = path.Replace("~\\", mAct.SolutionFolder); string FullPath = amdocs.ginger.GingerCoreNET.WorkSpace.Instance.SolutionRepository.ConvertSolutionRelativePath(path); FileStream FileStream = File.OpenRead(FullPath); var streamContent = new StreamContent(FileStream); var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, mAct.RequestKeyValues[i].ItemName.ToString(), Path.GetFileName(path)); } } RequestMessage.Content = requestContent; } break; case ApplicationAPIUtils.eContentType.XML: string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (BodyString.StartsWith(_byteOrderMarkUtf8)) { var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1; BodyString = BodyString.Remove(0, lastIndexOfUtf8); } RequestMessage.Content = new StringContent(BodyString, Encoding.UTF8, ContentType); break; default: RequestMessage.Content = new StringContent(BodyString, Encoding.UTF8, ContentType); break; } } }
// luu nhat ky public async void AddProjectDiary_Clicked(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(entTitleProjectDiary.Text)) { await Shell.Current.DisplayAlert(Language.thong_bao, Language.vui_long_nhap_tieu_de_nhat_ky, Language.dong); return; } if (string.IsNullOrWhiteSpace(edtModalDescriptionDiary.Text)) { await Shell.Current.DisplayAlert(Language.thong_bao, Language.vui_long_nhap_noi_dung_nhat_ky, Language.dong); return; } loadingPopup.IsVisible = true; // set image va avatar MultipartFormDataContent form = new MultipartFormDataContent(); string[] imageList = new string[viewModel.MediaDiary.Count]; if (imageList.Length > 8) { await Shell.Current.DisplayAlert(Language.thong_bao, Language.vui_long_upload_toi_da_8_hinh_anh_bat_dong_san, Language.dong); loadingPopup.IsVisible = false; return; } if (imageList.Count() != 0) { for (int i = 0; i < viewModel.MediaDiary.Count; i++) { var item = viewModel.MediaDiary[i]; // chua upload. upload roi link = null if (string.IsNullOrEmpty(item.Path) == false) // co link la co chon tu dien thoai. { imageList[i] = $"{Guid.NewGuid().ToString()}.jpg"; var stream = new MemoryStream(File.ReadAllBytes(item.Path)); var content = new StreamContent(stream); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files" + i, FileName = imageList[i] }; form.Add(content); } else { imageList[i] = item.PreviewPath.Replace(Configuration.ApiConfig.CloudStorageApiCDN + "/project/diary/", ""); } } viewModel.ProjectDiary.Image = string.Join(",", imageList); } else { viewModel.ProjectDiary.Image = null; } bool ImageUploaded = true; if (viewModel.MediaDiary.Any(x => x.Path != null)) { ApiResponse uploadImageResponse = await UploadImageDiary(form); if (!uploadImageResponse.IsSuccess) { await Shell.Current.DisplayAlert("", Language.hinh_anh_vuot_qua_dung_luong_vui_long_thu_lai, Language.dong); ImageUploaded = false; } } else { ImageUploaded = true; // ko can upload } if (ImageUploaded) { if (viewModel.ProjectDiary.Id == Guid.Empty) { viewModel.ProjectDiary.Id = Guid.NewGuid(); viewModel.ProjectDiary.ProjectId = _projectId; ApiResponse apiResponse = await ApiHelper.Post(ApiRouter.PROJECT_DIARY_ADD_PROJECTDIARY, viewModel.ProjectDiary, true); if (apiResponse.IsSuccess) { OnSaved?.Invoke(this, EventArgs.Empty); loadingPopup.IsVisible = false; } else { await Shell.Current.DisplayAlert(Language.thong_bao, apiResponse.Message, Language.dong); } } else { ApiResponse apiResponse = await ApiHelper.Put($"{ApiRouter.PROJECT_DIARY_UPDATE}", viewModel.ProjectDiary, true); if (apiResponse.IsSuccess) { OnSaved?.Invoke(this, EventArgs.Empty); if (!string.IsNullOrWhiteSpace(OldImages) && OldImages != viewModel.ProjectDiary.Image && viewModel.ProjectDiary.Image != null) { string[] arrOldImages = OldImages.Split(','); List <string> ImagesToDelete = new List <string>(); for (int i = 0; i < arrOldImages.Length; i++) { if (!imageList.Any(x => x == arrOldImages[i])) { ImagesToDelete.Add(arrOldImages[i]); } } await ApiHelper.Delete(ApiRouter.DELETE_IMAGE + "?bucketName=sundihome/project/diary&files=" + string.Join(",", ImagesToDelete.ToArray())); } loadingPopup.IsVisible = false; } else { await Shell.Current.DisplayAlert(Language.thong_bao, apiResponse.Message, Language.dong); } } } loadingPopup.IsVisible = false; }
public void Add_EmptyFileName_ThrowsArgumentException() { var content = new MultipartFormDataContent(); Assert.Throws<ArgumentException>(() => content.Add(new StringContent("Hello world"), "name", String.Empty)); }
Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return(paramList => { // make sure we strip out any cancelation tokens if (paramsContainsCancellationToken) { paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); } var ret = new HttpRequestMessage { Method = restMethod.HttpMethod, }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } var urlTarget = (basePath == "/" ? string.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary <string, string>(); var headersToAdd = new Dictionary <string, string>(restMethod.Headers); for (var i = 0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter .Format(paramList[i], restMethod.ParameterInfoMap[i]) .Replace("/", "%2F"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; if (paramList[i] is HttpContent httpContentParam) { ret.Content = httpContentParam; } else if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: var param = paramList[i]; ret.Content = new PushStreamContent((stream, _, __) => { using (var writer = new JsonTextWriter(new StreamWriter(stream))) { serializer.Serialize(writer, param); } }, "application/json"); break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i]?.ToString(); continue; } // ignore nulls if (paramList[i] == null) { continue; } // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; string parameterName; if (!restMethod.AttachmentNameMap.TryGetValue(i, out var attachment)) { itemName = restMethod.QueryParameterMap[i]; parameterName = itemName; } else { itemName = attachment.Item1; parameterName = attachment.Item2; } // Check to see if it's an IEnumerable var itemValue = paramList[i]; var enumerable = itemValue as IEnumerable <object>; var typeIsCollection = false; if (enumerable != null) { Type tType = null; var eType = enumerable.GetType(); if (eType.GetTypeInfo().ContainsGenericParameters) { tType = eType.GenericTypeArguments[0]; } else if (eType.IsArray) { tType = eType.GetElementType(); } // check to see if it's one of the types we support for multipart: // FileInfo, Stream, string or byte[] if (tType == typeof(Stream) || tType == typeof(string) || tType == typeof(byte[]) || tType.GetTypeInfo().IsSubclassOf(typeof(MultipartItem)) || tType == typeof(FileInfo) ) { typeIsCollection = true; } } if (typeIsCollection) { foreach (var item in enumerable) { AddMultipartItem(multiPartContent, itemName, parameterName, item); } } else { AddMultipartItem(multiPartContent, itemName, parameterName, itemValue); } } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. foreach (var header in headersToAdd) { SetHeader(ret, header.Key, header.Value); } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach (var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = string.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }); }
public static async Task <(int errorCode, string resultContent, TimeSpan executionTime, bool sentData)> UploadJournalItemToEDSM(HttpClient hc, string journalRow, Guid userIdentifier, EDSMIntegrationSettings edsmSettings, EDGameState gameState, StarSystemChecker starSystemChecker) { var element = JsonDocument.Parse(journalRow).RootElement; if (!element.TryGetProperty("event", out JsonElement journalEvent)) { return(303, string.Empty, TimeSpan.Zero, false); } Stopwatch sw = new Stopwatch(); sw.Start(); try { element = await SetGamestateProperties(element, gameState, edsmSettings.CommanderName.Trim(), starSystemChecker); if (System.Enum.TryParse(typeof(IgnoredEvents), journalEvent.GetString(), false, out _)) { return(304, string.Empty, TimeSpan.Zero, false); } if (!gameState.SendEvents) { return(104, string.Empty, TimeSpan.Zero, false); } var formContent = new MultipartFormDataContent(); var json = JsonSerializer.Serialize(element, new JsonSerializerOptions() { WriteIndented = true }); formContent.Add(new StringContent(edsmSettings.CommanderName.Trim()), "commanderName"); formContent.Add(new StringContent(edsmSettings.ApiKey), "apiKey"); formContent.Add(new StringContent("Journal Limpet"), "fromSoftware"); formContent.Add(new StringContent(SharedSettings.VersionNumber), "fromSoftwareVersion"); formContent.Add(new StringContent(json), "message"); await SSEActivitySender.SendUserLogDataAsync(userIdentifier, new { fromIntegration = "EDSM", data = element }); var policy = Policy .HandleResult <HttpResponseMessage>(res => !res.IsSuccessStatusCode) .Or <HttpRequestException>() .WaitAndRetryAsync(30, retryCount => TimeSpan.FromSeconds(retryCount * 5)); var status = await policy.ExecuteAsync(() => hc.PostAsync("https://www.edsm.net/api-journal-v1", formContent)); var postResponseBytes = await status.Content.ReadAsByteArrayAsync(); var postResponse = System.Text.Encoding.UTF8.GetString(postResponseBytes); if (!status.IsSuccessStatusCode) { return((int)status.StatusCode, postResponse, TimeSpan.FromSeconds(30), true); } var resp = JsonSerializer.Deserialize <EDSMApiResponse>(postResponse); sw.Stop(); return(resp.ResultCode, postResponse, sw.Elapsed, true); } catch (InvalidTimestampException) { return(206, string.Empty, TimeSpan.FromMilliseconds(100), false); } }
public async Task <ActionResult> Index(AddAdminViewModel model) { model.SetSharedData(User); if (model.Admin.Id == 0) { if (!ModelState.IsValid) { return(View(model)); } } MultipartFormDataContent content; //bool FileAttached = (Request.RequestContext.HttpContext.Session["AddAdminImage"] != null); //bool ImageDeletedOnEdit = false; //var imgDeleteSessionValue = Request.RequestContext.HttpContext.Session["ImageDeletedOnEdit"]; //if (imgDeleteSessionValue != null) //{ // ImageDeletedOnEdit = Convert.ToBoolean(imgDeleteSessionValue); //} //byte[] fileData = null; //var ImageFile = (HttpPostedFileWrapper)Request.RequestContext.HttpContext.Session["AddAdminImage"]; //if (FileAttached) //{ // using (var binaryReader = new BinaryReader(ImageFile.InputStream)) // { // fileData = binaryReader.ReadBytes(ImageFile.ContentLength); // } //} // ByteArrayContent fileContent; JObject response; bool firstCall = true; callAgain : content = new MultipartFormDataContent(); //if (FileAttached) //{ // fileContent = new ByteArrayContent(fileData); // fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ImageFile.FileName }; // content.Add(fileContent); //} //if (model.Admin.Id > 0) // content.Add(new StringContent(model.Admin.Id.ToString()), "Id"); //if (model.Admin.Store_Id.HasValue) // content.Add(new StringContent(model.Admin.Store_Id.Value.ToString()), "Store_Id"); //content.Add(new StringContent(model.Admin.firstName), "FirstName"); //content.Add(new StringContent(model.Admin.LastName), "LastName"); //content.Add(new StringContent(model.Admin.Email), "Email"); //content.Add(new StringContent(model.Admin.Phone), "Phone"); //content.Add(new StringContent(model.Admin.ImageUrl), "ImageUrl"); //content.Add(new StringContent(model.Admin.Role.ToString()), "Role"); //if (model.Admin.Id == 0) // content.Add(new StringContent(model.Admin.Password), "Password"); // content.Add(new StringContent(Convert.ToString(ImageDeletedOnEdit)), "ImageDeletedOnEdit"); response = await ApiCall.CallApi("api/Admin/AddAdmin", User, model.Admin); if (firstCall && response.ToString().Contains("UnAuthorized")) { firstCall = false; goto callAgain; } else if (response.ToString().Contains("UnAuthorized")) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "UnAuthorized Error")); } if (response is Error) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, (response as Error).ErrorMessage)); } else { model.Admin = response.GetValue("result").ToObject <AdminViewModel>(); var claimIdentity = ((ClaimsIdentity)User.Identity); if (model.Admin.Id == Convert.ToInt32(claimIdentity.Claims.FirstOrDefault(x => x.Type == "AdminId").Value)) { User.AddUpdateClaim("FullName", model.Admin.firstName + " " + model.Admin.LastName); User.AddUpdateClaim("ProfilePictureUrl", model.Admin.ImageUrl); } model.SetSharedData(User); return(Json(new { success = true, responseText = "Success" }, JsonRequestBehavior.AllowGet)); //return RedirectToAction("Index"); } }
public PluginExecutionResult InstallSolution(string sessionId, string bundleFileName) { Handler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = false }; using (var client = new HttpClient(Handler)) { client.DefaultRequestHeaders.ExpectContinue = false; client.DefaultRequestHeaders.Add("Cookie", $"sessionId={sessionId}"); client.Timeout = TimeSpan.FromMinutes(10); //find out if the device supports bundle installer var solutionInstaller = client.GetAsync(string.Format(CultureInfo.CurrentCulture, OmniDeviceSolutionUrl, Device.Address)); if (!solutionInstaller.Result.IsSuccessStatusCode) { return(new PluginExecutionResult(PluginResult.Failed, "Solution Installer not available")); } using (var formData = new MultipartFormDataContent()) { formData.Add(new StringContent(CsrfToken), "\"CSRFToken\""); var fileContent = new StreamContent(File.OpenRead(bundleFileName)); fileContent.Headers.Add("Content-Type", "application/octet-stream"); fileContent.Headers.Add("Content-Disposition", "form-data; name=\"bundleFile\"; filename=\"" + Path.GetFileName(bundleFileName) + "\""); formData.Add(fileContent, "bundleFile", Path.GetFileName(bundleFileName)); formData.Add(new StringContent("Install"), "\"InstallButton\""); formData.Add(new StringContent("SolutionInstallViewSectionId"), "\"StepBackAnchor\""); formData.Add(new StringContent("SolutionInstallViewSectionId"), "\"jsAnchor\""); var message = client.PostAsync(string.Format(CultureInfo.CurrentCulture, OmniDeviceSolutionSaveUrl, Device.Address), formData); if (message.Result.IsSuccessStatusCode) { var bodyString = message.Result.Content.ReadAsStringAsync(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(bodyString.Result); var summaryNode = doc.DocumentNode.SelectSingleNode("//div[@id='Summary']"); if (summaryNode.HasAttributes) { if (summaryNode.Attributes["class"].Value == "message message-warning") { return(new PluginExecutionResult(PluginResult.Failed, $"Solution not installed: {summaryNode.InnerText}")); } } HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[@id='SolutionsTable']"); if (table == null) { return(new PluginExecutionResult(PluginResult.Failed, $"Solution not installed: {summaryNode.InnerText}")); } return(new PluginExecutionResult(PluginResult.Passed, summaryNode.InnerText)); } return(new PluginExecutionResult(PluginResult.Failed, message.Exception?.InnerException)); } } }
internal static HttpRequestMessage UploadImageStreamRequest(string url, Stream image = null, string album = null, string name = null, string title = null, string description = null, IProgress <int> progressBytes = null, int?bufferSize = null) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException(nameof(url)); } if (image == null) { throw new ArgumentNullException(nameof(image)); } if (string.IsNullOrWhiteSpace(name)) { name = "name"; } var content = new MultipartFormDataContent($"{DateTime.UtcNow.Ticks}") { { new StringContent("file"), "type" } }; if (progressBytes != null) { content.Add(new ProgressStreamContent(image, progressBytes, bufferSize), "image", name); } else { content.Add(new StreamContent(image), "image", name); } if (!string.IsNullOrWhiteSpace(album)) { content.Add(new StringContent(album), "album"); } if (!string.IsNullOrWhiteSpace(title)) { content.Add(new StringContent(title), "title"); } if (!string.IsNullOrWhiteSpace(description)) { content.Add(new StringContent(description), "description"); } var request = new ProgressHttpRequestMessage(HttpMethod.Post, url) { Content = content }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); return(request); }
/// <summary> /// Antrag versenden /// </summary> /// <param name="application">Antrag</param> /// <param name="p10Data">PKCS#10-Daten</param> /// <param name="certStore">Zertifikat-Speicher für die Bildung der Zertifikatskette und die Abfrage des Empfänger-Zertifikats</param> /// <param name="pfx">Zertifikat für die Verschlüsselung - wenn nicht gesetzt, dann wird ein Erstantrag erstellt</param> /// <param name="validator">The validator for the OSTC certificate request document</param> /// <returns>Das Ergebnis der Antragstellung</returns> public async Task <OstcApplicationResult> SendApplicationAsync([NotNull] OstcAntrag application, [NotNull] Pkcs10Data p10Data, [CanBeNull] IOstcCertificateStore certStore, [CanBeNull] Pkcs12Store pfx, [CanBeNull] IValidator validator) { var senderId = SenderId.FromBnrOrIk(application.Antragsteller.IK_BN); var applicationData = OstcUtils.Serialize(application, Iso88591); string mimeType; if (pfx == null) { mimeType = "text/xml"; } else { var alias = pfx.Aliases.Cast <string>().FirstOrDefault(pfx.IsKeyEntry); if (alias != null) { var certEntry = pfx.GetCertificate(alias); var keyEntry = pfx.GetKey(alias); var certificate = certEntry.Certificate; var key = keyEntry.Key; if (certStore == null) { throw new ArgumentNullException(nameof(certStore)); } var certChain = certStore.GetChain(certificate).ToList(); Debug.Assert(certChain[0].SubjectDN.Equivalent(certificate.SubjectDN)); certChain.RemoveAt(0); applicationData = OstcUtils.SignData(applicationData, key, certificate, certChain); var receiverCert = certStore.GetCertificate(senderId.CommunicationServerReceiver); applicationData = OstcUtils.EncryptData(applicationData, receiverCert); mimeType = "application/octet-stream"; } else { mimeType = "text/xml"; } } var date = DateTime.ParseExact(application.Antragsinfo.Datum, "dd.MM.yyyy", CultureDe); var p10FileName = $"{senderId.Id}.p10"; var xmlFileName = $"{senderId}_{date:ddMMyyyy}.xml"; var reqSendAppContent = new MultipartFormDataContent { { new StringContent("4000"), "MAX_FILE_SIZE_XML" }, { new ByteArrayContent(applicationData) { Headers = { ContentType = MediaTypeHeaderValue.Parse(mimeType), } }, "xml_Datei", xmlFileName }, { new StringContent("4000"), "MAX_FILE_SIZE_P10" }, { new ByteArrayContent(p10Data.CertRequestDer) { Headers = { ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"), } }, "p10_Datei", p10FileName } }; var requestSendApp = new HttpRequestMessage(HttpMethod.Post, Network.Requests.Upload) { Content = reqSendAppContent, }; var responseSendApp = await _client.SendAsync(requestSendApp); responseSendApp.EnsureSuccessStatusCode(); var responseHtml = DecodeResponse(await responseSendApp.Content.ReadAsStreamAsync()); var responseFileUrl = GetResponseFileUrl(responseHtml); if (responseFileUrl == null) { throw new OstcException("Von der ITSG wurde kein Pfad zu einer Rückmeldungs-Datei geliefert."); } var downloadResponse = await _client.GetAsync(responseFileUrl); downloadResponse.EnsureSuccessStatusCode(); var resultData = await downloadResponse.Content.ReadAsByteArrayAsync(); var resultXml = XDocument.Load(new MemoryStream(resultData)); var trustCenterNode = resultXml .Elements("OSTCAntrag") .Elements("Trustcenter") .FirstOrDefault(); if (trustCenterNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var returnCodeNode = trustCenterNode .Elements("Returncode") .FirstOrDefault(); if (returnCodeNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var returnCode = Convert.ToInt32(returnCodeNode.Value.Trim(), 10); var errorCodeNode = trustCenterNode.Elements("Fehlercode").FirstOrDefault(); if (errorCodeNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var errorCodes = errorCodeNode.Value.Trim() .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt32(x.Trim(), 10)) .ToList(); var inputNumberNode = trustCenterNode.Elements("Eingangsnummer").FirstOrDefault(); if (inputNumberNode == null) { throw new InvalidOperationException("Die von der ITSG zurückgelieferte Antwort lag in einem unbekannten Format vor."); } var inputNumber = inputNumberNode.Value.Trim(); var result = new OstcApplicationResult() { OrderId = inputNumber, ReturnCode = returnCode, ErrorCodes = errorCodes, }; return(result); }
/// <summary>インポート処理の実施</summary> /// <param name="source"></param> /// <returns></returns> public async Task <List <string> > OutputAsync(List <HatarakuDBData> source) { var processIds = new List <string>(); var outputSetting = WebApiSetting.OutputSetting.ConvertToModel <WebApiHatarakuDBOutputSetting>(); source = source.Where(x => !string.IsNullOrEmpty(x.InvoiceCode)).ToList(); var offset = 0; var limit = 200; var count = 0; do { var request = GetRequestMessage(GetRequestUri(UriCsvDataImport), "multipart/form-data"); var contents = new MultipartFormDataContent(); var jsonParameter = new StringContent(outputSetting.ConvertToJson(), Encoding.UTF8, "application/json"); jsonParameter.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "json" }; contents.Add(jsonParameter); count = Math.Min(source.Count - count, offset + limit); var buffer = source.Skip(offset).Take(count).ToArray(); var csv = string.Join(Environment.NewLine, buffer.Select(x => string.Join(",", ConvertToLine(x).Select(y => EscapeField(y)))) ); var csvParameter = new StringContent(csv, Encoding.UTF8, "text/csv"); csvParameter.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data") { Name = "uploadFile", FileName = "uploadFile.csv", }; contents.Add(csvParameter, "uploadFile", "uploadFile.csv"); request.Content = contents; var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new System.Net.WebException(string.Concat(response.ToString(), content)); } var result = content.ConverToDynamic(); var id = Convert.ToString(result.processId); processIds.Add(id); if (count < limit || (offset + count) == source.Count) { break; } offset += count; await Task.Delay(TimeSpan.FromSeconds(RequestIntervalSeconds)); }while (count == limit); return(processIds); }
/// <inheritdoc /> public override HttpContent GetHttpContent() { // Save & restore the stream position on each GetHttpContent call. switch (status) { case STATUS_CREATED: IDictionary <Stream, long> sps = null; foreach (var p in fields) { if (p.Value is Stream s) { if (s.CanSeek) { if (sps == null) { sps = new Dictionary <Stream, long>(); } sps[s] = s.Position; } else { status = STATUS_UNRECOVERABLE; goto MAIN; } } } streamPositions = sps; status = STATUS_RECOVERABLE; break; case STATUS_RECOVERABLE: sps = streamPositions; if (sps != null) { foreach (var p in fields) { if (p.Value is Stream s) { s.Position = sps[s]; } } } break; case STATUS_UNRECOVERABLE: throw new InvalidOperationException(Prompts.ExceptionMediaWikiFormCannotRecoverState); } MAIN: if (AsMultipartFormData) { var content = new MultipartFormDataContent(); foreach (var p in fields) { switch (p.Value) { case string s: content.Add(new StringContent(s), p.Key); break; case Stream stream: content.Add(new KeepAlivingStreamContent(stream), p.Key, "dummy"); break; case null: // Ignore null entries. break; default: var stringValue = Utility.ToWikiQueryValue(p.Value); if (stringValue != null) { content.Add(new StringContent(stringValue), p.Key); } break; } } return(content); } else { return(new FormLongUrlEncodedContent(Utility.ToWikiStringValuePairs(fields) .Where(p => p.Value != null))); } }
/// <summary> /// 给.NET Core使用的HttpPost请求公共设置方法 /// </summary> /// <param name="url"></param> /// <param name="hc"></param> /// <param name="cookieContainer"></param> /// <param name="postStream"></param> /// <param name="fileDictionary"></param> /// <param name="refererUrl"></param> /// <param name="encoding"></param> /// <param name="cer"></param> /// <param name="useAjax"></param> /// <param name="timeOut"></param> /// <param name="checkValidationResult"></param> /// <returns></returns> public static HttpClient HttpPost_Common_NetCore(string url, out HttpContent hc, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT, bool checkValidationResult = false) { var handler = new HttpClientHandler() { UseProxy = _webproxy != null, Proxy = _webproxy, UseCookies = true, CookieContainer = cookieContainer, }; if (checkValidationResult) { handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult); } if (cer != null) { handler.ClientCertificates.Add(cer); } HttpClient client = new HttpClient(handler); HttpClientHeader(client, refererUrl, useAjax, timeOut); #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { //通过表单上传文件 string boundary = "----" + DateTime.Now.Ticks.ToString("x"); var multipartFormDataContent = new MultipartFormDataContent(boundary); hc = multipartFormDataContent; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { if (fileStream != null) { //存在文件 //multipartFormDataContent.Add(new StreamContent(fileStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常 multipartFormDataContent.Add(CreateFileContent(File.Open(fileName, FileMode.Open), Path.GetFileName(fileName)), file.Key, Path.GetFileName(fileName)); fileStream.Dispose(); } else { //不存在文件或只是注释 multipartFormDataContent.Add(new StringContent(string.Empty), file.Key, file.Value); } } } catch (Exception ex) { throw ex; } } hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary)); } else { hc = new StreamContent(postStream); hc.Headers.ContentType = new MediaTypeHeaderValue("text/xml"); //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded //去掉注释以测试Request.Body为空的情况 //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } //HttpContentHeader(hc, timeOut); #endregion if (!string.IsNullOrEmpty(refererUrl)) { client.DefaultRequestHeaders.Referrer = new Uri(refererUrl); } return(client); }
public async Task <HttpResponseMessage> PostAsyncV1(string uri, MultipartFormDataContent item) { return(await DoPostPutAsyncV1(HttpMethod.Post, uri, item)); }
private async void Save_Clicked(object sender, EventArgs e) { if (viewModel.ParentCategory == null) { await DisplayAlert("", Language.chon_nhom_danh_muc, Language.dong); return; } if (viewModel.ChildCategory == null) { await DisplayAlert("", Language.chon_danh_muc, Language.dong); return; } if (string.IsNullOrWhiteSpace(viewModel.AddProductModel.Name)) { await DisplayAlert("", Language.nhap_ten_noi_that, Language.dong); return; } if (!viewModel.AddProductModel.Price.HasValue) { await DisplayAlert("", Language.nhap_gia_san_pham, Language.dong); return; } if (viewModel.AddProductModel.IsPromotion == true) { if (viewModel.AddProductModel.PromotionFromDate == null) { await DisplayAlert("", Language.vui_long_chon_thoi_gian, Language.dong); return; } if (viewModel.AddProductModel.PromotionToDate == null) { await DisplayAlert("", Language.vui_long_chon_thoi_gian, Language.dong); return; } if (viewModel.AddProductModel.PromotionPrice == null) { await DisplayAlert("", Language.vui_long_nhap_gia_giam, Language.dong); return; } } if (viewModel.AddProductModel.Province == null) { await DisplayAlert("", Language.vui_long_chon_tinh_thanh, Language.dong); return; } if (viewModel.AddProductModel.District == null) { await DisplayAlert("", Language.vui_long_chon_quan_huyen, Language.dong); return; } if (viewModel.AddProductModel.Ward == null) { await DisplayAlert("", Language.vui_long_chon_phuong_xa, Language.dong); return; } if (viewModel.Media.Count < 1) { await DisplayAlert("", Language.chon_hinh_anh_cho_san_pham, Language.dong); return; } loadingPopup.IsVisible = true; FurnitureProduct product = new FurnitureProduct(); product.Name = viewModel.AddProductModel.Name; product.ParentCategoryId = viewModel.ParentCategory.Id; product.CategoryId = viewModel.ChildCategory.Id; product.CreatedById = Guid.Parse(UserLogged.Id); product.Price = viewModel.AddProductModel.Price; product.Status = viewModel.AddProductModel.Status; product.Model = viewModel.AddProductModel.Model; product.Origin = viewModel.AddProductModel.Origin; product.Guarantee = viewModel.AddProductModel.Guarantee; product.Description = viewModel.AddProductModel.Description; product.CreatedDate = viewModel.AddProductModel.CreatedDate; product.ProductStatus = 0; product.IsPromotion = viewModel.AddProductModel.IsPromotion; if (viewModel.AddProductModel.IsPromotion == true) { product.PromotionFromDate = viewModel.AddProductModel.PromotionFromDate; product.PromotionToDate = viewModel.AddProductModel.PromotionToDate; product.PromotionPrice = viewModel.AddProductModel.PromotionPrice; } if (viewModel.AddProductModel.Province != null) { product.ProvinceId = viewModel.AddProductModel.Province.Id; } if (viewModel.AddProductModel.District != null) { product.DistrictId = viewModel.AddProductModel.District.Id; } if (viewModel.AddProductModel.Ward != null) { product.WardId = viewModel.AddProductModel.Ward.Id; } product.Street = viewModel.AddProductModel.Street; product.Address = viewModel.AddProductModel.Address; string[] imageList = new string[viewModel.Media.Count]; for (int i = 0; i < viewModel.Media.Count; i++) { var item = viewModel.Media[i]; // chua upload. upload roi link = null if (string.IsNullOrEmpty(item.Path) == false) // co link la co chon tu dien thoai. { imageList[i] = $"{Guid.NewGuid().ToString()}.jpg"; var stream = new MemoryStream(File.ReadAllBytes(item.Path)); var content = new StreamContent(stream); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files" + i, FileName = imageList[i] }; MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(content); var response = await BsdHttpClient.Instance().PostAsync(ApiRouter.FURNITUREPRODUCT_IMAGE_UPLOAD, form); if (!response.IsSuccessStatusCode) { await DisplayAlert("", Language.khong_the_upload_hinh_anh, Language.dong); loadingPopup.IsVisible = false; return; } } else { imageList[i] = item.PreviewPath.Replace(Configuration.ApiConfig.CloudStorageApiCDN + "/furniture/product/", ""); } } product.AvatarUrl = imageList[0]; product.Images = string.Join(",", imageList); if (chkCompanyAddress.IsChecked && viewModel.Company != null) //sp cty { product.CompanyId = viewModel.Company.Id; } //save ApiResponse apiResponse = null; if (_productId == Guid.Empty)//add { apiResponse = await ApiHelper.Post(ApiRouter.FURNITUREPRODUCT_ADD_UPDATE, product, true); } else//upd { product.Id = _productId; apiResponse = await ApiHelper.Put($"{ApiRouter.FURNITUREPRODUCT_ADD_UPDATE}/update", product, true); } if (apiResponse.IsSuccess) { var responseProduct = JsonConvert.DeserializeObject <FurnitureProduct>(apiResponse.Content.ToString()); product.Id = responseProduct.Id; await Navigation.PopAsync(); if (_productId == Guid.Empty) { MessagingCenter.Send <AddProductPage, bool>(this, "AddProduct", (bool)viewModel.AddProductModel.IsPromotion); ToastMessageHelper.ShortMessage(Language.dang_thanh_cong); } else { MessagingCenter.Send <AddProductPage, FurnitureProduct>(this, "UpdateProduct", product); ToastMessageHelper.ShortMessage(Language.luu_san_pham_thanh_cong); } } else { ToastMessageHelper.ShortMessage($"{Language.loi}, {apiResponse.Message}"); } loadingPopup.IsVisible = false; }
/// <summary> /// Uploads a new host license file that was previously generated with Regutil. /// The content of the license is sent as a file embedded in the HTTP request. /// </summary> /// <remarks> /// Host only. Requires authentication. /// </remarks> /// <param name='file'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <HostLicenseDto> > UploadLicenseWithHttpMessagesAsync(Stream file, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (file == null) { throw new ValidationException(ValidationRules.CannotBeNull, "file"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("file", file); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UploadLicense", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/HostLicenses/UiPath.Server.Configuration.OData.UploadLicense").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); if (file != null) { StreamContent _file = new StreamContent(file); _file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "file"; // get filename from stream if it's a file otherwise, just use 'unknown' var _fileStream = file as FileStream; var _fileName = (_fileStream != null ? _fileStream.Name : null) ?? "unknown"; if (System.Linq.Enumerable.Any(_fileName, c => c > 127)) { // non ASCII chars detected, need UTF encoding: _contentDispositionHeaderValue.FileNameStar = _fileName; } else { // ASCII only _contentDispositionHeaderValue.FileName = _fileName; } _file.Headers.ContentDisposition = _contentDispositionHeaderValue; _multiPartContent.Add(_file, "file"); } _httpRequest.Content = _multiPartContent; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <HostLicenseDto>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <HostLicenseDto>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async static Task CreateCustomLevelWithLocalMP3Download(string url, Download download) { download.Status = "Downloading File"; var youtube = new YoutubeClient(); // You can specify video ID or URL var video = await youtube.Videos.GetAsync(url); var duration = video.Duration; // 00:07:14 if (video.Duration.Minutes + (video.Duration.Seconds / 60) > 10) { return; } string artistName = "Unknown"; string trackName = "Unknown"; var invalids = System.IO.Path.GetInvalidFileNameChars(); if (video.Author != null) { artistName = String.Join("_", video.Author.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } if (video.Title != null) { trackName = String.Join("_", video.Title.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } download.Artist = artistName; download.Title = trackName; string fileName = "[BSD] " + trackName + " - " + artistName; download.FilePath = fileName + ".mp3"; if (!Properties.Settings.Default.overwriteExisting) { if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName)))) { download.Status = "Already Exists"; download.IsAlive = false; return; } } var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id); var streamInfo = streamManifest.GetAudioOnly().WithHighestBitrate(); if (streamInfo != null) { // Get the actual stream var stream = await youtube.Videos.Streams.GetAsync(streamInfo); // Download the stream to file await youtube.Videos.Streams.DownloadAsync(streamInfo, fileName + ".mp3"); } string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms"; var content = new MultipartFormDataContent(boundary); byte[] bytes = System.IO.File.ReadAllBytes(download.FilePath); if (File.Exists(download.FilePath)) { File.Delete(download.FilePath); } content.Add(new ByteArrayContent(bytes), "audio_file", download.FilePath); using (WebClient client = new WebClient()) { try { client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/maxresdefault.jpg"), "cover.jpg"); } catch { try { client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/sddefault.jpg"), "cover.jpg"); } catch { try { client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/hqdefault.jpg"), "cover.jpg"); } catch { } } } } byte[] imageData = System.IO.File.ReadAllBytes("cover.jpg"); if (imageData != null) { var imageContent = new ByteArrayContent(imageData); imageContent.Headers.Remove("Content-Type"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\""); imageContent.Headers.Add("Content-Type", "image/jpeg"); content.Add(imageContent); } if (File.Exists("cover.jpg")) { File.Delete("cover.jpg"); } content.Add(new StringContent(trackName), "audio_metadata_title"); content.Add(new StringContent(artistName), "audio_metadata_artist"); content.Add(new StringContent(download.Difficulties), "difficulties"); content.Add(new StringContent(download.GameModes), "modes"); content.Add(new StringContent(download.SongEvents), "events"); content.Add(new StringContent(download.Environment), "environment"); content.Add(new StringContent(download.ModelVersion), "system_tag"); var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token); var responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); JObject jsonString = JObject.Parse(responseString); string levelID = (string)jsonString["id"]; Console.WriteLine(levelID); await CheckDownload(levelID, trackName, artistName, download); }
public void Ctor_NoParams_CorrectMediaType() { var content = new MultipartFormDataContent(); Assert.Equal("multipart/form-data", content.Headers.ContentType.MediaType); Assert.Equal(1, content.Headers.ContentType.Parameters.Count); }
static async Task CreateCustomLevel(JObject responseData, Download download) { download.Status = "Generating Custom Level"; string trackName = "Unknown"; if (((string)responseData["track"]) != null) { trackName = (string)responseData["track"]; } else if (((string)responseData["fulltitle"]) != null) { trackName = (string)responseData["fulltitle"]; } string artistName = "Unknown"; if (((string)responseData["artist"]) != null) { artistName = (string)responseData["artist"]; } else if (((string)responseData["uploader"]) != null) { artistName = (string)responseData["uploader"]; } var invalids = System.IO.Path.GetInvalidFileNameChars(); trackName = String.Join("_", trackName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); artistName = String.Join("_", artistName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); Console.WriteLine("trackName: " + trackName); Console.WriteLine("artistName: " + artistName); download.Title = trackName; download.Artist = artistName; string fileName = "[BSD] " + trackName + " - " + artistName; if (!Properties.Settings.Default.overwriteExisting) { if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName)))) { download.Status = "Already Exists"; download.IsAlive = false; return; } } Console.WriteLine("download.Title: " + download.Title); Console.WriteLine("download.Artist : " + download.Artist); string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms"; var content = new MultipartFormDataContent(boundary); content.Add(new StringContent((string)responseData["webpage_url"]), "youtube_url"); var imageContent = new ByteArrayContent((byte[])responseData["beatsage_thumbnail"]); imageContent.Headers.Remove("Content-Type"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\""); imageContent.Headers.Add("Content-Type", "image/jpeg"); content.Add(imageContent); content.Add(new StringContent(trackName), "audio_metadata_title"); content.Add(new StringContent(artistName), "audio_metadata_artist"); content.Add(new StringContent(download.Difficulties), "difficulties"); content.Add(new StringContent(download.GameModes), "modes"); content.Add(new StringContent(download.SongEvents), "events"); content.Add(new StringContent(download.Environment), "environment"); content.Add(new StringContent(download.ModelVersion), "system_tag"); var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token); var responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); JObject jsonString = JObject.Parse(responseString); string levelID = (string)jsonString["id"]; Console.WriteLine(levelID); await CheckDownload(levelID, trackName, artistName, download); }
public async Task Serialize_InvalidNamedFileName_Encoded() { var content = new MultipartFormDataContent("test_boundary"); content.Add(new StringContent("Hello World"), "testク\r\n namé", "fileク\r\n namé"); MemoryStream output = new MemoryStream(); await content.CopyToAsync(output); output.Seek(0, SeekOrigin.Begin); string result = new StreamReader(output).ReadToEnd(); Assert.Equal( "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n" + "Content-Disposition: form-data; name=\"=?utf-8?B?dGVzdOOCrw0KIG5hbcOp?=\";" + " filename=\"=?utf-8?B?ZmlsZeOCrw0KIG5hbcOp?=\"; filename*=utf-8\'\'file%E3%82%AF%0D%0A%20nam%C3%A9" + "\r\n\r\nHello World\r\n--test_boundary--\r\n", result); }
static async Task CreateCustomLevelFromFile(Download download) { download.Status = "Uploading File"; TagLib.File tagFile = TagLib.File.Create(download.FilePath); string artistName = "Unknown"; string trackName = "Unknown"; byte[] imageData = null; var invalids = System.IO.Path.GetInvalidFileNameChars(); if (tagFile.Tag.FirstPerformer != null) { artistName = String.Join("_", tagFile.Tag.FirstPerformer.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } if (tagFile.Tag.Title != null) { trackName = String.Join("_", tagFile.Tag.Title.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } else { trackName = System.IO.Path.GetFileNameWithoutExtension(download.FilePath); } if (tagFile.Tag.Pictures.Count() > 0) { if (tagFile.Tag.Pictures[0].Data.Data != null) { imageData = tagFile.Tag.Pictures[0].Data.Data; } } download.Artist = artistName; download.Title = trackName; string fileName = "[BSD] " + trackName + " - " + artistName; if (!Properties.Settings.Default.overwriteExisting) { if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName)))) { download.Status = "Already Exists"; download.IsAlive = false; return; } } byte[] bytes = System.IO.File.ReadAllBytes(download.FilePath); string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms"; var content = new MultipartFormDataContent(boundary); content.Add(new ByteArrayContent(bytes), "audio_file", download.FileName); if (imageData != null) { var imageContent = new ByteArrayContent(imageData); imageContent.Headers.Remove("Content-Type"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\""); imageContent.Headers.Add("Content-Type", "image/jpeg"); content.Add(imageContent); } content.Add(new StringContent(trackName), "audio_metadata_title"); content.Add(new StringContent(artistName), "audio_metadata_artist"); content.Add(new StringContent(download.Difficulties), "difficulties"); content.Add(new StringContent(download.GameModes), "modes"); content.Add(new StringContent(download.SongEvents), "events"); content.Add(new StringContent(download.Environment), "environment"); content.Add(new StringContent(download.ModelVersion), "system_tag"); var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token); var responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); JObject jsonString = JObject.Parse(responseString); string levelID = (string)jsonString["id"]; Console.WriteLine(levelID); await CheckDownload(levelID, trackName, artistName, download); }
public void Add_NullName_ThrowsArgumentException() { var content = new MultipartFormDataContent(); Assert.Throws<ArgumentException>(() => content.Add(new StringContent("Hello world"), null)); }
public void Add_NullContent_ThrowsArgumentNullException() { var content = new MultipartFormDataContent(); Assert.Throws <ArgumentNullException>(() => content.Add(null)); }
public void Add_NullName_ThrowsArgumentException() { var content = new MultipartFormDataContent(); Assert.Throws <ArgumentException>(() => content.Add(new StringContent("Hello world"), null)); }
public void Add_EmptyFileName_ThrowsArgumentException() { var content = new MultipartFormDataContent(); Assert.Throws <ArgumentException>(() => content.Add(new StringContent("Hello world"), "name", String.Empty)); }
/// <summary> /// Gets the multi-part content (with files) for a request /// </summary> /// <param name="client">The REST client that will execute the request</param> /// <param name="request">REST request to get the content for</param> /// <param name="parameters">The merged request parameters</param> /// <returns>The HTTP content to be sent</returns> private static IHttpContent GetMultiPartContent([CanBeNull] this IRestClient client, IRestRequest request, RequestParameters parameters) { var isPostMethod = client.GetEffectiveHttpMethod(request, parameters.OtherParameters) == Method.POST; var multipartContent = new MultipartFormDataContent(new GenericHttpHeaders()); foreach (var parameter in parameters.OtherParameters) { var fileParameter = parameter as FileParameter; if (fileParameter != null) { var file = fileParameter; var data = new ByteArrayContent((byte[])file.Value); if (!string.IsNullOrEmpty(file.ContentType)) { data.Headers.ReplaceWithoutValidation("Content-Type", file.ContentType); } data.Headers.ReplaceWithoutValidation("Content-Length", file.ContentLength.ToString()); multipartContent.Add(data, file.Name, file.FileName); } else if (isPostMethod && parameter.Type == ParameterType.GetOrPost) { IHttpContent data; var bytes = parameter.Value as byte[]; if (bytes != null) { var rawData = bytes; data = new ByteArrayContent(rawData); data.Headers.ReplaceWithoutValidation( "Content-Type", string.IsNullOrEmpty(parameter.ContentType) ? "application/octet-stream" : parameter.ContentType); data.Headers.ReplaceWithoutValidation("Content-Length", rawData.Length.ToString()); multipartContent.Add(data, parameter.Name); } else { var value = parameter.ToRequestString(); data = new StringContent(value, parameter.Encoding ?? ParameterExtensions.DefaultEncoding); if (!string.IsNullOrEmpty(parameter.ContentType)) { data.Headers.ReplaceWithoutValidation("Content-Type", parameter.ContentType); } multipartContent.Add(data, parameter.Name); } } else if (parameter.Type == ParameterType.RequestBody) { var data = request.GetBodyContent(parameter); multipartContent.Add(data, parameter.Name); } } return multipartContent; }
public static JObject PostResponse(MultipartFormDataContent content, string endpoint) { var response = http.PostAsync(endpoint, content); return(JObject.Parse(response.Result.Content.ReadAsStringAsync().Result)); }