Ejemplo n.º 1
0
        public static Operation GetOperation(string href, string operationName)
        {
            RequestMethodType restRequest = GetRestRequestMethodType(href);
            RequestMethodType kvpRequest  = GetKvpRequestMethodType($"{href}?");

            RequestMethodType[] requestMethodTypes = new RequestMethodType[]
            {
                restRequest, kvpRequest
            };
            ItemsChoiceType1[] itemsChoiceType1s = new ItemsChoiceType1[]
            {
                ItemsChoiceType1.Get, ItemsChoiceType1.Get
            };
            HTTP http = new HTTP()
            {
                Items            = requestMethodTypes,
                ItemsElementName = itemsChoiceType1s
            };
            DCP DCP = new DCP()
            {
                Item = http
            };

            DCP[] DCPs = new DCP[]
            {
                DCP
            };
            Operation operation = new Operation()
            {
                name = operationName,
                DCP  = DCPs
            };

            return(operation);
        }
        private string GetPostURL(DCP[] dcps)
        {
            DCP dcp = dcps[0];
            RequestMethodType postReq = null;
            int index = 0;

            foreach (ItemsChoiceType ict in dcp.Item.ItemsElementName)
            {
                if (ict == ItemsChoiceType.Post)
                {
                    postReq = dcp.Item.Items[index];
                }
                index++;
            }

            if (postReq != null)
            {
                string href = postReq.href;
                if (postReq.href.EndsWith("/"))
                {
                    href = postReq.href.Remove(postReq.href.LastIndexOf("/"));
                }
                return(href);
            }
            return("");
        }
Ejemplo n.º 3
0
        private static RequestMethodType GetRequestMethodType(string href, string value)
        {
            object[] allowedValues = new Ows1_1.ValueType[]
            {
                new Ows1_1.ValueType()
                {
                    Value = value
                }
            };
            DomainType constraint = new DomainType()
            {
                name          = "GetEncoding",
                AllowedValues = allowedValues
            };

            DomainType[] constraints = new DomainType[]
            {
                constraint
            };
            RequestMethodType restRequest = new RequestMethodType()
            {
                href       = href,
                Constraint = constraints
            };

            return(restRequest);
        }
Ejemplo n.º 4
0
        private static string GetPostUrl(IReadOnlyList <DCP> dcps)
        {
            var dcp = dcps[0];
            RequestMethodType postReq = null;
            var index = 0;

            foreach (var ict in dcp.Item.ItemsElementName)
            {
                if (ict == ItemsChoiceType1.Post)
                {
                    postReq = dcp.Item.Items[index];
                }
                index++;
            }

            if (postReq == null)
            {
                return("");
            }

            var href = postReq.href;

            if (postReq.href.EndsWith("/"))
            {
                href = postReq.href.Remove(postReq.href.LastIndexOf("/", StringComparison.Ordinal));
            }

            return(href);
        }
Ejemplo n.º 5
0
 public bool ParseMethod()
 {
     try
     {
         this.RequestMethod = (RequestMethodType)System.Enum.Parse(typeof(RequestMethodType), this.Context.Request.HttpMethod.ToUpper(), true);
         return(true);
     }
     catch (ArgumentException)
     {
         return(false);
     }
 }
