/// <summary>
        /// Retrieves customer details from eMaster API and returns a customer object.
        /// </summary>
        /// <returns>A customer object.</returns>
        public Customer Execute()
        {
            try
            {
                const string action   = "getcustomerdetails";
                var          input    = Config.SystemId + _customerId + Config.SecretKey + Config.Random;
                var          checksum = CryptoHelper.CalculateMd5Hash(input);

                var url      = string.Format(Config.HostUrl + "&checksum={0}&system_id={1}&action={2}&de_id={3}&random={4}&type=json", checksum, Config.SystemId, action, _customerId, Config.Random);
                var response = HttpWebRequestHelper.MakeRequest(url, 5000);
                var line     = HttpWebRequestHelper.GetHttpWebResponseData(response);

                dynamic obj = JsonConvert.DeserializeObject(line);
                if (obj.Error != null)
                {
                    Log.Error("GetCustomerDataCommand Error - " + obj.Error);
                    return(new Customer());
                }

                var customer = new Customer
                {
                    UserId    = _customerId.ToString(),
                    FirstName = obj.first_name,
                    LastName  = obj.surname,
                    Email     = obj.email
                };
                return(customer);
            }
            catch (Exception ex)
            {
                Log.Error("GetCustomerDataCommand", ex);
                return(new Customer());
            }
        }
示例#2
0
        public T SendGetRequest <T>(string methodName, Dictionary <string, string> parameters, string apiUrl, List <KeyValuePair <string, string> > keyValueParameters = null)
        {
            var response = HttpWebRequestHelper.SendGetRequest(String.Format("{0}{1}", apiUrl, methodName),
                                                               parameters, keyValueParameters);

            if (response == null)
            {
                throw new Exception("Unable to get resposne");
            }
            return(JsonConvert.DeserializeObject <T>(HttpWebRequestHelper.GetHttpWebResponseData(response)));
        }
示例#3
0
        public bool SendData(Customer customer, out string requestUrl)
        {
            var isComplete = false;

            requestUrl = string.Empty;

            const string action   = "recordoutcome";
            var          input    = Config.SystemId + customer.UserId + Config.SecretKey + Config.Random;
            var          checksum = CryptoHelper.CalculateMd5Hash(input);

            try
            {
                //var isFinance = customer.IsFinance;
                var isEmail = customer.IsEmail;
                var isPhone = customer.IsPhone;
                var isPost  = customer.IsPost;

                var capacity = customer.Selections.Capacity.Split(',');

                var viewModel = new ResultViewModel
                {
                    id         = customer.UserId ?? "",
                    title      = customer.Title ?? "",
                    first_name = customer.FirstName ?? "",
                    surname    = customer.LastName ?? "",
                    email      = customer.Email ?? "",
                    telephone  = customer.TelephoneHome ?? "",

                    request_callback         = "false",
                    request_early_redemption = "false",

                    email_communication = isEmail ? "true" : "false",
                    phone_communication = isPhone ? "true" : "false",
                    post_communication  = isPost ? "true" : "false",

                    model_name = customer.Car.Name ?? "",
                    model_code = customer.Car.Code ?? "",

                    price_range = customer.Selections.PriceRange ?? "",
                    economy     = customer.Selections.Economy ?? "",
                    luggage     = customer.Selections.Luggage ?? "",

                    awd = customer.Selections.Options.AWD,
                    dt  = customer.Selections.Options.DT,
                    hp  = customer.Selections.Options.HP,
                    tp  = customer.Selections.Options.TP,

                    performance = customer.Selections.Performance,
                    capacity    = capacity.CountCharacterFrequency(0),
                    use         = customer.Selections.Use
                };

                var json = JsonConvert.SerializeObject(viewModel);
                requestUrl =
                    string.Format(
                        Config.HostUrl +
                        "&checksum={0}&system_id={1}&action={2}&de_id={3}&random={4}&outcome={5}&type=json", checksum,
                        Config.SystemId, action, customer.UserId, Config.Random, json);

                Log.Info("Request URL:" + requestUrl);

                var response = HttpWebRequestHelper.MakeRequest(requestUrl, 5000);
                var data     = HttpWebRequestHelper.GetHttpWebResponseData(response);

                dynamic obj = JsonConvert.DeserializeObject(data);
                if (obj["Error"] != null)
                {
                    var error        = obj["Error"];
                    var responseCode = (Common.Enums.eMasterResponseCode)error;
                    var type         = typeof(Common.Enums.eMasterResponseCode);
                    var member       = type.GetMember(responseCode.ToString());
                    var attributes   = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    var description  = ((DescriptionAttribute)attributes[0]).Description;

                    Log.Error("eMaster recordoutcome method - " + description);
                }
                else
                {
                    Log.Info(obj.ToString());
                    isComplete = true;
                }
                return(isComplete);
            }
            catch (Exception ex)
            {
                Log.Error("EMaster Provider - " + ex.Message);
                return(isComplete);
            }
        }
