private static INetworkService Instance(Priority priority)
        {
            Func<HttpMessageHandler, INetworkService> createClient = messageHandler =>
            {
                // service registration
                var networkServiceSettings = new RefitSettings
                {
                    JsonSerializerSettings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        Error = (sender, args) => Debug.WriteLine(args)
                    }
                };

                var client = new HttpClient(messageHandler)
                {
                    BaseAddress = new Uri("http://vmkrcmar21.informatik.tu-muenchen.de/wordpress/")
                };

                return RestService.For<INetworkService>(client, networkServiceSettings);
            };

            return
                new SafeNetworkService(
                    createClient(new RateLimitedHttpMessageHandler(new NativeMessageHandler(), priority)));
        }
 public PlanGridHttpHandler(string accessToken, RefitSettings settings, string version, int? maxRetries)
 {
     authenticationToken = BuildAuthenticationToken(accessToken);
     this.settings = settings;
     this.version = version;
     this.maxRetries = maxRetries;
 }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="apiKey">The API key provided by PlanGrid.</param>
        /// <param name="baseUrl">The base URL -- you should not have to change this.</param>
        /// <param name="version">The version of the API you want to use.</param>
        /// <param name="timeout">The maximum time that may elapse when making a call before timing out.</param>
        /// <param name="maxRetries">The maximum number of attempts to make contacting the server in the event of a 503 service unavailable repsonse.  This defaults to unlimited retries, with a delay between each attempt that multiplies by two.</param>
        /// <returns>An interface upon which you can invoke the various methods exposed via the Public PlanGrid API.</returns>
        public static IPlanGridApi Create(string apiKey = null, string baseUrl = null, string version = "1", int timeout = 60, int? maxRetries = null)
        {
            apiKey = apiKey ?? Settings.ApiKey ?? Environment.GetEnvironmentVariable("PLANGRIDAPIKEY");
            if (apiKey == null)
            {
                throw new ArgumentException("An ApiKey is required. Either pass it in to this method, add it to your App.config file, or set the environment variable \"PLANGRIDAPIKEY\".", nameof(apiKey));
            }
            baseUrl = baseUrl ?? Settings.ApiBaseUrl ?? Environment.GetEnvironmentVariable("PLANGRIDAPIURL") ?? "https://io.plangrid.com";

            string url = baseUrl;
            var settings = new RefitSettings
            {
                UrlParameterFormatter = new PlanGridUrlParameterFormatter(),
                JsonSerializerSettings = new JsonSerializerSettings
                {
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                    Converters = new List<JsonConverter>(new JsonConverter[]
                    {
                        new StringEnumConverter(),
                        new DateConverter()
                    })
                }
            };
            var api = (AutoGeneratedIPlanGridApi)RestService.For<IPlanGridApi>(
                new HttpClient(new PlanGridHttpHandler(apiKey, settings, version, maxRetries))
                {
                    BaseAddress = new Uri(url), Timeout = TimeSpan.FromSeconds(timeout)
                },
                settings);
            api.Initialize(apiKey, settings, version, maxRetries);
            return api;
        }
 //
 //        public NugetApiManagerImpl ()
 //        {
 //        }
 //        public async void GetStatistics()
 //        {
 //            var nugetApi = RestService.For<INuGetApi>(DefaultNuGetServerUrl);
 //            var content = await nugetApi.GetStatistics ();
 //
 //            var results = JObject.Parse(content);
 //
 //            return new NuGetStatistics
 //            {
 //                TotalPackageDownloads = (string)o["page"]Downloads,
 //                UniquePackages = results.UniquePackages,
 //                TotalPackages = results.TotalPackages
 //            };
 //        }
 public IObservable<IList<NuGetPackage>> GetNuGetPackages(string query)
 {
     var settings = new RefitSettings();
     var nugetApi = RestService.For<INuGetApi>(DefaultNuGetServerUrl, settings);
     return null;
     //			var content = await nugetApi.GetStatistics ();
 }
        public void Initialize(string apiKey, RefitSettings settings, string version, int? maxRetries)
        {
            ApiKey = apiKey;
            Settings = settings;
            Version = version;
            MaxRetries = maxRetries;

            foreach (KeyValuePair<string, Func<HttpClient, object[], object>> methodImpl in methodImpls.ToArray())
            {
                methodImpls[methodImpl.Key] = (client, arguments) => methodImpl.Value(client, FixArguments(arguments));
            }
        }
