Ejemplo n.º 1
2
        public override bool Execute()
        {
            HttpClient client = null;
            try {
                var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
                var mediaType = new MediaTypeHeaderValue("application/json");
                var jsonSerializerSettings = new JsonSerializerSettings();
                var requestMessage = new HttpRequestMessage<string>(
                    this.PostContent,
                    mediaType,
                    new MediaTypeFormatter[] { jsonFormatter });

                client = new HttpClient();
                HttpResponseMessage response = null;
                System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => {
                    response = respMessage.Result;
                });

                System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask });

                response.EnsureSuccessStatusCode();

                return true;
            }
            catch (Exception ex) {
                string message = "Unable to post the message.";
                throw new LoggerException(message,ex);
            }
            finally {
                if (client != null) {
                    client.Dispose();
                    client = null;
                }
            }
        }
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/>.</returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            var parameters = request.RequestUri.ParseQueryString();

            var prettify = false;
            if (parameters[PrettifyParameterName] != null)
            {
                prettify = new[] { "yes", "1", "true" }.Contains(parameters[PrettifyParameterName], StringComparer.OrdinalIgnoreCase);
            }

            var fieldNamingStratgey = _fieldNamingStratgey;
            if (parameters[FieldNamingStrategyParameterName] != null)
            {
                switch (parameters[FieldNamingStrategyParameterName])
                {
                    case "none":
                        fieldNamingStratgey = new DefaultFieldNamingStrategy();
                        break;

                    case "dash":
                        fieldNamingStratgey = new DasherizedFieldNamingStrategy();
                        break;

                    case "snake":
                        fieldNamingStratgey = new SnakeCaseNamingStrategy();
                        break;
                }
            }

            return new JsonApiMediaTypeFormatter(ContractResolver, fieldNamingStratgey, prettify);
        }
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request,MediaTypeHeaderValue mediaType)
        {
            //所需的对象属性
            var includingFields = request.GetRouteData().Values["fields"];
            if (includingFields != null && !string.IsNullOrEmpty(includingFields.ToString()))
            {
                FieldsJsonMediaTypeFormatter frmtr = new FieldsJsonMediaTypeFormatter();
                frmtr.CurrentRequest = request;
                var resolve = new Share.IncludableSerializerContractResolver(this.SerializerSettings.ContractResolver as Share.IgnorableSerializerContractResolver);
                //type.IsAssignableFrom(typeof(IEnumerable<Model.dr_pre_visit>))
                if (type.GetInterface("IEnumerable") != null)
                {
                    resolve.Include(type.GenericTypeArguments[0], includingFields.ToString(), ',');
                }
                else
                {
                    resolve.Include(type, includingFields.ToString(), ",");
                }

                frmtr.SerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = resolve,
                };
                return frmtr;
            }
            else
            {
                return this;
            }
        }
 /// <summary>
 /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
 /// </summary>
 /// <param name="mediaType">The media type.</param>
 /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 /// <param name="parameterNames">The parameter names.</param>
 public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
 {
     if (mediaType == null)
     {
         throw new ArgumentNullException("mediaType");
     }
     if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
     {
         throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
     }
     if (controllerName == null)
     {
         throw new ArgumentNullException("controllerName");
     }
     if (actionName == null)
     {
         throw new ArgumentNullException("actionName");
     }
     if (parameterNames == null)
     {
         throw new ArgumentNullException("parameterNames");
     }
     ControllerName = controllerName;
     ActionName = actionName;
     MediaType = mediaType;
     ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
     SampleDirection = sampleDirection;
 }
        public TypedJsonMediaTypeFormatter(Type resourceType, MediaTypeHeaderValue mediaType)
        {
            this.resourceType = resourceType;

            this.SupportedMediaTypes.Clear();
            this.SupportedMediaTypes.Add(mediaType);
        }
        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);

            // Remove charset parameter. It must not be sent according to Json Api (http://jsonapi.org/format/#content-negotiation-servers)
            headers.ContentType.CharSet = null;
        }
