public static string UploadFile(string url, string fileName, string username, string password){ FileParameter param = new FileParameter(GetBytesFromFile(fileName), Path.GetFileName(fileName)); param.FileName = fileName; IDictionary<string, object> postParams = new Dictionary<string, object>(); postParams.Add("binaryContentFile", param); return MultipartFormDataPost(url, postParams, username, password); }
/// <exception cref="SwaggerException">A server side error occurred.</exception> public Task <bool> UploadFileAsync(FileParameter file) { return(UploadFileAsync(file, CancellationToken.None)); }
public async Task <FileResponse> TextStampAsync(FileParameter file, string text, string pages, AlignX alignX, AlignY alignY, string jobIdExt = null) { return(await TextStampAsync(text, pages, alignX, alignY, jobIdExt, file)); }
public async Task <FileResponse> CreatePdfAAsync(FileParameter file, PdfCompliance2?pdfCompliance, string jobIdExt = null) { return(await CreatePdfAAsync(pdfCompliance, jobIdExt, file)); }
public async Task <FileResponse> UnlockDocumentAsync(FileParameter file, string password, string jobIdExt = null) { return(await UnlockDocumentAsync(password, jobIdExt, file)); }
public async Task <FileResponse> RotateDocumentAsync(FileParameter file, Rotate3?rotate, string jobIdExt = null) { return(await RotateDocumentAsync(rotate, jobIdExt, file)); }
public async Task <FileResponse> Merge2PdfsAsync(FileParameter file1, FileParameter file2, string jobIdExt = null) { return(await Merge2PdfsAsync(jobIdExt, file1, file2)); }
/// <exception cref="GeoClientException">A server side error occurred.</exception> public System.Threading.Tasks.Task<bool> UploadFileAsync(FileParameter file) { return UploadFileAsync(file, System.Threading.CancellationToken.None); }
/// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, String path, RequestOptions options) { if (path == null) { throw new ArgumentNullException("path"); } if (options == null) { throw new ArgumentNullException("options"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } options.HeaderParameters.Add("Authorization", getBasicAuthorization(configuration.ApiKey, configuration.ApiSecret)); RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { request.RequestFormat = DataFormat.Json; request.AddJsonBody(options.Data); } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); } else { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return(request); }
public async Task <IActionResult> Index(IFormFile file, IFormCollection form) { MeshResultModel model = new MeshResultModel(); model.Original = new MeshDetailModel(); model.Result = new MeshDetailModel(); string webRootPath = _env.WebRootPath; string randomFilePath = Path.GetRandomFileName().Replace(".", ""); string relativeFolderPath = Path.Combine("models", "obj", randomFilePath); string newPath = Path.Combine(webRootPath, relativeFolderPath); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } var urlPath = relativeFolderPath.Replace("\\", "/"); model.Original.RelativeFolderPath = urlPath; model.Result.RelativeFolderPath = urlPath; List <ScriptParameterFilter> lstScriptParams = new List <ScriptParameterFilter>(); if (form != null && form.Any()) { foreach (var keyValuePair in form.ToList()) { var kp = keyValuePair.Key.Split("#"); if (kp.Length == 2) { var sp = lstScriptParams.FirstOrDefault(a => a.FilterName == kp[0]); if (sp == null) { sp = new ScriptParameterFilter(); sp.FilterName = kp[0]; lstScriptParams.Add(sp); } if (sp.FilterParameter == null) { sp.FilterParameter = new Dictionary <string, string>(); } sp.FilterParameter.Add(kp[1], keyValuePair.Value); } } } if (file?.Length > 0) { model.Original.Filename = file.FileName; var originalFilePath = await saveOriginalFile(file, newPath); HttpClient hc = new HttpClient(); hc.Timeout = TimeSpan.FromHours(2); Client c = new Client(_appSettings.RestApiUrl, hc); FileParameter fileParameter = new FileParameter(file.OpenReadStream(), file.FileName, file.ContentType); JobResult jobResult = null; try { jobResult = await c.UploadJobAsync(fileParameter, JsonConvert.SerializeObject(lstScriptParams), form.FirstOrDefault().Value, form.FirstOrDefault(a => a.Key == "selectedOutputFormat").Value); } catch (Exception e) { //TODO: Schöner ViewBag.Error = "Error at uploading."; ViewBag.Code = e.ToString(); return(View("Error")); } if (jobResult != null && jobResult.ResultCode.Number != JobResultCodeNumber._0) { //Job wasn't finished successfull ViewBag.Error = jobResult.ResultCode.Message; ViewBag.Code = jobResult.ResultCode.Number; return(View("Error")); } else if (jobResult != null) { var resultFile = await c.DownloadJobFileResultAsync(jobResult.FileResultName, jobResult.JobId, newPath); model.Result.Filename = resultFile; model.Result.AdditionalValues = new Dictionary <string, string>(jobResult.AdditionalData); model.Result.FileSize = jobResult.FileResultSize; model.Result.NumberOfFaces = jobResult.ResultNumberOfFaces; model.Result.NumberOfVertices = jobResult.ResultNumberOfVertices; model.ReducedBy = jobResult.ReducedBy; model.Original.FileSize = jobResult.FileInputSize; ViewBag.Link = $"{_appSettings.RestApiUrl}/api/DownloadLogForJob/{jobResult.JobId}"; } } else { //no file selected ViewBag.Error = "Please select file"; ViewBag.Code = ""; return(View("Error")); } return(View("~/Views/Visualization/ModelResultPreview.cshtml", model)); }
public async Task Import(ImportArguments arguments) { var session = configuration.StartSession(arguments.App); var assets = session.Assets; using (var fs = await FileSystems.CreateAsync(arguments.Path, session.WorkingDirectory)) { var folders = new FolderTree(session); var assetQuery = new AssetQuery(); foreach (var file in fs.GetFiles(FilePath.Root, ".*")) { var targetFolder = file.LocalFolderPath(); if (!string.IsNullOrWhiteSpace(arguments.TargetFolder)) { targetFolder = Path.Combine(arguments.TargetFolder, targetFolder); } assetQuery.ParentId = await folders.GetIdAsync(targetFolder); assetQuery.Filter = $"fileName eq '{file.Name}'"; var existings = await assets.GetAssetsAsync(session.App, assetQuery); var existing = existings.Items.FirstOrDefault(); var fileHash = file.GetFileHash(); try { var fileParameter = new FileParameter(file.OpenRead(), file.Name, MimeTypesMap.GetMimeType(file.Name)); log.WriteLine($"Uploading: {file.FullName}"); if (existings.Items.Any(x => string.Equals(x.FileHash, fileHash, StringComparison.Ordinal))) { log.StepSkipped("Same hash."); } else if (existings.Items.Count > 1) { log.StepSkipped("Multiple candidates found."); } else if (existing != null) { await assets.PutAssetContentAsync(session.App, existing.Id, fileParameter); log.StepSuccess("Existing Asset"); } else { var result = await assets.PostAssetAsync(session.App, assetQuery.ParentId, null, arguments.Duplicate, fileParameter); if (result._meta?.IsDuplicate == "true") { log.StepSkipped("duplicate."); } else { log.StepSuccess("New Asset"); } } } catch (Exception ex) { LogExtensions.HandleException(ex, error => log.WriteLine("Error: {0}", error)); } finally { log.WriteLine(); } } log.WriteLine("> Import completed"); } }
/// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream) stream).Name)); return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"); }
public NamedData(string name, FileParameter data) { Name = name; Data = data; }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <DocProof> PutProofDocAsync(FileParameter proofDoc, string bindingId, string citizenIdentifier, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DocProof/PutProofDocs?"); if (bindingId != null) { urlBuilder_.Append("bindingId=").Append(System.Uri.EscapeDataString(ConvertToString(bindingId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } if (citizenIdentifier != null) { urlBuilder_.Append("citizenIdentifier=").Append(System.Uri.EscapeDataString(ConvertToString(citizenIdentifier, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (proofDoc != null) { var content_proofDoc_ = new System.Net.Http.StreamContent(proofDoc.Data); if (!string.IsNullOrEmpty(proofDoc.ContentType)) { content_proofDoc_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(proofDoc.ContentType); } content_.Add(content_proofDoc_, "proofDoc", proofDoc.FileName ?? "proofDoc"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(DocProof); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <DocProof>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(DocProof)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
// Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary <String, String> queryParams, Object postBody, Dictionary <String, String> headerParams, Dictionary <String, String> formParams, Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams, String contentType) { var request = new RestRequest(path, method); // add path parameter, if any foreach (var param in pathParams) { request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); } // add header parameter, if any foreach (var param in headerParams) { request.AddHeader(param.Key, param.Value); } // add query parameter, if any foreach (var param in queryParams) { request.AddQueryParameter(param.Key, param.Value); } // add form parameter, if any foreach (var param in formParams) { request.AddParameter(param.Key, param.Value); } // add file parameter, if any foreach (var param in fileParams) { FileParameter file = new FileParameter { Name = param.Value.Name, Writer = param.Value.Writer, FileName = param.Value.FileName, ContentType = param.Value.ContentType, ContentLength = param.Value.ContentLength }; //request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); request.Files.Add(file); } if (postBody != null) // http body (model or byte[]) parameter { if (postBody.GetType() == typeof(String)) { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } else if (postBody.GetType() == typeof(byte[])) { request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } return(request); }
/// <summary> /// 写入 Form 的内容值(文件头) /// </summary> /// <param name="file"></param> /// <param name="boundary"></param> /// <returns></returns> private static string GetMultipartFileHeader(FileParameter file, string boundary) { var conType = file.ContentType ?? "application/octet-stream"; return($"--{boundary}{_lineBreak}Content-Disposition: form-data; name=\"{file.Name}\"; filename=\"{file.FileName}\"{_lineBreak}Content-Type: {conType}{_lineBreak}{_lineBreak}"); }
public static List<FileParameter> TakeScreenShot() { DateTime n = DateTime.Now; string t = n.ToString("yyyy.MM.dd-HH.mm.ss.FFF"); if (!Directory.Exists(FOLDER)) Directory.CreateDirectory(FOLDER); List<FileParameter> images = new List<FileParameter>(); foreach (var s in Screen.AllScreens) { try { using (Bitmap mScreenshot = new Bitmap(s.Bounds.Width, s.Bounds.Height)) { using (Graphics g = Graphics.FromImage(mScreenshot)) { g.CopyFromScreen(s.Bounds.Location, Point.Empty, s.Bounds.Size); string name = t + "-" + s.DeviceName.Replace("\\", "").Trim('.') + ".png"; String f = FOLDER + "/" + name; mScreenshot.Save(f); mScreenshot.Dispose(); FileInfo info = new FileInfo(f); FileParameter file = new FileParameter(info, name, "image/png"); images.Add(file); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } return images; }
/// <summary>uploads an image</summary> /// <param name="petId">ID of pet to update</param> /// <param name="additionalMetadata">Additional data to pass to server</param> /// <param name="file">file to upload</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>successful operation</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<ApiResponse> UploadFileAsync(int petId, string additionalMetadata, FileParameter file, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "pet/{petId}/uploadImage"); if (petId == null) throw new System.ArgumentNullException("petId"); url_ = url_.Replace("{petId}", System.Uri.EscapeDataString(petId.ToString())); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (additionalMetadata != null) content_.Add(new System.Net.Http.StringContent(additionalMetadata.ToString()), "additionalMetadata"); if (file != null) content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(ApiResponse); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length)); return result_; } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(ApiResponse); } }
public static PodioResponse <T> MultipartFormDataRequest <T>(string requestUri, string accessToken, Dictionary <string, object> requestData) { string boundary = String.Format("----------{0:N}", Guid.NewGuid()); string contentType = "multipart/form-data; boundary=" + boundary; MemoryStream ms = new MemoryStream(); bool first = true; foreach (var key in requestData.Keys) { if (!first) { ms.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); } first = false; var value = requestData[key]; if (value is FileParameter) { FileParameter upload = (FileParameter)value; string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, key, upload.FileName ?? key, upload.ContentType ?? "application/octet-stream"); ms.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); ms.Write(upload.Data, 0, upload.Data.Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, key, value); ms.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } string footer = "\r\n--" + boundary + "--\r\n"; ms.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); byte[] inputData = ms.ToArray();; requestUri = requestUri + "?oauth_token=" + accessToken; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.Method = "POST"; request.ContentType = contentType; request.Accept = "application/json"; request.ContentLength = inputData.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(inputData, 0, inputData.Length); } PodioResponse retval = GetResponse(request); retval.RequestUri = requestUri; PodioResponse <T> podioResponse = new PodioResponse <T>(retval); return(podioResponse); }
public async Task <FileResponse> OptimizeByProfileAsync(FileParameter file, Profile profile = Profile.Max, string jobIdExt = null) { return(await OptimizeByProfileAsync(profile, jobIdExt, file)); }
public void TestHappyPath() { // Engine client should point to a dedicated Camunda instance for test, preferrably locally available var camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), null, null); // Deploy the process under test string deploymentId = camunda.RepositoryService.Deploy("testcase", new List <object> { FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "Urlaubsantrag.Models.Urlaubsantrag.bpmn") }); try { string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("Urlaubsantrag", new Dictionary <string, object>() { { "name", "Bernd Rücker" }, { "vacationStartDate", 10 }, { "duration", 5 } }); var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>() { { "processInstanceId", processInstanceId } }); Assert.AreEqual(1, tasks.Count); Assert.AreEqual("UserTask_UrlaubGenehmigen", tasks.First().TaskDefinitionKey); camunda.HumanTaskService.Complete(tasks.First().Id, new Dictionary <string, object>() { { "approved", true } }); var externalTasks = camunda.ExternalTaskService.FetchAndLockTasks( "worker1", 100, "leaveAccount", 1000, new List <string>() { "name" }); // Do the real service logic / calls camunda.ExternalTaskService.Complete("worker1", externalTasks.First().Id, new Dictionary <string, object>() { { "someResult", 42 } }); // TODO: Simulate timer //externalTasks = camunda.ExternalTaskService.FetchAndLockTasks("testcase", 100, "informColleagues", 1000, new List<string>()); //Assert.AreEqual(1, externalTasks.Count); //Assert.AreEqual("ServiceTask_KollegenInformieren", externalTasks.First().ActivityId); //camunda.ExternalTaskService.Complete("testcase", externalTasks.First().Id, new Dictionary<string, object>()); // not the process instance has ended, TODO: Check state with History } finally { // cleanup after test case camunda.RepositoryService.DeleteDeployment(deploymentId); } }
public async Task <FileResponse> ProtectDocumentAsync(FileParameter file, string password, string permissions, string jobIdExt = null) { return(await ProtectDocumentAsync(password, permissions, jobIdExt, file, System.Threading.CancellationToken.None)); }
/// <summary>上传活动宣传图临时文件</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> > UploadForActivityTempFileAsync(FileParameter file) { return(UploadForActivityTempFileAsync(file, System.Threading.CancellationToken.None)); }
public async Task <FileResponse> RepairDocumentAsync(FileParameter file, string jobIdExt = null) { return(await RepairDocumentAsync(jobIdExt, file)); }
/// <summary>上传活动宣传图临时文件</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> UploadForActivityTempFile(FileParameter file) { return(System.Threading.Tasks.Task.Run(async() => await UploadForActivityTempFileAsync(file, System.Threading.CancellationToken.None)).GetAwaiter().GetResult()); }
public async Task <HashSet <byte[]> > SplitByPageNrAsync(FileParameter file, int pageNr, string jobIdExt = null) { return(await SplitByPageNrAsync(pageNr, jobIdExt, null, file)); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>上传活动宣传图临时文件</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> > UploadForActivityTempFileAsync(FileParameter file, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("Api/Activity/UploadForActivityTempFile"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file != null) { var content_file_ = new System.Net.Http.StreamContent(file.Data); if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
public async Task <ReadBarcodesRes> ReadBarcodesByTypeAsync(FileParameter file, BarcodeType barcodeType, string jobIdExt = null) { return(await ReadBarcodesByTypeAsync(barcodeType, jobIdExt, file)); }
public FileParameter ParameterToFile(string name, byte[] stream) { return(FileParameter.Create(name, stream, "no_file_name_provided")); }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public System.Threading.Tasks.Task <DocProof> PutProofDocAsync(FileParameter proofDoc, string bindingId, string citizenIdentifier) { return(PutProofDocAsync(proofDoc, bindingId, citizenIdentifier, System.Threading.CancellationToken.None)); }
public async Task <FileResponse> ConvertFileToPdfAsync(FileParameter file, string jobIdExt = null) { return(await ConvertFileToPdfAsync(file.FileName, jobIdExt, file)); }
/// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, string path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) { throw new ArgumentNullException("path"); } if (options == null) { throw new ArgumentNullException("options"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); if (fileParam.Value is FileStream fileStream) { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, Path.GetFileName(fileStream.Name))); } else { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } if (options.RequireApiV4Auth) { request.OnBeforeRequest = http => { http.Headers.Add(new HttpHeader { Name = "KEY", Value = configuration.ApiV4Key }); long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds(); http.Headers.Add(new HttpHeader { Name = "Timestamp", Value = timestamp.ToString() }); using (SHA512 sha512Hash = SHA512.Create()) { var sourceBytes = Encoding.UTF8.GetBytes(http.RequestBody ?? ""); var hashBytes = sha512Hash.ComputeHash(sourceBytes); var bodyHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); var queryString = string.IsNullOrEmpty(http.Url.Query) ? "" : http.Url.Query.Substring(1); var signatureString = $"{request.Method}\n{http.Url.AbsolutePath}\n{queryString}\n{bodyHash}\n{timestamp}"; using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(configuration.ApiV4Secret))) { var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(signatureString)); http.Headers.Add(new HttpHeader { Name = "SIGN", Value = BitConverter.ToString(signature).Replace("-", "").ToLowerInvariant() }); } } }; } return(request); }
public async Task <FileResponse> ExtractPagesAsync(FileParameter file, string pageNrs, string jobIdExt = null) { return(await ExtractPagesAsync(pageNrs, jobIdExt, file)); }
/// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest newRequest( HttpMethod method, String path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) { throw new ArgumentNullException("path"); } if (options == null) { throw new ArgumentNullException("options"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); } else { request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return(request); }
public async Task <FileResponse> CreateThumbnailAsync(FileParameter file, int width, string pageNr, string imageFormat, string jobIdExt = null) { return(await CreateThumbnailAsync(width, pageNr, imageFormat, jobIdExt, file)); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<bool> UploadFileAsync(FileParameter file, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/UploadFile"); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (file != null) content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(bool); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<bool>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); return result_; } catch (System.Exception exception) { throw new GeoClientException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(bool); } }
/// <summary>uploads an image</summary> /// <param name="petId">ID of pet to update</param> /// <param name="additionalMetadata">Additional data to pass to server</param> /// <param name="file">file to upload</param> /// <returns>successful operation</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public System.Threading.Tasks.Task<ApiResponse> UploadFileAsync(int petId, string additionalMetadata, FileParameter file) { return UploadFileAsync(petId, additionalMetadata, file, System.Threading.CancellationToken.None); }