public void Constructor1_SetsDerivedFormatters()
 {
     // force to array to get stable instances
     MediaTypeFormatter[] derivedFormatters = HttpTestData.DerivedFormatters.ToArray();
     MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(derivedFormatters);
     Assert.True(derivedFormatters.SequenceEqual(collection));
 }
示例#2
0
 /// <summary>
 /// Format json to camel case
 /// </summary>
 /// <param name="formatters"></param>
 public static void CamelCasePropertyNamesContractResolver(MediaTypeFormatterCollection formatters)
 {
     var jsonFormatter = formatters.JsonFormatter;
     var settings = jsonFormatter.SerializerSettings;
     //settings.Formatting = Formatting.Indented;
     settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 }
 public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.Remove(formatters.XmlFormatter);
     
     var json = formatters.JsonFormatter;
     json.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
 }
 private static MediaTypeFormatterCollection GetFormatters(IEnumerable<MediaTypeFormatter> formatters)
 {
     var mediaTypeFormatters = new MediaTypeFormatterCollection();
     foreach(var formatter in formatters)
         mediaTypeFormatters.Add(formatter);
     return mediaTypeFormatters;
 }
        public void Constructor1SetsProperties()
        {
            // All combination of formatters presented to ctor should still set XmlFormatter
            foreach (IEnumerable<MediaTypeFormatter> formatterCollection in HttpUnitTestDataSets.AllFormatterCollections)
            {
                MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatterCollection);
                if (collection.OfType<XmlMediaTypeFormatter>().Any())
                {
                    Assert.NotNull(collection.XmlFormatter);
                }
                else
                {
                    Assert.Null(collection.XmlFormatter);
                }

                if (collection.OfType<JsonMediaTypeFormatter>().Any())
                {
                    Assert.NotNull(collection.JsonFormatter);
                }
                else
                {
                    Assert.Null(collection.JsonFormatter);
                }
            }
        }
 public ActionInvokerComponent(AppFunc next, MediaTypeFormatterCollection formatters, IContentNegotiator contentNegotiator, IActionParameterBinder parameterBinder)
 {
     _next = next;
     _formatters = formatters;
     _contentNegotiator = contentNegotiator;
     _actionParameterBinder = parameterBinder;
 }
        public static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
        {
            formatters.Remove(formatters.XmlFormatter);

            JsonSerializerSettings settings = formatters.JsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.None;
        }
        private HttpConfiguration(HttpConfiguration configuration, HttpControllerSettings settings)
        {
            _routes = configuration.Routes;
            _filters = configuration.Filters;
            _messageHandlers = configuration.MessageHandlers;
            _properties = configuration.Properties;
            _dependencyResolver = configuration.DependencyResolver;
            IncludeErrorDetailPolicy = configuration.IncludeErrorDetailPolicy;

            // per-controller settings
            Services = settings.IsServiceCollectionInitialized ? settings.Services : configuration.Services;
            _formatters = settings.IsFormatterCollectionInitialized ? settings.Formatters : configuration.Formatters;
            ParameterBindingRules = settings.IsParameterBindingRuleCollectionInitialized ? settings.ParameterBindingRules : configuration.ParameterBindingRules;

            // Use the original configuration's initializer so that its Initialize()
            // will perform the same logic on this clone as on the original.
            Initializer = configuration.Initializer;

            // create a new validator cache if the validator providers have changed
            if (settings.IsServiceCollectionInitialized &&
                !settings.Services.GetModelValidatorProviders().SequenceEqual(configuration.Services.GetModelValidatorProviders()))
            {
                ModelValidatorCache validatorCache = new ModelValidatorCache(new Lazy<IEnumerable<ModelValidatorProvider>>(() => Services.GetModelValidatorProviders()));
                RegisterForDispose(validatorCache);
                settings.Services.Replace(typeof(IModelValidatorCache), validatorCache);
            }
        }
