public ActionResult GetThumb(int id) { // if the image id is not = to -1 then there is a real image if (id != -1) { int imageId = id; // retrieve image from database CoreysListEntities db = new CoreysListEntities(); CoreysList.Entity.Image image = db.Images.FirstOrDefault(i => i.ImageID == imageId); // convert image data to byte array byte[] buffer = image.ThumbContent; // return byte[](content), type of image, image filename return(File(buffer, image.ImageType, image.FileName)); } else { // return path to default image var dir = Server.MapPath("/Content/Images/defaultListingThumb.gif"); var path = Path.Combine(dir); return(base.File(path, "image/gif")); } }
// Constructor that excepts search result public DisplaySearchResultsViewModel(string searchTerm) { CoreysListEntities db = new CoreysListEntities(); // populate properties this.SearchTerm = searchTerm; this.Listings = db.Listings.Where(l => l.Headline.Contains(searchTerm) || l.Description.Contains(searchTerm)).ToList(); // instantiate lists of selectlistitems List <State> allStates = db.States.ToList(); States = new List <SelectListItem>(); Cities = new List <SelectListItem>(); // assign values to slider filter PriceMaxFilter = 100000; PriceMinFilter = 0; // convert all the states into selectlistitems foreach (State s in allStates) { SelectListItem castState = new SelectListItem(); castState.Text = s.StateName; castState.Value = s.StateID.ToString(); States.Add(castState); } }
// called to populate sub select list for states public ActionResult GetCities(int stateId) { CoreysListEntities db = new CoreysListEntities(); try { // get a list of cities where state id matches List <City> cities = db.Cities.Where(s => s.StateID == stateId) .OrderBy(s => s.CityName).ToList(); // create string builder to hold markup for new select list StringBuilder sb = new StringBuilder(); // add default selectlist item to stringbuilder sb.Append("<option value = '0'>Please select an item</option>"); // for each city with matching state id append markup to stringbuilder foreach (City city in cities) { sb.Append("<option value = '" + city.CityID.ToString() + "'>" + city.CityName + "</option>"); } // return new stringbuilder appended content using json return(Json(new { Success = true, SelectOptionsHtml = sb.ToString() }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(Json(new { Success = false, Error = "Activation or Deactivation Failed: " + e.Message }, JsonRequestBehavior.AllowGet)); } }
// Called when the user submits the apply filters form to the view listings page public ActionResult ApplyListingsFilters(ViewListingsViewModel model) { CoreysListEntities db = new CoreysListEntities(); // check filters if (model.HasImageFilter == true && model.PostedTodayFilter == true) { model.Listings = db.Listings.Where(l => l.CreatedDate == DateTime.Now && l.Images.Count() > 0 && l.CityID == model.CityId && l.SubCategoryID == model.SubCatId).ToList(); } else if (model.PostedTodayFilter == true) { model.Listings = db.Listings.Where(l => l.CreatedDate == DateTime.Now && l.CityID == model.CityId && l.SubCategoryID == model.SubCatId).ToList(); } else if (model.HasImageFilter == true) { model.Listings = db.Listings.Where(l => l.Images.Count() > 0 && l.CityID == model.CityId && l.SubCategoryID == model.SubCatId).ToList(); } else { model.Listings = db.Listings.Where(l => l.CityID == model.CityId && l.SubCategoryID == model.SubCatId).ToList(); } // return the filtered listings return(View("ViewListings", model)); }
// called when the user wants to activate or deactivate a listing public ActionResult ListingActivation(int listingId) { // establish connection to database CoreysListEntities db = new CoreysListEntities(); // create variable to get the current activation status string activationStatus; // get the selected listing to update Listing listing = db.Listings.FirstOrDefault(l => l.ListingID == listingId); try { // change the active listing status listing.IsActive = listing.IsActive ? false : true; // save the changes db.SaveChanges(); // get the new activation status activationStatus = listing.IsActive ? "active" : "notActive"; // return json with the new status return(Json(new { Success = true, ActivationStatus = activationStatus })); } catch (Exception e) { // if there was a problem with the return send error return(Json(new { Success = false, Error = "Activation or Deactivation Failed: " + e.Message })); } }
// Called when a user selects category in cascading select list to populate subcategory select list public ActionResult GetSubCategories(int categoryId) { CoreysListEntities db = new CoreysListEntities(); try { // get a list of subcategories where category Id matches selected category ID List <SubCategory> subcategories = db.SubCategories.Where(s => s.CategoryID == categoryId) .OrderBy(s => s.SubCategoryName).ToList(); // create a string builder and add the new markup for subcategory selectlist StringBuilder sb = new StringBuilder(); // append first default select list item sb.Append("<option value = '0'>Please select an item</option>"); // append a new selectlist item for each subcategory foreach (SubCategory subcategory in subcategories) { sb.Append("<option value = '" + subcategory.SubCategoryID.ToString() + "'>" + subcategory.SubCategoryName + "</option>"); } // return the stringbuilders appended string in json return(Json(new { Success = true, SelectOptionsHtml = sb.ToString() }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(Json(new { Success = false, Error = "Activation or Deactivation Failed: " + e.Message }, JsonRequestBehavior.AllowGet)); } }
// constructor for the model public StateSelectorViewModel(int stateId) { // Get the selected state and the cites that belong to it CoreysListEntities db = new CoreysListEntities(); this.Cities = db.Cities.Where(c => c.StateID == stateId).ToList(); this.StateName = db.States.FirstOrDefault(s => s.StateID == stateId).StateName; }
public ActionResult AccountUpdate() { // gets the current users info using userid stored in session and returns the user CoreysListEntities db = new CoreysListEntities(); int userId = Convert.ToInt32(Session["UserId"]); User user = db.Users.FirstOrDefault(u => u.UserID == userId); return(View("AccountUpdate", user)); }
public DisplayListingViewModel(int listingId) { CoreysListEntities db = new CoreysListEntities(); // populate the listing being displayed ListingToDisplay = db.Listings.FirstOrDefault(l => l.ListingID == listingId); SubCatId = ListingToDisplay.SubCategoryID; CityId = ListingToDisplay.CityID; }
// constructor for the model public LocatorViewModel() { // populate properties for page layout CoreysListEntities db = new CoreysListEntities(); this.States1 = db.States.Where(c => c.StateID <= 120).OrderBy(c => c.StateName).ToList(); this.States2 = db.States.Where(c => c.StateID > 120 && c.StateID <= 133).OrderBy(c => c.StateName).ToList(); this.States3 = db.States.Where(c => c.StateID > 133 && c.StateID <= 146).OrderBy(c => c.StateName).ToList(); this.States4 = db.States.Where(c => c.StateID > 146).OrderBy(c => c.StateName).ToList(); }
public ViewListingsViewModel(int cityId, int subCategoryId) { // populate the properties to display the listings CoreysListEntities db = new CoreysListEntities(); this.Listings = db.Listings.Where(l => l.CityID == cityId && l.SubCategoryID == subCategoryId).ToList(); this.SubCatHeader = db.SubCategories.FirstOrDefault(s => s.SubCategoryID == subCategoryId).SubCategoryName; this.SubCatId = subCategoryId; this.CityName = db.Cities.FirstOrDefault(c => c.CityID == cityId).CityName; this.CityId = cityId; this.TabId = 0; }
public EditListingImagesViewModel(int listingId) { // check to make sure user is logged in if (System.Web.HttpContext.Current.Session["UserId"] != null) { CoreysListEntities db = new CoreysListEntities(); // retrieve the image ids matching the listing id ImageIds = db.Images.Where(i => i.ListingID == listingId).Select(i => i.ImageID).ToList(); ListingId = listingId; } }
public ActionResult EditListing(EditListingViewModel model) { CoreysListEntities db = new CoreysListEntities(); try { // if the listing ID is -1 then it is a new listing if (model.Listing.ListingID == -1) { // add new listing Listing listing = new Listing(); listing.CityID = model.Listing.CityID; listing.UserID = Convert.ToInt32(Session["UserId"]); listing.SubCategoryID = model.Listing.SubCategoryID; listing.Headline = model.Listing.Headline; listing.Location = model.Listing.Location; listing.Description = model.Listing.Description; listing.Price = model.Listing.Price; listing.CreatedBy = "corey"; listing.CreatedDate = DateTime.Now; db.Listings.Add(listing); db.SaveChanges(); } else { // get the listing being edited Listing listing = db.Listings.FirstOrDefault(l => l.ListingID == model.Listing.ListingID); // update all the fields and save listing.CityID = model.Listing.CityID; listing.UserID = Convert.ToInt32(Session["UserId"]); listing.SubCategoryID = model.Listing.SubCategoryID; listing.Headline = model.Listing.Headline; listing.Location = model.Listing.Location; listing.Description = model.Listing.Description; listing.Price = model.Listing.Price; listing.ModifiedBy = listing.User.Email; listing.ModifiedDate = DateTime.Now; db.SaveChanges(); } } catch (Exception e) { throw e; } // return success and handle navigation in jquery return(Json(new { Success = true }, JsonRequestBehavior.AllowGet)); }
// constructor for the model public HomeIndexViewModel(int cityId) { CoreysListEntities db = new CoreysListEntities(); // populate properties for page layout this.Categories1 = db.Categories.Where(c => c.CategoryID <= 3).OrderBy(c => c.CategoryName).ToList(); this.Categories2 = db.Categories.Where(c => c.CategoryID > 3 && c.CategoryID <= 6).OrderBy(c => c.CategoryName).ToList(); this.Categories3 = db.Categories.Where(c => c.CategoryID > 6).OrderBy(c => c.CategoryName).ToList(); this.States = db.States.OrderBy(s => s.StateName).ToList(); this.TopCities = db.Cities.Where(c => c.MajorCity == true).OrderBy(c => c.CityName).ToList(); this.CityName = db.Cities.Where(c => c.CityID == cityId).FirstOrDefault().CityName; this.CityId = cityId; this.SearchTerm = ""; }
// when the user submits signup public ActionResult Create_Account(LoginViewModel model) { // establish connection to database CoreysListEntities db = new CoreysListEntities(); try { // Checking to see if the email entered already exist in database User testUser = db.Users.FirstOrDefault(u => u.Email == model.Email); // if not create and add new user if (testUser == null) { User newUser = new User(); newUser.FirstName = model.FirstName; newUser.LastName = model.LastName; newUser.Email = model.Email; newUser.PhoneNum = Convert.ToString(model.PhoneNumber.Replace("-", "")); newUser.Password = model.Password; newUser.CreatedBy = "Corey"; newUser.CreatedDate = DateTime.Now; // save the new user to the database db.Users.Add(newUser); db.SaveChanges(); // set the new users information in session variables Session["UserId"] = newUser.UserID; Session["UserEmail"] = newUser.Email; // send user to homepage UserHomeViewModel userHomeModel = new UserHomeViewModel(); return(View("UserHome", userHomeModel)); } else { // else return error message informing user that email already is registered model.CreateAccountErrorMessage = "Email already in use"; return(View("Index", model)); } } catch (Exception e) { // exception connecting to database string error = e.Message; return(View("Index", model)); } }
public ActionResult FilterSearchResults(DisplaySearchResultsViewModel model) { CoreysListEntities db = new CoreysListEntities(); // get a count of the cities int cityCount = model.Cities.Count(); // populate cities dropdown with selected state List <City> citiesList = db.Cities.Where(c => c.StateID == model.SelectedStateIdFilter).ToList(); foreach (City c in citiesList) { SelectListItem newListItem = new SelectListItem(); newListItem.Text = c.CityName; newListItem.Value = c.CityID.ToString(); model.Cities.Add(newListItem); } // first pull all the listings that still match the search term model.Listings = db.Listings.Where(l => l.Headline.Contains(model.SearchTerm) || l.Description.Contains(model.SearchTerm)).ToList(); // if a city was selected if (model.SelectedCityIdFilter > 0) { model.Listings = model.Listings.Where(l => l.CityID == model.SelectedCityIdFilter && l.Price >= model.PriceMinFilter && l.Price <= model.PriceMaxFilter).ToList(); } else if (model.SelectedStateIdFilter > 0) { // else if state was selected but no city model.Listings = model.Listings.Where(l => l.City.StateID == model.SelectedStateIdFilter && l.Price >= model.PriceMinFilter && l.Price <= model.PriceMaxFilter).ToList(); } else { // else just apply price range model.Listings = model.Listings.Where(l => l.Price >= model.PriceMinFilter && l.Price <= model.PriceMaxFilter).ToList(); } // return filtered model with view return(View("DisplaySearchResults", model)); }
// constructor for the model public UserHomeViewModel(int tabId = 0) { CoreysListEntities db = new CoreysListEntities(); // check to ensure user is logged in if (System.Web.HttpContext.Current.Session["UserId"] != null) { // populate the listings containing their id int userId = Convert.ToInt32(System.Web.HttpContext.Current.Session["UserId"]); User user = db.Users.FirstOrDefault(u => u.UserID == userId); UserName = user.FirstName + " " + user.LastName; AllUserListings = user.Listings.ToList(); ActiveUserListings = user.Listings.Where(u => u.IsActive == true).ToList(); InactiveUserListings = user.Listings.Where(u => u.IsActive == false).ToList(); TabId = tabId; } }
// called when user clicks delete linke in editImages partial public ActionResult Delete(int id) { CoreysListEntities db = new CoreysListEntities(); // get reference to image CoreysList.Entity.Image imgToDelete = db.Images.FirstOrDefault(i => i.ImageID == id); // get the listing associated with the image int listingId = imgToDelete.ListingID; // remove row from table and save db.Images.Remove(imgToDelete); db.SaveChanges(); // return partial EditListingImagesViewModel editListingImagesViewModel = new EditListingImagesViewModel(listingId); return(PartialView("~/views/Accounts/_EditListingImages.cshtml", editListingImagesViewModel)); }
static void Main(string[] args) { //connect to databas CoreysListEntities db = new CoreysListEntities(); //get all cities List <City> allCities = db.Cities.OrderBy(c => c.CityName).ToList(); //create a counter to track when to sleep thread due to api calls limit per sec int counter = 0; //for each city foreach (City c in allCities) { //if api call = 5 sleep the thread if (counter == 5) { Console.WriteLine(); Console.WriteLine("---Waiting on API------"); Console.WriteLine(); System.Threading.Thread.Sleep(5000); counter = 0; } //call the get postal code function string postalCode = GetPostalCode(c.CityName.Trim(), c.State.StateName); //get a reference for the correct city to update City updateCity = db.Cities.FirstOrDefault(u => u.CityID == c.CityID); //set the new value updateCity.PostalCode = postalCode; //save db.SaveChanges(); Console.WriteLine(c.CityName + " " + c.State.StateName + ": " + postalCode + " Record Updated"); counter++; } //pause application Console.WriteLine(); Console.WriteLine("Updates Finished....."); Console.ReadLine(); }
public ActionResult AccountUpdate(User updatedUserInfo) { // get the user from the database and update thier information CoreysListEntities db = new CoreysListEntities(); User user = db.Users.FirstOrDefault(u => u.UserID == updatedUserInfo.UserID); user.PhoneNum = updatedUserInfo.PhoneNum; user.FirstName = updatedUserInfo.FirstName; user.LastName = updatedUserInfo.LastName; user.Password = updatedUserInfo.Password; // save the changes made to the user db.SaveChanges(); // send the user to their homepage UserHomeViewModel userHomeModel = new UserHomeViewModel(); return(View("UserHome", userHomeModel)); }
// constructor for the model public DisplaySearchResultsViewModel() { CoreysListEntities db = new CoreysListEntities(); // get all the states List <State> allStates = db.States.ToList(); // instantiate lists of selectlistitems States = new List <SelectListItem>(); Cities = new List <SelectListItem>(); // convert all the states into selectlistitems foreach (State s in allStates) { SelectListItem castState = new SelectListItem(); castState.Text = s.StateName; castState.Value = s.StateID.ToString(); States.Add(castState); } }
public ActionResult GetCitiesByStateId(int stateid) { CoreysListEntities db = new CoreysListEntities(); // retreive the cities matching the state id List <City> cities = new List <City>(); cities = db.Cities.Where(m => m.StateID == stateid).ToList(); // create a stringbuilder and append the mark up for each city to add selectlist items StringBuilder sb = new StringBuilder(); sb.Append("<option value = '0'>-- Select City --</option>"); foreach (City city in cities) { sb.Append("<option value = '" + city.CityID.ToString() + "'>" + city.CityName + "</option>"); } // return the stringbuilder appended content via json return(Json(new { Success = true, SelectOptionsHtml = sb.ToString() }, JsonRequestBehavior.AllowGet)); }
// called when a user uploads images recieving the listing id public ActionResult Upload(int id) { int listingId = id; CoreysListEntities db = new CoreysListEntities(); // for each of the requested files for (int i = 0; i < Request.Files.Count; i++) { try { // create a new [image] CoreysList.Entity.Image newImage = new CoreysList.Entity.Image(); // Uploaded file HttpPostedFileBase file = Request.Files[i]; // Get the size of the file newImage.ImageSize = file.ContentLength; // get the file name newImage.FileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1); // get the type of file .jpg .gif .png etc.. newImage.ImageType = file.ContentType; // create a new byte array to fit the content size byte[] imageData = new byte[file.ContentLength]; // read in the file withe the byte array and content size file.InputStream.Read(imageData, 0, (int)file.ContentLength); // reposition the input stream to the beginning file.InputStream.Position = 0; // stream the file again into a System.Drawing.Image System.Drawing.Image sysImg = System.Drawing.Image.FromStream(file.InputStream); // assign the sizes from system image to coreyslist image newImage.ImageHeight = sysImg.Height; newImage.ImageWidth = sysImg.Width; newImage.ImageContent = imageData; // create encoding object to send image type ImageEncoding imgResizerEnc = new ImageEncoding(); // set the values for thumb images int thumbHeight = 75; int thumbWidth = 75; // switch statement to get the content type switch (file.ContentType) { case "image/jpeg": imgResizerEnc = ImageEncoding.Jpg90; break; case "image/gif": imgResizerEnc = ImageEncoding.Gif; break; case "image/png": imgResizerEnc = ImageEncoding.Png; break; } // create a resizer and send the image content ImageResizer resizer = new ImageResizer(imageData); // call the resizer method along with the desired height, width and img type byte[] thumbData = resizer.Resize(thumbHeight, thumbWidth, imgResizerEnc); // save the new thumb data for the coreyslist image entity newImage.ThumbContent = thumbData; newImage.ThumbSize = thumbData.Length; newImage.ThumbWidth = thumbWidth; newImage.ThumbHeight = thumbHeight; // connect image to the correct listing through listing ID newImage.ListingID = listingId; newImage.CreatedDate = DateTime.Now; newImage.CreatedBy = System.Web.HttpContext.Current.Session["UserId"].ToString(); // To save file, use SaveAs method db.Images.Add(newImage); db.SaveChanges(); } catch (Exception e) { throw e; } } // Return partial view EditListingImagesViewModel editListingImagesViewModel = new EditListingImagesViewModel(listingId); return(PartialView("~/views/Accounts/_EditListingImages.cshtml", editListingImagesViewModel)); }
public EditListingViewModel(int listingId) { // check to make sure user is logged in if (System.Web.HttpContext.Current.Session["UserId"] != null) { CoreysListEntities db = new CoreysListEntities(); // instantiate lists of selectlistitems this.States = new List <SelectListItem>(); this.Categories = new List <SelectListItem>(); this.Subcategories = new List <SelectListItem>(); this.Cities = new List <SelectListItem>(); // if the listing is a new listing if (listingId == -1) { // create the new listing this.Listing = new Listing(); this.Listing.ListingID = -1; // populate states property for dropdown list List <State> states = db.States.OrderBy(c => c.StateName).ToList(); // add default value SelectListItem stateItem1 = new SelectListItem { Text = "Select a State", Value = "" }; this.States.Add(stateItem1); // convert the rest of the states into select list items and add them to list foreach (State state in states) { SelectListItem stateItem = new SelectListItem { Text = state.StateName, Value = state.StateID.ToString() }; this.States.Add(stateItem); } // get all the categories List <Category> categories = db.Categories.OrderBy(c => c.CategoryName).ToList(); // add default item to select list SelectListItem categoryItem1 = new SelectListItem { Text = "Select a Category", Value = "" }; this.Categories.Add(categoryItem1); // convert all the categories to select list items and add them to selectlist foreach (Category category in categories) { SelectListItem categoryItem = new SelectListItem { Text = category.CategoryName, Value = category.CategoryID.ToString() }; this.Categories.Add(categoryItem); } } else { // Else listing is existing and get the current listing this.Listing = db.Listings.FirstOrDefault(l => l.ListingID == listingId); // get all the states List <State> states = db.States.OrderBy(c => c.StateName).ToList(); // for each state foreach (State state in states) { // check to see if the state is the current state for the listing bool selected = Listing.City.StateID == state.StateID ? true : false; // convert to select list item and add selected attribute if true SelectListItem stateItem = new SelectListItem { Text = state.StateName, Value = state.StateID.ToString(), Selected = selected }; this.States.Add(stateItem); } // get all the cities where belonging to selected state List <City> cities = db.Cities.Where(c => c.StateID == this.Listing.City.StateID).OrderBy(c => c.CityName).ToList(); foreach (City city in cities) { // check if the city is the current city for the listing bool selected = Listing.CityID == city.CityID ? true : false; // convert to selectlist item and set selected attribute SelectListItem cityItem = new SelectListItem { Text = city.CityName, Value = city.CityID.ToString(), Selected = selected }; this.Cities.Add(cityItem); } // get all the categories List <Category> categories = db.Categories.OrderBy(c => c.CategoryName).ToList(); foreach (Category category in categories) { // check if category is the current category for the selected listing bool selected = Listing.SubCategory.CategoryID == category.CategoryID ? true : false; // convert to select list item and set selected attribte SelectListItem categoryItem = new SelectListItem { Text = category.CategoryName, Value = category.CategoryID.ToString(), Selected = selected }; this.Categories.Add(categoryItem); } // get a list of subcategories belonging to the selected category List <SubCategory> subcategories = db.SubCategories.Where(s => s.CategoryID == this.Listing.SubCategory.CategoryID).OrderBy(s => s.SubCategoryName).ToList(); foreach (SubCategory subcategory in subcategories) { // check to see if the subcategory is the current for the listing bool selected = Listing.SubCategoryID == subcategory.SubCategoryID ? true : false; // convert to select list item and set selected attribute SelectListItem subcategoryItem = new SelectListItem { Text = subcategory.SubCategoryName, Value = subcategory.SubCategoryID.ToString(), Selected = selected }; this.Subcategories.Add(subcategoryItem); } } } }