Esempio n. 1
0
        private static async Task GetList()
        {
            var requestUri = $"{baseUri}";
            var response   = await _httpRequestFactory.Get(requestUri).ConfigureAwait(false);

            Console.WriteLine($"Status: {response.StatusCode}");
            //Console.WriteLine(response.ContentAsString());
            var outputModel = response.ContentAsType <List <MovieOutputModel> >();

            outputModel.ForEach(item =>
                                Console.WriteLine("{0} - {1}", item.Id, item.Title));
        }
        public async Task <IActionResult> Get()
        {
            var requestUri = "http://35.240.134.131:4790/api/values";
            var response   = await HttpRequestFactory.Get(requestUri);

            return(Ok(response.ContentAsString()));
        }
        public async Task <IActionResult> GetProjectNumberWithDataD1(string ProjectNumber)
        {
            var    requestUri = $"{_WebApiModel.BaseURL}/{"PrivateDocMenuD"}/{"GetProjectNumberWithDataD1"}/{ProjectNumber}";
            string authHeader = HttpContext.Request?.Headers["Authorization"];

            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                BearerToken = authHeader.Substring("Bearer ".Length).Trim();
            }
            var response = await HttpRequestFactory.Get(requestUri, BearerToken);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                return(Unauthorized(response.ContentAsString()));

            case HttpStatusCode.BadRequest:
                return(BadRequest(response.ContentAsString()));

            case HttpStatusCode.OK:
                return(Ok(response.ContentAsString()));

            default:
                return(StatusCode(500));
            }
        }
        public async Task <OutputResponse> SendMessage(MessageModel message)
        {
            var result = new OutputResponse
            {
                IsErrorOccured = false
            };

            if (message != null)
            {
                var url = string.Format("{0}?username={1}&password={2}&to={3}&smsc={4}&from={5}&text={6}",
                                        _smsConfiguration.BaseUrl, _smsConfiguration.RapidProUserName,
                                        _smsConfiguration.RapidProPassword, message.DestinationRecipients.FirstOrDefault(),
                                        _smsConfiguration.RapidProSmsCode, _smsConfiguration.SmsSender,
                                        message.MessageBody);

                var response = await HttpRequestFactory.Get(url);

                if (response.StatusCode == HttpStatusCode.Accepted)
                {
                    result.Message = "Message Queued for delivery";
                }
                else
                {
                    result.Message        = "Sending of message failed";
                    result.IsErrorOccured = true;
                }
            }
            else
            {
                result.IsErrorOccured = true;
                result.Message        = "Message model cannot be null or empty";
            }
            return(result);
        }
Esempio n. 5
0
        public async Task <IActionResult> Index(int teamMemberId)
        {
            if (teamMemberId == 0)
            {
                if (_teamMemberId == 0)
                {
                    return(RedirectToAction("Index", "ResponseTeamMembers"));
                }
            }
            else
            {
                _teamMemberId = teamMemberId;
                var teamMember = await GetResponseTeamMember(teamMemberId);

                _teamMemberName = $"{teamMember.FirstName} {teamMember.OtherNames} {teamMember.Surname}";
            }
            ViewBag.TeamMemberName = _teamMemberName;

            string url = $"{CoreApiUrl}ResponseTeamMappings/GetByMember?teamMemberId={_teamMemberId}";
            var    ResponseTeamMembers = Enumerable.Empty <TeamMappingResponse>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                ResponseTeamMembers = response.ContentAsType <IEnumerable <TeamMappingResponse> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(ResponseTeamMembers));
        }