Ejemplo n.º 7
1
 public StringResponseWriter(string text, MediaTypeHeaderValue contentType)
 {
     VerifyArgument.IsNotNull("mediaType", contentType);
     _text = text;
     _contentType = contentType;
     _enforceSizeCap = true;
 }
        protected virtual string MakeCachekey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
        {
            var controller = context.ControllerContext.ControllerDescriptor.ControllerName;
            var action = context.ActionDescriptor.ActionName;
            var key = context.Request.GetConfiguration().CacheOutputConfiguration().MakeBaseCachekey(controller, action);
            var parametersCollections = context.ActionArguments.Where(x => x.Value != null).Select(x => x.Key + "=" + x.Value);
            var parameters = "-"+string.Join("&", parametersCollections);

            if (excludeQueryString)
            {
                parameters = string.Empty;
            }
            else
            {
                var callbackValue = GetJsonpCallback(context.Request);
                if (!string.IsNullOrWhiteSpace(callbackValue))
                {
                    var callback = "callback=" + callbackValue;
                    if (parameters.Contains("&" + callback)) parameters = parameters.Replace("&" + callback, string.Empty);
                    if (parameters.Contains(callback + "&")) parameters = parameters.Replace(callback + "&", string.Empty);
                    if (parameters.Contains("-" + callback)) parameters = parameters.Replace("-" + callback, string.Empty);
                    if (parameters.EndsWith("&")) parameters = parameters.TrimEnd('&');
                }
            }

            if (parameters == "-") parameters = string.Empty;

            var cachekey = string.Format("{0}{1}:{2}", key, parameters, mediaType.MediaType);
            return cachekey;
        }
 public FileRepresentationModel(string filename, string fileExtension, byte[] contentAsByteArray, MediaTypeHeaderValue mediaTypeHeaderValue)
 {
     Filename = filename;
     FileExtension = fileExtension;
     ContentAsByteArray = contentAsByteArray;
     MediaTypeHeaderValue = mediaTypeHeaderValue;
 }
        public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList<ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList();
            IObjectFacade target = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full) {
                var tempProperties = new List<OptionalProperty>();

                if (!string.IsNullOrEmpty(contextFacade?.Reason)) {
                    tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
                }

                var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy));
                tempProperties.Add(dt);

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray()));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else {
                mapRepresentation = Create(memberValues.ToArray());
            }

            mapRepresentation.SetContentType(mt);

            return mapRepresentation;
        }
Ejemplo n.º 11
1
 public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
 {
     base.SetDefaultContentHeaders(type, headers, mediaType);
     headers.ContentType = new MediaTypeHeaderValue(ApplicationJsonMediaType);
     this.SerializerSettings.Formatting = Formatting.None;
     this.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 }
 public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaType)
 {
     this.mediaType = mediaType;
     string[] splitMediaType = mediaType.MediaType.Split(MediaTypeSubTypeDelimiter);
     this.type = splitMediaType[0];
     this.subType = splitMediaType[1];
 }
 public OpenSearchDescription(MediaTypeHeaderValue contentType, Stream stream) : this(XDocument.Load(stream))
 {
     //if (contentType.MediaType != "application/opensearchdescription+xml")
     //{
     //    throw new NotSupportedException("Do not understand " + contentType.MediaType + " as a search description language");
     //}
 }
        public override void OnActionExecuting(HttpActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            else if (this.IsCacheable(context))
            {
                cachekey = string.Join(":", context.Request.RequestUri.AbsolutePath, context.Request.Headers.Accept.FirstOrDefault().ToString());

                if (WebApiOutputCacheAttribute.webApiCache.Contains(this.cachekey))
                {
                    var val = WebApiOutputCacheAttribute.webApiCache.Get(this.cachekey) as string;

                    if (val != null)
                    {
                        var contenttype = WebApiOutputCacheAttribute.webApiCache.Get(cachekey + ":response-ct") as MediaTypeHeaderValue;
                        if (contenttype == null)
                        {
                            contenttype = new MediaTypeHeaderValue(this.cachekey.Split(':')[1]);
                        }

                        context.Response = context.Request.CreateResponse();
                        context.Response.Content = new StringContent(val);

                        context.Response.Content.Headers.ContentType = contenttype;
                        context.Response.Headers.CacheControl = this.SetClientCache();

                        return;
                    }
                }
            }
        }
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            if (_viewLocator == null || _viewParser == null)
            {
                var config = request.GetConfiguration();

                if (config != null)
                {
                    IViewLocator viewLocator = null;
                    IViewParser viewParser = null;

                    var resolver = config.DependencyResolver;

                    if (_viewLocator == null)
                        viewLocator = (IViewLocator) resolver.GetService(typeof (IViewLocator));

                    if (_viewParser == null)
                        viewParser = (IViewParser) resolver.GetService(typeof (IViewParser));

                    return new HtmlMediaTypeViewFormatter(_siteRootPath, viewLocator, viewParser);
                }
            }

            return base.GetPerRequestFormatterInstance(type, request, mediaType);
        }
