/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <returns></returns> Upload UploadAttachment(ZenFile file, string token = "") { var requestUrl = ZendeskUrl; if (!requestUrl.EndsWith("/")) { requestUrl += "/"; } requestUrl += string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } WebRequest req = WebRequest.Create(requestUrl); req.ContentType = file.ContentType; req.Method = "POST"; req.Credentials = new System.Net.NetworkCredential(User, Password); req.Headers["Authorization"] = GetAuthHeader(User, Password); var dataStream = req.GetWebRequestStream(); dataStream.Write(file.FileData, 0, file.FileData.Length); WebResponse response = req.GetWebResponse(); dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); return(responseFromServer.ConvertToObject <UploadResult>().Upload); }
public void CanUploadAttachmentsForArticle() { var file = new ZenFile() { ContentType = "text/plain", FileName = "testupload.txt", FileData = File.ReadAllBytes(TestContext.CurrentContext.TestDirectory + "\\testupload.txt") }; var articleResponse = api.HelpCenter.Articles.CreateArticle(_sectionId, new Article { Title = "My Test article", Body = "The body of my article", Locale = "en-us" }); var resp = api.HelpCenter.ArticleAttachments.UploadAttachment(articleResponse.Article.Id, file); Assert.That(resp.Attachment, Is.Not.Null); var res = api.HelpCenter.ArticleAttachments.GetAttachments(articleResponse.Article.Id); Assert.That(res.Attachments, Is.Not.Null); Assert.That(api.HelpCenter.ArticleAttachments.DeleteAttachment(resp.Attachment.Id), Is.True); Assert.That(api.HelpCenter.Articles.DeleteArticle(articleResponse.Article.Id.Value), Is.True); }
public async Task CanUploadAttachmentsForArticleAsync() { var file = new ZenFile() { ContentType = "image/jpeg", FileName = "gracehoppertocat3.jpg", FileData = File.ReadAllBytes(TestContext.CurrentContext.TestDirectory + "\\gracehoppertocat3.jpg") }; var articleResponse = await api.HelpCenter.Articles.CreateArticleAsync(_sectionId, new Article { Title = "My Test article", Body = "The body of my article", Locale = "en-us" }); var resp = await api.HelpCenter.ArticleAttachments.UploadAttachmentAsync(articleResponse.Article.Id, file, true); Assert.That(resp.Attachment, Is.Not.Null); Assert.That(resp.Attachment.Inline, Is.True); var res = await api.HelpCenter.ArticleAttachments.GetAttachmentsAsync(articleResponse.Article.Id); Assert.That(res.Attachments, Is.Not.Null); Assert.That(await api.HelpCenter.ArticleAttachments.DeleteAttachmentAsync(resp.Attachment.Id), Is.True); Assert.That(await api.HelpCenter.Articles.DeleteArticleAsync(articleResponse.Article.Id.Value), Is.True); }
public async Task CanUploadAttachmentsForArticleAsync() { var fileData = ResourceUtil.GetResource(ResourceName); var file = new ZenFile() { ContentType = "text/plain", FileName = "testupload.txt", FileData = fileData }; var respSections = await api.HelpCenter.Sections.GetSectionsAsync(); var articleResponse = await api.HelpCenter.Articles.CreateArticleAsync(respSections.Sections[0].Id.Value, new Article { Title = "My Test article", Body = "The body of my article", Locale = "en-us" }); var resp = await api.HelpCenter.ArticleAttachments.UploadAttchmentAsync(articleResponse.Article.Id, file, true); Assert.NotNull(resp.Attachment); Assert.True(resp.Attachment.Inline); Assert.True(await api.HelpCenter.ArticleAttachments.DeleteAttchmentAsync(resp.Attachment.Id)); Assert.True(await api.HelpCenter.Articles.DeleteArticleAsync(articleResponse.Article.Id.Value)); }
public async Task CanUploadAttachmentsForArticleAsync() { var file = new ZenFile() { ContentType = "text/plain", FileName = "testupload.txt", FileData = File.ReadAllBytes(Path.Combine(TestContext.CurrentContext.TestDirectory + Path.DirectorySeparatorChar + "testupload.txt")) }; var articleResponse = await api.HelpCenter.Articles.CreateArticleAsync(_sectionId, new Article { Title = "My Test article", Body = "The body of my article", Locale = "en-us" }); var resp = await api.HelpCenter.ArticleAttachments.UploadAttachmentAsync(articleResponse.Article.Id, file, true); Assert.That(resp.Attachment, Is.Not.Null); Assert.That(resp.Attachment.Inline, Is.True); var res = await api.HelpCenter.ArticleAttachments.GetAttachmentsAsync(articleResponse.Article.Id); Assert.That(res.Attachments, Is.Not.Null); Assert.That(await api.HelpCenter.ArticleAttachments.DeleteAttachmentAsync(resp.Attachment.Id), Is.True); Assert.That(await api.HelpCenter.Articles.DeleteArticleAsync(articleResponse.Article.Id.Value), Is.True); }
public ArticleAttachment UploadAttachment(ZenFile file, bool inline = false) { var form = new Dictionary <string, object> { { "inline", inline }, { "file", file } }; return(GenericPostForm <ArticleAttachment>($"help_center/articles/attachments.json", formParameters: form)); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <param name="timeout"></param> /// <returns></returns> Upload UploadAttachment(ZenFile file, string token, int?timeout) { var requestUrl = ZendeskUrl; if (!requestUrl.EndsWith("/")) { requestUrl += "/"; } requestUrl += string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } WebRequest req = WebRequest.Create(requestUrl); req.ContentType = file.ContentType; req.Method = "POST"; req.ContentLength = file.FileData.Length; req.Headers["Authorization"] = GetPasswordOrTokenAuthHeader(); //If timeout has value set a specific Timeout in the WebRequest if (timeout.HasValue) { req.Timeout = timeout.Value; } //var credentials = new System.Net.CredentialCache // { // { // new System.Uri(ZendeskUrl), "Basic", // new System.Net.NetworkCredential(User, Password) // } // }; //req.Credentials = credentials; req.PreAuthenticate = true; //req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired; var dataStream = req.GetRequestStream(); dataStream.Write(file.FileData, 0, file.FileData.Length); dataStream.Dispose(); WebResponse response = req.GetResponse(); dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); dataStream.Dispose(); response.Close(); return(responseFromServer.ConvertToObject <UploadResult>().Upload); }
private WebException GetWebException(string resource, object body, WebException originalWebException) { string error = string.Empty; WebException innerException = originalWebException.InnerException as WebException; if (originalWebException.Response != null || (innerException != null && innerException.Response != null)) { using (Stream stream = (originalWebException.Response ?? innerException.Response).GetResponseStream()) { if (stream != null && stream.CanRead) { using (var sr = new StreamReader(stream)) { error = sr.ReadToEnd(); } } else { error = "Cannot read error stream."; } } } Debug.WriteLine(originalWebException.Message); Debug.WriteLine(error); string headersMessage = string.Format("Error content: {0} \r\n Resource String: {1} + \r\n", error, resource); string bodyMessage = string.Empty; if (body != null) { ZenFile zenFile = body as ZenFile; if (zenFile == null) { bodyMessage = string.Format(" Body: {0}", JsonConvert.SerializeObject(body, Formatting.Indented, jsonSettings)); } else { bodyMessage = string.Format(" File Name: {0} \r\n File Length: {1}\r\n", zenFile.FileName, (zenFile.FileData != null ? zenFile.FileData.Length.ToString() : "No Data")); } } headersMessage += bodyMessage; if (originalWebException.Response != null && originalWebException.Response.Headers != null) { headersMessage += originalWebException.Response.Headers; } var wException = new WebException(originalWebException.Message + headersMessage, originalWebException); wException.Data.Add("jsonException", error); return(wException); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <param name="timeout"></param> /// <returns></returns> Upload UploadAttachment(ZenFile file, string token, int?timeout = null) { var resource = string.Format("uploads.json?filename={0}", file.FileName); if (!token.IsNullOrWhiteSpace()) { resource += string.Format("&token={0}", token); } var requestResult = RunRequest <UploadResult>(resource, RequestMethod.Post, file, timeout); return(requestResult.Upload); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <param name="timeout"></param> /// <returns></returns> public async Task <Upload> UploadAttachmentAsync(ZenFile file, string token = "", int?timeout = null) { var resource = $"uploads.json?filename={file.FileName}"; if (!token.IsNullOrWhiteSpace()) { resource += $"&token={token}"; } var result = await RunRequestAsync <UploadResult>(resource, RequestMethod.Post, file, timeout); return(result.Upload); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <param name="timeout"></param> /// <returns></returns> public async Task <Upload> UploadAttachmentAsync(ZenFile file, string token = "", int?timeout = null) { string resource = string.Format("uploads.json?filename={0}", file.FileName); if (!token.IsNullOrWhiteSpace()) { resource += string.Format("&token={0}", token); } UploadResult result = await RunRequestAsync <UploadResult>(resource, RequestMethod.Post, file, timeout); return(result.Upload); }
public Task <ArticleAttachment> UploadAttachmentAsync(long?articleId, ZenFile file, bool inline = false) { if (!articleId.HasValue) { throw new ArgumentNullException(nameof(articleId)); } var form = new Dictionary <string, object> { { "inline", inline }, { "file", file } }; return(GenericPostFormAsync <ArticleAttachment>($"help_center/articles/{articleId}/attachments.json", formParameters: form)); }
public async Task <ZenFile> DownloadAttachmentAsync(Attachment attachment) { var file = new ZenFile { FileName = attachment.FileName, ContentType = attachment.ContentType }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", GetPasswordOrTokenAuthHeader()); file.FileData = await client.GetByteArrayAsync(attachment.ContentUrl); } return(file); }
public async Task CanSetUserPhotoAsync() { var file = new ZenFile() { ContentType = "image/jpeg", FileName = "gracehoppertocat3.jpg", FileData = File.ReadAllBytes(TestContext.CurrentContext.TestDirectory + "\\gracehoppertocat3.jpg") }; var user = await api.Users.SetUserPhotoAsync(Settings.UserId, file); Assert.That(user.User.Photo.ContentUrl, Is.Not.Null); Assert.That(user.User.Photo.Size, Is.EqualTo(6553)); }
public async Task CanSetUserPhotoAsync() { var fileData = ResourceUtil.GetResource(ResourceName); var file = new ZenFile() { ContentType = "image/jpeg", FileName = "gracehoppertocat3.jpg", FileData = fileData }; var user = await api.Users.SetUserPhotoAsync(Settings.UserId, file); Assert.NotNull(user.User.Photo.ContentUrl); Assert.True(user.User.Photo.Size != 0); }
public void CanUploadAttachment() { var file = new ZenFile() { ContentType = "text/plain", FileName = "testupload.txt", FileData = File.ReadAllBytes(Path.Combine(TestContext.CurrentContext.TestDirectory + Path.DirectorySeparatorChar + "testupload.txt")) }; var uploadAttachmentResponse = api.HelpCenter.ArticleAttachments.UploadAttachment(file); Assert.That(uploadAttachmentResponse.Attachment, Is.Not.Null); Assert.That(api.HelpCenter.ArticleAttachments.DeleteAttachment(uploadAttachmentResponse.Attachment.Id), Is.True); }
public void CanSetUserPhoto() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "gracehoppertocat3.jpg"); var file = new ZenFile() { ContentType = "image/jpeg", FileName = "gracehoppertocat3.jpg", FileData = File.ReadAllBytes(path) }; var user = api.Users.SetUserPhoto(Settings.UserId, file); Assert.That(user.User.Photo.ContentUrl, Is.Not.Null); Assert.That(user.User.Photo.Size, Is.Not.Zero); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <returns></returns> public async Task <Upload> UploadAttachmentAsync(ZenFile file, string token = "") { var requestUrl = ZendeskUrl; if (!requestUrl.EndsWith("/")) { requestUrl += "/"; } requestUrl += string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } HttpWebRequest req = WebRequest.Create(requestUrl) as HttpWebRequest; req.ContentType = file.ContentType; //req.Credentials = new System.Net.NetworkCredential(User, Password); req.Headers["Authorization"] = GetPasswordOrTokenAuthHeader(); req.Method = "POST"; //GET POST PUT DELETE req.Accept = "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml"; var requestStream = Task.Factory.FromAsync( req.BeginGetRequestStream, asyncResult => req.EndGetRequestStream(asyncResult), (object)null); var dataStream = await requestStream.ContinueWith(t => t.Result.WriteAsync(file.FileData, 0, file.FileData.Length)); Task.WaitAll(dataStream); Task <WebResponse> task = Task.Factory.FromAsync( req.BeginGetResponse, asyncResult => req.EndGetResponse(asyncResult), (object)null); return(await task.ContinueWith(t => { var httpWebResponse = t.Result as HttpWebResponse; return ReadStreamFromResponse(httpWebResponse).ConvertToObject <UploadResult>().Upload; })); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <returns></returns> Upload UploadAttachment(ZenFile file, string token = "") { var requestUrl = ZenDeskUrl; if (!requestUrl.EndsWith("/")) { requestUrl += "/"; } requestUrl += string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } WebRequest req = WebRequest.Create(requestUrl); req.ContentType = file.ContentType; req.Method = "POST"; req.ContentLength = file.FileData.Length; var credentials = new System.Net.CredentialCache { { new System.Uri(ZenDeskUrl), "Basic", new System.Net.NetworkCredential(User, Password) } }; req.Credentials = credentials; req.PreAuthenticate = true; //req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired; var dataStream = req.GetRequestStream(); dataStream.Write(file.FileData, 0, file.FileData.Length); dataStream.Close(); WebResponse response = req.GetResponse(); dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); return(responseFromServer.ConvertToObject <UploadResult>().Upload); }
private byte[] GetFromData(ZenFile zenFile, HttpWebRequest req, string formKey) { string boundaryString = "FEF3F395A90B452BB8BFDC878DDBD152"; req.ContentType = "multipart/form-data; boundary=" + boundaryString; MemoryStream postDataStream = new MemoryStream(); StreamWriter postDataWriter = new StreamWriter(postDataStream); // Include the file in the post data postDataWriter.Write("\r\n--" + boundaryString + "\r\n"); postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", formKey, zenFile.FileName, zenFile.ContentType); postDataWriter.Flush(); postDataStream.Write(zenFile.FileData, 0, zenFile.FileData.Length); postDataWriter.Write("\r\n--" + boundaryString + "--\r\n"); postDataWriter.Flush(); return(postDataStream.ToArray()); }
public static ZenFile ToZenFile(this IFormFile formFile) { var res = new ZenFile(); var stream = formFile.OpenReadStream(); res.FileSize = formFile.Length; res.Id = stream.HashGuid(); res.Locator = res.Id; res.OriginalName = formFile.Name; res.StorageName = res.Id + "-" + formFile.FileName.ToFriendlyUrl() + Path.GetExtension(formFile.FileName); res.MimeType = formFile.ContentType; res.Creation = DateTime.Now; stream.Position = 0; res.Store(stream).Wait(); res.Save(); return(res); }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <param name="timeout"></param> /// <returns></returns> Upload UploadAttachment(ZenFile file, string token, int?timeout) { var requestUrl = ZendeskUrl + string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } WebRequest req = WebRequest.Create(requestUrl); req.ContentType = file.ContentType; req.Method = "POST"; req.ContentLength = file.FileData.Length; req.Headers["Authorization"] = GetPasswordOrTokenAuthHeader(); //If timeout has value set a specific Timeout in the WebRequest if (timeout.HasValue) { req.Timeout = timeout.Value; } req.PreAuthenticate = true; var dataStream = req.GetRequestStream(); dataStream.Write(file.FileData, 0, file.FileData.Length); dataStream.Dispose(); WebResponse response = req.GetResponse(); dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); dataStream.Dispose(); response.Close(); return(responseFromServer.ConvertToObject <UploadResult>().Upload); }
public async Task <Upload> UploadAttachmentAsync(ZenFile file) { return(await UploadAttachmentAsync(file, "")); }
public Upload UploadAttachment(ZenFile file, int?timeout = null) { return(UploadAttachment(file, "", timeout)); }
public Task <IndividualUserResponse> SetUserPhotoAsync(long userId, ZenFile photo) { return(GenericPutAsync <IndividualUserResponse>(string.Format("users/{0}.json", userId), photo, "user[photo][uploaded_data]")); }
public async Task <Upload> UploadAttachmentAsync(ZenFile file, int?timeout = null) { return(await UploadAttachmentAsync(file, "", timeout)); }
public Task <IndividualUserResponse> SetUserPhotoAsync(long userId, ZenFile photo) { return(GenericPutAsync <IndividualUserResponse>($"users/{userId}.json", null, new Dictionary <string, object> { { "user[photo][uploaded_data]", photo } })); }
public Upload UploadAttachment(ZenFile file) { return(UploadAttachment(file, "")); }
public object Get([FromQuery] string id) { // First, prep. Log.Add <MediaStorageController>("FETCH " + id); var query = Request.Query; var dictQuery = query .Where(i => i.Key != "id") .OrderBy(i => i.Key) .ToDictionary(i => i.Key, i => i.Value); var hasParameter = dictQuery.Count != 0; DateTimeOffset offset; var idPayload = id + dictQuery.ToJson(); var cacheTag = idPayload.Sha512Hash(); var mimeCacheTag = cacheTag + "_mimeType"; var entityTag = new EntityTagHeaderValue($"\"{cacheTag}\""); // Is this configuration already cached? Fetch and reply. using var cachedStream = Local.Read(cacheTag); var cachedMimeType = Local.ReadString(mimeCacheTag); if (hasParameter) { if (cachedStream != null && cachedMimeType != null) { var cachedStreamContent = cachedStream.ToByteArray(); offset = DateTime.MinValue; Log.KeyValuePair(id, cacheTag + " " + cachedMimeType); return(File(cachedStreamContent, cachedMimeType, offset, entityTag)); } } var file = ZenFile.Get(id); if (file == null) { return(NotFound()); } if (!file.Exists().Result) { return(NotFound()); } using var stream = file.Fetch().Result; var targetStreamMimeType = file.MimeType; if (!hasParameter) // No modifiers, so just return the fetched entry. { return(File(stream.ToByteArray(), targetStreamMimeType)); } var pipeline = Request.Query.ToRasterImagePipeline(); pipeline.SourcePackage = stream.ToImagePackage(); using var resultStream = pipeline.Process(); // Save in cache. Local.Write(cacheTag, resultStream); Local.WriteString(mimeCacheTag, pipeline.Format.DefaultMimeType); Log.KeyValuePair(pipeline.Format.DefaultMimeType + " media cache ", mimeCacheTag); offset = file.Creation; return(File(resultStream.ToByteArray(), pipeline.Format.DefaultMimeType, offset, entityTag)); }