Ejemplo n.º 6
0
        private static Operation CreateOperation(string operationName, string parameterName, params string[] parameterValues)
        {
            Operation node = new Operation();

            node.name = operationName;
            List <DCP> dcpList = new List <DCP>();
            DCP        dcp     = new DCP();

            dcp.Item = new HTTP();

            //GET
            ItemsChoiceType ictGet = new ItemsChoiceType();

            ictGet = ItemsChoiceType.Get;
            List <ItemsChoiceType> listIct = new List <ItemsChoiceType>();

            listIct.Add(ictGet);
            List <RequestMethodType> reqMethods = new List <RequestMethodType>();
            RequestMethodType        reqMethod  = new RequestMethodType();

            reqMethod.href = ServiceData.ServiceUrlWithQuestionMark();
            reqMethods.Add(reqMethod);


            //POST
            ItemsChoiceType ictPost = new ItemsChoiceType();

            ictPost = new ItemsChoiceType();
            ictPost = ItemsChoiceType.Post;
            listIct.Add(ictPost);
            reqMethod      = new RequestMethodType();
            reqMethod.href = ServiceData.ServiceUrl(true);
            reqMethods.Add(reqMethod);
            dcp.Item.Items            = reqMethods.ToArray();
            dcp.Item.ItemsElementName = listIct.ToArray();
            dcpList.Add(dcp);
            node.DCP = dcpList.ToArray();
            if (parameterName != String.Empty)
            {
                List <DomainType> lstDomains = new List <DomainType>();
                lstDomains.Add(CreateParameter(parameterName, parameterValues));
                node.Parameter = lstDomains.ToArray();
            }
            return(node);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="path">The path.</param>
        /// <param name="version">The version.</param>
        public Request(RequestMethodType method, string path, string version)
        {
            Body = new MemoryStream();
            Method = method;
            HttpVersion = version;
            Encoding = Encoding.UTF8;

            HeaderFactory headerFactory = HttpFactory.Current == null
                                              ? new HeaderFactory()
                                              : HttpFactory.Current.Create<HeaderFactory>();

            _headers = new HeaderCollection(headerFactory);
            if (!string.IsNullOrEmpty(path))
            {
                int pos = path.IndexOf("?", StringComparison.Ordinal);
                QueryString = pos != -1 ? UrlParser.Parse(path.Substring(pos + 1)) : new ParameterCollection();
            }

            Parameters = QueryString ?? new ParameterCollection();
            Uri = new Uri("http://not.specified.yet" + path);
        }
Ejemplo n.º 8
0
        public static RequestMethodType GetKvpRequestMethodType(string href)
        {
            RequestMethodType restRequest = GetRequestMethodType(href, "KVP");

            return(restRequest);
        }
Ejemplo n.º 9
0
        public static RequestMethodType GetKvpRequestMethodType(string href)
        {
            RequestMethodType restRequest = GetRequestMethodType(href, WmtsRequestType.KVP);

            return(restRequest);
        }
Ejemplo n.º 10
0
        private async Task <HttpResponseMessage> ExexuteSendAsync(string url, RequestMethodType type = RequestMethodType.GET, object keys = null)
        {
            var httpClient = await CreateHttpClient();

            switch (type)
            {
            case RequestMethodType.GET: return(await httpClient.GetAsync(url));

            case RequestMethodType.POST: {
                if (keys.GetType() == typeof(List <KeyValuePair <string, string> >))
                {
                    var response = await httpClient.PostAsync(url, new FormUrlEncodedContent((List <KeyValuePair <string, string> >)keys));

                    return(response);
                }
                else
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    string body = "";
                    if (keys.GetType() == typeof(string))
                    {
                        body = (string)keys;
                    }
                    else
                    {
                        var settings = new JsonSerializerSettings {
                            ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                            NullValueHandling = NullValueHandling.Ignore
                        };

                        body = JsonConvert.SerializeObject(keys, Formatting.Indented, settings);
                    }
                    var response = await httpClient.PostAsync(url, new StringContent(body, Encoding.UTF8, "application/json"));

                    return(response);
                }
            }

            case RequestMethodType.PATCH: {
                string body = "";
                if (keys.GetType() == typeof(string))
                {
                    body = (string)keys;
                }
                else
                {
                    var settings = new JsonSerializerSettings {
                        ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                        NullValueHandling = NullValueHandling.Ignore
                    };

                    body = JsonConvert.SerializeObject(keys, Formatting.Indented, settings);
                }
                var method  = new HttpMethod("PATCH");
                var request = new HttpRequestMessage(method, url)
                {
                    Content = new StringContent(body, Encoding.UTF8, "application/json")
                };
                return(await httpClient.SendAsync(request));
            }

            default: {
                System.Diagnostics.Debug.WriteLine($"EXCEPTION: {GetType().Name}.PostAsync({url}): ");
                break;
            }
            }
            return(null);
        }