Ejemplo n.º 16
1
        public static MapRepresentation Create(HttpRequestMessage req, IList<ContextSurface> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            OptionalProperty[] memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToArray();
            INakedObjectSurface target = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full) {
                var tempProperties = new List<OptionalProperty>();

                if (flags.SimpleDomainModel) {
                    var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName());
                    tempProperties.Add(dt);
                }

                if (flags.FormalDomainModel) {
                    var links = new OptionalProperty(JsonPropertyNames.Links, new[] {
                        Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy),
                               new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(req, target.Specification).GetDomainTypeUri()))
                    });
                    tempProperties.Add(links);
                }

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else {
                mapRepresentation = Create(memberValues);
            }

            mapRepresentation.SetContentType(mt);

            return mapRepresentation;
        }
        public override void OnActionExecuting(HttpActionContext ac)
        {
            if (ac != null)
            {
                if (_isCacheable(ac))
                {
                    _cachekey = string.Join(":", new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() });

                    if (WebApiCache.Contains(_cachekey))
                    {
                        var val = (string)WebApiCache.Get(_cachekey);

                        if (val != null)
                        {
                            var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct");
                            if (contenttype == null)
                                contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);

                            ac.Response = ac.Request.CreateResponse();
                            ac.Response.Content = new StringContent(val);

                            ac.Response.Content.Headers.ContentType = contenttype;
                            ac.Response.Headers.CacheControl = setClientCache();
                            return;
                        }
                    }
                }
            }
            else
            {
                throw new ArgumentNullException("actionContext");
            }
        }
        public void Negotiate_ForRequestReturnsFirstMatchingFormatter()
        {
            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/myMediaType");

            MediaTypeFormatter formatter1 = new MockMediaTypeFormatter()
            {
                CanWriteTypeCallback = (Type t) => false
            };

            MediaTypeFormatter formatter2 = new MockMediaTypeFormatter()
            {
                CanWriteTypeCallback = (Type t) => true
            };

            formatter2.SupportedMediaTypes.Add(mediaType);

            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(
                new MediaTypeFormatter[] 
                {
                    formatter1,
                    formatter2
                });

            _request.Content = new StringContent("test", Encoding.Default, mediaType.MediaType);

            var result = _negotiator.Negotiate(typeof(string), _request, collection);
            Assert.Same(formatter2, result.Formatter);
            Assert.MediaType.AreEqual(mediaType, result.MediaType, "Expected the formatter's media type to be returned.");
        }