示例#9
0
        private static void TestWebApi()
        {
            Console.WriteLine();
            Console.WriteLine("------------------------------------------------------------");
            Console.WriteLine("Web API");
            Console.WriteLine("------------------------------------------------------------");

            var client = new HttpClient {BaseAddress = new Uri("http://localhost:14851/")};

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var mediaTypeFormatterCollection = new MediaTypeFormatterCollection();
            ExecuteAction(NumberOfRequestsToSend + " requests to api/item/id", () =>
            {
                for (int i = 0; i < NumberOfRequestsToSend; i++)
                {
                    var response = client.GetAsync("api/item/" + Guid.NewGuid()).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var item = response.Content.ReadAsAsync<Item>(mediaTypeFormatterCollection).Result;
                        if (item == null)
                            throw new Exception("Item not received.");
                        //Console.WriteLine("ItemID\t\t{0}\nDescription\t{1}\nModifiedAt\t{2}", item.ItemID, item.Description, item.ModifiedAt);
                    }
                    else
                    {
                        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    }
                }
            });
        }
 public void Constructor()
 {
     MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();
     Assert.Equal(3, collection.Count);
     Assert.NotNull(collection.XmlFormatter);
     Assert.NotNull(collection.JsonFormatter);
     Assert.NotNull(collection.FormUrlEncodedFormatter);
 }
示例#11
0
        private static void Configure(MediaTypeFormatterCollection formatters, HttpConfiguration config)
        {
            var xml = config.Formatters.XmlFormatter;
            formatters.Remove(xml);

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
示例#12
0
        internal HttpResponseErrorHandler(IEnumerable<MediaTypeFormatter> formatters, Uri helpUri, bool includeExceptionDetail)
        {
            Fx.Assert(formatters != null, "The 'formatters' parameter should not be null.");

            this.formatters = new MediaTypeFormatterCollection(formatters);
            this.helpUri = helpUri;
            this.includeExceptionDetail = includeExceptionDetail;
        }
        public ItunesRepository()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 1000000; // 1MB

            formatters = new MediaTypeFormatterCollection();
            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
        }
        public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            var jsonFormatter = formatters.JsonFormatter;
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var jsonpFormatter = new JsonpMediaTypeFormatter(jsonFormatter);
            formatters.Add(jsonpFormatter);
        }
 public MultipartMediaTypeFormatter([NotNull] MediaTypeFormatterCollection mediaTypeFormatterCollection,
                                    [NotNull] IPropertyHelper propertyHelper)
 {
     if (mediaTypeFormatterCollection == null) throw new ArgumentNullException(nameof(mediaTypeFormatterCollection));
     if (propertyHelper == null) throw new ArgumentNullException(nameof(propertyHelper));
     _mediaTypeFormatterCollection = mediaTypeFormatterCollection;
     _propertyHelper = propertyHelper;
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
 }
示例#16
0
        private static void SetFormatters(MediaTypeFormatterCollection formatters)
        {
            formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

            formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
            formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;
        }
 public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.Remove(formatters.JsonFormatter);
     formatters.Insert(0, new JsonpMediaTypeFormatter {
         SerializerSettings = new JsonSerializerSettings {
             ContractResolver = new CamelCasePropertyNamesContractResolver()
         }
     });
 }
        /// <summary>
        /// Internal constructor used to build collection of available MediaTypeFormatters
        /// </summary>
        protected MediaTypeFormatters()
        {
            formatters = new MediaTypeFormatterCollection();

            IMediaTypeFormatterFactory jsonFactory = new JsonFormatterFactory();
            formatters.Add(jsonFactory.Formatter());
            IMediaTypeFormatterFactory xmlFactory = new XmlFormatterFactory();
            formatters.Add(xmlFactory.Formatter());
        }
 public ResttpConfiguration(Assembly controllersAssembly)
 {
     HttpRoutes = new HttpRouteList();
     ControllersAssembly = controllersAssembly;
     Formatters = new MediaTypeFormatterCollection();
     //Formatters.Remove(Formatters.First(f=>f is FormUrlEncodedMediaTypeFormatter));
     ContentNegotiator = new ContentNegotiation.ContentNegotiator();
     ActionParameterBinder = new Resttp.ActionInvoker.ActionParameterBinder();
 }