예제 #6
0
        async void GetChannels()
        {
            try
            {
                var settings = new RefitSettings 
                { 
                    UrlParameterFormatter = new CustomUrlParameterFormatter() 
                };
                var api = RestService.For<IChannels>( ("https://slack.com/api/"), settings);

                var channels = await api.ChannelsList();
                foreach(Channel channel in channels.Channels)
                {
                    Debug.WriteLine(channel.Name);
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine("Exception: " + ex);
            }
        }
        public RequestBuilderImplementation(Type targetInterface, RefitSettings refitSettings = null)
        {
            settings = refitSettings ?? new RefitSettings();
            if (targetInterface == null || !targetInterface.IsInterface())
            {
                throw new ArgumentException("targetInterface must be an Interface");
            }

            targetType           = targetInterface;
            interfaceHttpMethods = targetInterface.GetMethods()
                                   .SelectMany(x => {
                var attrs         = x.GetCustomAttributes(true);
                var hasHttpMethod = attrs.OfType <HttpMethodAttribute>().Any();
                if (!hasHttpMethod)
                {
                    return(Enumerable.Empty <RestMethodInfo>());
                }

                return(EnumerableEx.Return(new RestMethodInfo(targetInterface, x, settings)));
            })
                                   .ToDictionary(k => k.Name, v => v);
        }
예제 #8
0
        public static async Task <ApiException> Create(HttpResponseMessage response, RefitSettings refitSettings = null)
        {
            var exception = new ApiException(response.StatusCode, response.ReasonPhrase, response.Headers, refitSettings);

            if (response.Content == null)
            {
                return(exception);
            }

            try {
                exception.ContentHeaders = response.Content.Headers;
                exception.Content        = await response.Content.ReadAsStringAsync();

                response.Content.Dispose();
            } catch {
                // NB: We're already handling an exception at this point,
                // so we want to make sure we don't throw another one
                // that hides the real error.
            }

            return(exception);
        }
예제 #9
0
        public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null)
        {
            RefitSettings = refitSettings ?? new RefitSettings();
            Type          = targetInterface;
            Name          = methodInfo.Name;
            MethodInfo    = methodInfo;

            var hma = methodInfo.GetCustomAttributes(true)
                      .OfType <HttpMethodAttribute>()
                      .First();

            HttpMethod   = hma.Method;
            RelativePath = hma.Path;

            verifyUrlPathIsSane(RelativePath);
            determineReturnTypeInfo(methodInfo);

            var parameterList = methodInfo.GetParameters().ToList();

            ParameterInfoMap = parameterList
                               .Select((parameter, index) => new { index, parameter })
                               .ToDictionary(x => x.index, x => x.parameter);
            ParameterMap      = buildParameterMap(RelativePath, parameterList);
            BodyParameterInfo = findBodyParameter(parameterList);

            Headers            = parseHeaders(methodInfo);
            HeaderParameterMap = buildHeaderParameterMap(parameterList);

            QueryParameterMap = new Dictionary <int, string>();
            for (int i = 0; i < parameterList.Count; i++)
            {
                if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i))
                {
                    continue;
                }

                QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]);
            }
        }
 public RequestBuilderImplementation(RefitSettings refitSettings = null) : base(typeof(TApi), refitSettings)
 {
 }
예제 #11
0
 public static IRequestBuilder ForType <T>(RefitSettings settings)
 {
     return(ForType(typeof(T), settings));
 }
