public async Task <MultipartReader> GetMultipartReader(HttpRequest request) { FormOptions _defaultFormOptions = new FormOptions(); var boundary = await Task.Run(() => MultipartRequest.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit)); var reader = new MultipartReader(boundary, request.Body); return(reader); }
public async Task <string> ValidateImportRequestData(HttpRequest request) { FormOptions _defaultFormOptions = new FormOptions(); var accumulator = new KeyValueAccumulator(); string filePath = Path.GetTempFileName(); var boundary = MultipartRequest.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequest.HasFileContentDisposition(contentDisposition)) { using (var targetStream = File.Create(filePath)) { await section.Body.CopyToAsync(targetStream); } } else if (MultipartRequest.HasFormDataContentDisposition(contentDisposition)) { var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name).ToString(); var encoding = GetEncoding(section); using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { var value = await streamReader.ReadToEndAsync(); if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = String.Empty; } accumulator.Append(key, value); if (accumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"For key count limit {_defaultFormOptions.ValueCountLimit} exceeded"); } } } } section = await reader.ReadNextSectionAsync(); } return(filePath); }
public bool IsMultipartContent(HttpRequest request) { try { if (!MultipartRequest.IsMultipartContentType(request.ContentType)) { return(false); } else { return(true); } } catch (Exception) { throw; } }
public async Task <bool> IsMultipartContent(HttpRequest request) { try { var isMultipart = await Task.Run(() => MultipartRequest.IsMultipartContentType(request.ContentType)); if (!isMultipart) { return(false); } else { return(true); } } catch (Exception) { throw; } }
public PicasaPicture UploadPicture(string title, string description, string mime_type, Stream input) { if (title == null) { throw new ArgumentNullException("title"); } if (input == null) { throw new ArgumentNullException("input"); } if (!input.CanRead) { throw new ArgumentException("Cannot read from stream", "input"); } string url = GDataApi.GetURLForUpload(conn.User, id); if (url == null) { throw new UnauthorizedAccessException("You are not authorized to upload to this album."); } MultipartRequest request = new MultipartRequest(conn, url); MemoryStream ms = null; if (UploadProgress != null) { // We do 'manual' buffering request.Request.AllowWriteStreamBuffering = false; ms = new MemoryStream(); request.OutputStream = ms; } request.BeginPart(true); request.AddHeader("Content-Type: application/atom+xml; \r\n", true); string upload = GetXmlForUpload(title, description); request.WriteContent(upload); request.EndPart(false); request.BeginPart(); request.AddHeader("Content-Type: " + mime_type + "\r\n", true); byte [] data = new byte [8192]; int nread; while ((nread = input.Read(data, 0, data.Length)) > 0) { request.WritePartialContent(data, 0, nread); } request.EndPartialContent(); request.EndPart(true); // It won't call Close() on the MemoryStream if (UploadProgress != null) { int req_length = (int)ms.Length; request.Request.ContentLength = req_length; DoUploadProgress(title, 0, req_length); using (Stream req_stream = request.Request.GetRequestStream()) { byte [] buffer = ms.GetBuffer(); int nwrite = 0; int offset; for (offset = 0; offset < req_length; offset += nwrite) { nwrite = System.Math.Min(16384, req_length - offset); req_stream.Write(buffer, offset, nwrite); // The progress uses the actual request size, not file size. DoUploadProgress(title, offset, req_length); } DoUploadProgress(title, offset, req_length); } } string received = request.GetResponseAsString(); XmlDocument doc = new XmlDocument(); doc.LoadXml(received); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); XmlUtil.AddDefaultNamespaces(nsmgr); XmlNode entry = doc.SelectSingleNode("atom:entry", nsmgr); return(new PicasaPicture(conn, this, entry, nsmgr)); }
public async Task <bool> SendMailAsync(MailMessage message, IMailServerSettings settings) { var mgSettings = settings as MailgunMailServerSettings; if (string.IsNullOrEmpty(mgSettings.Domain)) { return(false); } var request = new MultipartRequest(); if (message.Subject != null) { request.AddField("subject", message.Subject); } if (message.From != null) { request.AddField("from", ComposeEmailDisplayAndAddress(message.From.DisplayName, message.From.Address)); } if (message.To != null && message.To.Count > 0) { foreach (var to in message.To) { request.AddField("to", ComposeEmailDisplayAndAddress(to.DisplayName, to.Address)); } } if (message.CC != null) { foreach (var to in message.CC) { request.AddField("cc", ComposeEmailDisplayAndAddress(to.DisplayName, to.Address)); } } if (message.Bcc != null) { foreach (var to in message.Bcc) { request.AddField("bcc", ComposeEmailDisplayAndAddress(to.DisplayName, to.Address)); } } if (message.ReplyToList != null && message.ReplyToList.Count > 0) { request.AddField("h:Reply-To", string.Join(",", message.ReplyToList.Select(x => ComposeEmailDisplayAndAddress(x.DisplayName, x.Address)))); } foreach (var key in message.Headers.AllKeys) { if (key.StartsWith("h:") || key.StartsWith("o:") || key.StartsWith("v:")) { var values = message.Headers.GetValues(key); foreach (var value in values) { request.AddField(key, value); } } else if (key.StartsWith("Mailgun:")) // Any mailgun header to pass. "Mailgun:" will be stripped from the key. { var values = message.Headers.GetValues(key); var keyPart = key.Remove(0, 8); foreach (var value in values) { request.AddField(keyPart, value); } } else if (key == "X-Mailgun-Tag") // Compatibility with SMTP api { var values = message.Headers.GetValues(key); foreach (var value in values) { request.AddField("o:tag", value); } } } var hasHtmlBody = false; var hasTextBody = false; if (!string.IsNullOrWhiteSpace(message.Body)) { request.AddField(message.IsBodyHtml ? "html" : "text", message.Body); if (message.IsBodyHtml) { hasHtmlBody = true; } else { hasTextBody = true; } } if (!hasHtmlBody) { var content = message.AlternateViews.FirstOrDefault(x => x.ContentType.MediaType == "text/html"); if (content != null) { request.AddField("html", content); } } if (!hasTextBody) { var content = message.AlternateViews.FirstOrDefault(x => x.ContentType.MediaType == "text/plain"); if (content != null) { request.AddField("text", content); } } if (message.Attachments != null) { foreach (var attachment in message.Attachments) { var fileStream = attachment.ContentStream as FileStream; if (fileStream == null) { continue; } if (attachment.ContentDisposition.Inline) { request.AddFile( "inline", fileStream.Name, attachment.ContentId, attachment.ContentType.MediaType); } else { request.AddFile( "attachment", fileStream.Name, attachment.Name, attachment.ContentType.MediaType); } } } var url = string.Format("https://api.mailgun.net/v3/{0}/messages", mgSettings.Domain); var webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "POST"; webRequest.ContentType = request.ContentTypeHeader; webRequest.Timeout = mgSettings.ConnectionTimeout; webRequest.Headers.Add("Authorization", "basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes($"api:{mgSettings.ApiKey}"))); using (var stream = await webRequest.GetRequestStreamAsync()) { await request.SendAsync(stream); } try { using (var response = (HttpWebResponse)(await webRequest.GetResponseAsync())) { if (response == null || response.StatusCode != HttpStatusCode.OK) { throw new WebException( string.Format("Status {0} returned from MailGun API", response == null ? 0 : (Int32)response.StatusCode)); } if (!response.ContentType.StartsWith("application/json")) { throw new WebException( string.Format("Invalid response returned from MailGun API", response == null ? 0 : (Int32)response.StatusCode)); } } } catch (WebException ex) { HttpWebResponse response = null; if (ex.Response != null) { response = (HttpWebResponse)ex.Response; } // Figure out more data about the error string responseData = ""; try { responseData = new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch { // Rethrow default throw ex; } // Rethrow throw new WebException(ex.Message + ": " + responseData, ex, ex.Status, ex.Response); } return(true); // Consumed it }
public object Any(MultipartRequest request) => request;
public PicasaPicture UploadPicture(string title, string description, string mime_type, Stream input) { if (title == null) throw new ArgumentNullException ("title"); if (input == null) throw new ArgumentNullException ("input"); if (!input.CanRead) throw new ArgumentException ("Cannot read from stream", "input"); string url = GDataApi.GetURLForUpload (conn.User, id); if (url == null) throw new UnauthorizedAccessException ("You are not authorized to upload to this album."); MultipartRequest request = new MultipartRequest (conn, url); FileStream fs = null; try { if (UploadProgress != null) { // We do 'manual' buffering request.Request.AllowWriteStreamBuffering = false; fs = new FileStream (Path.GetTempFileName (), FileMode.OpenOrCreate, FileAccess.Read | FileAccess.Write, FileShare.None); request.OutputStream = fs; } request.BeginPart (true); request.AddHeader ("Content-Type: application/atom+xml; \r\n", true); string upload = GetXmlForUpload (title, description); request.WriteContent (upload); request.EndPart (false); request.BeginPart (); request.AddHeader ("Content-Type: " + mime_type + "\r\n", true); byte [] data = new byte [8192]; int nread; while ((nread = input.Read (data, 0, data.Length)) > 0) { request.WritePartialContent (data, 0, nread); } request.EndPartialContent (); request.EndPart (true); // It won't call Close() on the MemoryStream if (UploadProgress != null) { int req_length = (int) fs.Length; request.Request.ContentLength = req_length; fs.Position = 0; DoUploadProgress (title, 0, req_length); using (Stream req_stream = request.Request.GetRequestStream ()) { while ((nread = fs.Read (data, 0, data.Length)) > 0) { req_stream.Write (data, 0, nread); // The progress uses the actual request size, not file size. DoUploadProgress (title, fs.Position, req_length); } DoUploadProgress (title, fs.Position, req_length); } } } finally { if (fs != null) { string name = fs.Name; fs.Close (); File.Delete (name); } } string received = request.GetResponseAsString (); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr); return new PicasaPicture (conn, this, entry, nsmgr); }
public PicasaPicture UploadPicture(string title, string description, string mime_type, Stream input) { if (title == null) throw new ArgumentNullException ("title"); if (input == null) throw new ArgumentNullException ("input"); if (!input.CanRead) throw new ArgumentException ("Cannot read from stream", "input"); string url = GDataApi.GetURLForUpload (conn.User, id); if (url == null) throw new UnauthorizedAccessException ("You are not authorized to upload to this album."); MultipartRequest request = new MultipartRequest (conn, url); MemoryStream ms = null; if (UploadProgress != null) { // We do 'manual' buffering request.Request.AllowWriteStreamBuffering = false; ms = new MemoryStream (); request.OutputStream = ms; } request.BeginPart (true); request.AddHeader ("Content-Type: application/atom+xml; \r\n", true); string upload = GetXmlForUpload (title, description); request.WriteContent (upload); request.EndPart (false); request.BeginPart (); request.AddHeader ("Content-Type: " + mime_type + "\r\n", true); byte [] data = new byte [8192]; int nread; while ((nread = input.Read (data, 0, data.Length)) > 0) { request.WritePartialContent (data, 0, nread); } request.EndPartialContent (); request.EndPart (true); // It won't call Close() on the MemoryStream if (UploadProgress != null) { int req_length = (int) ms.Length; request.Request.ContentLength = req_length; DoUploadProgress (title, 0, req_length); using (Stream req_stream = request.Request.GetRequestStream ()) { byte [] buffer = ms.GetBuffer (); int nwrite = 0; int offset; for (offset = 0; offset < req_length; offset += nwrite) { nwrite = System.Math.Min (16384, req_length - offset); req_stream.Write (buffer, offset, nwrite); // The progress uses the actual request size, not file size. DoUploadProgress (title, offset, req_length); } DoUploadProgress (title, offset, req_length); } } string received = request.GetResponseAsString (); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr); return new PicasaPicture (conn, this, entry, nsmgr); }