Ejemplo n.º 19
1
        public static MapRepresentation Create(HttpRequestMessage req, ContextSurface context, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            var objectContextSurface = context as ObjectContextSurface;
            var actionResultContextSurface = context as ActionResultContextSurface;
            MapRepresentation mapRepresentation;


            if (objectContextSurface != null) {
                List<OptionalProperty> optionalProperties = objectContextSurface.VisibleProperties.Where(p => p.Reason != null || p.ProposedValue != null).Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList();
                if (!string.IsNullOrEmpty(objectContextSurface.Reason)) {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, objectContextSurface.Reason));
                }
                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else if (actionResultContextSurface != null) {
                List<OptionalProperty> optionalProperties = actionResultContextSurface.ActionContext.VisibleParameters.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList();

                if (!string.IsNullOrEmpty(actionResultContextSurface.Reason)) {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, actionResultContextSurface.Reason));
                }
                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else {
                mapRepresentation = GetMap(req, context, flags);
            }


            mapRepresentation.SetContentType(mt);


            return mapRepresentation;
        }
 public void Constructor(string queryStringParameterName, string queryStringParameterValue, MediaTypeHeaderValue mediaType)
 {
     QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);
     Assert.Equal(queryStringParameterName, mapping.QueryStringParameterName);
     Assert.Equal(queryStringParameterValue, mapping.QueryStringParameterValue);
     Assert.MediaType.AreEqual(mediaType, mapping.MediaType, "MediaType failed to set.");
 }
        public void Equals_Returns_True_If_MediaTypes_Differ_Only_By_Case()
        {
            MediaTypeHeaderValueEqualityComparer comparer = MediaTypeHeaderValueEqualityComparer.EqualityComparer;

            MediaTypeHeaderValue mediaType1 = new MediaTypeHeaderValue("text/xml");
            MediaTypeHeaderValue mediaType2 = new MediaTypeHeaderValue("TEXT/xml");
            Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'.");

            mediaType1 = new MediaTypeHeaderValue("text/*");
            mediaType2 = new MediaTypeHeaderValue("TEXT/*");
            Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'.");

            mediaType1 = new MediaTypeHeaderValue("*/*");
            mediaType2 = new MediaTypeHeaderValue("*/*");
            Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'.");

            mediaType1 = new MediaTypeHeaderValue("text/*");
            mediaType1.CharSet = "someCharset";
            mediaType2 = new MediaTypeHeaderValue("TEXT/*");
            mediaType2.CharSet = "SOMECHARSET";
            Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'.");

            mediaType1 = new MediaTypeHeaderValue("application/*");
            mediaType1.CharSet = "";
            mediaType2 = new MediaTypeHeaderValue("application/*");
            mediaType2.CharSet = null;
            Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'.");
        }
 /// <summary>
 ///     Sets the sample request directly for the specified media type of the action.
 /// </summary>
 /// <param name="config">The <see cref="HttpConfiguration" />.</param>
 /// <param name="sample">The sample response.</param>
 /// <param name="mediaType">The media type.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 public static void SetSampleResponse(this HttpConfiguration config, object sample,
     MediaTypeHeaderValue mediaType, string controllerName, string actionName) {
     config.GetHelpPageSampleGenerator()
         .ActionSamples.Add(
             new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] {"*"}),
             sample);
 }
 /// <summary>
 /// Constructor which initializes this serializer
 /// </summary>
 public JsonSerializer()
 {
     ContentType = new MediaTypeHeaderValue("application/json")
     {
         CharSet = _encoding.WebName,
     };
 }
 ///<summary>
 /// Creates a file parameter from an array of bytes.
 ///</summary>
 ///<param name="name">The parameter name to use in the request.</param>
 ///<param name="input">The input stream for the file's contents.</param>
 ///<param name="filename">The filename to use in the request.</param>
 ///<param name="contentType">The content type to use in the request.</param>
 ///<returns>The <see cref="FileParameter"/></returns>
 public static FileParameter Create(string name, Stream input, string filename, MediaTypeHeaderValue contentType)
 {
     var temp = new MemoryStream();
     input.CopyTo(temp);
     var data = temp.ToArray();
     return Create(name, data, filename, contentType);
 }
Ejemplo n.º 25
0
 public void Ctor_MediaTypeValidFormat_SuccessfullyCreated()
 {
     MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("text/plain");
     Assert.Equal("text/plain", mediaType.MediaType);
     Assert.Equal(0, mediaType.Parameters.Count);
     Assert.Null(mediaType.CharSet);
 }
Ejemplo n.º 26
0
        public RouteDataMapping(string routeDataValueName, string routeDataValueValue, MediaTypeHeaderValue mediaType) : 
            base(mediaType) {

            _routeDataValueName = routeDataValueName;
            _routeDataValueValue = routeDataValueValue;

        }
Ejemplo n.º 27
0
        public static HttpContentType CreateFromBase64(HttpContentHeaderData headerData, string base64)
        {
            var content = CreateBase64(base64);

            content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(headerData.ContentType);
            return(content);
        }
