public async Task<ColorScheme> GetByHex(string hex, ColorSchemeMode? mode = null) {
            if (!hexColorRegex.IsMatch(hex)) {
                throw new ArgumentException("hex is not valid", "hex");
            }

            if (hex.StartsWith("#")) {
                hex = hex.Substring(1);
            }

            var uriBuilder = new Common.UriBuilder(ColorConfiguration.Current.BaseUrl);
            uriBuilder.AppendPathPart("scheme");
            uriBuilder.AppendQueryPart("hex", hex.ToUpper());

            if (mode.HasValue) {
                uriBuilder.AppendQueryPart("mode", mode.ToString().ToLower());
            }

            using (var client = new HttpClient()) {
                var responseMessage = await client.GetAsync(uriBuilder.StringUri);
                if (!responseMessage.IsSuccessStatusCode) {
                    throw new HttpRequestException(responseMessage.ReasonPhrase);
                }

                var body = await responseMessage.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<ColorScheme>(body);
            }
        }
        public async Task<ColorIdentifier> GetByCmyk(int c, int m, int y, int k) {
            if (c < 0 | m < 0 | y < 0 | k < 0) {
                throw new ArgumentException("cmyk cannot be less than zero");
            }

            var uriBuilder = new Common.UriBuilder(ColorConfiguration.Current.BaseUrl);
            uriBuilder.AppendPathPart("id");
            uriBuilder.AppendQueryPart("cmyk", string.Format("cmyk({0},{1},{2},{3})", c, m, y, k));

            using (var client = new HttpClient()) {
                var responseMessage = await client.GetAsync(uriBuilder.StringUri);
                if (!responseMessage.IsSuccessStatusCode) {
                    throw new HttpRequestException(responseMessage.ReasonPhrase);
                }

                var body = await responseMessage.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<ColorIdentifier>(body);
            }
        }
        public async Task<IEnumerable<Listing>> GetInterestingListings() {
            var uriBuilder = new Common.UriBuilder(EtsyConfiguration.Current.BaseUrl);
            uriBuilder.AppendPathPart("listings/interesting");

            using (var client = new HttpClient()) {
                uriBuilder.AppendQueryPart("api_key", EtsyConfiguration.Current.KeyString);
                uriBuilder.AppendQueryPart("limit", this.Request.Headers.GetTop(25));

                var responseMessage = await client.GetAsync(uriBuilder.StringUri);

                if (!responseMessage.IsSuccessStatusCode) {
                    throw new HttpRequestException(responseMessage.ReasonPhrase);
                }

                var body = await responseMessage.Content.ReadAsStringAsync();
                var listings = JsonConvert.DeserializeObject<EtsyResponse<Listing>>(body);

                return listings.Results;
            }
        }
        public async Task<ColorScheme> GetByRgb(int r, int g, int b, ColorSchemeMode? mode = null) {
            if (r < 0 | g < 0 | b < 0) {
                throw new ArgumentException("rgb cannot be less than zero");
            }

            var uriBuilder = new Common.UriBuilder(ColorConfiguration.Current.BaseUrl);
            uriBuilder.AppendPathPart("scheme");
            uriBuilder.AppendQueryPart("rgb", string.Format("rgb({0},{1},{2})", r, g, b));

            if (mode.HasValue) {
                uriBuilder.AppendQueryPart("mode", mode.ToString().ToLower());
            }

            using (var client = new HttpClient()) {
                var responseMessage = await client.GetAsync(uriBuilder.StringUri);
                if (!responseMessage.IsSuccessStatusCode) {
                    throw new HttpRequestException(responseMessage.ReasonPhrase);
                }

                var body = await responseMessage.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<ColorScheme>(body);
            }
        }