Ejemplo n.º 11
0
        protected async Task <ApiResponse <T> > SendAsync <T>(string url, RequestMethodType type = RequestMethodType.GET, object keys = null) where T : BaseDBO, new()
        {
            ApiResponse <T> result;

            System.Diagnostics.Debug.WriteLine($"BASESERVICE: {GetType().Name}.SendAsync<{typeof(T).Name}>({url}, methodType = {type.ToString()})");
            using (var realaser = await m_lock.LockAsync()) {
                try {
                    var response = await ExexuteSendAsync(url, type, keys);

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (await RefreshToken())
                        {
                            response = await ExexuteSendAsync(url, type, keys);
                        }
                    }
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (await ReLogin())
                        {
                            response = await ExexuteSendAsync(url, type, keys);
                        }
                    }
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        var newFragment = new MessageAlert("Паролі не співпадають");

                        //Add fragment
                        //newFragment.Show(FragmentManager.BeginTransaction(), "dialog");
                    }

                    var responseString = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        if (!string.IsNullOrEmpty(responseString))
                        {
                            try {
                                var settings = new JsonSerializerSettings {
                                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                                    NullValueHandling = NullValueHandling.Ignore
                                };
                                var token = JToken.Parse(responseString);
                                var error = token["error"]["message"].ToString();

                                return(new ApiResponse <T> {
                                    Succeed = false,
                                    Errors = error,
                                    StatusCode = response.StatusCode
                                });
                            } catch { }
                        }
                        return(new ApiResponse <T> {
                            Succeed = false,
                            Errors = "Unknow http error",
                            StatusCode = response.StatusCode
                        });
                    }

                    result = new ApiResponse <T>()
                    {
                        Succeed        = true,
                        ResponseObject = ConvertToBaseObject <T>(responseString)
                    };
                } catch (JsonReaderException ex) {
                    System.Diagnostics.Debug.WriteLine($"{this.GetType().Name}: GatAsync<{typeof(T).Name}>: Exception: {ex.Message}");
                    return(new ApiResponse <T>()
                    {
                        Succeed = false,
                        Errors = "Cannot parse result"
                    });
                } catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine($"EXCEPTION: {GetType().Name}.PostAsync({url}): {ex.Message}");
                    return(new ApiResponse <T>()
                    {
                        Succeed = false,
                        Errors = "Unknow http error"
                    });
                }
            }
            return(result);
        }
Ejemplo n.º 12
0
        protected async Task <ApiResponse> SendAsync(string url, RequestMethodType type = RequestMethodType.GET, object keys = null)
        {
            using (var realaser = await m_lock.LockAsync()) {
                try {
                    var response = await ExexuteSendAsync(url, type, keys);

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (await RefreshToken())
                        {
                            response = await ExexuteSendAsync(url, type, keys);
                        }
                    }
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (await ReLogin())
                        {
                            response = await ExexuteSendAsync(url, type, keys);
                        }
                    }
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        var newFragment = new MessageAlert("Паролі не співпадають");
                        // TODO: make somethins
                        //Add fragment
                        //newFragment.Show(FragmentManager.BeginTransaction(), "dialog");
                    }

                    var responseString = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        if (!string.IsNullOrEmpty(responseString))
                        {
                            try {
                                var settings = new JsonSerializerSettings {
                                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                                    NullValueHandling = NullValueHandling.Ignore
                                };
                                var token = JToken.Parse(responseString);
                                var error = token["error"]["message"].ToString();
                                //var error = JsonConvert.DeserializeObject<ErrorResponse>(responseString, settings);
                                return(new ApiResponse {
                                    Succeed = false,
                                    Errors = error,
                                    StatusCode = response.StatusCode
                                                 //ErrorType = error.Error,
                                });
                            } catch { }
                        }
                        return(new ApiResponse {
                            Succeed = false,
                            Errors = "Unknow http error",
                            StatusCode = response.StatusCode
                        });
                    }
                } catch (Exception ex) {
                    var t = await CheckUrl(AuthUrl);

                    System.Diagnostics.Debug.WriteLine($"{this.GetType().Name}: PostAsync({url}): Exception: {ex.Message}");
                    return(new ApiResponse()
                    {
                        Succeed = false,
                        Errors = t ? "Unknow http error" : "Please check internet connection",
                    });
                }
            }
            return(new ApiResponse()
            {
                Succeed = true,
            });
        }
Ejemplo n.º 13
0
        public static RequestMethodType GetRestRequestMethodType(string href)
        {
            RequestMethodType restRequest = GetGetRequestMethodType(href, "REST");

            return(restRequest);
        }