Esempio n. 6
0
        public async Task ThenTheMenuIsUpdatedCorrectly()
        {
            lastResponse.StatusCode.ShouldBe(HttpStatusCode.NoContent,
                                             $"Response from {lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} was not as expected");

            var updatedResponse = await HttpRequestFactory.Get(baseUrl, $"{menuPath}{existingMenuId}");

            if (updatedResponse.StatusCode == HttpStatusCode.OK)
            {
                var updateMenuResponse = JsonConvert.DeserializeObject <Menu>(await updatedResponse.Content.ReadAsStringAsync());

                updateMenuResponse.name.ShouldBe(updateMenuRequest.name,
                                                 $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");

                updateMenuResponse.description.ShouldBe(updateMenuRequest.description,
                                                        $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");

                updateMenuResponse.enabled.ShouldBe(updateMenuRequest.enabled,
                                                    $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");
            }
            else
            {
                //throw exception rather than use assertions if the GET request fails as GET is not the subject of the test
                //Assertions should only be used on the subject of the test
                throw new Exception($"Could not retrieve the updated menu using GET /menu/{existingMenuId}");
            }
        }
Esempio n. 7
0
        public OpenResult GetOpenResult()
        {
            var response = HttpRequestFactory.Get("https://kaijiang.500.com/static/info/kaijiang/xml/index.xml");

            Byte[]      b             = response.Result.Content.ReadAsByteArrayAsync().Result;
            var         streamReceive = new GZipStream(response.Result.Content.ReadAsStreamAsync().Result, CompressionMode.Decompress);
            XmlDocument dom           = new XmlDocument();

            dom.Load(streamReceive);//这个地方需要注意
            XmlNodeList xmlNodeList = dom.SelectNodes("//lottery");
            XmlNode     xmlNode     = null;

            foreach (XmlNode el in xmlNodeList)
            {
                if (el.InnerXml.Contains("qxc") && el.InnerXml.Contains("7星彩"))
                {
                    xmlNode = el;
                }
            }
            lottery l = null;

            if (xmlNode != null)
            {
                l = XMLSerilizable.XMLToObject <lottery>(xmlNode.OuterXml, Encoding.UTF8);
            }
            return(l);
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestUri">The request URI.</param>
        /// <returns></returns>
        public async Task <T> GetAsync <T>(string requestUri)
        {
            T result = default(T);

            try
            {
                HttpResponseMessage response = await HttpRequestFactory.Get(requestUri, this.auth_token, this.dbName);

                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <T>());
                }
                else
                {
                    var error = response.Content.ReadAsStringAsync().Result;
                    ViewBag.Message     = error;
                    TempData["Message"] = error;
                    Utilities.LogAppInformation(this.logger, error);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("CommonController", ex.Message);
                ViewBag.Message     = ex.Message;
                TempData["Message"] = ex.Message;
                Utilities.LogAppError(this.logger, ex);
                return(result);
            }
        }
Esempio n. 9
0
        public async Task <string> GetCuix(string du, string sexo)
        {
            var service = new HttpRequestFactory();
            var isError = false;
            var url     = $"{_configuration["GetCuix:Url"]}?du={du}&cuixType={sexo}";

            try
            {
                var response = await service.Get(url);

                return(response.ContentAsType <string>());
            }
            catch (Exception e)
            {
                isError = true;
                throw new Exception("Error getting cuix.", e);
            }
            finally
            {
                this.Communicator_TraceHandler(this,
                                               new TraceEventArgs
                {
                    Description = "Get cuix.",
                    ElapsedTime = service.ElapsedTime,
                    ForceDebug  = false,
                    IsError     = isError,
                    Request     = service.Request,
                    Response    = service.Response,
                    URL         = url
                });
            }
        }
Esempio n. 10
0
        public async Task <ClientData> GetClientAfip(string cuix)
        {
            var service = new HttpRequestFactory();
            var isError = false;
            var url     = $"{_configuration["GetClientAfip:Url"]}/{cuix}";

            try
            {
                var response = await service.Get(url);

                return(response.ContentAsType <ClientData>());
            }
            catch (Exception e)
            {
                isError = true;
                throw new Exception("Error getting client from afip.", e);
            }
            finally
            {
                this.Communicator_TraceHandler(this,
                                               new TraceEventArgs
                {
                    Description = "Get client afip.",
                    ElapsedTime = service.ElapsedTime,
                    ForceDebug  = false,
                    IsError     = isError,
                    Request     = service.Request,
                    Response    = service.Response,
                    URL         = url
                });
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Consulta tabla de Atreference por GET. Acepta solamente 1 filtro. Formato de los Filtros: Key=Columna, Value=Nombre de columna, Key=Valor, Value= Valor a filtar
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tableName"></param>
        /// <param name="filters"></param>
        /// <returns></returns>
        public async Task <T> GetTableByGet <T>(string tableName, Dictionary <string, string> filters)
        {
            var service = new HttpRequestFactory();
            var url     = $"{_configuration["ATReference:Url"]}/{tableName}?{string.Join("&", filters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)))}";
            var isError = false;

            try
            {
                return((await service.Get(url, _cert)).ContentAsType <T>());
            }
            catch (Exception)
            {
                isError = true;
                throw;
            }
            finally
            {
                this.Communicator_TraceHandler(this,
                                               new TraceEventArgs
                {
                    Description = "Get table ATReference.",
                    ElapsedTime = service.ElapsedTime,
                    ForceDebug  = false,
                    IsError     = isError,
                    Request     = service.Request,
                    Response    = service.Response,
                    URL         = url
                });
            }
        }
Esempio n. 12
0
        public async Task <JsonResult> GetPatientsByDate(DateTime fromDate, DateTime toDate)
        {
            string url      = $"{PatientsApiUrl}GetPatientsByDate?fromSubmissionDate={fromDate}&toSubmissionDate={toDate}";
            var    patients = Enumerable.Empty <PatientDTO>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                patients = response.ContentAsType <IEnumerable <PatientDTO> >();
                return(Json(patients));
            }
            else
            {
                if (response.StatusCode != HttpStatusCode.NoContent)
                {
                    return(Json(HttpResponseHandler.Process(response)));
                }
                else
                {
                    return(Json(patients));
                }
            }
        }
Esempio n. 13
0
        public ActionResult PerfilesLoad(bool loadAll)
        {
            PerfilesLoadDTO ret = new PerfilesLoadDTO()
            {
                Perfiles      = new List <PerfilDto>(),
                EstadosPerfil = new List <EstadoPerfilDto>(),
                TiposPerfil   = new List <TipoPerfilDto>()
            };

            string token = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetTokenAsync(HttpContext, "access_token").Result;

            var response0 = HttpRequestFactory.Get(_configuration["Endpoints:Perfiles"], token).Result;

            _logger.LogInformation(string.Format("GetPerfiles: StatusCode:{0} , RequestMessage:{1} ", response0.StatusCode, response0.RequestMessage));
            ret.Perfiles = response0.ContentAsType <List <PerfilDto> >();

            if (response0.IsSuccessStatusCode)
            {
                if (loadAll)
                {
                    var response1 = HttpRequestFactory.Get(_configuration["Endpoints:TipoPerfiles"], token).Result;
                    _logger.LogInformation(string.Format("GetTiposPerfiles: StatusCode:{0} , RequestMessage:{1} ", response1.StatusCode, response1.RequestMessage));
                    ret.TiposPerfil = response1.ContentAsType <List <TipoPerfilDto> >();

                    var response2 = HttpRequestFactory.Get(_configuration["Endpoints:EstadoPerfiles"], token).Result;
                    _logger.LogInformation(string.Format("GetEstadosPerfiles: StatusCode:{0} , RequestMessage:{1} ", response2.StatusCode, response2.RequestMessage));
                    ret.EstadosPerfil = response2.ContentAsType <List <EstadoPerfilDto> >();
                }
            }

            return(convertMessage(response0, ret));
        }
Esempio n. 14
0
        public static async Task <List <OperatorModel> > GetOperator(string text, string side, string baseUrl, string api_key)
        {
            var requestUri = $"{baseUrl}/Operators";

            var queryParams = new List <KeyValuePair <string, string> >();

            queryParams.Add(new KeyValuePair <string, string>("side", side));
            queryParams.Add(new KeyValuePair <string, string>("randomize", "true"));

            if (!string.IsNullOrEmpty(text))
            {
                queryParams.Add(new KeyValuePair <string, string>("numberOfOperators", text));
            }

            var response = await HttpRequestFactory.Get(requestUri, api_key, queryParams);

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

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Error from Strat Operator API, code: " + response.StatusCode + " text: " + responseString);
            }

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            var model = JsonConvert.DeserializeObject <List <OperatorModel> >(responseString, jsonSerializerSettings);

            return(model);
        }
Esempio n. 15
0
        public async Task <IActionResult> Index(int statusId)
        {
            if (statusId == 0)
            {
                if (_statusId == 0)
                {
                    return(RedirectToAction("Index", "PatientStatuses"));
                }
            }
            else
            {
                _statusId = statusId;
                var patientStatus = await GetPatientStatus(statusId);

                _patientStatusName = patientStatus.PatientStatusName;
            }
            ViewBag.PatientStatusName = _patientStatusName;

            string url = $"{ResourcesApiUrl}ResourcesAllocation/GetByPatientStatusId?statusId={_statusId}";
            var    resourcesAllocation = Enumerable.Empty <ResourceAllocationResponse>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resourcesAllocation = response.ContentAsType <IEnumerable <ResourceAllocationResponse> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(resourcesAllocation));
        }
        public async Task GetAblums_Based_on_User_StateUnderTest()
        {
            HttpRequestFactory httpRequestFactory = new HttpRequestFactory();
            var response = await httpRequestFactory.Get($"{_albumsUri}/1");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Esempio n. 17
0
        public async Task <Models.Utility.Interfaces.IApiResponse> GetFindPerson(IPerson person)
        {
            if (person == null)
            {
                throw new ArgumentNullException(nameof(person));
            }

            var log = logger.With("person", person);

            var requestUri = GetFindPersonUri(person);

            log.With("Uri", requestUri);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var httpResponse = await HttpRequestFactory.Get(requestUri);

            stopwatch.Stop();

            var apiResponse = new Models.Utility.ApiResponse
            {
                RequestUri = requestUri,
                StatusCode = (int?)httpResponse.StatusCode,
                Content    = await httpResponse.Content.ReadAsStringAsync()
            };

            log.With("apiResponse", apiResponse);

            log.InformationEvent("GetFindPerson", "Request completed in {ms}ms with HTTP Status Code {statusCode}", stopwatch.ElapsedMilliseconds, apiResponse.StatusCode);

            return(apiResponse);
        }
        public async Task <IActionResult> ActiveUserAccountInterface(string RegisterId)
        {
            var    requestUri = $"{_WebApiModel.BaseURL}/{"PrivateRegister"}/{"ActiveUserAccountInterface"}/{RegisterId}";
            string authHeader = HttpContext.Request?.Headers["Authorization"];

            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                BearerToken = authHeader.Substring("Bearer ".Length).Trim();
            }
            var response = await HttpRequestFactory.Get(requestUri, BearerToken);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                return(Unauthorized(response.ContentAsString()));

            case HttpStatusCode.BadRequest:
                return(BadRequest(response.ContentAsString()));

            case HttpStatusCode.OK:
                return(Ok(response.ContentAsString()));

            default:
                return(StatusCode(500));
            }
        }
Esempio n. 19
0
        public static async Task <PlayerModel> GetPlayerInfoFromR6DB(string text, string baseUrl, string xAppId)
        {
            var requestUri = $"{baseUrl}/Players";

            var region            = regionEnum.GetAttribute <RegionInformation>().Description;
            var platform          = platformEnum.GetAttribute <PlatformInformation>().Description;
            var technicalPlatform = platformEnum.GetAttribute <PlatformInformation>().TechnicalName;

            var queryParams = new List <KeyValuePair <string, string> >();

            queryParams.Add(new KeyValuePair <string, string>("name", text));
            queryParams.Add(new KeyValuePair <string, string>("platform", technicalPlatform));
            queryParams.Add(new KeyValuePair <string, string>("exact", "true")); //to make sure the name is exactly this. TODO: change this later into less exact with intelligence for questions like "did you mean.... "

            var response = await HttpRequestFactory.Get(requestUri, xAppId, queryParams);

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

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            var outputModel = JsonConvert.DeserializeObject <IList <PlayerModel> >(responseString, jsonSerializerSettings);

            if (outputModel.Count == 0)
            {
                return(null);
            }

            //Find the best match, if there isn't anyone with this exact name, than return the first one we found (likely to be the best)
            var model = new PlayerModel();

            model = outputModel.Where(m => m.name.ToLower() == text.ToLower()).FirstOrDefault();
            if (model == null)
            {
                //await ReplyAsync($"We found **{outputModel.Count}** likely results for the name **{text}** if the folowing stats are not the once you are looking for, please be more specific with the name/region/platform.");
                model         = outputModel.FirstOrDefault();
                model.guessed = new GuessedModel
                {
                    IsGuessed    = true,
                    PlayersFound = outputModel.Count
                };
            }

            var playerURL = $"{baseUrl}/Players/{model.id}";

            var queryParams2 = new List <KeyValuePair <string, string> >();
            var response2    = await HttpRequestFactory.Get(playerURL, xAppId, queryParams2);

            var responseString2 = await response2.Content.ReadAsStringAsync();

            var jsonSerializerSettings2 = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            var fullModel = JsonConvert.DeserializeObject <PlayerModel>(responseString2, jsonSerializerSettings2);

            fullModel.guessed = model.guessed;
            return(fullModel);
        }
Esempio n. 20
0
        public async Task <IActionResult> Index(int centerId)
        {
            if (centerId == 0)
            {
                if (_centerId == 0)
                {
                    return(RedirectToAction("Index", "DataCenters"));
                }
            }
            else
            {
                _centerId = centerId;
                var dataCenter = await GetDataCenter(centerId);

                _centerName = dataCenter.CenterName;
            }
            ViewBag.CenterName = _centerName;
            string url = $"{CoreApiUrl}HealthCareWorkers/GetByDataCenter?centerId={_centerId}";
            var    healthCareWorkers = Enumerable.Empty <HealthCareWorkerDTO>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                healthCareWorkers = response.ContentAsType <IEnumerable <HealthCareWorkerDTO> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(healthCareWorkers));
        }