Ejemplo n.º 28
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                name: "GetStringAPI",
                routeTemplate: "api/{controller}/{category}/{query}",
                defaults: new { category = "getmovielist", query = RouteParameter.Optional }
                );
            config.Routes.MapHttpRoute(
                name: "GetblockListAPI",
                routeTemplate: "api/{controller}/{category}/{id}",
                defaults: new { category = "getblocklist", id = RouteParameter.Optional }
                );
            config.Routes.MapHttpRoute(
                name: "GetblockQueryAPI",
                routeTemplate: "api/{controller}/{category}/{query}",
                defaults: new { category = "getblocklist", id = RouteParameter.Optional }
                );
            System.Net.Http.Headers.MediaTypeHeaderValue appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
        private static MediaTypeHeaderValue GetContentTypeFromQueryString(IEdmModel model, Type type, string dollarFormat)
        {
            var formatters = CreateOutputFormatters(model);
            var path       = new ODataPath();
            var request    = string.IsNullOrEmpty(dollarFormat)
                ? RequestFactory.CreateFromModel(model, "http://any", "OData", path)
                : RequestFactory.CreateFromModel(model, "http://any/?$format=" + dollarFormat, "OData", path);

            var context = new OutputFormatterWriteContext(
                request.HttpContext,
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                type,
                new MemoryStream());

            foreach (var formatter in formatters)
            {
                context.ContentType = new StringSegment();
                context.ContentTypeIsServerDefined = false;

                if (formatter.CanWriteResult(context))
                {
                    MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(context.ContentType.ToString());

                    // We don't care what the charset is for these tests.
                    if (mediaType.Parameters.Where(p => p.Name == "charset").Any())
                    {
                        mediaType.Parameters.Remove(mediaType.Parameters.Single(p => p.Name == "charset"));
                    }

                    return(mediaType);
                }
            }

            return(null);
        }
Ejemplo n.º 30
0
        public async Task Download(HttpResponseMessage httpResponseMessage, int id, string field, Database.Sqlite db)
        {
            string filename = httpResponseMessage.Content.Headers.ContentDisposition.FileName.Replace("\"", "");

            System.Net.Http.Headers.MediaTypeHeaderValue contenttype = httpResponseMessage.Content.Headers.ContentType;
            using (Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync()) {
                using (MemoryStream ms = new MemoryStream()) {
                    //string filename = $"{docid}_{(int)type}";
                    stream.CopyTo(ms);
                    byte[] buffer = ms.ToArray();
                    stream.Flush();
                    if (filename == "404.json")
                    {
                        filename = httpResponseMessage.RequestMessage.RequestUri.ToString();
                    }
                    else
                    {
                        int year = 20 * 100 + id / 100000000;
                        SaveFile(buffer, filename, year);
                        db.UpdateFilenameOfDisclosure(id, field, filename);
                    }
#pragma warning disable CS4014
                    SaveLog(GetLog(httpResponseMessage.StatusCode, RequestType.Archive, contenttype, filename));
#pragma warning restore CS4014
                }
            }

            httpResponseMessage.Dispose();
        }
Ejemplo n.º 31
0
        public void GetMediaType_HandlesUnknownMediaTypes(string extension)
        {
            MediaTypeMap map = new MediaTypeMap();
            MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue("application/octet-stream");

            Assert.Equal(expectedMediaType, map.GetMediaType(extension));
        }
Ejemplo n.º 32
0
        public async Task <ArchiveResponse> DownloadArchive(string docid, DocumentType type, int retry)
        {
            ArchiveResponse response = new ArchiveResponse();
            string          url      = string.Format("/api/{0}/documents/{1}?type={2}", Version, docid, (int)type);
            int             i        = 0;

            do
            {
                if (i > 0)
                {
                    SaveLog($"  retry[{i}] {docid} {type}");
                    Debug.Write($"retry Download[{i}] ");
                    await Task.Delay(2000);
                }
                try {
                    debug.ProgramCodeInfo.SetDebugQueue();
                    using (HttpResponseMessage res = await client.GetAsync(url)) {
                        debug.ProgramCodeInfo.SetDebugQueue();
                        string filename = res.Content.Headers.ContentDisposition.FileName.Replace("\"", "");
                        //string filename = $"{docid}_{(int)type}";
                        System.Net.Http.Headers.MediaTypeHeaderValue contenttype = res.Content.Headers.ContentType;
                        if (filename == "404.json")
                        {
                            filename = url;
                        }
#pragma warning disable CS4014
                        SaveLog(GetLog(res.StatusCode, RequestType.Archive, contenttype, filename));
#pragma warning restore CS4014
                        using (Stream stream = await res.Content.ReadAsStreamAsync()) {
                            using (MemoryStream ms = new MemoryStream()) {
                                stream.CopyTo(ms);
                                byte[] buffer = ms.ToArray();
                                stream.Flush();
                                response.Update(buffer, res.StatusCode, filename, contenttype);
                                debug.ProgramCodeInfo.SetDebugQueue();
                                return(response);
                            }
                        }
                    }
                } catch (TaskCanceledException ex) {
                    response.Update(ex);
#pragma warning disable CS4014
                    SaveLog(GetLog(response));
#pragma warning restore CS4014
                    debug.ProgramCodeInfo.SetDebugQueue();
                } catch (Exception ex) {
                    response.Update(ex);
#pragma warning disable CS4014
                    SaveLog(GetLog(response));
#pragma warning restore CS4014
                    debug.ProgramCodeInfo.SetDebugQueue();
                    return(response);
                }
                i++;
            } while (i <= retry);
            return(response);
        }
        public void TestCreate_Property_DefaultContentType()
        {
            // Arrange
            IEdmModel model        = CreateModelWithEntity <SampleType>();
            Type      propertyType = typeof(int);

            // Act
            MediaTypeHeaderValue mediaType = GetDefaultContentType(model, propertyType);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse("application/json;odata.metadata=minimal;odata.streaming=true"), mediaType);
        }
