public HttpResponseMessage Get(string postcode) { if (String.IsNullOrEmpty(postcode)) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Postcode must not be null."))); } var regex = new Regex(Common.Config.PostcodeExpression); var match = regex.Match(postcode.ToUpper()); if (match.Success) { var postcodeInfo = postcode.Replace(" ", ""); bool isCacheEnabled; bool.TryParse(Common.Config.CacheEnabled, out isCacheEnabled); if (isCacheEnabled) { //Check Cached Result if (Cache.IsInCache("MC-DEALERLOOKUP-" + postcodeInfo)) { var list = Cache.GetFromCache <List <Models.DealerLookUp> >("MC-DEALERLOOKUP-" + postcodeInfo); return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(list))); } } // Check Database var postcodeData = _dbContext.GetDealer(postcodeInfo).ToList(); if (postcodeData.Any()) { var dealers = postcodeData.Select(x => new Models.DealerLookUp { DealerId = x.DealerId, Phone = x.Phone, Name = x.Name, Longitude = x.Longitude, Latitude = x.Latitude, Distance = x.Distance, Address = x.Address }).OrderBy(x => x.Distance).ToList(); double time; var isParsed = double.TryParse(Common.Config.CacheExpiration, out time); if (!isParsed) { return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(dealers))); } if (isCacheEnabled) { Cache.SaveToCache("MC-DEALERLOOKUP-" + postcodeInfo, dealers, DateTimeOffset.Now.AddMinutes(time)); } return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(dealers))); } else { // Make API WebRequest var googleUri = new Uri(Common.Config.GoogleMapsApi) .AddParameter("address", postcodeInfo) .AddParameter("sensor", "false"); var response = HttpWebRequestHelper.MakeRequest(googleUri.ToString(), 5000); var json = HttpWebRequestHelper.GetHttpWebResponseData(response); var addresses = (GoogleGeoCodeResponse)JsonConvert.DeserializeObject(json, typeof(GoogleGeoCodeResponse)); var location = addresses.results.Select(x => x.geometry.location).SingleOrDefault(); if (location == null) { return(null); } var dealerUri = new Uri(Common.Config.DealerApi) .AddParameter("application", Common.Config.DealerApplication) .AddParameter("brand", Common.Config.DealerCategory) .AddParameter("resultcount", Common.Config.DealerMaxTotal) .AddParameter("latitude", location.lat) .AddParameter("longitude", location.lng); var dealerResponse = HttpWebRequestHelper.MakeRequest(dealerUri.ToString(), 5000); var feed = HttpWebRequestHelper.GetHttpWebResponseData(dealerResponse); var dealerList = (DealerResponse)JsonConvert.DeserializeObject(feed, typeof(DealerResponse)); var viewModel = dealerList.dealers.Select(loc => new Models.DealerLookUp() { Address = loc.address, DealerId = Convert.ToInt32(loc.dealerid), Phone = loc.telephone, Latitude = double.Parse(loc.latitude), Longitude = double.Parse(loc.longitude), Name = loc.name, Distance = double.Parse(loc.distance) }).OrderBy(x => x.Distance).ToList(); //Save Result to DB foreach (var dealer in viewModel) { _dbContext.Dealers.InsertOnSubmit(new Dealer { Postcode = postcodeInfo, DealerLookUp = new DealerLookUp { Address = dealer.Address, DealerId = dealer.DealerId, Distance = dealer.Distance, Latitude = dealer.Latitude, Longitude = dealer.Longitude, Name = dealer.Name, Phone = dealer.Phone } }); } _dbContext.SubmitChanges(); if (!isCacheEnabled) { return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(viewModel))); } double time; var isParsed = double.TryParse(Common.Config.CacheExpiration, out time); if (!isParsed) { Cache.SaveToCache("MC-DEALERLOOKUP-" + postcodeInfo, viewModel, DateTimeOffset.Now.AddMinutes(time)); } return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(viewModel))); } } var message = string.Format("Postcode is not valid."); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message)); }
public HttpResponseMessage Get(string postcode) { if (String.IsNullOrEmpty(postcode)) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Postcode must not be null."))); } var regex = new Regex(Common.Config.PostcodeExpression); var match = regex.Match(postcode.ToUpper()); if (match.Success) { var postcodeInfo = postcode.Replace(" ", "").ToUpper(); bool isCacheEnabled; bool.TryParse(Common.Config.CacheEnabled, out isCacheEnabled); if (isCacheEnabled) { //Check Cached Result if (Cache.IsInCache("MC-POSTCODELOOKUP-" + postcodeInfo)) { var list = Cache.GetFromCache <List <Models.PostcodeLookUp> >("MC-POSTCODELOOKUP-" + postcodeInfo); return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(list))); } } // Check Database var postcodeData = _dbContext.GetPostCode(postcodeInfo).ToList(); if (postcodeData.Any()) { var postcodes = postcodeData.Select(x => new Models.PostcodeLookUp { Address1 = x.Address1, Address2 = x.Address2, Address3 = x.Address3, Town = x.Town, County = x.County, Postcode = x.Postcode.NormalizePostcode().ToUpper() }).ToList(); double time; var isParsed = double.TryParse(Common.Config.CacheExpiration, out time); if (!isParsed) { return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(postcodes))); } if (isCacheEnabled) { Cache.SaveToCache("MC-POSTCODELOOKUP-" + postcodeInfo, postcodes, DateTimeOffset.Now.AddMinutes(time)); } return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(postcodes))); } else { //Make Grass Roots API WebRequest var uri = new Uri(Common.Config.PostcodeApi) .AddParameter("postcode", postcodeInfo.ToUpper()) .AddParameter("application", Common.Config.PostcodeApp); var response = HttpWebRequestHelper.MakeRequest(uri.ToString(), 5000); var json = HttpWebRequestHelper.GetHttpWebResponseData(response); if (!String.IsNullOrEmpty(json)) { var postcodeApi = (PostcodeLookUpApiViewModel) JsonConvert.DeserializeObject(json, typeof(PostcodeLookUpApiViewModel)); //Save Result to DB foreach (var address in postcodeApi.Addresses) { address.Postcode = postcode.ToUpper(); _dbContext.PostcodeLookUps.InsertOnSubmit(new PostcodeLookUp { Address1 = address.Address1, Address2 = address.Address2, Address3 = address.Address3, Town = address.Town, County = address.County, Postcode = postcode.ToUpper() }); } _dbContext.SubmitChanges(); if (!isCacheEnabled) { return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(postcodeApi.Addresses))); } double time; var isParsed = double.TryParse(Common.Config.CacheExpiration, out time); if (!isParsed) { Cache.SaveToCache("MC-POSTCODELOOKUP-" + postcodeInfo, postcodeApi.Addresses, DateTimeOffset.Now.AddMinutes(time)); } return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(postcodeApi.Addresses))); } else { return(ResponseHelper.FormatMessage(JsonConvert.SerializeObject(""))); } } } var message = string.Format("Postcode is not valid."); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message)); }
/// <summary> /// Reads a local CSV file and imports the data into database. /// </summary> public void Index(string type) { switch (type) { case "csv": var fileName = Server.MapPath("~/App_Data/MINI_FS_logic_v48.csv"); var fileEncoding = GetEncoding(fileName); using (var fileReader = System.IO.File.OpenText(fileName)) using (var csv = new CsvReader(fileReader)) { csv.Configuration.Encoding = fileEncoding; csv.Configuration.IgnoreReadingExceptions = true; csv.Configuration.ReadingExceptionCallback = ReadingExceptionCallback; csv.Configuration.WillThrowOnMissingField = false; csv.Configuration.IsHeaderCaseSensitive = false; csv.Configuration.HasHeaderRecord = true; csv.Configuration.TrimFields = true; csv.Configuration.IgnoreHeaderWhiteSpace = true; csv.Configuration.RegisterClassMap <NewCarConfig>(); var records = csv.GetRecords <Models.NewCar>().Distinct().ToList(); using (var context = new CombobulatorDataContext()) { foreach (var record in records) { var finance = new EntitySet <Finance> { new Finance { Info = record.Info, Term = record.Term ?? 0, FinalPayment = record.FinalPayment ?? 0.0, FinancePrice = record.FinancePrice ?? 0.0, APR = record.APR, ROI = record.ROI, Contribution = record.Contribution ?? 0.0, CreditCharge = record.CreditCharge ?? 0.0, Deposit = record.Deposit ?? 0.0, Payment = record.Payment ?? 0.0, PurchaseFee = record.PurchaseFee ?? 0.0, TotalAmount = record.TotalAmount ?? 0.0, DealerDiscount = record.DealerDiscount ?? 0.0, TotalDeposit = record.TotalDeposit ?? 0.0 } }; context.Cars.InsertOnSubmit(new Car { Brand = Common.Config.Brand, Code = record.Code, Color = record.Color, Engine = record.Engine, EngineName = record.EngineName, Model = record.Model, Url = record.Url, Joke = record.Joke, Name = record.Name, Capacity = record.Capacity, Luggage = record.Luggage, Lifestyle = record.Lifestyle, Awd = record.Awd, High = record.High, Convertible = record.Convertible, Price = record.Price, Cost = record.Cost, Speed = record.Speed, Mph = record.Mph, Economy = record.Economy, Mpg = record.Mph, Alt1 = record.Alt_1, Alt2 = record.Alt_2, Alt3 = record.Alt_3, Terms = record.Terms, Finances = finance }); context.SubmitChanges(); } } } break; case "json": var file = Server.MapPath("~/App_Data/data.json"); var json = System.IO.File.ReadAllText(file); var dataViewModel = JsonConvert.DeserializeObject <List <DataViewModel> >(json); using (var context = new CombobulatorDataContext()) { foreach (var record in dataViewModel) { var finance = new EntitySet <Finance> { new Finance { Info = record.Finance.Info, Term = record.Finance.Term, FinalPayment = record.Finance.Final_Payment, FinancePrice = record.Finance.Price, APR = record.Finance.APR, ROI = record.Finance.ROI, Contribution = record.Finance.Contribution, CreditCharge = record.Finance.Credit_Charge, Deposit = record.Finance.Deposit, Payment = record.Finance.Payment, PurchaseFee = record.Finance.Purchase_Fee } }; context.Cars.InsertOnSubmit(new Car { Code = record.Code, Color = record.Color, Engine = record.Engine, Name = record.Name, Capacity = record.Capacity, Luggage = record.Luggage, Lifestyle = record.Lifestyle, Awd = record.Awd, High = record.High, Convertible = record.Convertible, Price = record.Price, Cost = record.Cost, Speed = record.Speed, Mph = record.Mph, Economy = record.Economy, Mpg = record.Mph, Alt1 = record.Alt_1, Alt2 = record.Alt_2, Alt3 = record.Alt_3, Terms = record.Terms, Finances = finance }); context.SubmitChanges(); } } break; } }