Exemplo n.º 1
0
        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[HttpResponseHeader.ETag];
            _location = response.Headers[HttpResponseHeader.Location] ?? redirectLocation;
            _files    = new List <AttachedFile>();

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

                    if (_contentType == MediaType.Multipart && TryGetMultipartBoundary(response.ContentType, out boundary))
                    {
                        var multipart = MimeMessage.Parse(responseStream, boundary);
                        var isFirst   = true;

                        foreach (var part in multipart)
                        {
                            if (isFirst)
                            {
                                _contentType = MediaTypeNames.GetMediaType(part.ContentType);
                                _content     = LoadContent(part.Content, _contentType.Value);
                                isFirst      = false;
                            }
                            else
                            {
                                var fileName = part.ContentDisposition != null ? part.ContentDisposition.FileName : null;
                                _files.Add(new AttachedFile(part.ContentType, fileName, part.Content));
                            }
                        }
                    }
                    else
                    {
                        _content = LoadContent(responseStream, _contentType.Value);
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="innerException"></param>
        public SDataException(WebException innerException)
            : base(innerException.Message, innerException, innerException.Status, innerException.Response)
        {
            if (Response == null)
            {
                return;
            }

            var httpResponse = Response as HttpWebResponse;

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

            if (MediaTypeNames.TryGetMediaType(Response.ContentType, out mediaType) && mediaType == MediaType.Xml)
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (var responseStream = Response.GetResponseStream())
                    {
                        responseStream.CopyTo(memoryStream);
                    }

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    _diagnoses = memoryStream.DeserializeXml <Diagnoses>();

                    if (_diagnoses == null)
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        var diagnosis = memoryStream.DeserializeXml <Diagnosis>();

                        if (diagnosis != null)
                        {
                            _diagnoses = new Collection <Diagnosis> {
                                diagnosis
                            };
                        }
                    }
                }
            }
        }
        private WebRequest CreateRequest(string uri, RequestOperation op)
        {
            var request = WebRequest.Create(uri);

            request.Method          = op.Method.ToString().ToUpper();
            request.Timeout         = Timeout;
            request.PreAuthenticate = true;

            if (_proxySet)
            {
                request.Proxy = _proxy;
            }

            var httpRequest = request as HttpWebRequest;

            if (httpRequest != null)
            {
                httpRequest.AllowAutoRedirect = false;
                httpRequest.ReadWriteTimeout  = Timeout;
                httpRequest.KeepAlive         = false;
                httpRequest.ProtocolVersion   = HttpVersion.Version10;

                if (Accept != null)
                {
                    httpRequest.Accept = string.Join(",", Array.ConvertAll(Accept, type => MediaTypeNames.GetMediaType(type)));
                }

                if (Cookies != null)
                {
                    httpRequest.CookieContainer = Cookies;
                }

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    httpRequest.UserAgent = UserAgent;
                }
            }

            if (Credentials != null)
            {
                request.Credentials = Credentials;
            }
            else if (!string.IsNullOrEmpty(UserName) || !string.IsNullOrEmpty(Password))
            {
                var uriPrefix = new Uri(uri);
                var cred      = new NetworkCredential(UserName, Password);
                request.Credentials = new CredentialCache
                {
                    { uriPrefix, "Basic", cred },
                    { uriPrefix, "Digest", cred },
                    { uriPrefix, "NTLM", cred },
                    { uriPrefix, "Kerberos", cred },
                    { uriPrefix, "Negotiate", cred }
                };
            }
            else
            {
                request.Credentials = CredentialCache.DefaultCredentials;
            }

            if (!string.IsNullOrEmpty(op.ETag))
            {
                var header = op.Method == HttpMethod.Get
                                 ? HttpRequestHeader.IfNoneMatch
                                 : HttpRequestHeader.IfMatch;
                request.Headers[header] = op.ETag;
            }

            var isMultipart = op.Form.Count > 0 || op.Files.Count > 0;

            if (op.Resource != null || isMultipart)
            {
                using (var stream = request.GetRequestStream())
                {
                    var       requestStream = isMultipart ? new MemoryStream() : stream;
                    MediaType?mediaType;

                    if (op.Resource is ISyndicationResource)
                    {
                        mediaType = op.Resource is AtomFeed ? MediaType.Atom : MediaType.AtomEntry;
                        ((ISyndicationResource)op.Resource).Save(requestStream);
                    }
                    else if (op.Resource is IXmlSerializable)
                    {
                        mediaType = MediaType.Xml;

                        using (var xmlWriter = XmlWriter.Create(requestStream))
                        {
                            ((IXmlSerializable)op.Resource).WriteXml(xmlWriter);
                        }
                    }
                    else if (op.Resource is string)
                    {
                        mediaType = MediaType.Text;

                        using (var writer = new StreamWriter(requestStream))
                        {
                            writer.Write((string)op.Resource);
                        }
                    }
                    else
                    {
                        mediaType = null;
                    }

                    if (op.ContentType != null)
                    {
                        mediaType = op.ContentType.Value;
                    }

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

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

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

                            foreach (var file in op.Files)
                            {
                                var contentDisposition = new ContentDisposition(DispositionTypeNames.Attachment);
                                if (file.FileName != null)
                                {
                                    if (file.FileName == Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(file.FileName)))
                                    {
                                        contentDisposition.FileName = file.FileName;
                                    }
                                    else
                                    {
                                        contentDisposition.Parameters["filename*"] = string.Format("{0}''{1}", Encoding.UTF8.WebName, HttpUtility.UrlEncode(file.FileName));
                                    }
                                }

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

                            multipart.WriteTo(stream);
                            request.ContentType = new ContentType("multipart/" + (op.Files.Count > 0 ? "related" : "form-data"))
                            {
                                Boundary = multipart.Boundary
                            }.ToString();
                        }
                    }
                    else if (mediaType != null)
                    {
                        request.ContentType = MediaTypeNames.GetMediaType(mediaType.Value);
                    }
                }
            }

            return(request);
        }