Exemplo n.º 1
0
        private HttpWebRequest CreateApiRequest(WeatherDataRequest request)
        {
            // API uses different query params depending on the type of search
            var queryType = request.LocationIsZip ? "zip" : "q";

            var queryPrefix = ApiEndpoint.Contains("?") ? "&" : "?";

            // Create request from weather API URL - note that we're passing in Imperial for the units param, but
            // this would likely be something that we could break out into a configuration param.
            var apiRequest = (HttpWebRequest)WebRequest.Create(String.Format("{0}{1}{2}={3}&APPID={4}&units=imperial", ApiEndpoint, queryPrefix, queryType, request.Location, ApiKey));

            return(apiRequest);
        }
Exemplo n.º 2
0
        public async Task Invalid_Model_Returns_Bad_Request_Response()
        {
            WeatherController controller = new WeatherController();

            controller.Request       = new HttpRequestMessage();
            controller.Configuration = new HttpConfiguration();

            var wdRequest = new WeatherDataRequest();

            controller.Validate(wdRequest);
            var response = await controller.Post(wdRequest);

            Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.BadRequest, "An invalid model should return a Bad Request response message.");
        }
        public async Task <HttpResponseMessage> Post(WeatherDataRequest request)
        {
            try
            {
                // Ensure that we have a valid request and the model passes validation
                if (request == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You must provide a valid request body."));
                }
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                var repo        = new WeatherApiRepository(Settings.WeatherApi.WeatherApiEndPoint, Settings.WeatherApi.WeatherApiKey);
                var weatherData = await repo.GetAsync(request);

                return(Request.CreateResponse(HttpStatusCode.OK, weatherData));
            }
            catch (WebException wex)
            {
                logger.Error(wex);
                if (wex.Status == WebExceptionStatus.ProtocolError && wex.Response != null)
                {
                    var response = (HttpWebResponse)wex.Response;
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(Request.CreateErrorResponse(response.StatusCode, "Could not find anything with the provided parameters."));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(response.StatusCode, "There was an error processing your request."));
                    }
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "There was an error processing your request."));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "There was an error processing your request."));
            }
        }
 public IEnumerable <WeatherData> Get(WeatherDataRequest request)
 {
     return(new List <WeatherData>()
     {
         new WeatherData()
         {
             CityName = "Foo", Description = "Bar", Humidity = 90, Temperature = 73.4
         },
         new WeatherData()
         {
             CityName = "Bar", Description = "Bar", Humidity = 67, Temperature = 63.4
         },
         new WeatherData()
         {
             CityName = "Baz", Description = "Bar", Humidity = 10, Temperature = 90.4
         },
     }.Where(w => w.CityName.Equals(request.Location, StringComparison.CurrentCultureIgnoreCase)));
 }
Exemplo n.º 5
0
        public async Task <IEnumerable <WeatherData> > GetAsync(WeatherDataRequest dataRequest)
        {
            var data = new List <WeatherData>();

            var apiRequest = CreateApiRequest(dataRequest);

            using (var response = await apiRequest.GetResponseAsync())
            {
                using (var stream = response.GetResponseStream())
                {
                    var reader  = new StreamReader(stream);
                    var content = await reader.ReadToEndAsync();

                    data = TransformData(content);
                }
            }

            return(data);
        }
Exemplo n.º 6
0
 public async Task <List <WeatherData> > Get([FromQuery] WeatherDataRequest request)
 {
     return(await _weatherService.GetWeatherData(_mapper.Map <WeatherDataRequestEntity>(request)));
 }
Exemplo n.º 7
0
        public string UploadFiles()
        {
            try
            {
                // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
                string sPath       = System.Web.Hosting.HostingEnvironment.MapPath("~/InputFolder/");
                string outputSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/OutputFolder/");
                string fileName    = "";

                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];
                    fileName = hpf.FileName;
                    if (hpf.ContentLength > 0)
                    {
                        // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                        if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                        {
                            // SAVE THE FILE IN THE FOLDER.
                            hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        }
                    }
                }
                // Read entire text file content in one string
                string text       = File.ReadAllText(sPath + fileName);
                var    cityIdList = text.Split(',');

                foreach (var cityId in cityIdList)
                {
                    var factory = RegistryFactory.GetResolver().Resolve <ICommandFactory>();

                    var weatherDataRequest = new WeatherDataRequest();
                    weatherDataRequest.CityID = Convert.ToInt32(cityId);
                    var command = factory.FetchWeatherDataCommand();
                    WeatherDataResult results = command.Execute(weatherDataRequest);

                    // File name with City Id and Date
                    var outputFileName = "CityId_" + cityId + "_" + DateTime.Now.Date.ToShortDateString();
                    if (File.Exists(outputSPath + outputFileName))
                    {
                        File.Delete(outputSPath + outputFileName);
                    }

                    // Create a Response Weather Data City Wise
                    using (FileStream fs = File.Create(outputSPath + outputFileName))
                    {
                        // Add some text to file
                        Byte[] weatherData = new UTF8Encoding(true).GetBytes(results.WeatherData);
                        fs.Write(weatherData, 0, weatherData.Length);
                    }
                }

                // Delete File in the Input Folder (Request File)
                if (File.Exists(sPath + fileName))
                {
                    File.Delete(sPath + fileName);
                }

                return($"File Processed Successfully, For Weather Data Please browse to path: {outputSPath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return($"File Processing Failed with error: {ex.Message} and stack trace: {ex.StackTrace}");
            }
        }