예제 #12
0
        public static T For <T>(HttpClient client, RefitSettings settings)
        {
            IRequestBuilder <T> requestBuilder = RequestBuilder.ForType <T>(settings);

            return(For <T>(client, requestBuilder));
        }
예제 #13
0
        public static object For(Type refitInterfaceType, HttpClient client, RefitSettings settings)
        {
            var requestBuilder = RequestBuilder.ForType(refitInterfaceType, settings);

            return(For(refitInterfaceType, client, requestBuilder));
        }
예제 #14
0
 public static IRequestBuilder <T> ForType <T>(RefitSettings settings)
 {
     return(PlatformRequestBuilderFactory.Create <T>(settings));
 }
예제 #15
0
 protected ApiException(HttpRequestMessage message, HttpMethod httpMethod, HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings = null) :
     base(CreateMessage(statusCode, reasonPhrase))
 {
     RequestMessage = message;
     HttpMethod     = httpMethod;
     StatusCode     = statusCode;
     ReasonPhrase   = reasonPhrase;
     Headers        = headers;
     RefitSettings  = refitSettings;
 }
예제 #16
0
 internal static T Create <T, TBody>(HttpResponseMessage resp, object?content, RefitSettings settings, ApiException?error = null)
 {
     return((T)Activator.CreateInstance(typeof(ApiResponse <TBody>), resp, content, settings, error) !);
 }
예제 #17
0
 protected ApiException(HttpRequestMessage message, HttpMethod httpMethod, HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings = null) :
     this(CreateMessage(statusCode, reasonPhrase), message, httpMethod, statusCode, reasonPhrase, headers, refitSettings)
 {
 }
예제 #18
0
		public async Task<Dictionary<string, string>> Validate(Settings settings, IMessageManager messageManager = null)
		{
			_logger.Info("Validating settings...");
			var errors = new Dictionary<string, string>();

			// pinballx folder
			if (string.IsNullOrEmpty(settings.PbxFolder)) {
				errors.Add("PbxFolder", "The folder where PinballX is installed must be set.");
			} else if (!Directory.Exists(settings.PbxFolder) || !Directory.Exists(settings.PbxFolder + @"\Config")) {
				errors.Add("PbxFolder", "The folder \"" + settings.PbxFolder + "\" is not a valid PinballX folder.");
			}

			// network params
			if (string.IsNullOrEmpty(settings.ApiKey)) {
				errors.Add("ApiKey", "The API key is mandatory and needed in order to communicate with VPDB.");
			}
			if (string.IsNullOrEmpty(settings.Endpoint)) {
				errors.Add("Endpoint", "The endpoint is mandatory. In doubt, put \"https://vpdb.io\".");
			}

			// xml file name
			var badFilenameChars = new Regex("[\\\\" + Regex.Escape(new string(Path.GetInvalidPathChars())) + "]");
			var filename = settings.XmlFile[Platform.PlatformType.VP];
			if (string.IsNullOrWhiteSpace(filename)) {
				errors.Add("XmlFileVP", "You need to provide a file name for the XML database.");
			} else if (badFilenameChars.IsMatch(filename)) {
				errors.Add("XmlFileVP", "That doesn't look like a valid file name!");
			} else if (filename.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) {
				errors.Add("XmlFileVP", "No need to provide the .xml extension, we'll do that!");
			}

			// test params if set
			if (!string.IsNullOrEmpty(settings.ApiKey) && !string.IsNullOrEmpty(settings.Endpoint)) {
				try {
					var handler = new AuthenticatedHttpClientHandler(settings.ApiKey, settings.AuthUser, settings.AuthPass);
					var client = new HttpClient(handler) {BaseAddress = new Uri(settings.Endpoint)};
					var s = new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings {ContractResolver = new SnakeCasePropertyNamesContractResolver()} };
					var api = RestService.For<IVpdbApi>(client, s);
					var user = await api.GetProfile().SubscribeOn(Scheduler.Default).ToTask();

					_logger.Info("Logged as <{0}>", user.Email);
					OnValidationResult(user);

				} catch (ApiException e) {
					HandleApiError(errors, e);
					OnValidationResult(null);
					messageManager?.LogApiError(e, "Error while logging in");

				} catch (Exception e) {
					errors.Add("ApiKey", e.Message);
					OnValidationResult(null);
					messageManager?.LogError(e, "Error while logging in");
				}
			}
			settings.IsValidated = errors.Count == 0;

			return errors;
		}
        /// <summary>
        /// Adds a Refit client to the DI container
        /// </summary>
        /// <typeparam name="T">Type of the Refit interface</typeparam>
        /// <param name="services">container</param>
        /// <param name="settings">Optional. Settings to configure the instance with</param>
        /// <returns></returns>
        public static IHttpClientBuilder AddRefitClient <T>(this IServiceCollection services, RefitSettings settings = null) where T : class
        {
            services.AddSingleton(provider => RequestBuilder.ForType <T>(settings));

            return(services.AddHttpClient(UniqueName.ForType <T>())
                   .ConfigureHttpMessageHandlerBuilder(builder =>
            {
                // check to see if user provided custom auth token
                HttpMessageHandler innerHandler = null;
                if (settings != null)
                {
                    if (settings.HttpMessageHandlerFactory != null)
                    {
                        innerHandler = settings.HttpMessageHandlerFactory();
                    }

                    if (settings.AuthorizationHeaderValueGetter != null)
                    {
                        innerHandler = new AuthenticatedHttpClientHandler(settings.AuthorizationHeaderValueGetter, innerHandler);
                    }
                    else if (settings.AuthorizationHeaderValueWithParamGetter != null)
                    {
                        innerHandler = new AuthenticatedParameterizedHttpClientHandler(settings.AuthorizationHeaderValueWithParamGetter, innerHandler);
                    }
                }

                if (innerHandler != null)
                {
                    builder.PrimaryHandler = innerHandler;
                }
            })
                   .AddTypedClient((client, serviceProvider) => RestService.For <T>(client, serviceProvider.GetService <IRequestBuilder <T> >())));
        }
