public void GetReportByRegion(string endpoint, string apikey, bool expected)
        {
            //RESTful API Report By Region Consumption and Deserialization
            var request = new RequestCovid19Stats()
            {
                RegionIso = "USA"
            };
            var json = Utils.GetJSON(request);

            endpoint += "?iso=" + request.RegionIso;
            IRestResponse responseAPI    = Utils.RestClientExec(endpoint, Method.POST, apikey, json);
            var           responseReport = JsonConvert.DeserializeObject <ServiceResponse>(responseAPI.Content);
            var           response       = new ServiceResponse()
            {
                Status              = (int)responseAPI.StatusCode,
                Code                = responseReport.Code,
                Message             = responseReport.Message,
                ErrorMessage        = responseReport.ErrorMessage,
                StackTrace          = responseReport.StackTrace,
                TransactionDateTime = responseReport.TransactionDateTime,
                Data                = JsonConvert.DeserializeObject <List <TopStatistics> >(responseReport.Data.ToString())
            };

            var  jsonResponse  = Utils.GetJSON(response);
            bool statusCode200 = (int)responseAPI.StatusCode == (int)HttpStatusCode.OK;

            Console.WriteLine("StatusCode => " + (int)responseAPI.StatusCode);
            Console.WriteLine("JSON response => " + jsonResponse);

            Assert.Equal(statusCode200, expected);
        }
        public ActionResult Report([FromBody] RequestCovid19Stats requestCovid19Stats)
        {
            //Response object is initialized
            var response = new ServiceResponse()
            {
                Status              = 0,
                Code                = string.Empty,
                Message             = string.Empty,
                ErrorMessage        = string.Empty,
                StackTrace          = string.Empty,
                TransactionDateTime = DateTime.Now,
                Data                = new List <object>()
            };

            try
            {
                //Get the parameters from appsettings.json
                var globalReportEndpoint     = Configuration.GetValue <string>("Covid-19APISettings:APIEndpoints:Reports");          //Global Report Endpoint
                var regionsCatalogEndpoint   = Configuration.GetValue <string>("Covid-19APISettings:APIEndpoints:RegionsCatalog");   //Regions Catalog Endpoint
                var provincesCatalogEndpoint = Configuration.GetValue <string>("Covid-19APISettings:APIEndpoints:ProvincesCatalog"); //Provinces Catalog Endpoint
                var xRapidApiKey             = Configuration.GetValue <string>("Covid-19APISettings:Headers:x-rapidapi-key");        //API key
                var xRapidApiHost            = Configuration.GetValue <string>("Covid-19APISettings:Headers:x-rapidapi-host");       //API host

                //Parameters from appsettings.json are validated
                if (string.IsNullOrEmpty(globalReportEndpoint))
                {
                    throw new Exception("Global report endpoint is not configured");
                }
                if (string.IsNullOrEmpty(regionsCatalogEndpoint))
                {
                    throw new Exception("Regions catalog endpoint is not configured");
                }
                if (string.IsNullOrEmpty(provincesCatalogEndpoint))
                {
                    throw new Exception("Provinces catalog endpoint is not configured");
                }
                if (string.IsNullOrEmpty(xRapidApiKey))
                {
                    throw new Exception("API key is not configured");
                }
                if (string.IsNullOrEmpty(xRapidApiHost))
                {
                    throw new Exception("API host is not configured");
                }

                //API Key is validated
                Request.Headers.TryGetValue("x-rapidapi-key", out StringValues xApiKey);
                if (!xRapidApiKey.ToString().Equals(xApiKey))
                {
                    //Request is not authorized
                    response.Status       = (int)HttpStatusCode.Unauthorized;
                    response.Code         = "ERROR";
                    response.Message      = "You are not unauthorized to do the request.";
                    response.ErrorMessage = "401 Unauthorized";
                    response.StackTrace   = string.Empty;
                    return(StatusCode((int)HttpStatusCode.Unauthorized, response));
                }

                //Request is validated
                if (requestCovid19Stats == null)
                {
                    //Bad Request
                    response.Status       = (int)HttpStatusCode.BadRequest;
                    response.Code         = "ERROR";
                    response.Message      = "We are sorry, the request sent is not valid.";
                    response.ErrorMessage = "400 Bad Request";
                    response.StackTrace   = string.Empty;
                    return(BadRequest(response));
                }

                //Get ISO from request
                var regionIso = requestCovid19Stats.RegionIso?.Trim();

                //RapidAPI Regions/Provinces Catalog Consumption
                var           catalogEndpoint = string.IsNullOrEmpty(regionIso) ? regionsCatalogEndpoint : provincesCatalogEndpoint += "?iso=" + regionIso;
                IRestResponse responseCatalog = RapidAPIResponse(catalogEndpoint, Method.GET, xRapidApiKey, xRapidApiHost);
                if ((int)responseCatalog.StatusCode == (int)HttpStatusCode.OK) //SUCCESS response from the RapidAPI (Regions/Provinces Catalog)
                {
                    //Rapid API Global Report Service Consumption with RestSharp
                    var           globalEndpoint = string.IsNullOrEmpty(regionIso) ? globalReportEndpoint : globalReportEndpoint += "?iso=" + regionIso;
                    IRestResponse responseReport = RapidAPIResponse(globalEndpoint, Method.GET, xRapidApiKey, xRapidApiHost);
                    if ((int)responseReport.StatusCode == (int)HttpStatusCode.OK) //SUCCESS response from the RapidAPI (Global Report)
                    {
                        //Deserialization of JSON data COVID-19 cases around the world
                        var globalReport = JsonConvert.DeserializeObject <GlobalReport>(responseReport.Content).Data.ToList();
                        //Definition of generic list to store the top regions/provinces with most COVID-19 cases
                        var genericList = new List <TopStatistics>();
                        //
                        // TOP 10 GLOBAL DATA / COVID-19
                        //
                        if (string.IsNullOrEmpty(regionIso))
                        {
                            //Deserialization of Regions Data (JSON)
                            var regionCatalog = JsonConvert.DeserializeObject <RegionCatalog>(responseCatalog.Content).Data.ToList();
                            //Iteration of the region catalog to sum COVID-19 data per region
                            regionCatalog.ForEach(r =>
                            {
                                var regionStatistic = new TopStatistics()
                                {
                                    Name   = r.Name,
                                    Cases  = globalReport.Where(g => r.Iso.Equals(g.Region.Iso)).ToList().Sum(g => g.Confirmed),
                                    Deaths = globalReport.Where(g => r.Iso.Equals(g.Region.Iso)).ToList().Sum(g => g.Deaths)
                                };
                                genericList.Add(regionStatistic);
                            });
                        }
                        //
                        // TOP 10 PROVINCES BY REGION / COVID-19
                        //
                        else
                        {
                            //Deserialization of Provinces Data (JSON)
                            var provinceCatalog = JsonConvert.DeserializeObject <ProvinceCatalog>(responseCatalog.Content).Data.ToList();
                            //Iteration of the region catalog to sum COVID-19 data per region
                            provinceCatalog.ForEach(p =>
                            {
                                var provinceStatistic = new TopStatistics()
                                {
                                    Name   = string.IsNullOrEmpty(p.Province) ? p.Name : p.Province,
                                    Cases  = globalReport.Where(g => p.Province.Equals(g.Region.Province)).ToList().Sum(g => g.Confirmed),
                                    Deaths = globalReport.Where(g => p.Province.Equals(g.Region.Province)).ToList().Sum(g => g.Deaths)
                                };
                                genericList.Add(provinceStatistic);
                            });
                        }
                        //Get the TOP 10 of regions/provinces with most COVID-19 cases
                        var topList = genericList.OrderByDescending(a => a.Cases).Take(10).ToList();
                        //Adding correlatives and commas in thousands places
                        int i = 0;
                        topList.ForEach(a =>
                        {
                            a.Item      = ++i;
                            a.CasesStr  = string.Format("{0:n0}", a.Cases);
                            a.DeathsStr = string.Format("{0:n0}", a.Deaths);
                        });
                        //Preparing the RESTful API Successful response
                        response.Status  = (int)responseReport.StatusCode;
                        response.Code    = "OK";
                        response.Message = "Data obtained successfully";
                        response.Data    = topList; //Top 10 list is added to response
                        return(Ok(response));
                    }
                    else //Another status code from the RapidAPI (Global Report)
                    {
                        response.Status       = (int)responseReport.StatusCode;
                        response.Code         = "ERROR";
                        response.Message      = "An error occurred in the data query of the global report, please try again later.";
                        response.ErrorMessage = (int)responseReport.StatusCode + " " + responseReport.StatusDescription;
                        response.StackTrace   = "JSON returned from the Rapid API => " + responseReport.Content;
                        return(StatusCode((int)responseReport.StatusCode, response));
                    }
                }
                else //Another status code from the RapidAPI (Regions/Provinces Catalog)
                {
                    var catalogType = string.IsNullOrEmpty(regionIso) ? "regions" : "provinces";
                    response.Status       = (int)responseCatalog.StatusCode;
                    response.Code         = "ERROR";
                    response.Message      = "An error occurred in the data query of the " + catalogType + " catalog, please try again later.";
                    response.ErrorMessage = (int)responseCatalog.StatusCode + " " + responseCatalog.StatusDescription;
                    response.StackTrace   = "JSON returned from the Rapid API => " + responseCatalog.Content;
                    return(StatusCode((int)responseCatalog.StatusCode, response));
                }
            }
            catch (Exception ex)
            {
                response.Status       = (int)HttpStatusCode.InternalServerError;
                response.Code         = "ERROR";
                response.Message      = "An internal server error has ocurred, please try again later.";
                response.ErrorMessage = "500 Internal Server Error | " + ex.Message;
                response.StackTrace   = ex.StackTrace;
                return(StatusCode((int)HttpStatusCode.InternalServerError, response));
            }
        }
