public ActionResult LocationToSearch(string address)
        {
            if (!string.IsNullOrEmpty(address))
            {

                GLatLong loc = new GLatLong();
                //    loc = GeoCodingHelper.GetLatLong(address);//uncomment this

                loc.Latitude = 41.330215; //comment this
                loc.Longitude = -73.859004;//comment this

                Session["UserLocLat"] = loc.Latitude;
                Session["UserLocLong"] = loc.Longitude;
                Session["UserLoc"] = address;

                LocationsSearched ls = new LocationsSearched();
                ls.Location = address;
                ls.Latitude = Convert.ToDecimal(loc.Latitude);
                ls.Longitude = Convert.ToDecimal(loc.Longitude);
                ls.DateCreated = DateTime.Now;
                ls.UserID = WebSecurity.CurrentUserId;
                dbmeals.LocationsSearcheds.Add(ls);
                dbmeals.SaveChanges();

                SearchParam searchparam = new SearchParam();
                return RedirectToAction("Index", "Home", new RouteValueDictionary(searchparam));

            }

            return View();
        }
        public RedirectToRouteResult RedirectPage(int userid)
        {
            string ipaddress = Request.ServerVariables["REMOTE_ADDR"];
            ipaddress = ipaddress == null ? String.Empty : ipaddress;
            ipaddress = ipaddress.Replace("\r\n", ",");
            ipaddress = ipaddress.Replace(" ", ",");
            ipaddress = ipaddress.Replace(":", "");
            string[] arripaddress = ipaddress.Split(',');
            string location = string.Empty;
            string address = String.Empty;
            if (arripaddress.Length != 0)
            {
                for (int i = 0; i <= arripaddress.Length - 1; i++)
                {
                    if (arripaddress[i] != "")
                    {
                        // check if the IP address is supported in demo version
                        long ipno = IP2Decimal(arripaddress[i]);
                        if ((ipno > 0) || (ipno < 33554431))
                        {
                            SqlDataReader reader;
                            // select MS-SQL database using DSNless connection
                            SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                            // query string to lookup the country by matching the range of IP address number
                            SqlCommand sqlCmd = new SqlCommand("SELECT TOP 1 * FROM ip2location_db3_ipv6 WHERE " + ipno.ToString() + " <= ip_to ORDER BY ip_to", sqlConn);
                            sqlCmd.Connection.Open();
                            // execute the query
                            reader = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                            // display results
                            if (reader.Read())
                            {
                                location = Convert.ToString(reader["city_name"]);
                                address = Convert.ToString(reader["city_name"]) + "," + Convert.ToString(reader["region_name"]) + "," + Convert.ToString(reader["country_name"]);

                                //Response.Write("<tr>");
                                //Response.Write("<td align=center>" + arripaddress[i] + "</td>");
                                //Response.Write("<td align=center>" + reader.GetString(0) + "</td>");
                                //Response.Write("<td align=center>" + reader.GetString(1) + "</td>");
                                //Response.Write("</tr>");
                            }
                            sqlCmd.Connection.Close();
                        }
                    }
                }
            }
            var user = db.UserProfiles.Where(x => x.UserId.Equals(userid)).First();
            Session["FirstName"] = user.FirstName;
            LocationsSearched ls = new LocationsSearched();
            ls = dbmeals.LocationsSearcheds.Where(x => x.UserID.Equals(userid)).OrderByDescending(y => y.DateCreated).FirstOrDefault();
            if (ls != null)
            {
                Session["UserLoc"] = ls.Location;
                Session["UserLocLat"] = Convert.ToDouble(ls.Latitude);
                Session["UserLocLong"] = Convert.ToDouble(ls.Longitude);
            }
            else
            {
                if (!string.IsNullOrEmpty(location))
                {
                    Session["UserLoc"] = location;

                    GLatLong latlng = GetLatLng(address);
                    Session["UserLocLat"] = (decimal)latlng.Latitude;
                    Session["UserLocLong"] = (decimal)latlng.Longitude;
                }
                else
                {
                    return RedirectToAction("LocationToSearch", "Home", null);
                }
            }

            if (Session["UserLoc"] == null)
            {

                UserDetail userdetail = new UserDetail();
                userdetail = dbmeals.UserDetails.Where(x => x.UserId.Equals(userid)).FirstOrDefault();
                if (userdetail != null)
                {
                    Session["UserLoc"] = Common.GetFullAddress(userdetail.AddressList);
                    Session["UserLocLat"] = Convert.ToDouble(userdetail.AddressList.Latitude);
                    Session["UserLocLong"] = Convert.ToDouble(userdetail.AddressList.Longitude);
                }
                else
                    Session["UserLoc"] = null;

                if (Session["UserLocLat"] == null)
                    return RedirectToAction("LocationToSearch", "Home", null);

            }
            SearchParam searchparam = new SearchParam();
            return RedirectToAction("Index", "Home", new RouteValueDictionary(searchparam));
        }
        public ActionResult Index(SearchParam parameters)
        {
            if (TempData["ErrorMessage"] != null)
            {
                ViewBag.ErrorMessage = TempData["ErrorMessage"];
            }
            else
            {
                ViewBag.ErrorMessage = "";
            }
            var ChangeLocation = HttpContext.Request.QueryString["ChangeLocation"];

            if ((ChangeLocation != null) && (ChangeLocation != ""))
            {

                GLatLong loc = new GLatLong();
                loc = GeoCodingHelper.GetLatLong(ChangeLocation.ToString());

                if (loc != null)
                {
                    Session["UserLocLat"] = loc.Latitude;
                    Session["UserLocLong"] = loc.Longitude;
                }
                Session["UserLoc"] = ChangeLocation;
            }
            else
            {
                var LocationsSearched = dbmeals.LocationsSearcheds.Where(x => x.UserID == WebSecurity.CurrentUserId).OrderByDescending(x => x.DateCreated).ToList().FirstOrDefault();
                if (LocationsSearched != null)
                {
                    Session["UserLoc"] = LocationsSearched.Location;
                    parameters.FreeSearch = LocationsSearched.Keywords;
                    Session["UserLocLat"] = LocationsSearched.Latitude;
                    Session["UserLocLong"] = LocationsSearched.Longitude;
                    parameters.DistanceSearch = LocationsSearched.Distance.HasValue ? LocationsSearched.Distance.Value.ToString() : string.Empty;
                    parameters.PickUpDateSearch = Common.AbsoluteEnd(LocationsSearched.DateRangeStart.HasValue ? LocationsSearched.DateRangeStart.Value : DateTime.Now);// LocationsSearched.DateRangeStart;
                    //parameters.DateRangeEnd = LocationsSearched.DateRangeEnd;
                }
            }

            if (String.IsNullOrEmpty(parameters.DistanceSearch))
                parameters.DistanceSearch = "100";

            if (parameters.PickUpDateSearch == null)
                parameters.PickUpDateSearch = DateTime.Now;

            string pointofreference = Session["UserLocLat"] + "," + Session["UserLocLong"];

            LocationsSearched ls = new LocationsSearched();
            ls.Location = Convert.ToString(Session["UserLoc"]);//.ToString();
            ls.Keywords = parameters.FreeSearch;
            ls.Latitude = Convert.ToDecimal(Session["UserLocLat"]);
            ls.Longitude = Convert.ToDecimal(Session["UserLocLong"]);
            ls.DateRangeStart = Common.AbsoluteStart(parameters.PickUpDateSearch);
            ls.DateRangeEnd = Common.AbsoluteEnd(parameters.PickUpDateSearch);
            ls.Distance = Convert.ToInt32(parameters.DistanceSearch);
            ls.DistanceUnit = "km";
            ls.DateCreated = DateTime.Now;
            ls.UserID = WebSecurity.CurrentUserId;
            try
            {
                dbmeals.LocationsSearcheds.Add(ls);
                dbmeals.SaveChanges();
            }
            catch (Exception e)
            {

                string message = e.Message;
            }
            try
            {

                ICollection<ISolrFacetQuery> list =
                AllFacetFields.Except(SelectedFacetFields(parameters)).
            Select(f => new SolrFacetFieldQuery(f) { MinCount = 1 })
            .Cast<ISolrFacetQuery>().ToList();

                var start = (parameters.PageIndex - 1) * parameters.PageSize;

                var matchingProducts = solr.Query(BuildQuery(parameters), new QueryOptions
                {
                    FilterQueries = BuildFilterQueries(parameters),
                    Rows = parameters.PageSize,
                    Start = start,
                    OrderBy = GetSelectedSort(parameters),
                    SpellCheck = new SpellCheckingParameters(),
                    Facet = new FacetParameters
                    {
                        Queries = list

                    },

                    ExtraParams = new Dictionary<string, string>
                                          {
                                              // uncomment for filtering by distance
                                              {"fq", "{!geofilt}"},
                                              {"d", parameters.DistanceSearch},// distance.ToString(CultureInfo.InvariantCulture)} replace distance with your radius filter
                                              {"sfield", "latlng"}, // replace lat_long with your field in solr that stores the lat long values
                                              {"pt", pointofreference},// this is the point of reference
                                             // {"sort","geodist() asc"},
                                               {"fl","*,Distance:geodist()"},

                                          }

                });

                var distancemodel = new DistanceViewModel();

                // var matchingProducts

                var ProductModel = new ProductView
                {
                    WholeSet = matchingProducts,
                    Search = parameters,
                    TotalCount = matchingProducts.NumFound,
                    Facets = matchingProducts.FacetFields,
                    //  PickUpTimeFacet = GetPickUpTimeFacet(matchingProducts.FacetQueries),
                    // DistanceFacet = GetDistanceFacet(matchingProducts.FacetQueries),
                    DidYouMean = GetSpellCheckingResult(matchingProducts),
                    //DistanceLimitList.SelectedDistance = parameters.DistanceLimit

                };

                // Preselect the option with Value = "US"
                // Make sure you have such option in the Countries list

                List<SolrResultSet> SolrResultSetList = new List<SolrResultSet>();
                SolrResultSetList = (from n in ProductModel.WholeSet
                                     select n).ToList();

                var ProductViewModel = new ResultSetViewModel();
                ProductViewModel.Search = ProductModel.Search;
                ProductViewModel.TotalCount = ProductModel.TotalCount;
                ProductViewModel.Facets = ProductModel.Facets;
                ProductViewModel.DidYouMean = ProductModel.DidYouMean;
                ProductViewModel.ProviderList = (from n in SolrResultSetList
                                                 group n by new
                                                 {
                                                     n.ProviderName,
                                                     n.ProviderType
                                                     ,
                                                     n.Distance,
                                                     n.latlng,
                                                     n.PhoneNumber,
                                                     n.FullAddress,
                                                     n.Cuisine
                                                 } into g
                                                 select new Provider()
                                                 {
                                                     ProviderName = g.Key.ProviderName,
                                                     ProviderType = g.Key.ProviderType,
                                                     Distance = g.Key.Distance,
                                                     latlng = g.Key.latlng,
                                                     PhoneNumber = g.Key.PhoneNumber,
                                                     FullAddress = g.Key.FullAddress,
                                                     Cuisine = g.Key.Cuisine,
                                                 }).ToList();

                foreach (Provider p in ProductViewModel.ProviderList)
                {

                    p.Products = (from n in SolrResultSetList
                                  where n.ProviderName == p.ProviderName
                                  select new Product()

                                      {
                                          MealAdID = n.MealAdID,
                                          MealItemName = n.MealItemName,
                                          FoodType = n.FoodType,
                                          MealType = n.MealType,
                                          Price = n.Price,
                                          Ingredients = n.Ingredients,
                                          AllergenicIngredients = n.AllergenicIngredients,
                                          Timestamp = n.Timestamp,
                                          Description = n.Description

                                      }).ToList();
                }

                distancemodel.SelectedDistanceLimit = parameters.DistanceSearch;
                ProductViewModel.DistanceDD = distancemodel;

                return View(ProductViewModel);

            }
            catch (SolrConnectionException e)
            {

                string msg = e.Message;
                return View(new ResultSetViewModel
                {
                    QueryError = true,
                });

            }
        }