示例#20
0
        /// <summary>Construct an HTTP request message.</summary>
        /// <param name="method">The HTTP method.</param>
        /// <param name="resource">The URI to send the request to.</param>
        /// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
        public virtual HttpRequestMessage GetRequestMessage(HttpMethod method, Uri resource, MediaTypeFormatterCollection formatters)
        {
            HttpRequestMessage request = new HttpRequestMessage(method, resource);

            // add default headers
            request.Headers.Add("user-agent", "FluentHttpClient/0.4 (+http://github.com/Pathoschild/Pathoschild.FluentHttpClient)");
            request.Headers.Add("accept", formatters.SelectMany(p => p.SupportedMediaTypes).Select(p => p.MediaType));

            return request;
        }
示例#21
0
        public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            var jsonFormatter = formatters.JsonFormatter;
            jsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            formatters.Add(new CountryImageFormatter());

            GlobalConfiguration.Configuration.AddJsonpFormatter();
        }
        public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            // Remove xml formatter (at least for the moment)
            formatters.Remove(formatters.XmlFormatter);

            // Json formatter
            //formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            //formatters.JsonFormatter.Indent = true; ?
            //formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
            //formatters.JsonFormatter.MaxDepth = 1;
            //formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        }
示例#23
0
        public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            var jsonFormatter = formatters.JsonFormatter;
            jsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            // Insert the JSONP formatter in front of the standard JSON formatter.
            var jsonpFormatter = new JsonpMediaTypeFormatter(formatters.JsonFormatter);
            formatters.Insert(0, jsonpFormatter);
        }
示例#24
0
 public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.Remove(formatters.JsonFormatter);
     var formatter = new JsonMediaTypeFormatter
     {
         SerializerSettings = new JsonSerializerSettings
         {
             ContractResolver = new CamelCasePropertyNamesContractResolver()
         }
     };
     formatter.SerializerSettings.Converters.Add(new ExpandoObjectConverter());
     formatters.Insert(0, formatter);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpConfiguration"/> class.
        /// </summary>
        /// <param name="routes">The <see cref="HttpRouteCollection"/> to associate with this instance.</param>
        public HttpConfiguration(HttpRouteCollection routes)
        {
            if (routes == null)
            {
                throw Error.ArgumentNull("routes");
            }

            _routes = routes;
            _formatters = DefaultFormatters(this);

            Services = new DefaultServices(this);
            ParameterBindingRules = DefaultActionValueBinder.GetDefaultParameterBinders();
        }
示例#26
0
        public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            var jsonFormatter = formatters.JsonFormatter;
            jsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            };

            formatters.Remove(formatters.XmlFormatter);
            formatters.Insert(0, new JsonMediaTypeFormatter());
        }
示例#27
0
        /***
        ** HttpClient
        ***/
        /// <summary>Get the formatter for an HTTP content type.</summary>
        /// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
        /// <param name="contentType">The HTTP content type (or <c>null</c> to automatically select one).</param>
        /// <exception cref="InvalidOperationException">No MediaTypeFormatters are available on the API client for this content type.</exception>
        public virtual MediaTypeFormatter GetFormatter(MediaTypeFormatterCollection formatters, MediaTypeHeaderValue contentType = null)
        {
            if (!formatters.Any())
                throw new InvalidOperationException("No MediaTypeFormatters are available on the fluent client.");

            MediaTypeFormatter formatter = contentType != null
                ? formatters.FirstOrDefault(f => f.MediaTypeMappings.Any(m => m.MediaType.MediaType == contentType.MediaType))
                : formatters.FirstOrDefault();
            if (formatter == null)
                throw new InvalidOperationException(String.Format("No MediaTypeFormatters are available on the fluent client for the '{0}' content-type.", contentType));

            return formatter;
        }