Esempio n. 21
0
        public async Task ThenTheItemIsUpdatedCorrectly()
        {
            lastResponse.StatusCode.ShouldBe(HttpStatusCode.NoContent,
                                             $"Response from {lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} was not as expected");

            var updatedResponse = await HttpRequestFactory.Get(baseUrl, $"{MenuSteps.menuPath}{existingMenuId}");

            if (updatedResponse.StatusCode == HttpStatusCode.OK)
            {
                var updateItemResponse =
                    JsonConvert.DeserializeObject <Menu>(await updatedResponse.Content.ReadAsStringAsync());


                updateItemResponse.categories[0].items[0].name.ShouldBe(updateItemRequest.name,
                                                                        $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");

                updateItemResponse.categories[0].items[0].description.ShouldBe(updateItemRequest.description,
                                                                               $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");

                updateItemResponse.categories[0].items[0].price.ShouldBe(updateItemRequest.price.ToString(),
                                                                         $"{lastResponse.RequestMessage.Method} {lastResponse.RequestMessage.RequestUri} did not create the menu as expected");
                updateItemResponse.categories[0].items[0].available.ShouldBeTrue();
            }
            else
            {
                throw new Exception($"Could not retrieve the updated menu using GET /menu/{existingMenuId}");
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Get mappings. Retrieves a list of mappings.
        /// </summary>
        /// <param name="filter">Filter as JSON object.</param>
        /// <param name="size">The maximum number of elements in a page.</param>
        /// <param name="page">The (0-based) index of page.</param>
        /// <param name="sort">The order of returned elements. Multiple fields could be used separated by commas (e.g. &#39;&#39;field1,field2&#39;&#39;). Descending order could be requested by appending &#39;&#39;,desc&#39;&#39; at the end of parameter.(e.g. &#39;&#39;field1,field2,desc&#39;&#39;)&#39; </param>
        /// <returns>PagedMapping</returns>
        public PagedMapping DataPointMappingsGet(string filter, int?size, int?page, string sort)
        {
            const string endpoint   = "/dataPointMappings";
            string       requestUri = $"{BasePath}{endpoint}";

            var queryParams = new Dictionary <String, String>();

            if (filter != null)
            {
                queryParams.Add("filter", Helpers.ParameterToString(filter));                 // query parameter
            }
            if (size != null)
            {
                queryParams.Add("size", Helpers.ParameterToString(size));               // query parameter
            }
            if (page != null)
            {
                queryParams.Add("page", Helpers.ParameterToString(page));               // query parameter
            }
            if (sort != null)
            {
                queryParams.Add("sort", Helpers.ParameterToString(sort));               // query parameter
            }
            var response = HttpRequestFactory.Get(requestUri, Helpers.DictionaryToUriQueryString(queryParams)).Result;

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling DataPointMappingsGet: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling DataPointMappingsGet: " + response.ReasonPhrase, response.ReasonPhrase);
            }
            return(response.ContentAsType <PagedMapping>());
        }
Esempio n. 23
0
        private static async Task GetItem()
        {
            var requestUrl = $"{baseUrl}/1";
            var response   = await HttpRequestFactory.Get(requestUrl);

            var outputModel = response.ContentAsType <MovieOutputModel>();
        }
Esempio n. 24
0
        public void GetsTest()
        {
            var response = HttpRequestFactory.Get("https://kaijiang.500.com/static/info/kaijiang/xml/index.xml");
            var result   = response.Result.ContentAsString();

            Console.WriteLine(result);
        }
Esempio n. 25
0
        public async Task <IActionResult> MenuA1InterfaceDataEdit(int DocId, string userid, string username)
        {
            var    requestUri = $"{_WebApiModel.BaseURL}/{"PrivateDocMenuA"}/{"MenuA1InterfaceDataEdit"}/{DocId}/{userid}/{username}";
            string authHeader = HttpContext.Request?.Headers["Authorization"];

            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                BearerToken = authHeader.Substring("Bearer ".Length).Trim();
            }
            var response = await HttpRequestFactory.Get(requestUri, BearerToken);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                return(Unauthorized(response.ContentAsString()));

            case HttpStatusCode.BadRequest:
                return(BadRequest(response.ContentAsString()));

            case HttpStatusCode.OK:
                return(Ok(response.ContentAsString()));

            default:
                return(StatusCode(500));
            }
        }
Esempio n. 26
0
        public async Task <dynamic> GetCustomerDynamic()
        {
            var requestUri = $"{baseUri}";
            var response   = await HttpRequestFactory.Get(requestUri);

            return(JsonConvert.DeserializeObject <dynamic>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)));
        }