Ejemplo n.º 34
0
        public void TestCreate_MetadataDocument_DollarFormat(string dollarFormatValue, string expectedMediaType)
        {
            // Arrange
            IEdmModel model = CreateModel();
            Type      metadataDocumentType = typeof(IEdmModel);

            // Act
            MediaTypeHeaderValue mediaType = GetContentTypeFromQueryString(model, metadataDocumentType, dollarFormatValue);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), mediaType);
        }
        public void TestCreate_MetadataDocument_DefaultContentType()
        {
            // Arrange
            IEdmModel model = CreateModel();
            Type      serviceDocumentType = typeof(IEdmModel);

            // Act
            MediaTypeHeaderValue mediaType = GetDefaultContentType(model, serviceDocumentType);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse("application/xml"), mediaType);
        }
        public void TestCreate_DollarFormat_Collection(string dollarFormatValue, string expectedMediaType)
        {
            // Arrange
            IEdmModel model          = CreateModelWithEntity <SampleType>();
            Type      collectionType = typeof(IEnumerable <int>);

            // Act
            MediaTypeHeaderValue mediaType = GetContentTypeFromQueryString(model, collectionType, dollarFormatValue);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), mediaType);
        }
        public void TestCreate_DollarFormat_Error(string dollarFormatValue, string expectedMediaType)
        {
            // Arrange
            IEdmModel model     = CreateModelWithEntity <SampleType>();
            Type      errorType = typeof(ODataError);

            // Act
            MediaTypeHeaderValue mediaType = GetContentTypeFromQueryString(model, errorType, dollarFormatValue);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), mediaType);
        }
        public void TestCreate_ServiceDocument_DefaultContentType()
        {
            // Arrange
            IEdmModel model = CreateModel();
            Type      serviceDocumentType = typeof(ODataServiceDocument);

            // Act
            MediaTypeHeaderValue mediaType = GetDefaultContentType(model, serviceDocumentType);

            // Assert
            Assert.Equal(MediaTypeHeaderValue.Parse("application/json;odata.metadata=minimal;odata.streaming=true"), mediaType);
        }
        private Stream Serialize <T>(System.Net.Http.Formatting.MediaTypeFormatter formatter,
                                     T value, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            Stream stream = new MemoryStream();

            try
            {
                HttpContent content = new StreamContent(stream);
                content.Headers.ContentType = mediaType;
                formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
                stream.Position = 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Serialization error: " + ex.ToString());
            }
            return(stream);
        }