示例#28
0
        private static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
        {
            // Remove unnecessary formatters
            MediaTypeFormatter jqueryFormatter = formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter));
            formatters.Remove(formatters.XmlFormatter);
            formatters.Remove(formatters.FormUrlEncodedFormatter);
            formatters.Remove(jqueryFormatter);

            // Suppressing the IRequiredMemberSelector for all formatters
            foreach (var formatter in formatters)
            {
                formatter.RequiredMemberSelector = new SuppressedRequiredMemberSelector();
            }
        }
        public void Constructor()
        {
            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();
#if !NETFX_CORE // No FormUrlEncodedMediaTypeFormatter in portable library version
            Assert.Equal(3, collection.Count);
#else
            Assert.Equal(2, collection.Count);
#endif
            Assert.NotNull(collection.XmlFormatter);
            Assert.NotNull(collection.JsonFormatter);
#if !NETFX_CORE // No FormUrlEncodedMediaTypeFormatter in portable library version
            Assert.NotNull(collection.FormUrlEncodedFormatter);
#endif
        }
示例#30
0
        /// <summary>
        /// Media formatter settings
        /// </summary>
        private static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            formatters.Add(new JQueryMvcFormUrlEncodedFormatter());
            formatters.Add(new XmlMediaTypeFormatter());

            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/javascript"));
            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-www-form-urlencoded"));

            formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            formatters.XmlFormatter.UseXmlSerializer = true;
            formatters.XmlFormatter.Indent = true;
        }
示例#31
0
 public static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
 }
示例#32
0
        public static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
        {
            var settings = formatters.JsonFormatter.SerializerSettings;

            settings.Formatting = Formatting.Indented;
        }
 /// <summary>
 /// Determines whether instances of a particular type should be validated
 /// </summary>
 /// <param name="type">The type to validate.</param>
 /// <returns><c>true</c> if the type should be validated; <c>false</c> otherwise</returns>
 public virtual bool ShouldValidateType(Type type)
 {
     return(!MediaTypeFormatterCollection.IsTypeExcludedFromValidation(type));
 }
示例#34
0
        public static HttpResponseMessage ReturnContent(object returnObj, IContentNegotiator content, MediaTypeFormatterCollection formatter, HttpRequestMessage request)
        {
            IContentNegotiator       negotiator = content;
            ContentNegotiationResult result     = null;

            result = negotiator.Negotiate(typeof(object), request, formatter);
            return(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content = new ObjectContent <object>(returnObj, result.Formatter, result.MediaType.MediaType)
            });
        }
 public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
 {
     GlobalConfiguration.Configuration.Formatters.JsonFormatter.Indent = true;
     GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
 }
示例#36
0
 private static void ConfigFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
     formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     formatters.Remove(formatters.XmlFormatter);
 }
示例#37
0
 internal static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
 }
示例#38
0
 public Request(HttpRequestMessage message, MediaTypeFormatterCollection formatters, Func <Request, Task <HttpResponseMessage> > dispatcher)
 {
     Message    = message;
     Formatters = formatters;
     dispatch   = new Lazy <Task <HttpResponseMessage> >(() => dispatcher(this));
 }
示例#39
0
 public static void RegisterJsonNetMediaTypeFormatter(MediaTypeFormatterCollection formatters)
 {
     formatters.Remove(formatters.OfType <JsonMediaTypeFormatter>().FirstOrDefault());
     formatters.Add(new JsonNetMediaTypeFormatter());
 }