Esempio n. 27
0
        public async Task <GoogleMapsAddress> GetFullAddress(string placeId)
        {
            var service = new HttpRequestFactory();
            var url     = $"{_configuration["GoogleMaps:Url"]}place_id={placeId}&key={_configuration["GoogleMaps:Key"]}";
            var isError = false;

            try
            {
                return((await service.Get(url)).ContentAsType <GoogleMapsAddress>());
            }
            catch (Exception)
            {
                isError = true;
                throw;
            }
            finally
            {
                this.Communicator_TraceHandler(this,
                                               new TraceEventArgs
                {
                    Description = "Get full address.",
                    ElapsedTime = service.ElapsedTime,
                    ForceDebug  = false,
                    IsError     = isError,
                    Request     = service.Request,
                    Response    = service.Response,
                    URL         = url
                });
            }
        }
Esempio n. 28
0
        public async Task <IActionResult> PopulateTopNavbarData(string areaCode, string roleCode)
        {
            // var model = JsonConvert.DeserializeObject<TopNavbarMenuFormViewModel>(json);
            var email    = User.Identity.Name;
            var response = await HttpRequestFactory.Get(Constants.BaseAdminApiUrl + "user/areas/" + email);

            var outputModel = response.ContentAsType <SingleModelResponse <UserEx> >();
            var role        = outputModel.Model.MyRoles.FirstOrDefault(x => x.RoleCode == roleCode);
            //var saleRole = outputModel.Model.MyRoles.FirstOrDefault(x => x.RoleCode == Constants.SaleRoleCode);
            //var saleArea = saleRole?.MyAreas.FirstOrDefault(x => x.AreaCode == areaCode);
            //var areas = outputModel.Model.MyRoles.SelectMany(x => x.MyAreas);
            // var functions = areas.SelectMany(x => x.MyFunctions);
            //var childItems = functions.SelectMany(x => x.ChildItems);
            //var functions = saleArea.MyFunctions.SelectMany(x => x.ChildItems);
            var area = role?.MyAreas.FirstOrDefault(x => x.AreaCode == areaCode);

            //foreach (var function in functions)
            //{
            //    if (area.MyFunctions.Any(x => x.Id != function.Id))
            //    {
            //        area.MyFunctions.Add(function);
            //    }
            //}
            return(PartialView("TopNavbarMenu", area?.MyFunctions));
        }
Esempio n. 29
0
        public async Task <IList <Product> > GetProductListAsync()
        {
            var response = await HttpRequestFactory.Get(_settings.ProductListUri);

            var result = response.ContentAsType <ProductListResult>();

            return(result.Products);
        }
Esempio n. 30
0
        public ActionResult GetPerfil(string Login)
        {
            string token    = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetTokenAsync(HttpContext, "access_token").Result;
            var    response = HttpRequestFactory.Get(_configuration["Endpoints:Perfiles"] + "/" + Login, token).Result;

            _logger.LogInformation(string.Format("GetPerfil: StatusCode:{0} , RequestMessage:{1} ", response.StatusCode, response.RequestMessage));
            return(convertMessage(response, response.ContentAsJson()));
        }