public static void GetFile(ref FileStreamInfo info, string fileName, Stream stream, int length) { if (info != null) { //FileStreamInfo info = new FileStreamInfo(); info.name = fileName; info.length = length; info.buffer = new byte[length]; int size = 0; int index = 0; if (stream != null) { while (true) { size = stream.Read(info.buffer, 0, length); if (size > 0) { index += size; } else { break; } } } } }
/// <summary> /// This endpoint can be used to validate an API description document *on the fly* and see detailed error messages along with any warnings or useful information. /// </summary> /// <param name="body">Required parameter: The input file to use for validation</param> /// <return>Returns the Models.ValidateAnAPIDescriptionResponse response from the API call</return> public Models.ValidateAnAPIDescriptionResponse UsingFile(FileStreamInfo body) { Task <Models.ValidateAnAPIDescriptionResponse> t = UsingFileAsync(body); APIHelper.RunTaskSynchronously(t); return(t.Result); }
/// <summary> /// Upload a file and convert it to the given format. The API description format of the uploaded file will be detected automatically. The converted file is returned as the response. /// </summary> /// <param name="format">Required parameter: The API format to convert to</param> /// <param name="file">Required parameter: The input file to convert</param> /// <return>Returns the Stream response from the API call</return> public Stream UsingFile(Models.FormatTransformer format, FileStreamInfo file) { Task <Stream> t = UsingFileAsync(format, file); APIHelper.RunTaskSynchronously(t); return(t.Result); }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="file">Required parameter: Example: </param> /// <param name="ticketId">Required parameter: Example: </param> /// <return>Returns the Ticket response from the API call</return> public Ticket UploadPicture(FileStreamInfo file, string ticketId) { Task <Ticket> t = UploadPictureAsync(file, ticketId); Task.WaitAll(t); return(t.Result); }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="file">Required parameter: Example: </param> /// <return>Returns the ServerResponse response from the API call</return> public ServerResponse SendFile(FileStreamInfo file) { Task <ServerResponse> t = SendFileAsync(file); Task.WaitAll(t); return(t.Result); }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="file">Required parameter: Example: </param> /// <param name="ticketId">Required parameter: Example: </param> /// <return>Returns the string response from the API call</return> public string UploadInvoice(FileStreamInfo file, string ticketId) { Task <string> t = UploadInvoiceAsync(file, ticketId); Task.WaitAll(t); return(t.Result); }
public async Task TestSendFile() { // Parameters for the API call FileStreamInfo file = TestHelper.GetFile("https://dl.dropboxusercontent.com/u/31838656/binary.png"); // Perform API call ServerResponse result = null; try { result = await controller.SendFileAsync(file); } catch (APIException) {}; // Test response code Assert.AreEqual(200, httpCallBackHandler.Response.StatusCode, "Status should be 200"); // Test whether the captured response is as we expected Assert.IsNotNull(result, "Result should exist"); Assert.IsTrue(TestHelper.IsJsonObjectProperSubsetOf( "{\"passed\":true}", TestHelper.ConvertStreamToString(httpCallBackHandler.Response.RawBody), true, true, false), "Response body should have matching keys"); }
public async Task UploadAndDownloadMedia() { var accountId = TestConstants.AccountId; var mediaId = $"text-media-id-{Guid.NewGuid()}"; var content = "Hello world"; var contentType = "text/plain"; var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); FileStreamInfo fileStreamInfo = new FileStreamInfo(memoryStream); // Upload the media content. await _client.Messaging.APIController.UploadMediaAsync(accountId, mediaId, fileStreamInfo, contentType); // Get the media content which we've just uploaded. var response = await _client.Messaging.APIController.GetMediaAsync(accountId, mediaId); Assert.Equal(200, response.StatusCode); Assert.Equal(contentType, response.Headers["Content-Type"]); // Validate that the media content is correct. var streamReader = new StreamReader(response.Data); var actualContent = streamReader.ReadToEnd(); Assert.Equal(content, actualContent); // Delete the media content. await _client.Messaging.APIController.DeleteMediaAsync(accountId, mediaId); }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="file">Required parameter: Example: </param> /// <return>Returns the ServerResponse response from the API call</return> public async Task <ServerResponse> SendFileAsync(FileStreamInfo file) { //validating required parameters if (null == file) { throw new ArgumentNullException("file", "The parameter \"file\" is a required parameter and cannot be null."); } //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/form/file"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "Stamplay SDK" }, { "accept", "application/json" } }; //append form/field parameters var _fields = new Dictionary <string, object>() { { "file", file } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request, _response); //return null on 404 if (_response.StatusCode == 404) { return(null); } //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <ServerResponse>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
/// <summary> /// Send a variety for form params. Returns file count and body params /// </summary> /// <param name="file">Required parameter: TODO: type parameter description here</param> /// <param name="models">Required parameter: TODO: type parameter description here</param> /// <param name="numbers">Required parameter: TODO: type parameter description here</param> /// <param name="strings">Required parameter: TODO: type parameter description here</param> /// <return>Returns the dynamic response from the API call</return> public async Task <dynamic> SendMixedArrayAsync( FileStreamInfo file, List <Person> models, List <int> numbers, List <string> strings) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/form/mixed"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "Stamplay SDK" }, { "accept", "application/json" } }; //append form/field parameters var _fields = new Dictionary <string, object>() { { "file", file } }; _fields.Add(APIHelper.PrepareFormFieldsFromObject("models", models)); _fields.Add(APIHelper.PrepareFormFieldsFromObject("numbers", numbers)); _fields.Add(APIHelper.PrepareFormFieldsFromObject("strings", strings)); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request, _response); //Error handling using HTTP status codes if ((_response.StatusCode < 200) || (_response.StatusCode > 206)) //[200,206] = HTTP OK { throw new APIException(@"HTTP Response Not OK", _context); } try { return(APIHelper.JsonDeserialize <dynamic>(_response.Body)); } catch (Exception ex) { throw new APIException("Failed to parse the response: " + ex.Message, _context); } }
private byte[] ReadPiece(int idx) { FileStreamInfo fileStreamInfo = Seek(idx); int pieceLength = fileStreamInfo.File.Length / _pieceLen == idx ? (idx * _pieceLen) - fileStreamInfo.File.Length : _pieceLen; byte[] payload = new byte[pieceLength]; fileStreamInfo.Stream.Read(payload, 0, pieceLength); return(payload); }
public override string GetItemDisplayName(int index) { FileStreamInfo fsi = internal_list.Keys[index]; if (fsi.Name == string.Empty) { return("<Default stream>"); } return(fsi.Name); }
/// <summary> /// Uploads a file to use as evidence in a dispute challenge. The endpoint accepts HTTP. /// multipart/form-data file uploads in HEIC, HEIF, JPEG, PDF, PNG, and TIFF formats.. /// </summary> /// <param name="disputeId">Required parameter: The ID of the dispute you want to upload evidence for..</param> /// <param name="request">Optional parameter: Defines the parameters for a `CreateDisputeEvidenceFile` request..</param> /// <param name="imageFile">Optional parameter: Example: .</param> /// <returns>Returns the Models.CreateDisputeEvidenceFileResponse response from the API call.</returns> public Models.CreateDisputeEvidenceFileResponse CreateDisputeEvidenceFile( string disputeId, Models.CreateDisputeEvidenceFileRequest request = null, FileStreamInfo imageFile = null) { Task <Models.CreateDisputeEvidenceFileResponse> t = this.CreateDisputeEvidenceFileAsync(disputeId, request, imageFile); ApiHelper.RunTaskSynchronously(t); return(t.Result); }
/// <summary> /// Create binary multipart content from file. /// </summary> internal static MultipartContent CreateFileMultipartContent(FileStreamInfo input, Dictionary <string, IReadOnlyCollection <string> > headers = null) { if (headers == null) { return(new MultipartFileContent(input)); } else { return(new MultipartFileContent(input, headers)); } }
/// <summary> /// uploadMedia /// </summary> /// <param name="userId">Required parameter: Example: </param> /// <param name="mediaId">Required parameter: Example: </param> /// <param name="contentLength">Required parameter: Example: </param> /// <param name="body">Required parameter: Example: </param> /// <param name="contentType">Optional parameter: Example: application/octet-stream</param> /// <param name="cacheControl">Optional parameter: Example: </param> /// <return>Returns the void response from the API call</return> public void UploadMedia( string userId, string mediaId, long contentLength, FileStreamInfo body, string contentType = "application/octet-stream", string cacheControl = null) { Task t = UploadMediaAsync(userId, mediaId, contentLength, body, contentType, cacheControl); ApiHelper.RunTaskSynchronously(t); }
/// <summary> /// Uploads a file the normal HTTP way. You may add headers to the request in order to provide some control to your media-file. /// </summary> /// <param name="accountId">Required parameter: User's account ID.</param> /// <param name="mediaId">Required parameter: The user supplied custom media ID.</param> /// <param name="body">Required parameter: Example: .</param> /// <param name="contentType">Optional parameter: The media type of the entity-body.</param> /// <param name="cacheControl">Optional parameter: General-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.</param> public void UploadMedia( string accountId, string mediaId, FileStreamInfo body, string contentType = "application/octet-stream", string cacheControl = null) { Task t = this.UploadMediaAsync(accountId, mediaId, body, contentType, cacheControl); ApiHelper.RunTaskSynchronously(t); }
/// <summary> /// 用于下载FileStreamInfo类型的文件流 /// </summary> /// <param name="stream"></param> public static void DownLoadStream(FileStreamInfo stream) { var bytes = stream.ToArray(); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlDecode(stream.FileName)); HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString()); HttpContext.Current.Response.BinaryWrite(bytes); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }
public StreamList(string file_name, bool read_security_streams, int sort_criteria, bool sort_reverse) : base(sort_criteria, sort_reverse) { read_sec_streams = read_security_streams; file_name_full = file_name; internal_comparer = new InternalComparer(sort_criteria, sort_reverse); internal_list = new SortedList <FileStreamInfo, object>(internal_comparer); //fake info internal_parent_info = new FileStreamInfo("..", 0, FileStreamID.DATA, FileStreamAttributes.NORMAL); }
public override string GetItemDisplaySummaryInfo(int index) { FileStreamInfo info = internal_list.Keys[index]; return (string.Format ("{0} [{1}] [{2}]", IOhelper.SizeToString(info.Size), IOhelper.FileStreamID2String(info.ID), IOhelper.FileStreamAttributes2String(info.Attributes))); }
/// <summary> /// The code generation endpoint! Upload a file and convert it to the given format. The API description format of uploaded file will be detected automatically. The response is generated zip file as per selected template. /// </summary> /// <param name="name">Required parameter: The name of the API being used for code generation</param> /// <param name="format">Required parameter: The format of the API description to use for code generation</param> /// <param name="template">Required parameter: The template to use for code generation</param> /// <param name="body">Required parameter: The input file to use for code generation</param> /// <param name="dl">Optional parameter: Optional</param> /// <return>Returns the Stream response from the API call</return> public Stream UsingFileAsBinary( string name, Models.Format format, Models.Template template, FileStreamInfo body, int?dl = 1) { Task <Stream> t = UsingFileAsBinaryAsync(name, format, template, body, dl); APIHelper.RunTaskSynchronously(t); return(t.Result); }
/// <summary> /// The code generation endpoint. The response is a path to the generated zip file relative to https://apimatic.io/ /// </summary> /// <param name="name">Required parameter: The name of the API being used for code generation</param> /// <param name="format">Required parameter: The format of the API description to use for code generation</param> /// <param name="template">Required parameter: The template to use for code generation</param> /// <param name="body">Required parameter: The input file to use for code generation</param> /// <param name="dl">Optional parameter: Optional</param> /// <return>Returns the string response from the API call</return> public string UsingFileAsString( string name, Models.Format format, Models.Template template, FileStreamInfo body, int?dl = 0) { Task <string> t = UsingFileAsStringAsync(name, format, template, body, dl); APIHelper.RunTaskSynchronously(t); return(t.Result); }
/// <summary> /// 获取永久素材。 /// </summary> /// <param name="mediaId">媒体ID</param> /// <param name="accessToken">全局凭证</param> /// <param name="stream">文件流</param> /// <returns>当请求的是图文消息时,返回图文消息实体。其他类型的消息则返回文件流</returns> public static MaterialNews Get(string mediaId, string accessToken, out FileStreamInfo stream) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}", accessToken); var retdata = Utils.HttpPost(url, "{\"media_id\":" + mediaId + "}", out stream); if (retdata == "")//说明非图文消息 { return(new MaterialNews { ErrCode = 0 }); } return(JsonConvert.DeserializeObject <MaterialNews>(retdata)); }
/// <summary> /// This endpoint can be used to validate an API description document *on the fly* and see detailed error messages along with any warnings or useful information. /// </summary> /// <param name="body">Required parameter: The input file to use for validation</param> /// <return>Returns the Models.ValidateAnAPIDescriptionResponse response from the API call</return> public async Task <Models.ValidateAnAPIDescriptionResponse> UsingFileAsync(FileStreamInfo body) { //the base uri for api requests string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/validate"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" } }; //append form/field parameters var _fields = new List <KeyValuePair <string, Object> >() { new KeyValuePair <string, object>("body", body) }; //remove null parameters _fields = _fields.Where(kvp => kvp.Value != null).ToList(); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields, Configuration.BasicAuthUserName, Configuration.BasicAuthPassword); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <Models.ValidateAnAPIDescriptionResponse>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
public override string GetItemDisplayNameLong(int index) { FileStreamInfo fsi = internal_list.Keys[index]; if (fsi == internal_parent_info) { return(file_name_full); } if (fsi.Name == string.Empty) { return(file_name_full); } return(fsi.Name); }
/// <summary> /// 根据文件中的物理路径或网络路径下载文件 /// </summary> /// <param name="fileUrl">文件路径,可为网络资源,也可以为文件物理路径</param> /// <param name="fileName">文件名</param> public static void DownLoadFile(string fileUrl, string fileName) { using (var client = new WebClient()) { // 将网络资源下载为二进制数据 var bytes = client.DownloadData(fileUrl); using (var fsi = new FileStreamInfo()) { // 将二进制数据写入文件流 fsi.Write(bytes, 0, bytes.Length); fsi.FileName = fileName; DownLoadStream(fsi); } } }
public InternalListViewItem(FileStreamInfo data) { InternalData = data; if (data.Name == string.Empty) { Text = "<Default stream>"; } else { Text = data.Name; } SubItems.Add(data.Size.ToString("#,##0")); SubItems.Add(data.ID.ToString()); SubItems.Add(data.Attributes.ToString()); }
private void copy_selected_to_file() { if (listViewResult.SelectedItems.Count == 0) { return; } FileStreamInfo sel_info = ((InternalListViewItem)listViewResult.SelectedItems[0]).InternalData; string source = internal_file_name + sel_info.Name; saveFileDialog1.AddExtension = false; saveFileDialog1.AutoUpgradeEnabled = true; saveFileDialog1.CheckFileExists = false; saveFileDialog1.CheckFileExists = false; saveFileDialog1.OverwritePrompt = true; saveFileDialog1.ValidateNames = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string destinsation = saveFileDialog1.FileName; this.UseWaitCursor = true; try { WinAPiFSwrapper.CopyFile (source, destinsation, true, null, IntPtr.Zero, 131072); } catch (Exception ex) { UseWaitCursor = false; Messages.ShowException(ex); } UseWaitCursor = false; } }
/// <summary> /// HTTP POST请求URL。 /// </summary> /// <param name="url">请求的url</param> /// <param name="param">请求的参数</param> /// <param name="stream">如果响应的是文件,则此参数表示的是文件流</param> public static string HttpPost(string url, string param, out FileStreamInfo stream) { stream = null; //当请求为https时,验证服务器证书 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => { return(true); }); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; string responseStr = ""; using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream())) { requestStream.Write(param);//将请求的数据写入到请求流中 } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.ContentType == "application/octet-stream")//如果响应的是文件流,则不将响应流转换成字符串 { stream = new FileStreamInfo(); response.GetResponseStream().CopyTo(stream); #region 获取响应的文件名 Regex reg = new Regex(@"(\w+)\.(\w+)"); var result = reg.Match(response.GetResponseHeader("Content-disposition")).Groups; stream.FileName = result[0].Value; #endregion responseStr = ""; } else { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { responseStr = reader.ReadToEnd();//获取响应 } } } return(responseStr); }
/// <summary> /// 生成二维码流 /// </summary> /// <param name="qrcontent">二维码的内容</param> /// <param name="size">生成的二维码的尺寸。单位是像素</param> /// <returns>内存流。可保存为文件,或下载到客户端</returns> public static FileStreamInfo GetQrCodeStream(string qrcontent, int size) { //误差校正水平 ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel.M; //空白区域 QuietZoneModules quietZone = QuietZoneModules.Zero; int ModuleSize = size;//大小 Gma.QrCodeNet.Encoding.QrCode qrCode; var encoder = new QrEncoder(ecLevel); //对内容进行编码,并保存生成的矩阵 if (encoder.TryEncode(qrcontent, out qrCode)) { var render = new GraphicsRenderer(new FixedCodeSize(ModuleSize, quietZone)); var stream = new FileStreamInfo(); render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, stream); stream.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"; return(stream); } return(null); }
/// <summary> ///根据文件路径获取文件流信息,包括文件名(支持网络路径) /// </summary> /// <param name="filepath">文件路径</param> /// <returns></returns> public static FileStreamInfo GetFileStreamInfo(string filepath) { var fsi = new FileStreamInfo(); if (!filepath.Contains("http")) { using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { fs.Position = 0L; fs.CopyTo(fsi); } } else { using (var client = new WebClient()) { var bytes = client.DownloadData(filepath); fsi.Write(bytes, 0, bytes.Length); } } fsi.FileName = Path.GetFileName(filepath); return(fsi); }
/// <summary> /// The text should be provided as multipart/form-data with the key 'text'. Files can be uploaded. /// </summary> /// <param name="text">Required parameter: Supply text to be classified.</param> /// <return>Returns the dynamic response from the API call</return> public async Task<dynamic> CreateReturnEnglishGeneralSentimentMultipartFormAsync( FileStreamInfo text) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/sentiment"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { {"user-agent", "APIMATIC 2.0"}, {"accept", "application/json"} }; _headers.Add("X-Mashape-Key", Configuration.XMashapeKey); //append form/field parameters var _fields = new Dictionary<string,object>() { {"text", text} }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //Error handling using HTTP status codes if ((_response.StatusCode < 200) || (_response.StatusCode > 206)) //[200,206] = HTTP OK throw new APIException(@"HTTP Response Not OK", _context); try { return APIHelper.JsonDeserialize<dynamic>(_response.Body); } catch (Exception ex) { throw new APIException("Failed to parse the response: " + ex.Message, _context); } }