예제 #20
0
        public IVpdbClient Initialize()
        {
            // setup rest client
            var handler = new AuthenticatedHttpClientHandler(_settingsManager.Settings.ApiKey, _settingsManager.Settings.AuthUser, _settingsManager.Settings.AuthPass);
            // todo enable gzip in api!!
            // AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate

            var client = new HttpClient(handler) {
                BaseAddress = new Uri(_settingsManager.Settings.Endpoint)
            };
            var settings = new RefitSettings {
                JsonSerializerSettings = new JsonSerializerSettings {
                    ContractResolver = new SnakeCasePropertyNamesContractResolver()
                }
            };
            Api = RestService.For<IVpdbApi>(client, settings);

            // subscribe to pusher if profile allows
            _settingsManager.ApiAuthenticated.Subscribe(user => {
                if (user != null && user.Permissions.Messages?.Contains("receive") == true) {
                    SetupPusher(user);
                }
            }, exception => HandleApiError(exception, "subscribing to ApiAuthenticated for Pusher"));

            return this;
        }
        /// <summary>
        /// Adds a Refit client to the DI container
        /// </summary>
        /// <param name="services">container</param>
        /// <param name="refitInterfaceType">Type of the Refit interface</param>
        /// <param name="settings">Optional. Settings to configure the instance with</param>
        /// <returns></returns>
        public static IHttpClientBuilder AddRefitClient(this IServiceCollection services, Type refitInterfaceType, RefitSettings settings = null)
        {
            return(services.AddHttpClient(UniqueName.ForType(refitInterfaceType))
                   .ConfigureHttpMessageHandlerBuilder(builder =>
            {
                // check to see if user provided custom auth token
                HttpMessageHandler innerHandler = null;
                if (settings != null)
                {
                    if (settings.HttpMessageHandlerFactory != null)
                    {
                        innerHandler = settings.HttpMessageHandlerFactory();
                    }

                    if (settings.AuthorizationHeaderValueGetter != null)
                    {
                        innerHandler = new AuthenticatedHttpClientHandler(settings.AuthorizationHeaderValueGetter, innerHandler);
                    }
                    else if (settings.AuthorizationHeaderValueWithParamGetter != null)
                    {
                        innerHandler = new AuthenticatedParameterizedHttpClientHandler(settings.AuthorizationHeaderValueWithParamGetter, innerHandler);
                    }
                }

                if (innerHandler != null)
                {
                    builder.PrimaryHandler = innerHandler;
                }
            })
                   .AddTypedClient(refitInterfaceType, (client, serviceProvider) => RestService.For(refitInterfaceType, client, settings)));
        }