示例#40
0
        /// <summary>Construct an HTTP request message.</summary>
        /// <param name="method">The HTTP method.</param>
        /// <param name="resource">The URI to send the request to.</param>
        /// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
        public static HttpRequestMessage GetRequestMessage(HttpMethod method, Uri resource, MediaTypeFormatterCollection formatters)
        {
            HttpRequestMessage request = new HttpRequestMessage(method, resource);

            // add default headers
            request.Headers.Add("user-agent", "FluentHttpClient/0.4 (+http://github.com/Pathoschild/Pathoschild.FluentHttpClient)");
            request.Headers.Add("accept", formatters.SelectMany(p => p.SupportedMediaTypes).Select(p => p.MediaType));

            return(request);
        }
示例#41
0
        public static async Task <T> Receive <T>(this Task <IFlurlResponse> response, MediaTypeFormatterCollection formatterCollection, CancellationToken cancellationToken = default)
        {
            var resp = await response.ConfigureAwait(false);

            if (resp == null)
            {
                return(default);
示例#42
0
 public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
 {
     formatters.Remove(formatters.XmlFormatter);
     formatters.Add(new FlickerFeedMediaFormatter());
 }
示例#43
0
 public HttpClientWrapper(HttpClient httpClient, MediaTypeFormatterCollection mediaTypeFormatters)
 {
     _httpClient          = httpClient;
     _mediaTypeFormatters = mediaTypeFormatters;
 }
示例#44
0
        public static HttpRequestMessage GetRequestMessage(HttpMethod method, Uri resource, MediaTypeFormatterCollection formatters)
        {
            HttpRequestMessage request = new HttpRequestMessage(method, resource);

            // add default headers
            request.Headers.Add("accept", formatters.SelectMany(p => p.SupportedMediaTypes).Select(p => p.MediaType));

            return(request);
        }
示例#45
0
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="message">The underlying HTTP request message.</param>
 /// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
 public Response(HttpResponseMessage message, MediaTypeFormatterCollection formatters)
 {
     this.Message    = message;
     this.Formatters = formatters;
 }
示例#46
0
 public ContentBuilder(MediaTypeFormatterCollection formatters)
 {
     _formatters = formatters;
 }
示例#47
0
 public Formatter()
 {
     MediaTypeFormatters = new MediaTypeFormatterCollection().FluentAdd(new StringMediaFormatter());
 }
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="message">The underlying HTTP request message.</param>
 /// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
 /// <param name="responseBuilder">Executes an HTTP request.</param>
 public RequestBuilder(HttpRequestMessage message, MediaTypeFormatterCollection formatters, Func <IRequestBuilder, Task <HttpResponseMessage> > responseBuilder)
 {
     this.Message         = message;
     this.Formatters      = formatters;
     this.ResponseBuilder = responseBuilder;
 }
示例#49
0
 public WebApiCompatShimOptions()
 {
     // Start with an empty collection, our options setup will add the default formatters.
     Formatters = new MediaTypeFormatterCollection(Enumerable.Empty <MediaTypeFormatter>());
 }
示例#50
0
        public static ModelMediaTypeFormatter <TModel> AddModelMediaTypeFormatter <TFormatter, TModel>(this MediaTypeFormatterCollection formatters, IUnityContainer container, string name, string mediaType, params Action <MediaTypeFormatter, string, string>[] f)
            where TModel : class
            where TFormatter : IFormatter <TModel>
        {
            var formatter = new ModelMediaTypeFormatter <TModel>(container.GetFactory <TFormatter, TModel>(), mediaType);

            foreach (var addMapping in f)
            {
                addMapping(formatter, name, mediaType);
            }

            formatters.Add(formatter);
            return(formatter);
        }
示例#51
0
 public ObjectContent(Type type, object v, MediaTypeFormatterCollection c)
 {
     _t = type;
     _v = v;
     _c = c;
 }
        public async void ScanForExperiments()
        {
            if (!BluetoothImpl.Instance.IsConnected ||
                BluetoothImpl.Instance.ActiveModel == Models.NULL ||
                DeviceMessageCache.Instance.ExtendedStatusUpdate == null)
            {
                return;
            }

            Log.Debug("ExperimentClient: Scanning for experiments...");

            if (SettingsProvider.Instance.Experiments.Disabled)
            {
                Log.Information("ExperimentClient: Feature is disabled. You can enable it here: 'Options > Crowdsourcing'");
                return;
            }

            ExperimentRequest[]? requests = null;
            try
            {
                HttpResponseMessage response =
                    await _client.GetAsync($"{API_GET_EXPERIMENTS}/{BluetoothImpl.Instance.ActiveModel.ToString()}");

                if (response.IsSuccessStatusCode)
                {
                    MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection();
                    formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

                    requests = await response.Content.ReadAsAsync <ExperimentRequest[]>(formatters);
                }
                else
                {
                    Log.Error($"ExperimentClient: HTTP error {response.StatusCode}");
                }

                if (requests == null)
                {
                    Log.Warning("ExperimentClient: Scan failed; no data received");
                    return;
                }

                var results = requests
                              .VerifyDecode()
                              .Where(ExperimentRequestFilters.FilterByEnvironment)
                              .Where(ExperimentRequestFilters.FilterByVersion)
                              .Where(ExperimentRequestFilters.IsNotDone)
                              .ToList()
                              .AsReadOnly();

                Log.Debug($"ExperimentClient: {results.Count} experiment(s) found.");
                NewResultsFound?.Invoke(this, results);
            }
            catch (HttpRequestException ex)
            {
                Log.Error("ExperimentClient: Scan failed due to network issues: " + ex.Message);
            }
            catch (Exception ex)
            {
                Log.Error("ExperimentClient: Scan failed: " + ex.Message);
            }
        }
 static HttpContentExtensions()
 {
     MediaTypeFormatters = new MediaTypeFormatterCollection();
     MediaTypeFormatters.JsonFormatter.SerializerSettings.ContractResolver = new ODataContractResolver();
 }
 public MediaTypeFormatterBootstrapper(
     MediaTypeFormatterCollection formatters)
 {
     _formatters = formatters;
 }
示例#55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnprocessableEntityNegotiatedContentResult"/> class.
 /// </summary>
 /// <param name="controller">
 /// The formatterCollection.
 /// </param>
 public UnprocessableEntityNegotiatedContentResult(ApiController controller)
     : base(null, controller)
 {
     this.modelState          = controller.ModelState;
     this.formatterCollection = controller.Configuration.Formatters;
 }
 public static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
 {
 }
 /// <summary>
 /// Initializes an instance.
 /// </summary>
 /// <param name="identifier"></param>
 /// <param name="formatters"></param>
 public FluentHttpMiddlewareClientContext(string identifier, MediaTypeFormatterCollection formatters)
 {
     Formatters = formatters;
     Identifier = identifier;
 }
        public static void ConfigureFormatters(MediaTypeFormatterCollection formatters)
        {
            JsonSerializerSettings settings = formatters.JsonFormatter.SerializerSettings;

            settings.Formatting = Formatting.None;
        }
示例#59
0
        private static void RemoveMediaTypes()
        {
            MediaTypeFormatterCollection formatters = GlobalConfiguration.Configuration.Formatters;

            formatters.Remove(formatters.XmlFormatter);
        }
        public static async Task <TResult> ToObjectAsync <TResult>(this HttpResponseMessage message, MediaTypeFormatterCollection mediaTypeFormatters)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (mediaTypeFormatters == null)
            {
                throw new ArgumentNullException(nameof(mediaTypeFormatters));
            }

            var content        = message.Content;
            var contentHeaders = content.Headers;

            var reader = mediaTypeFormatters.FindReader(typeof(TResult), contentHeaders.ContentType);

            using (var stream = await content.ReadAsStreamAsync()) {
                var obj = await reader.ReadFromStreamAsync(typeof(TResult), stream, content, null);

                if (obj is TResult objectResult)
                {
                    return(objectResult);
                }

                throw new NotSupportedException($"Got '{obj}' expected '{typeof(TResult)}'");
            }
        }