Beispiel #3
0
        public ActionResult Report([FromBody] RequestCovid19Stats requestCovid19Stats)
        {
            try
            {
                //Get the parameters from appsettings.json
                var globalReportEndpoint = configuration.GetValue <string>("RESTfulAPISettings:GlobalReportEndpoint");
                var xApiKey = configuration.GetValue <string>("RESTfulAPISettings:Headers:x-rapidapi-key");

                //Parameters from appsettings.json are validated
                if (string.IsNullOrEmpty(globalReportEndpoint))
                {
                    throw new Exception("Global report endpoint is not configured");
                }
                if (string.IsNullOrEmpty(xApiKey))
                {
                    throw new Exception("API key is not configured");
                }

                //Request is validated
                if (requestCovid19Stats == null)
                {
                    //Bad Request
                    var response400 = new ServiceResponse
                    {
                        Status       = (int)HttpStatusCode.BadRequest,
                        Code         = "ERROR",
                        Message      = "We are sorry, the request sent is not valid.",
                        ErrorMessage = "400 Bad Request",
                        StackTrace   = string.Empty
                    };
                    return(BadRequest(response400));
                }

                //Get the JSON serialization from the object request
                var contractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };

                var json = JsonConvert.SerializeObject(requestCovid19Stats, new JsonSerializerSettings
                {
                    ContractResolver  = contractResolver,
                    NullValueHandling = NullValueHandling.Ignore
                });

                //RESTful API Global Report Consumption and Deserialization
                IRestResponse responseAPI    = RESTfulApiResponse(globalReportEndpoint, Method.POST, xApiKey, json);
                var           responseReport = JsonConvert.DeserializeObject <ServiceResponse>(responseAPI.Content);
                var           response       = new ServiceResponse()
                {
                    Status              = (int)responseAPI.StatusCode,
                    Code                = responseReport.Code,
                    Message             = responseReport.Message,
                    ErrorMessage        = responseReport.ErrorMessage,
                    StackTrace          = responseReport.StackTrace,
                    TransactionDateTime = responseReport.TransactionDateTime,
                    Data                = JsonConvert.DeserializeObject <List <TopStatistics> >(responseReport.Data.ToString())
                };
                //Assign values to global variables to export data
                RegionIso           = requestCovid19Stats.RegionIso?.Trim();
                GlobalTopStatistics = JsonConvert.DeserializeObject <List <TopStatistics> >(responseReport.Data.ToString());
                return(StatusCode((int)responseAPI.StatusCode, response));
            }
            catch (Exception ex)
            {
                var response = new ServiceResponse()
                {
                    Status              = (int)HttpStatusCode.InternalServerError,
                    Code                = "ERROR",
                    Message             = "An internal error occurred while obtaining the regions catalog, please try again later.",
                    ErrorMessage        = "500 Internal Server Error | " + ex.Message,
                    StackTrace          = ex.StackTrace,
                    TransactionDateTime = DateTime.Now,
                    Data                = new List <object>()
                };
                return(StatusCode((int)HttpStatusCode.InternalServerError, response));
            }
        }