示例#4
0
        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));
        }
示例#5
0
        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));
        }
示例#6
0
        public bool SendData(Customer customer, out string requestUrl)
        {
            var isComplete = false;

            requestUrl = string.Empty;
            try
            {
                var capacity = customer.Selections.Capacity.Split(',');

                var result = new GRGViewModel
                {
                    model   = customer.Car.Code ?? "",
                    luggage = customer.Selections.Luggage ?? "",

                    awd = Convert.ToBoolean(customer.Selections.Options.AWD) ? "Yes" : "No",
                    dt  = Convert.ToBoolean(customer.Selections.Options.DT) ? "Yes" : "No",
                    hp  = Convert.ToBoolean(customer.Selections.Options.HP) ? "Yes" : "No",
                    cn  = Convert.ToBoolean(customer.Selections.Options.TP) ? "Yes" : "No",

                    price = customer.Selections.PriceRange ?? "",
                    mpg   = customer.Selections.Economy ?? "",

                    capacity = capacity.CountCharacterFrequency(0),
                    speed    = customer.Selections.Performance,
                    use      = customer.Selections.Use
                };

                var json = JsonConvert.SerializeObject(result);

                Log.Info("JSON: " + json);

                /*
                 * var url =
                 *  string.Format(
                 *      Config.GrassRootsHostUrl +
                 *      "&checksum={0}&system_id={1}&action={2}&de_id={3}&random={4}&outcome={5}&type=json", checksum,
                 *      Config.SystemId, action, customer.UserId, Config.Random, json);
                 */

                var url = new Uri(Config.GrassRootsHostUrl)
                          .AddParameter("application", Config.GrassRootsAppName)
                          .AddParameter("form", Config.GrassRootsPDICode)
                          .AddParameter("brand", Config.Brand)
                          .AddParameter("title", customer.Title)
                          .AddParameter("firstname", customer.FirstName)
                          .AddParameter("surname", customer.LastName)
                          .AddParameter("email", customer.Email)
                          .AddParameter("addresstype", customer.AddressType)
                          .AddParameter("address1", customer.AddressLine1)
                          .AddParameter("address2", customer.AddressLine2)
                          .AddParameter("address3", customer.AddressLine3)
                          .AddParameter("town", customer.Town)
                          .AddParameter("postcode", customer.AddressPostcode)
                          .AddParameter("hometelephone", customer.TelephoneHome.Replace(" ", ""))
                          .AddParameter("worktelephone", customer.TelephoneWork)
                          .AddParameter("mobiletelephone", customer.TelephoneMobile)
                          .AddParameter("mobiletelephone", customer.TelephoneMobile)
                          .AddParameter("emailmarketing", customer.IsEmail ? "O" : "I")
                          .AddParameter("postmarketing", customer.IsPost ? "O" : "I")
                          .AddParameter("telephonemarketing", customer.IsPhone ? "O" : "I")
                          .AddParameter("dealer", customer.Dealer)
                          .AddParameter("model", customer.Car.Code);

                requestUrl = string.Format(url + "&comments={0}", json);

                Log.Info("Request URL:" + requestUrl);

                var data = String.Empty;
                try
                {
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                    httpWebRequest.ContentType = "text/xml";
                    httpWebRequest.Method      = "GET";
                    httpWebRequest.KeepAlive   = false;
                    httpWebRequest.Timeout     = 50000;

                    try
                    {
                        var testResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                        var response = HttpWebRequestHelper.MakeRequest(requestUrl, 5000);
                        Log.Info("Response Code: " + response.StatusCode);
                        Log.Info("Response: " + response.StatusDescription);
                        data = HttpWebRequestHelper.GetHttpWebResponseData(response);
                        Log.Info("JSON Response: " + data);
                    }
                    catch (WebException ex)
                    {
                        Log.Info("Error - " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Log.Info("Error - " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("No data received.");
                    Log.Error(ex.Message);
                    Log.Info(ex.StackTrace);
                }
                if (string.IsNullOrEmpty(data))
                {
                    return(isComplete);
                }

                dynamic obj = JsonConvert.DeserializeObject(data);
                if (obj["responsecode"] != "0")
                {
                    var error = obj["errormessage"];
                    Log.Error("GrassRoots - " + error);
                }
                else
                {
                    isComplete = true;
                }
                return(isComplete);
            }
            catch (Exception ex)
            {
                Log.Error("GrassRoots Provider - " + ex.StackTrace);
                return(isComplete);
            }
        }