예제 #22
0
 /// <summary>
 /// Adds a Refit client to the DI container
 /// </summary>
 /// <param name="services">container</param>
 /// <param name="refitInterfaceType">Type of the Refit interface</typeparam>
 /// <param name="settings">Optional. Settings to configure the instance with</param>
 /// <returns></returns>
 public static IHttpClientBuilder AddRefitClient(this IServiceCollection services, Type refitInterfaceType, RefitSettings settings = null)
 {
     return(services.AddHttpClient(UniqueName.ForType(refitInterfaceType))
            .AddTypedClient((client, serviceProvider) => RestService.For(refitInterfaceType, client, settings)));
 }
예제 #23
0
 ApiException(HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings = null) :
     base(createMessage(statusCode, reasonPhrase))
 {
     StatusCode    = statusCode;
     ReasonPhrase  = reasonPhrase;
     Headers       = headers;
     RefitSettings = refitSettings;
 }
예제 #24
0
 public IRequestBuilder <T> Create <T>(RefitSettings settings = null)
 {
     return(new CachedRequestBuilderImplementation <T>(new RequestBuilderImplementation <T>(settings)));
 }
예제 #25
0
        public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null)
        {
            RefitSettings = refitSettings ?? new RefitSettings();
            Type          = targetInterface;
            Name          = methodInfo.Name;
            MethodInfo    = methodInfo;

            var hma = methodInfo.GetCustomAttributes(true)
                      .OfType <HttpMethodAttribute>()
                      .First();

            HttpMethod   = hma.Method;
            RelativePath = hma.Path;

            IsMultipart = methodInfo.GetCustomAttributes(true)
                          .OfType <MultipartAttribute>()
                          .Any();

            MultipartBoundary = IsMultipart ? methodInfo.GetCustomAttribute <MultipartAttribute>(true).BoundaryText : string.Empty;

            VerifyUrlPathIsSane(RelativePath);
            DetermineReturnTypeInfo(methodInfo);

            // Exclude cancellation token parameters from this list
            var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList();

            ParameterInfoMap = parameterList
                               .Select((parameter, index) => new { index, parameter })
                               .ToDictionary(x => x.index, x => x.parameter);
            ParameterMap      = BuildParameterMap(RelativePath, parameterList);
            BodyParameterInfo = FindBodyParameter(parameterList, IsMultipart, hma.Method);

            Headers            = ParseHeaders(methodInfo);
            HeaderParameterMap = BuildHeaderParameterMap(parameterList);

            // get names for multipart attachments
            AttachmentNameMap = new Dictionary <int, Tuple <string, string> >();
            if (IsMultipart)
            {
                for (var i = 0; i < parameterList.Count; i++)
                {
                    if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i))
                    {
                        continue;
                    }

                    var attachmentName = GetAttachmentNameForParameter(parameterList[i]);
                    if (attachmentName == null)
                    {
                        continue;
                    }

                    AttachmentNameMap[i] = Tuple.Create(attachmentName, GetUrlNameForParameter(parameterList[i]).ToLowerInvariant());
                }
            }

            QueryParameterMap = new Dictionary <int, string>();
            for (var i = 0; i < parameterList.Count; i++)
            {
                if (ParameterMap.ContainsKey(i) ||
                    HeaderParameterMap.ContainsKey(i) ||
                    (BodyParameterInfo != null && BodyParameterInfo.Item3 == i))
                {
                    continue;
                }

                if (parameterList[i].GetCustomAttribute <QueryAttribute>() != null)
                {
                    var typeInfo    = parameterList[i].ParameterType.GetTypeInfo();
                    var isValueType = typeInfo.IsValueType && !typeInfo.IsPrimitive && !typeInfo.IsEnum;
                    if (typeInfo.IsArray || parameterList[i].ParameterType.GetInterfaces().Contains(typeof(IEnumerable)) || isValueType)
                    {
                        QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForParameter(parameterList[i]));
                    }
                    else
                    {
                        foreach (var member in parameterList[i].ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                        {
                            QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForMember(member));
                        }
                    }
                    continue;
                }

                QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForParameter(parameterList[i]));
            }

            var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList();

            if (ctParams.Count > 1)
            {
                throw new ArgumentException($"Argument list to method \"{methodInfo.Name}\" can only contain a single CancellationToken");
            }

            CancellationToken = ctParams.FirstOrDefault();

            IsApiResponse = SerializedReturnType.GetTypeInfo().IsGenericType&&
                            SerializedReturnType.GetGenericTypeDefinition() == typeof(ApiResponse <>);
        }
