Beispiel #1
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        public SDataException(WebException innerException)
            : base(GetMessage(innerException), innerException, innerException.Status, innerException.Response)
        {
            if (Response == null)
            {
                return;
            }

            var httpResponse = Response as HttpWebResponse;

            _statusCode = httpResponse != null ? httpResponse.StatusCode : (HttpStatusCode?)null;
            MediaType contentType;

            if (MediaTypeNames.TryGetMediaType(Response.ContentType, out contentType))
            {
                var handler = ContentManager.GetHandler(contentType);
                if (handler != null)
                {
                    using (var responseStream = Response.GetResponseStream())
                    {
                        _content = handler.ReadFrom(responseStream);
                    }

                    if (ContentHelper.IsDictionary(_content))
                    {
                        var diagnosis = ContentHelper.Deserialize <Diagnosis>(_content);
                        if (diagnosis != null)
                        {
                            _diagnoses = new Diagnoses {
                                diagnosis
                            };
                        }
                    }
                    else if (ContentHelper.IsCollection(_content))
                    {
                        var diagnoses = ContentHelper.Deserialize <Diagnoses>(_content);
                        if (diagnoses != null)
                        {
                            _diagnoses = diagnoses;
                        }
                    }
                }
            }
        }
        internal SDataResponse(WebResponse response, string redirectLocation)
        {
            var httpResponse = response as HttpWebResponse;

            _statusCode = httpResponse != null ? httpResponse.StatusCode : 0;

            MediaType contentType;

            if (MediaTypeNames.TryGetMediaType(response.ContentType, out contentType))
            {
                _contentType = contentType;
            }

            _eTag     = response.Headers["ETag"];
            _location = response.Headers["Location"] ?? redirectLocation;

            var            header = response.Headers["Expires"];
            DateTimeOffset date;

            if (DateTimeOffset.TryParse(header, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date))
            {
                _expires = date;
            }

            header = response.Headers["Retry-After"];
            int num;

            if (DateTimeOffset.TryParse(header, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date))
            {
                _retryAfter = date;
            }
            else if (int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
            {
                _retryAfter = DateTimeOffset.UtcNow.AddSeconds(num);
            }

            _form  = new Dictionary <string, string>();
            _files = new List <AttachedFile>();

            if (_statusCode != HttpStatusCode.NoContent)
            {
                using (var responseStream = response.GetResponseStream())
                {
                    string boundary;

                    if (_contentType == MediaType.Multipart && TryGetMultipartBoundary(response.ContentType, out boundary))
                    {
                        var multipart  = MimeMessage.Parse(responseStream, boundary);
                        var isFormData = string.Equals(new ContentType(response.ContentType).SubType, "form-data", StringComparison.OrdinalIgnoreCase);

                        foreach (var part in multipart)
                        {
                            if (_content == null && MediaTypeNames.TryGetMediaType(part.ContentType, out contentType))
                            {
                                _contentType = contentType;
                                _content     = LoadContent(part.Content, _contentType.Value);
                            }
                            else
                            {
                                if (isFormData)
                                {
                                    var name = ContentDisposition.Parse(part.ContentDisposition)["name"];
                                    if (name != null)
                                    {
                                        var value = new StreamReader(part.Content).ReadToEnd();
                                        _form.Add(name, value);
                                        continue;
                                    }
                                }

                                _files.Add(new AttachedFile(part));
                            }
                        }
                    }
                    else
                    {
                        _content = LoadContent(responseStream, _contentType);

                        if (_statusCode == HttpStatusCode.Accepted)
                        {
                            var tracking = ContentHelper.Deserialize <Tracking>(_content);
                            if (tracking != null)
                            {
                                _content = tracking;
                            }
                        }
                        else if (_statusCode >= HttpStatusCode.BadRequest)
                        {
                            if (ContentHelper.IsDictionary(_content))
                            {
                                var diagnosis = ContentHelper.Deserialize <Diagnosis>(_content);
                                if (diagnosis != null)
                                {
                                    throw new SDataException(new Diagnoses {
                                        diagnosis
                                    }, _statusCode);
                                }
                            }
                            else if (ContentHelper.IsCollection(_content))
                            {
                                var diagnoses = ContentHelper.Deserialize <Diagnoses>(_content);
                                if (diagnoses != null)
                                {
                                    throw new SDataException(diagnoses, _statusCode);
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #3
0
        private void WriteRequestContent(MediaType?contentType, object content, Stream stream)
        {
            var isMultipart   = Form.Count > 0 || Files.Count > 0;
            var requestStream = isMultipart ? new MemoryStream() : stream;

            if (contentType == null)
            {
                if (ContentHelper.IsDictionary(content))
                {
                    contentType = MediaType.AtomEntry;
                }
                else if (ContentHelper.IsCollection(content))
                {
                    contentType = MediaType.Atom;
                }
                else if (content is IXmlSerializable)
                {
                    contentType = MediaType.Xml;
                }
                else if (content is string)
                {
                    contentType = MediaType.Text;
                }
                else if (ContentHelper.IsObject(content))
                {
                    contentType = MediaType.AtomEntry;
                }
            }

            if (contentType != null && content != null)
            {
                var handler = ContentManager.GetHandler(contentType.Value);
                if (handler == null)
                {
                    throw new NotSupportedException(string.Format("Content type '{0}' not supported", contentType));
                }

                handler.WriteTo(content, requestStream, NamingScheme);
            }

            if (isMultipart)
            {
                requestStream.Seek(0, SeekOrigin.Begin);

                using (var multipart = new MimeMessage())
                {
                    if (contentType != null)
                    {
                        var part = new MimePart(requestStream)
                        {
                            ContentType = MediaTypeNames.GetMediaType(contentType.Value)
                        };
                        multipart.Add(part);
                    }

                    foreach (var data in Form)
                    {
                        var part = new MimePart(new MemoryStream(Encoding.UTF8.GetBytes(data.Value)))
                        {
                            ContentType             = MediaTypeNames.TextMediaType,
                            ContentTransferEncoding = "binary",
                            ContentDisposition      = "inline; name=" + data.Key
                        };
                        multipart.Add(part);
                    }

                    foreach (var file in Files)
                    {
                        var contentDisposition = "attachment";
                        if (file.FileName != null)
                        {
                            contentDisposition += Encoding.UTF8.GetByteCount(file.FileName) == file.FileName.Length
                                ? "; filename=" + string.Format("\"{0}\"", file.FileName.Replace("\"", "\\\""))
                                : "; filename*=" + string.Format("{0}''{1}", Encoding.UTF8.WebName, System.Uri.EscapeDataString(file.FileName));
                        }

                        var part = new MimePart(file.Stream)
                        {
                            ContentType             = file.ContentType ?? "application/octet-stream",
                            ContentTransferEncoding = "binary",
                            ContentDisposition      = contentDisposition
                        };
                        multipart.Add(part);
                    }

                    multipart.WriteTo(stream);
                    _request.ContentType = string.Format("multipart/{0}; boundary={1}", (Files.Count > 0 ? "related" : "form-data"), multipart.Boundary);
                }
            }
            else if (contentType != null)
            {
                _request.ContentType = MediaTypeNames.GetMediaType(contentType.Value);
            }
        }