Beispiel #5
0
        private static bool Command_DirectInvoke(string input)
        {
            // okay, we're calling a command
            input = input.Substring(input.IndexOf(' ') + 1);

            var serviceName = input.GetPart(0, ' ');
            input = input.Substring(input.IndexOf(' ') + 1);

            DispatcherServiceWrapper wrapper = new DispatcherServiceWrapper(baseDispatcherUrl);
            var metadata = DispatcherService.GetAllMetadata();

            var service = metadata.FirstOrDefault(x => x.Name.Equals(serviceName, StringComparison.OrdinalIgnoreCase) || x.Name.EndsWith("." + serviceName, StringComparison.OrdinalIgnoreCase));
            if (service == null) {
                Console.WriteLine("No service with name '{0}' found", serviceName);
                return false;
            }

            var additionalHeaders = new NameValueCollection();

            // okay now lookup the route
            var routePath = input.GetPart(0, ' ').ToLower();
            input = input.Substring(routePath.Length).Trim();
            var route = service.Routes.FirstOrDefault(x => x.PathFormat.Equals(routePath, StringComparison.OrdinalIgnoreCase) || x.MethodName.Equals(routePath, StringComparison.OrdinalIgnoreCase));
            if (route == null) {
                Console.WriteLine("No route with path '{0}' was found in service '{1}'", routePath, service.Name);
                return false;
            }

            routePath = route.PathFormat;

            var uriBuilder = new Common.UriBuilder(service.BaseUrl);

            // okay thats the route now get parameters
            if (!string.IsNullOrWhiteSpace(input)) {
                foreach (var stringPair in input.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)) {
                    var key = input.Substring(1).GetPart(0, ' ').ToLower();
                    var value = input.Substring(key.Length + 1).Trim();

                    // do route replacement, if it's not in the route it's a query string param
                    var keyReplacementRegex = new Regex(string.Concat('{', key, ".*}"), RegexOptions.IgnoreCase);
                    if (keyReplacementRegex.IsMatch(routePath)) {
                        routePath = keyReplacementRegex.Replace(routePath, value);
                    }
                    else {
                        // it's not in the path
                        // now check if it's a header parameter or not
                        QueryOption headerEnumValue = QueryOption.None;
                        if (Enum.TryParse<QueryOption>(key, true, out headerEnumValue)) {
                            // okay it parses but does it have the flag?
                            if (route.AcceptedQueryOptions.HasFlag(headerEnumValue)) {
                                // now assign it and move onto the next pair
                                additionalHeaders.Add(QueryOptionNameBuilder.CreateHeaderName(headerEnumValue), value);
                                continue;
                            }
                        }

                        // okay it's not for the header, it's just a plain old query string parameter
                        uriBuilder.AppendQueryPart(key, value);
                    }
                }
            }

            uriBuilder.AppendPathPart(routePath);

            Console.WriteLine("Calling endpoint with:");
            using (var client = new HttpClient()) {
                Console.WriteLine("\tUri: {0}://{1}:{2}/{3}", uriBuilder.Scheme, uriBuilder.Host, uriBuilder.Port.GetValueOrDefault(80), string.Join("/", uriBuilder.PathParts));

                // now add the header values, if any
                foreach (string nameKey in additionalHeaders) {
                    Console.WriteLine("\t{0}: {1}", nameKey, additionalHeaders[nameKey]);

                    client.DefaultRequestHeaders.Add(nameKey, additionalHeaders[nameKey]);
                }
                Console.WriteLine();

                // TODO: check the type, probably a get
                var result = client.GetAsync(uriBuilder.StringUri).Result;

                if (!result.IsSuccessStatusCode) {
                    Console.WriteLine("Failed call. Message: " + result.ReasonPhrase);
                    return false;
                }

                var body = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Call success; message follows:");

                var originalBodyLength = body.Length;
                body = body.Truncate(2048, string.Empty);

                Console.WriteLine(body);

                if (body.Length != originalBodyLength) {
                    Console.WriteLine();
                    Console.WriteLine("Body was truncated to {0} because the original length was too long ({1} bytes)", body.Length, originalBodyLength);
                }
            }

            return false;
        }