예제 #26
0
 protected ApiException(HttpRequestMessage message, HttpMethod httpMethod, string?content, HttpStatusCode statusCode, string?reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings, Exception?innerException = null) :
     this(CreateMessage(statusCode, reasonPhrase), message, httpMethod, content, statusCode, reasonPhrase, headers, refitSettings, innerException)
 {
 }
예제 #27
0
        public static T For <T>(string hostUrl, RefitSettings settings)
        {
            var client = CreateHttpClient(hostUrl, settings);

            return(For <T>(client, settings));
        }
예제 #28
0
 protected ApiException(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, string?content, HttpStatusCode statusCode, string?reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings, Exception?innerException = null) :
     base(exceptionMessage, innerException)
 {
     RequestMessage = message;
     HttpMethod     = httpMethod;
     StatusCode     = statusCode;
     ReasonPhrase   = reasonPhrase;
     Headers        = headers;
     RefitSettings  = refitSettings;
     Content        = content;
 }
예제 #29
0
        public static object For(Type refitInterfaceType, string hostUrl, RefitSettings settings)
        {
            var client = CreateHttpClient(hostUrl, settings);

            return(For(refitInterfaceType, client, settings));
        }
예제 #30
0
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
        public static Task <ApiException> Create(HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings, Exception?innerException = null)
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
        {
            var exceptionMessage = CreateMessage(response.StatusCode, response.ReasonPhrase);

            return(Create(exceptionMessage, message, httpMethod, response, refitSettings, innerException));
        }
예제 #31
0
 public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings)
 {
     return(platformRequestBuilderFactory.Create(interfaceType, settings));
 }
예제 #32
0
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
        public static async Task <ApiException> Create(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings, Exception?innerException = null)
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
        {
            var exception = new ApiException(exceptionMessage, message, httpMethod, null, response.StatusCode, response.ReasonPhrase, response.Headers, refitSettings, innerException);

            if (response.Content == null)
            {
                return(exception);
            }

            try
            {
                exception.ContentHeaders = response.Content.Headers;
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                exception.Content = content;

                if (response.Content.Headers?.ContentType?.MediaType?.Equals("application/problem+json") ?? false)
                {
                    exception = ValidationApiException.Create(exception);
                }

                response.Content.Dispose();
            }
            catch
            {
                // NB: We're already handling an exception at this point,
                // so we want to make sure we don't throw another one
                // that hides the real error.
            }

            return(exception);
        }
