예제 #1
0
        public static HttpResponseMessage SetBearerTokenAndDuration()
        {
            if (TokenCacher.GetToken("testadmin") != null)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            using (var client = new HttpClient())
            {
                var login = new Dictionary <string, string>
                {
                    { "grant_type", "password" },
                    { "username", "testadmin" },
                    { "password", "gnpla55!" },
                };

                //Act
                var response = client.PostAsync(new Uri(ConfigurationManager.AppSettings["IntegrationTestBaseUrl"] + "token"), new FormUrlEncodedContent(login)).Result;
                if (response.ReasonPhrase != HttpStatusCode.OK.ToString() || !response.IsSuccessStatusCode)
                {
                    return(response);
                }

                //Guid corrId;
                var corrId = response.Headers.GetValues("http-correlation-id").FirstOrDefault();
                if (string.IsNullOrEmpty(corrId))
                {
                    var failedResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        ReasonPhrase = "Missing CorrelationId",
                        StatusCode   = HttpStatusCode.InternalServerError
                    };
                    return(failedResponse);
                }
                var correlationId = Guid.Parse(corrId);
                var tokenDetails  = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Content.ReadAsStringAsync().Result);
                if (tokenDetails != null && tokenDetails.Any())
                {
                    //var tokenNo = tokenDetails.FirstOrDefault().Value;
                    tokenDetails.TryGetValue("access_token", out _bearerToken);
                    tokenDetails.TryGetValue("expires_in", out _tokenExpiration);
                    tokenDetails.Add("ermsSecurityToken", correlationId.ToString());
                }

                var expirationDate = DateTimeOffset.UtcNow.AddSeconds(Convert.ToDouble(_tokenExpiration));

                TokenCacher.Delete("testadmin");
                TokenCacher.Add("testadmin", _bearerToken, expirationDate);
                TokenCacher.Add("CorrelationId", correlationId, expirationDate);


                return(response);
            }
        }
예제 #2
0
        public static async Task <CommandResult> GetEntity(string query, string uri)
        {
            var cmdResult   = new CommandResult();
            var bearerToken = TokenCacher.GetToken("testadmin");

            if (bearerToken == null)
            {
                Assert.Fail("Token is not cached");
            }
            string authToken = $"bearer {bearerToken}";

            using (HttpClient client = new HttpClient())
            {
                UriBuilder builder = new UriBuilder(uri)
                {
                    Query = query
                };
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authToken);

                using (var response = await client.GetAsync(builder.Uri))
                {
                    if (response.ReasonPhrase == HttpStatusCode.OK.ToString() && response.IsSuccessStatusCode)
                    {
                        var asyncReadresult = await response.Content.ReadAsStringAsync();

                        try
                        {
                            JObject jEntity = JObject.Parse(asyncReadresult);

                            cmdResult.OperationException = jEntity.SelectToken("OperationException");
                            cmdResult.Entity             = jEntity;
                            cmdResult.Success            = Convert.ToBoolean(jEntity.SelectToken("Success"));
                            return(cmdResult);
                        }
                        catch (Exception ex)
                        {
                            cmdResult.OperationException = ex;
                            cmdResult.Success            = false;
                            cmdResult.Entity             = asyncReadresult;
                            return(cmdResult);
                        }
                    }
                    else
                    {
                        cmdResult.Entity  = response.ReasonPhrase;
                        cmdResult.Success = false;
                        return(cmdResult);
                    }
                }
            }
        }
예제 #3
0
        public static async Task <CommandResult> PostHttpRequestKeyValuePairsAsync(string uri, Dictionary <string, string> keyValuePairs = null)
        {
            var cmdResult   = new CommandResult();
            var bearerToken = TokenCacher.GetToken("testadmin");

            if (bearerToken == null)
            {
                Assert.Fail("Token is not cached");
            }

            var authToken = $"bearer {bearerToken}";

            using (var client = new HttpClient())
            {
                var requestMessage = new HttpRequestMessage(new HttpMethod("POST"), ConfigurationManager.AppSettings["IntegrationTestBaseUrl"] + uri);
                requestMessage.Headers.Accept.Clear();
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                requestMessage.Headers.TryAddWithoutValidation("Authorization", authToken);

                if (keyValuePairs != null)
                {
                    requestMessage.Content = new FormUrlEncodedContent(keyValuePairs);
                }


                using (HttpResponseMessage apiResponse = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead))
                {
                    //var apiResponseResult = apiResponse.Content.ReadAsAsync<CommandResult>();
                    //return apiResponseResult.Result;
                    var apiResponseResult = apiResponse.Content.ReadAsStringAsync().Result;
                    try
                    {
                        var jEntity = JObject.Parse(apiResponseResult);
                        cmdResult.OperationException = jEntity.SelectToken("OperationException");
                        cmdResult.Entity             = jEntity;
                        cmdResult.Success            = Convert.ToBoolean(jEntity.SelectToken("Success"));
                        return(cmdResult);
                    }
                    catch (Exception ex)
                    {
                        cmdResult.OperationException = ex;
                        cmdResult.Success            = false;
                        return(cmdResult);
                    }
                }
            }
        }
예제 #4
0
        public static async Task <CommandResult> PostDataCommandHttpRequestAsync(string uriSuffix, List <DataCommand> dataCommands)
        {
            var cmdResult   = new CommandResult();
            var bearerToken = TokenCacher.GetToken("testadmin");

            if (bearerToken == null)
            {
                Assert.Fail("Token is not cached");
            }

            var authToken = $"bearer {bearerToken}";

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["IntegrationTestBaseUrl"]);

                //HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod("POST"), ConfigurationManager.AppSettings["IntegrationTestBaseUrl"] + uriSuffix);
                //    requestMessage.Headers.Accept.Clear();
                //    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                //    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //    requestMessage.Headers.TryAddWithoutValidation("Authorization", authToken);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authToken);
                //var response = client.SendAsync(requestMessage<DataCommand> dataCommand).ContinueWith(postTask => postTask.Result.EnsureSuccessStatusCode());
                var apiResponse = await client.PostAsJsonAsync(uriSuffix, dataCommands).ContinueWith(postTask => postTask.Result.EnsureSuccessStatusCode());

                string apiResponseResult = apiResponse.Content.ReadAsStringAsync().Result;
                try
                {
                    JObject jEntity = JObject.Parse(apiResponseResult);
                    cmdResult.OperationException = jEntity.SelectToken("OperationException");
                    cmdResult.Entity             = jEntity;
                    cmdResult.Success            = Convert.ToBoolean(jEntity.SelectToken("Success"));
                    return(cmdResult);
                }
                catch (Exception ex)
                {
                    cmdResult.OperationException = ex;
                    cmdResult.Success            = false;
                    return(cmdResult);
                }
            }
        }