Ejemplo n.º 40
0
        //Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq"
        // The spec at https://tools.ietf.org/html/rfc2046#section-5.1 states that 70 characters is a reasonable limit.

        public static string GetBoundary(System.Net.Http.Headers.MediaTypeHeaderValue contentType, int lengthLimit)
        {
            string boundary = "----WebKitFormBoundarymx2fSWqWSd0OxQqq";

            //string boundary = HeaderUtilities.RemoveQuotes().Value;

            if (string.IsNullOrWhiteSpace(boundary))
            {
                throw new InvalidDataException("Missing content-type boundary.");
            }

            if (boundary.Length > lengthLimit)
            {
                throw new InvalidDataException(
                          $"Multipart boundary length limit {lengthLimit} exceeded.");
            }

            return(boundary);
        }
        public static HttpContentType CreateFromBody(HttpContentHeaderData headerData, string body)
        {
            if (headerData.ContentEncoding == "gzip")
            {
                var content = CreateGzip(body);
                content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(headerData.ContentType);
#if WINDOWS_UWP
                content.Headers.ContentEncoding.ParseAdd(headerData.ContentEncoding);
#else
                content.Headers.ContentEncoding.Add(headerData.ContentEncoding);
#endif
                return(content);
            }
            else
            {
                var content = CreateString(body);
                content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(headerData.ContentType);
                return(content);
            }
        }
        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            string fileName;

            // Look for ExcelDocumentAttribute on class.
            var itemType = util.GetEnumerableItemType(type);
            var excelDocumentAttribute = util.GetAttribute <ExcelDocumentAttribute>(itemType ?? type);

            if (excelDocumentAttribute != null && !string.IsNullOrEmpty(excelDocumentAttribute.FileName))
            {
                // If attribute exists with file name defined, use that.
                fileName = excelDocumentAttribute.FileName;
            }
            else
            {
                // Otherwise, use  "data".
                fileName = "data";
            }

            // Add XLSX extension if not present.
            if (!fileName.EndsWith("xlsx", StringComparison.CurrentCultureIgnoreCase))
            {
                fileName += ".xlsx";
            }

            // Set content disposition to use this file name.
            headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
            {
                FileName = fileName
            };

            base.SetDefaultContentHeaders(type, headers, mediaType);
        }
 private static IEnumerable <MediaTypeHeaderValue> GetMediaTypes(string[] mediaTypes)
 {
     return(mediaTypes.Select(m => MediaTypeHeaderValue.Parse(m)));
 }
Ejemplo n.º 44
0
 internal static object GetBoundary(System.Net.Http.Headers.MediaTypeHeaderValue mediaTypeHeaderValue, object multipartBoundaryLengthLimit)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 45
-1
        /// <summary>
        /// Validate HttpResponse message, throws an Api Exception with context
        /// </summary>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <param name="apiContext"></param>
        /// <exception cref="ApiException"></exception>
        public static void EnsureSuccess(HttpResponseMessage response, HttpRequestMessage request=null, IApiContext apiContext=null)
        {
		    if (response.IsSuccessStatusCode) return;
		    if (response.StatusCode == HttpStatusCode.NotModified) return;
		    var content = response.Content.ReadAsStringAsync().Result;
		    ApiException exception ;
		    var htmlMediaType = new MediaTypeHeaderValue("text/html");
		    if (response.Content.Headers.ContentType != null && 
		        response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType)
		    {
		        var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode,
		            response.RequestMessage.RequestUri.AbsoluteUri);
		        exception = new ApiException(message, new Exception(content));
		    }
		    else if (!String.IsNullOrEmpty(content))
		        exception = JsonConvert.DeserializeObject<ApiException>(content);
		    else if (HttpStatusCode.NotFound == response.StatusCode && string.IsNullOrEmpty(content) && request != null)
                exception = new ApiException("Uri "+request.RequestUri.AbsoluteUri + " does not exist");
            else
		        exception = new ApiException("Unknow Exception");
		    exception.HttpStatusCode = response.StatusCode;
		    exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers);
		    exception.ApiContext = apiContext;
		    if (!MozuConfig.ThrowExceptionOn404 &&
		        string.Equals(exception.ErrorCode, "ITEM_NOT_FOUND", StringComparison.OrdinalIgnoreCase)
		        && response.RequestMessage.Method.Method == "GET")
		        return;
		    throw exception;
        }
Ejemplo n.º 46
-1
        /// <summary>
        ///     Creates a new <see cref="HelpPageSampleKey" /> based on media type and CLR type.
        /// </summary>
        /// <param name="mediaType">The media type.</param>
        /// <param name="type">The CLR type.</param>
        public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
            : this(mediaType)
        {
            if (type == null) throw new ArgumentNullException("type");

            this.ParameterType = type;
        }
 /// <summary>
 ///     Sets the sample request directly for the specified media type and action with parameters.
 /// </summary>
 /// <param name="config">The <see cref="HttpConfiguration" />.</param>
 /// <param name="sample">The sample request.</param>
 /// <param name="mediaType">The media type.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 /// <param name="parameterNames">The parameter names.</param>
 public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType,
     string controllerName, string actionName, params string[] parameterNames) {
     config.GetHelpPageSampleGenerator()
         .ActionSamples.Add(
             new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames),
             sample);
 }