예제 #33
0
 public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null)
 {
     throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!");
 }
        /// <summary>
        /// Adds a Refit client to the DI container
        /// </summary>
        /// <typeparam name="T">Type of the Refit interface</typeparam>
        /// <param name="services">container</param>
        /// <param name="settings">Optional. Settings to configure the instance with</param>
        /// <returns></returns>
        public static IHttpClientBuilder AddRefitClient <T>(this IServiceCollection services, RefitSettings settings = null) where T : class
        {
            services.AddSingleton(provider => RequestBuilder.ForType <T>(settings));

            return(services.AddHttpClient(typeof(T).GetFriendlyName())
                   .AddTypedClient((client, serviceProvider) => RestService.For <T>(client, serviceProvider.GetService <IRequestBuilder <T> >())));
        }
 public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null)
 {
     return(new RequestBuilderImplementation(interfaceType, settings));
 }
예제 #36
0
 ApiException(Uri uri, HttpMethod httpMethod, HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings = null) :
     base(CreateMessage(statusCode, reasonPhrase))
 {
     Uri           = uri;
     HttpMethod    = httpMethod;
     StatusCode    = statusCode;
     ReasonPhrase  = reasonPhrase;
     Headers       = headers;
     RefitSettings = refitSettings;
 }
        public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null)
        {
            RefitSettings = refitSettings ?? new RefitSettings();
            Type          = targetInterface;
            Name          = methodInfo.Name;
            MethodInfo    = methodInfo;

            var hma = methodInfo.GetCustomAttributes(true)
                      .OfType <HttpMethodAttribute>()
                      .First();

            HttpMethod   = hma.Method;
            RelativePath = hma.Path;

            IsMultipart = methodInfo.GetCustomAttributes(true)
                          .OfType <MultipartAttribute>()
                          .Any();

            verifyUrlPathIsSane(RelativePath);
            determineReturnTypeInfo(methodInfo);

            // Exclude cancellation token parameters from this list
            var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList();

            ParameterInfoMap = parameterList
                               .Select((parameter, index) => new { index, parameter })
                               .ToDictionary(x => x.index, x => x.parameter);
            ParameterMap      = buildParameterMap(RelativePath, parameterList);
            BodyParameterInfo = findBodyParameter(parameterList, IsMultipart, hma.Method);

            Headers            = parseHeaders(methodInfo);
            HeaderParameterMap = buildHeaderParameterMap(parameterList);

            // get names for multipart attachments
            AttachmentNameMap = new Dictionary <int, Tuple <string, string> >();
            if (IsMultipart)
            {
                for (int i = 0; i < parameterList.Count; i++)
                {
                    if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i))
                    {
                        continue;
                    }

                    var attachmentName = getAttachmentNameForParameter(parameterList[i]);
                    if (attachmentName == null)
                    {
                        continue;
                    }

                    AttachmentNameMap[i] = Tuple.Create(attachmentName, getUrlNameForParameter(parameterList[i]).ToLowerInvariant());
                }
            }

            QueryParameterMap = new Dictionary <int, string>();
            for (int i = 0; i < parameterList.Count; i++)
            {
                if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i) || AttachmentNameMap.ContainsKey(i))
                {
                    continue;
                }

                QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]);
            }

            var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList();

            if (ctParams.Count > 1)
            {
                throw new ArgumentException("Argument list can only contain a single CancellationToken");
            }

            CancellationToken = ctParams.FirstOrDefault();
        }
예제 #38
0
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
        public static async Task <ApiException> Create(Uri uri, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings = null)
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
        {
            var exception = new ApiException(uri, httpMethod, response.StatusCode, response.ReasonPhrase, response.Headers, refitSettings);

            if (response.Content == null)
            {
                return(exception);
            }

            try {
                exception.ContentHeaders = response.Content.Headers;
                exception.Content        = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                response.Content.Dispose();
            } catch {
                // NB: We're already handling an exception at this point,
                // so we want to make sure we don't throw another one
                // that hides the real error.
            }

            return(exception);
        }