Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- html {
- margin: 0;
- padding: 0;
- }
- h2 {
- position: center
- }
- .full-width-image {
- height: auto;
- background: url("containerimage.jpg") no-repeat center center fixed;
- background-size: cover;
- }
- .jumbotron {
- border-radius: 0 !important;
- background: rgba(204, 204, 204, 0.9);
- }
- .container-fluid {
- padding-top: 15px;
- padding-bottom: 15px;
- background-color: #F5F5F5;
- }
- body {
- /*"background: url('') no-repeat center center fixed;*/
- background-color: whitesmoke;
- -webkit-background-size: cover;
- -moz-background-size: cover;
- background-size: cover;
- -o-background-size: cover;
- background-size: cover;
- border-top: solid 0px #000;
- color: #333;
- /*font-family: 'Roboto', sans-serif;*/
- font-family: 'Roboto Slab', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
- margin: 0;
- padding: 0;
- }
- .push {
- height: 50px; /* we push down the footer */
- }
- header, footer, hgroup,
- nav, section {
- display: block;
- }
- footer {
- clear: both;
- background-color: #e2e2e2;
- font-size: .8em;
- height: 20px;
- width: 100%;
- position: fixed;
- bottom: 0;
- padding-right: 10px;
- text-align: right;
- }
- /* menu ----------------------------------------------------------*/
- ul#menu {
- font-size: 1.3em;
- font-weight: 600;
- margin: 0 0 5px;
- padding: 0;
- text-align: right;
- }
- ul#menu li {
- display: inline;
- list-style: none;
- padding-left: 15px;
- }
- ul#menu li a {
- background: none;
- color: #007bff;
- text-decoration: none;
- }
- ul#menu li a:hover {
- color: black;
- text-decoration: none;
- }
- /* DataTables modification for BootStrap 4 */
- table.dataTable thead .sorting:after,
- table.dataTable thead .sorting_asc:after,
- table.dataTable thead .sorting_desc:after,
- table.dataTable thead .sorting_asc_disabled:after,
- table.dataTable thead .sorting_desc_disabled:after {
- font-family: 'Font Awesome 5 Free';
- }
- table.dataTable thead .sorting:after {
- content: "\f0dc";
- }
- table.dataTable thead .sorting_asc:after {
- content: "\f0de";
- }
- table.dataTable thead .sorting_desc:after {
- content: "\f0dd";
- }
- /* info and error */
- .message-info {
- border: 1px solid;
- clear: both;
- padding: 10px 20px;
- }
- .message-error {
- clear: both;
- color: #e80c4d;
- font-size: 1.1em;
- font-weight: bold;
- margin: 20px 0 10px 0;
- }
- .message-success {
- color: #7ac0da;
- font-size: 1.3em;
- font-weight: bold;
- margin: 20px 0 10px 0;
- }
- .error {
- color: #e80c4d;
- }
- .navbar-nav {
- flex-direction: row;
- font-weight: bolder;
- }
- .nav-link {
- padding-right: .5rem !important;
- padding-left: .5rem !important;
- }
- .ml-auto .dropdown-menu {
- left: auto !important;
- right: 0px;
- }
- .navbar-nav a.link {
- color: rgba(0, 0, 0, 0.5);
- text-decoration: none;
- background-color: transparent;
- padding: 0.5rem 1rem;
- }
- .navbar-nav a:hover {
- color: black;
- background-color: lightgrey;
- border-radius: 4px;
- text-decoration: none;
- }
- .navbar-nav a {
- padding: 0.3rem 0.1rem;
- }
- .nav-item a {
- color: #007bff !important;
- }
- .nav-item a:hover {
- color: black !important;
- background-color: lightgray;
- border-radius: 4px;
- text-decoration: none;
- }
- .my-small-btn {
- background-color: blue;
- width: 340px;
- border: none;
- color: white;
- padding: 16px 32px;
- text-align: center;
- font-size: 16px;
- opacity: 0.7;
- transition: 0.3s;
- }
- .my-small-btn:hover {
- opacity: 1
- }
- .dropdown-item {
- font-weight: bold;
- color: #007bff !important;
- }
- /* column delimiter */
- @media ( min-width: 768px ) {
- .grid-divider {
- position: relative;
- padding: 0;
- }
- .grid-divider > [class*='col-'] {
- position: static;
- }
- .grid-divider > [class*='col-']:nth-child(n+2):before {
- content: "";
- border-left: 1px solid #007bff;
- position: absolute;
- top: 0;
- bottom: 0;
- }
- .col-padding {
- padding: 0 15px;
- }
- }
- /**/
- .fa.k-sprite, .fa.k-sprite::before {
- font-size: 12px;
- line-height: 12px;
- }
- .dropdown-item {
- width: inherit;
- }
- .sold-car {
- text-decoration: line-through;
- color: red;
- }
- .row-clickable-light {
- background: lightgray;
- padding: 0.5rem;
- }
- .row-clickable-normal {
- background: gray;
- padding: 0.5rem;
- }
- .hide {
- display: none;
- }
- .btn-filters {
- background: black;
- padding-left: 15px;
- padding-right: 15px;
- color: white;
- }
- /* MESSAGE CSS */
- .close-click {
- cursor: pointer;
- }
- .openDiv {
- cursor: pointer;
- width: 75%;
- }
- .closeDiv {
- cursor: pointer;
- width: 75%;
- }
- .messageDiv {
- margin-top: 1rem;
- margin-bottom: 1rem;
- margin-left: 3rem;
- margin-right: 3rem;
- border-radius: 5px;
- border: 1px solid #000;
- padding-left: 1rem;
- padding-right: 1rem;
- width: 75%;
- }
- .message-reply-icon {
- margin: 3px;
- }
- /* MESSAGE CSS END */
- /*Picture*/
- #premiumCars dl {
- width: 350px;
- overflow: hidden;
- background: white;
- padding: 0;
- margin: 0;
- box-shadow: 1px 1px 2px #aaaaaa;
- border-radius: 0px;
- }
- #premiumCars dt {
- float: left;
- width: 350px;
- background: white;
- padding: 0px;
- margin: 0;
- }
- #premiumCars dd {
- float: left;
- width: 350px;
- height: auto;
- background: white;
- padding: 10px;
- margin: 0;
- text-transform: uppercase;
- color: black;
- }
- .price {
- alignment: right;
- color: red;
- font-weight: bold;
- }
- img.featured-car-img {
- width: 350px;
- height: 250px;
- border-radius: 0px;
- }
- .main-active-adverts {
- background-color: white;
- width: 70%;
- box-shadow: 55px 55px 55px 55px #000000;
- }
- body {
- padding-top: 50px;
- padding-bottom: 20px;
- }
- /* Set padding to keep content from hitting the edges */
- .body-content {
- padding-left: 5px;
- padding-right: 5px;
- }
- /* Override the default bootstrap behavior where horizontal description lists
- will truncate terms that are too long to fit in the left column
- */
- .dl-horizontal dt {
- white-space: normal;
- }
- /* Set width on the form input elements since they're 100% wide by default */
- /* ez nem kell, butaság fixen megadni a max szélességet */
- /*input,
- select,
- textarea {
- max-width: 280px;
- }*/
- using CarAdvertiser.DAL.Identity;
- using CarAdvertiser.DTO;
- using CarAdvertiser.Models;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- using Microsoft.Owin.Security;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- namespace CarAdvertiser.Controllers
- {
- [Authorize]
- public class AccountController : BaseController
- {
- public AccountController()
- {
- }
- [AllowAnonymous]
- public ActionResult Login(string returnUrl)
- {
- ViewBag.ReturnUrl = returnUrl;
- return View();
- }
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- SignInStatus result = await RepositoryAppUserV2.LoginAsync(model.Email, model.Password, model.RememberMe);
- switch (result)
- {
- case SignInStatus.Success:
- return RedirectToLocal(returnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- //return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
- case SignInStatus.Failure:
- default:
- ModelState.AddModelError("", "Invalid login attempt.");
- return View(model);
- }
- }
- //[AllowAnonymous]
- //public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
- //{
- // if (!await SignInManager.HasBeenVerifiedAsync())
- // {
- // return View("Error");
- // }
- // return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
- //}
- //[HttpPost]
- //[AllowAnonymous]
- //[ValidateAntiForgeryToken]
- //public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
- //{
- // if (!ModelState.IsValid)
- // {
- // return View(model);
- // }
- // var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
- // switch (result)
- // {
- // case SignInStatus.Success:
- // return RedirectToLocal(model.ReturnUrl);
- // case SignInStatus.LockedOut:
- // return View("Lockout");
- // case SignInStatus.Failure:
- // default:
- // ModelState.AddModelError("", "Invalid code.");
- // return View(model);
- // }
- //}
- [AllowAnonymous]
- public ActionResult Register()
- {
- return View();
- }
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Register(RegisterViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = new AppUserV2 { UserName = model.Email, Email = model.Email };
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.RegisterAsync(user, model.Password);
- if (result.Succeeded)
- {
- await RepositoryAppUserV2.SignInAsync(user, false, false);
- return RedirectToAction("Index", "Home");
- }
- AddErrors(result);
- }
- return View(model);
- }
- [AllowAnonymous]
- public async Task<ActionResult> ConfirmEmail(int userId, string code)
- {
- if (userId < 1 || string.IsNullOrEmpty(code))
- {
- return View("Error");
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.ConfirmEmailAsync(userId, code);
- return View(result.Succeeded ? "ConfirmEmail" : "Error");
- }
- [AllowAnonymous]
- public ActionResult ForgotPassword()
- {
- return View();
- }
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
- {
- if (ModelState.IsValid)
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var user = await RepositoryAppUserV2.FindByNameAsync(model.Email);
- if (user == null || !(await RepositoryAppUserV2.IsEmailConfirmedAsync(user.Id)))
- {
- return View("ForgotPasswordConfirmation");
- }
- // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
- // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
- // return RedirectToAction("ForgotPasswordConfirmation", "Account");
- }
- return View(model);
- }
- [AllowAnonymous]
- public ActionResult ForgotPasswordConfirmation()
- {
- return View();
- }
- [AllowAnonymous]
- public ActionResult ResetPassword(string code)
- {
- return code == null ? View("Error") : View();
- }
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- AppUserV2 user = await RepositoryAppUserV2.FindByNameAsync(model.Email);
- if (user == null)
- {
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- IdentityResult result = await RepositoryAppUserV2.ResetPasswordAsync(user.Id, model.Code, model.Password);
- if (result.Succeeded)
- {
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- AddErrors(result);
- return View();
- }
- [AllowAnonymous]
- public ActionResult ResetPasswordConfirmation()
- {
- return View();
- }
- //[HttpPost]
- //[AllowAnonymous]
- //[ValidateAntiForgeryToken]
- //public ActionResult ExternalLogin(string provider, string returnUrl)
- //{
- // return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
- //}
- //[AllowAnonymous]
- //public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
- //{
- // RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- // RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- // var userId = await RepositoryAppUserV2.GetVerifiedUserIdAsync();
- // if (userId == null)
- // {
- // return View("Error");
- // }
- // var userFactors = await RepositoryAppUserV2.GetValidTwoFactorProvidersAsync(userId);
- // var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
- // return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
- //}
- //[HttpPost]
- //[AllowAnonymous]
- //[ValidateAntiForgeryToken]
- //public async Task<ActionResult> SendCode(SendCodeViewModel model)
- //{
- // if (!ModelState.IsValid)
- // {
- // return View();
- // }
- // RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- // RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- // if (!await RepositoryAppUserV2.SendTwoFactorCodeAsync(model.SelectedProvider))
- // {
- // return View("Error");
- // }
- // return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
- //}
- //[AllowAnonymous]
- //public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
- //{
- // var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
- // if (loginInfo == null)
- // {
- // return RedirectToAction("Login");
- // }
- // var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
- // switch (result)
- // {
- // case SignInStatus.Success:
- // return RedirectToLocal(returnUrl);
- // case SignInStatus.LockedOut:
- // return View("Lockout");
- // case SignInStatus.RequiresVerification:
- // return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
- // case SignInStatus.Failure:
- // default:
- // ViewBag.ReturnUrl = returnUrl;
- // ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
- // return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
- // }
- //}
- //[HttpPost]
- //[AllowAnonymous]
- //[ValidateAntiForgeryToken]
- //public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
- //{
- // if (User.Identity.IsAuthenticated)
- // {
- // return RedirectToAction("Index", "Manage");
- // }
- // if (ModelState.IsValid)
- // {
- // var info = await AuthenticationManager.GetExternalLoginInfoAsync();
- // if (info == null)
- // {
- // return View("ExternalLoginFailure");
- // }
- // var user = new AppUserV2 { UserName = model.Email, Email = model.Email };
- // var result = await UserManager.CreateAsync(user);
- // if (result.Succeeded)
- // {
- // result = await UserManager.AddLoginAsync(user.Id, info.Login);
- // if (result.Succeeded)
- // {
- // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- // return RedirectToLocal(returnUrl);
- // }
- // }
- // AddErrors(result);
- // }
- // ViewBag.ReturnUrl = returnUrl;
- // return View(model);
- //}
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult LogOff()
- {
- AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
- return RedirectToAction("Index", "Home");
- }
- //[AllowAnonymous]
- //public ActionResult ExternalLoginFailure()
- //{
- // return View();
- //}
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- //if (_userManager != null)
- //{
- // _userManager.Dispose();
- // _userManager = null;
- //}
- //if (_signInManager != null)
- //{
- // _signInManager.Dispose();
- // _signInManager = null;
- //}
- RepositoryAppUserV2?.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Helpers
- private const string XsrfKey = "XsrfId";
- private IAuthenticationManager AuthenticationManager
- {
- get
- {
- return HttpContext.GetOwinContext().Authentication;
- }
- }
- private void AddErrors(IdentityResult result)
- {
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError("", error);
- }
- }
- private ActionResult RedirectToLocal(string returnUrl)
- {
- if (Url.IsLocalUrl(returnUrl))
- {
- return Redirect(returnUrl);
- }
- return RedirectToAction("Index", "Home");
- }
- internal class ChallengeResult : HttpUnauthorizedResult
- {
- public ChallengeResult(string provider, string redirectUri)
- : this(provider, redirectUri, null)
- {
- }
- public ChallengeResult(string provider, string redirectUri, string userId)
- {
- LoginProvider = provider;
- RedirectUri = redirectUri;
- UserId = userId;
- }
- public string LoginProvider { get; set; }
- public string RedirectUri { get; set; }
- public string UserId { get; set; }
- public override void ExecuteResult(ControllerContext context)
- {
- var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
- if (UserId != null)
- {
- properties.Dictionary[XsrfKey] = UserId;
- }
- context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
- }
- }
- #endregion
- }
- }
- using CarAdvertiser.DTO;
- using CarAdvertiser.DTO.ValueEntities;
- using CarAdvertiser.Helpers;
- using CarAdvertiser.Models;
- using Microsoft.AspNet.Identity;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Mail;
- using System.Web;
- using System.Web.Mvc;
- namespace CarAdvertiser.Controllers
- {
- public class AdvertController : BaseController
- {
- [HttpGet]
- [Authorize]
- public ActionResult AddAdvert()
- {
- AddAdvertViewModel model = new AddAdvertViewModel();
- FillAdvertView();
- FillCheckBoxes(model);
- return View(model);
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- [Authorize]
- public ActionResult AddAdvert(AddAdvertViewModel model, HttpPostedFileBase[] files)
- {
- TempData["error"] = null;
- TempData["success"] = null;
- if (!ModelState.IsValid)
- {
- TempData["error"] = "Please fill all mandatory fields!";
- FillAdvertView();
- model.Additionals = new List<CheckBoxList>();
- FillCheckBoxes(model);
- return View(model);
- }
- int saved = 0;
- Advertisement advert = new Advertisement
- {
- AppUserId = User.Identity.GetUserId<int>(),
- CarModelId = model.CarModelId,
- Price = model.Price,
- CurrentMileage = model.CurrentMileage,
- HorsePower = model.HorsePower,
- AmountOfPrevOwners = model.AmountOfPrevOwners,
- AdvertDescription = model.AdvertDescription,
- RegYear = model.RegYear,
- AdvertOpenDate = model.AdvertOpenDate,
- EngineSizeId = model.EngineSizeId,
- BodyTypeId = model.BodyTypeId,
- TransmissionId = model.TransmissionId,
- SeatAmountId = model.SeatAmountId,
- DriveTrainId = model.DriveTrainId,
- FuelTypeId = model.FuelTypeId,
- DoorAmountId = model.DoorAmountId,
- ColourId = model.ColourId,
- AdvertCloseDate = model.AdvertOpenDate.AddDays(model.AdvertAliveDays),
- IsPremium = model.IsPremium,
- IsSold = false,
- };
- var dates = AdvertisementService.GenerateDates(model.AdvertOpenDate,
- model.AdvertOpenDate.AddDays(model.AdvertAliveDays));
- AdvertisementService.Create(advert);
- saved++;
- foreach (DateTime date in dates)
- {
- BookingAvailabilityService.Create(new BookingAvailability
- {
- AvailableDate = date,
- AdvertId = advert.Id
- });
- saved++;
- }
- foreach (CheckBoxList addItem in model.Additionals.Where(x => x.IsChecked))
- {
- ExtrasService.Create(new CarExtras
- {
- EquipmentId = addItem.Id,
- ExtrasAdvertId = advert.Id
- });
- saved++;
- }
- foreach (HttpPostedFileBase file in files)
- {
- if (file.ContentLength > 0)
- {
- byte[] data = null;
- using (MemoryStream target = new MemoryStream())
- {
- file.InputStream.CopyTo(target);
- data = target.ToArray();
- }
- ImageService.Create(new Image
- {
- ContentType = file.ContentType,
- ImageName = file.FileName,
- ImageData = data
- });
- saved++;
- }
- }
- if (Uow.Commit() == saved)
- {
- TempData["success"] = $"Thank you! Confirmation email has been sent to your inbox";
- SmtpClient client = new SmtpClient();
- MailMessage mailMessage = new MailMessage();
- mailMessage.To.Add(User.Identity.GetUserName());
- mailMessage.Subject = "Car Advertiser";
- mailMessage.Body = $"Greetings from Car Advertiser. Your advert will be live from {model.AdvertOpenDate} and will close on {model.AdvertOpenDate.AddDays(model.AdvertAliveDays)}";
- client.Send(mailMessage);
- return RedirectToAction("AddAdvert");
- }
- TempData["error"] = $"Error Occured When Trying To Add The Advert. Please try again!";
- return View(model);
- }
- private void FillAdvertView()
- {
- ViewData["Make"] = ManufacturerService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- ViewData["Model"] = ModelService.GetAllNotDeleted(x => x.CarManufacturer).Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- ViewData["Engine"] = EngineSizeService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Size.ToString(),
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["BodyType"] = BodyTypeService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["Transmission"] = TransmissionService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["Seat"] = SeatAmountService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.NumberOfSeats.ToString(),
- Value = x.Id.ToString()
- });
- ViewData["DriveTrain"] = DriveTrainService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["FuelType"] = FuelTypeService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["Door"] = DoorService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.NumberOfDoors.ToString(),
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- ViewData["Colour"] = ColourService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- }).OrderBy(x => x.Text);
- List<SelectListItem> years = new List<SelectListItem>();
- {
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- years.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["Year"] = years.ToList().OrderByDescending(x => x.Text);
- List<SelectListItem> days = new List<SelectListItem>();
- {
- for (int i = 1; i < 31; i++)
- {
- days.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["Days"] = days.ToList();
- }
- private void FillCheckBoxes(AddAdvertViewModel model)
- {
- foreach (AdditionalEquipment item in EquipmentService.GetAllNotDeleted())
- {
- CheckBoxList newItem = new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- };
- if (model.Additionals.All(x => x.Id != newItem.Id))
- model.Additionals.Add(newItem);
- }
- }
- [HttpGet]
- [Authorize]
- public ActionResult AddWantedCar()
- {
- WantedCarViewModel wanted = new WantedCarViewModel();
- FillWantedCarView();
- return View(wanted);
- }
- [HttpPost]
- [Authorize]
- public ActionResult AddWantedCar(WantedCarViewModel wanted)
- {
- TempData["error"] = null;
- TempData["success"] = null;
- if (!ModelState.IsValid)
- {
- FillWantedCarView();
- return View(wanted);
- }
- int saved = 0;
- WantedCar wantedCar = new WantedCar
- {
- MinimumYear = wanted.MinYear,
- MaxPrice = wanted.MaxPrice,
- IsWanted = true,
- UserId = User.Identity.GetUserId<int>(),
- ModelId = wanted.Model
- };
- WantedCarService.Create(wantedCar);
- saved++;
- if (Uow.Commit() == saved)
- {
- TempData["success"] = $"Thank you! As soon as chosen car appears in our database we notify you via an email.";
- return RedirectToAction("AddWantedCar");
- }
- TempData["error"] = $"Error Occured When Trying To Add The Advert. Please try again!";
- return View(wanted);
- }
- private void FillWantedCarView()
- {
- ViewData["Make"] = ManufacturerService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- ViewData["Model"] = ModelService.GetAllNotDeleted(x => x.CarManufacturer).Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- List<SelectListItem> years = new List<SelectListItem>();
- {
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- years.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["Year"] = years.ToList().OrderByDescending(x => x.Text);
- List<SelectListItem> maxPrice = new List<SelectListItem>();
- for (int i = 0; i < 50000; i += 500)
- {
- {
- maxPrice.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["MaxPrice"] = maxPrice;
- }
- [HttpPost]
- public JsonResult GetModels(int makeId)
- {
- List<SelectListItem> result = ModelService.GetAllNotDeleted().Where(x => x.ManufacturerId == makeId).Select(
- x =>
- new SelectListItem
- {
- Value = x.Id.ToString(),
- Text = x.Value
- }).ToList();
- return Json(new SelectList(result, "Value", "Text"));
- }
- [HttpGet]
- public ActionResult AdvertSearch()
- {
- AdvertSearchViewModel result = new AdvertSearchViewModel();
- FillAdvertSearchView(result);
- return View(result);
- }
- private void FillAdvertSearchView(AdvertSearchViewModel result)
- {
- ViewData["Make"] = ManufacturerService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- List<SelectListItem> fromYear = new List<SelectListItem>();
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- fromYear.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["FromYear"] = fromYear.OrderBy(x => x.Text);
- List<SelectListItem> toYear = new List<SelectListItem>();
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- toYear.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["ToYear"] = toYear.OrderByDescending(x => x.Text);
- List<SelectListItem> minPrice = new List<SelectListItem>();
- for (int i = 0; i < 50000; i += 500)
- {
- minPrice.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["MinPrice"] = minPrice;
- List<SelectListItem> maxPrice = new List<SelectListItem>();
- for (int i = 0; i < 50000; i += 500)
- {
- {
- maxPrice.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["MaxPrice"] = maxPrice;
- List<SelectListItem> maxMileage = new List<SelectListItem>();
- for (int i = 0; i < 250000; i += 1000)
- {
- {
- maxMileage.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["Mileage"] = maxMileage;
- List<SelectListItem> minHorsePower = new List<SelectListItem>();
- for (int i = 0; i < 500; i += 20)
- {
- {
- minHorsePower.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["HorsePower"] = minHorsePower;
- foreach (BodyType item in BodyTypeService.GetAllNotDeleted())
- {
- result.Styles.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- });
- }
- foreach (EngineSize item in EngineSizeService.GetAllNotDeleted())
- {
- result.Engines.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = Convert.ToString(item.Size),
- IsChecked = false
- });
- }
- foreach (DoorAmount item in DoorService.GetAllNotDeleted())
- {
- result.Doors.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = Convert.ToString(item.NumberOfDoors),
- IsChecked = false
- });
- }
- foreach (SeatAmount item in SeatAmountService.GetAllNotDeleted())
- {
- result.Seats.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = Convert.ToString(item.NumberOfSeats),
- IsChecked = false
- });
- }
- foreach (Colour item in ColourService.GetAllNotDeleted())
- {
- result.Colours.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- });
- }
- foreach (Transmission item in TransmissionService.GetAllNotDeleted())
- {
- result.Transmissions.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- });
- }
- foreach (DriveTrain item in DriveTrainService.GetAllNotDeleted())
- {
- result.Drivetrains.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- });
- }
- foreach (FuelType item in FuelTypeService.GetAllNotDeleted())
- {
- result.Fueltypes.Add(new CheckBoxList
- {
- Id = item.Id,
- Display = item.Value,
- IsChecked = false
- });
- }
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult AdvertSearch(AdvertSearchViewModel searchModel, string frontendMakeId, string frontendModelId)
- {
- IEnumerable<Advertisement> searchResult = AdvertisementService.GetAllActiveAdverts().ToList();
- if (!string.IsNullOrEmpty(frontendModelId))
- {
- searchModel.CarModel = ModelService.FindById(int.Parse(frontendModelId));
- searchResult = searchResult.Where(x => x.CarModelId == searchModel.CarModel.Id).ToList();
- }
- if (!string.IsNullOrEmpty(frontendMakeId))
- {
- searchModel.CarManufacturer = ManufacturerService.FindById(int.Parse(frontendMakeId));
- searchResult = searchResult.Where(x => x.CarModel?.ManufacturerId == searchModel.CarManufacturer.Id)
- .ToList();
- }
- searchResult =
- AdvertisementService.FilterPriceRange(searchModel.MinPrice, searchModel.MaxPrice, searchResult);
- searchResult =
- AdvertisementService.FilterYearRange(searchModel.MinRegYear, searchModel.MaxRegYear, searchResult);
- searchResult = AdvertisementService.FilterBHP(searchModel.MinHorsePower, searchResult);
- searchResult = AdvertisementService.FilterMileage(searchModel.MaxMilleage, searchResult);
- searchResult = FilterSearch(searchResult.ToList(), searchModel);
- List<SmallSearchResultViewModel> result = new List<SmallSearchResultViewModel>();
- foreach (Advertisement item in searchResult)
- {
- result.Add(new SmallSearchResultViewModel
- {
- Model = item.CarModel.Value,
- Make = item.CarModel.CarManufacturer.Value,
- Price = item.Price,
- EngineSize = item.EngineSize.Size,
- RegYear = item.RegYear,
- Description = item.AdvertDescription,
- Images = item.Images.Select(x => x.ImageData),
- IsSold = item.IsSold,
- AdvertisementId = item.Id
- });
- }
- return View("MainActiveAdverts", result);
- }
- private List<Advertisement> FilterSearch(List<Advertisement> searchResult, AdvertSearchViewModel model)
- {
- List<int> id = new List<int>();
- bool required = false;
- foreach (CheckBoxList item in model.Styles)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.BodyTypeId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Engines)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.EngineSizeId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Doors)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.DoorAmountId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Seats)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.SeatAmountId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Colours)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.ColourId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Transmissions)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.TransmissionId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Drivetrains)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.DriveTrainId)).ToList();
- }
- id = new List<int>();
- required = false;
- foreach (CheckBoxList item in model.Fueltypes)
- {
- if (item.IsChecked)
- {
- required = true;
- id.Add(item.Id);
- }
- }
- if (required)
- {
- searchResult = searchResult.Where(x => id.Contains(x.FuelTypeId)).ToList();
- }
- return searchResult;
- }
- public ActionResult SelectedAdvert(int id)
- {
- Advertisement selectedAdvertisement = AdvertisementService.FindById(id, x => x.CarModel.CarManufacturer, x => x.BodyType, x => x.Transmission, x => x.SeatAmount, x => x.DriveTrain, x => x.FuelType, x => x.DoorAmount, x => x.Colour, x => x.EngineSize, x => x.Images, x => x.Extras);
- if (selectedAdvertisement == null) throw new ArgumentNullException(nameof(selectedAdvertisement));
- var result = new SelectedAdvertViewModel
- {
- Model = selectedAdvertisement.CarModel.Value,
- Make = selectedAdvertisement.CarModel.CarManufacturer.Value,
- HorsePower = selectedAdvertisement.HorsePower,
- AmountOfOwners = selectedAdvertisement.AmountOfPrevOwners,
- Description = selectedAdvertisement.AdvertDescription,
- AdvertCloseDate = selectedAdvertisement.AdvertCloseDate,
- BodyType = selectedAdvertisement.BodyType.Value,
- Transmission = selectedAdvertisement.Transmission.Value,
- SeatAmount = selectedAdvertisement.SeatAmount.NumberOfSeats,
- DriveTrain = selectedAdvertisement.DriveTrain.Value,
- FuelType = selectedAdvertisement.FuelType.Value,
- DoorAmount = selectedAdvertisement.DoorAmount.NumberOfDoors,
- Colour = selectedAdvertisement.Colour.Value,
- RegYear = selectedAdvertisement.RegYear,
- Price = selectedAdvertisement.Price,
- EngineSize = selectedAdvertisement.EngineSize.Size,
- Images = selectedAdvertisement.Images.Select(x => x.ImageData),
- AdvertiserId = selectedAdvertisement.AppUserId
- };
- result.Extras = ExtrasService.GetAllByAdvertId(id);
- return View(result);
- }
- [HttpPost]
- [NoDirectAccess]
- public ActionResult MainActiveAdverts(AdvertSearchViewModel model, string frontendMakeId, string frontendModelId)
- {
- List<SmallSearchResultViewModel> result = new List<SmallSearchResultViewModel>();
- List<Advertisement> adverts = new List<Advertisement>();
- // Make and Model searches
- if (!string.IsNullOrEmpty(frontendModelId) && int.TryParse(frontendModelId, out int tempModel))
- {
- adverts = AdvertisementService
- .GetAllActiveAdverts().Where(x => x.CarModelId == tempModel).ToList();
- }
- else if (!string.IsNullOrEmpty(frontendMakeId) && int.TryParse(frontendMakeId, out int tempMake))
- {
- adverts = AdvertisementService.GetAllActiveAdverts().Where(x => x.CarModel.ManufacturerId == tempMake)
- .ToList();
- }
- else
- {
- adverts = AdvertisementService.GetAllActiveAdverts().ToList();
- }
- adverts =
- AdvertisementService.FilterPriceRange(model.MinPrice, model.MaxPrice, adverts);
- adverts =
- AdvertisementService.FilterYearRange(model.MinRegYear, model.MaxRegYear, adverts);
- foreach (Advertisement item in adverts)
- {
- result.Add(new SmallSearchResultViewModel
- {
- Model = item.CarModel.Value,
- Make = item.CarModel.CarManufacturer.Value,
- Price = item.Price,
- EngineSize = item.EngineSize.Size,
- RegYear = item.RegYear,
- Description = item.AdvertDescription,
- Images = item.Images.Select(x => x.ImageData),
- IsSold = item.IsSold,
- AdvertisementId = item.Id
- });
- }
- return View(result);
- }
- }
- }
- using System.Web;
- using CarAdvertiser.DAL;
- using CarAdvertiser.DAL.Interfaces;
- using CarAdvertiser.DAL.Repository;
- using CarAdvertiser.DTO;
- using System.Web.Mvc;
- using CarAdvertiser.BLL.Interfaces;
- using CarAdvertiser.BLL.Services;
- using CarAdvertiser.DAL.Identity;
- using CarAdvertiser.DAL.UnitOfWork;
- using CarAdvertiser.DTO.ValueEntities;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- namespace CarAdvertiser.Controllers
- {
- public abstract class BaseController : Controller
- {
- private readonly ICarAdvertiserContext _context;
- protected readonly IUnitOfWork Uow;
- protected readonly IRepositoryAppUserV2<AppUserV2> RepositoryAppUserV2;
- protected readonly IRepositoryAppRole<AppRole> RepositoryAppRole;
- private readonly IRepository<Image> _imageRepository;
- protected readonly IImageService ImageService;
- private readonly IRepository<Advertisement> _advertRepository;
- protected readonly IAdvertisementService AdvertisementService;
- private readonly IRepository<CarExtras> _extrasRepository;
- protected readonly IExtrasService ExtrasService;
- private readonly IRepository<AdditionalEquipment> _equipmentRepository;
- protected readonly IService<AdditionalEquipment> EquipmentService;
- private readonly IRepository<BodyType> _bodyTypeRepository;
- protected readonly IService<BodyType> BodyTypeService;
- private readonly IRepository<CarManufacturer> _manufacturerRepository;
- protected readonly IService<CarManufacturer> ManufacturerService;
- private readonly IRepository<CarModel> _modelRepository;
- protected readonly IService<CarModel> ModelService;
- private readonly IRepository<Colour> _colourRepository;
- protected readonly IService<Colour> ColourService;
- private readonly IRepository<DoorAmount> _doorRepository;
- protected readonly IService<DoorAmount> DoorService;
- private readonly IRepository<DriveTrain> _driveTrainRepository;
- protected readonly IService<DriveTrain> DriveTrainService;
- private readonly IRepository<EngineSize> _engineSizeRepository;
- protected readonly IService<EngineSize> EngineSizeService;
- private readonly IRepository<FuelType> _fuelTypeRepository;
- protected readonly IService<FuelType> FuelTypeService;
- private readonly IRepository<ListingTime> _listingTimeRepository;
- protected readonly IService<ListingTime> ListingTimeService;
- private readonly IRepository<SeatAmount> _seatAmountRepository;
- protected readonly IService<SeatAmount> SeatAmountService;
- private readonly IRepository<Transmission> _transmissionRepository;
- protected readonly IService<Transmission> TransmissionService;
- private readonly IRepository<Messages> _messagesRepository;
- protected readonly IMessageService MessagesService;
- private readonly IRepository<Booking> _bookingRepository;
- protected readonly IService<Booking> BookingService;
- private readonly IRepository<BookingAvailability> _bookingAvailabilityRepository;
- protected readonly IService<BookingAvailability> BookingAvailabilityService;
- private readonly IRepository<WantedCar> _wantedCarRepository;
- protected readonly IService<WantedCar> WantedCarService;
- protected BaseController()
- {
- _context = new CarAdvertiserContext();
- Uow = new UnitOfWork(_context);
- RepositoryAppUserV2 = new RepositoryAppUserV2<AppUserV2>(_context);
- RepositoryAppRole = new RepositoryAppRole<AppRole>(_context);
- _imageRepository = new Repository<Image>(_context);
- ImageService = new ImageService(_imageRepository, Uow);
- _advertRepository = new Repository<Advertisement>(_context);
- AdvertisementService = new AdvertisementService(_advertRepository, Uow);
- _extrasRepository = new Repository<CarExtras>(_context);
- ExtrasService = new ExtrasService(_extrasRepository, Uow);
- _equipmentRepository = new Repository<AdditionalEquipment>(_context);
- EquipmentService = new Service<AdditionalEquipment>(_equipmentRepository, Uow);
- _bodyTypeRepository = new Repository<BodyType>(_context);
- BodyTypeService = new Service<BodyType>(_bodyTypeRepository, Uow);
- _manufacturerRepository = new Repository<CarManufacturer>(_context);
- ManufacturerService = new Service<CarManufacturer>(_manufacturerRepository, Uow);
- _modelRepository = new Repository<CarModel>(_context);
- ModelService = new Service<CarModel>(_modelRepository, Uow);
- _colourRepository = new Repository<Colour>(_context);
- ColourService = new Service<Colour>(_colourRepository, Uow);
- _doorRepository = new Repository<DoorAmount>(_context);
- DoorService = new Service<DoorAmount>(_doorRepository, Uow);
- _driveTrainRepository = new Repository<DriveTrain>(_context);
- DriveTrainService = new Service<DriveTrain>(_driveTrainRepository, Uow);
- _engineSizeRepository = new Repository<EngineSize>(_context);
- EngineSizeService = new Service<EngineSize>(_engineSizeRepository, Uow);
- _fuelTypeRepository = new Repository<FuelType>(_context);
- FuelTypeService = new Service<FuelType>(_fuelTypeRepository, Uow);
- _listingTimeRepository = new Repository<ListingTime>(_context);
- ListingTimeService = new Service<ListingTime>(_listingTimeRepository, Uow);
- _seatAmountRepository = new Repository<SeatAmount>(_context);
- SeatAmountService = new Service<SeatAmount>(_seatAmountRepository, Uow);
- _transmissionRepository = new Repository<Transmission>(_context);
- TransmissionService = new Service<Transmission>(_transmissionRepository, Uow);
- _messagesRepository = new Repository<Messages>(_context);
- MessagesService = new MessageService(_messagesRepository, Uow);
- _bookingRepository = new Repository<Booking>(_context);
- BookingService = new Service<Booking>(_bookingRepository, Uow);
- _bookingAvailabilityRepository = new Repository<BookingAvailability>(_context);
- BookingAvailabilityService = new Service<BookingAvailability>(_bookingAvailabilityRepository, Uow);
- _wantedCarRepository = new Repository<WantedCar>(_context);
- WantedCarService = new Service<WantedCar>(_wantedCarRepository, Uow);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using CarAdvertiser.DTO;
- using CarAdvertiser.DTO.ValueEntities;
- using Newtonsoft.Json;
- namespace CarAdvertiser.Controllers
- {
- [Authorize]
- public class DatabaseController : BaseController
- {
- public ActionResult InitializeDatabase()
- {
- if (!ManufacturerService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Manufacturers.json")))
- {
- var manufacturers = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in manufacturers)
- {
- ManufacturerService.Create(new CarManufacturer
- {
- Value = item.Value
- });
- ManufacturerService.Save();
- }
- }
- }
- if (!ModelService.GetAllNotDeleted().Any())
- {
- var manufacturers = ManufacturerService.GetAllNotDeleted().ToList();
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Models.json")))
- {
- var models = JsonConvert.DeserializeObject<List<TempModel>>(StreamToString(r));
- foreach (TempModel item in models)
- {
- var manufacturer = manufacturers.FirstOrDefault(x => x.Value.Equals(item.CarManufacturer.Value));
- ModelService.Create(new CarModel
- {
- ManufacturerId = manufacturer.Id,
- Value = item.Value
- });
- ModelService.Save();
- }
- }
- }
- if (!ColourService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Colours.json")))
- {
- var colours = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in colours)
- {
- ColourService.Create(new Colour
- {
- Value = item.Value
- });
- ColourService.Save();
- }
- }
- }
- if (!TransmissionService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Transmissions.json")))
- {
- var transmissions = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in transmissions)
- {
- TransmissionService.Create(new Transmission
- {
- Value = item.Value
- });
- TransmissionService.Save();
- }
- }
- }
- if (!BodyTypeService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Bodies.json")))
- {
- var bodies = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in bodies)
- {
- BodyTypeService.Create(new BodyType
- {
- Value = item.Value
- });
- BodyTypeService.Save();
- }
- }
- }
- if (!EngineSizeService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/EngineSizes.json")))
- {
- var engines = JsonConvert.DeserializeObject<List<TempEngine>>(StreamToString(r));
- foreach (TempEngine item in engines)
- {
- EngineSizeService.Create(new EngineSize
- {
- Size = item.Size
- });
- EngineSizeService.Save();
- }
- }
- }
- if (!FuelTypeService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Fuels.json")))
- {
- var fuels = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in fuels)
- {
- FuelTypeService.Create(new FuelType
- {
- Value = item.Value
- });
- FuelTypeService.Save();
- }
- }
- }
- if (!DriveTrainService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Drives.json")))
- {
- var drives = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in drives)
- {
- DriveTrainService.Create(new DriveTrain
- {
- Value = item.Value
- });
- DriveTrainService.Save();
- }
- }
- }
- if (!EquipmentService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/AdditionalEqu.json")))
- {
- var equipments = JsonConvert.DeserializeObject<List<TempValue>>(StreamToString(r));
- foreach (TempValue item in equipments)
- {
- EquipmentService.Create(new AdditionalEquipment
- {
- Value = item.Value
- });
- EquipmentService.Save();
- }
- }
- }
- if (!SeatAmountService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Seats.json")))
- {
- var seats = JsonConvert.DeserializeObject<List<TempSeat>>(StreamToString(r));
- foreach (TempSeat item in seats)
- {
- SeatAmountService.Create(new SeatAmount
- {
- NumberOfSeats = item.NumberOfSeats
- });
- SeatAmountService.Save();
- }
- }
- }
- if (!DoorService.GetAllNotDeleted().Any())
- {
- using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Doors.json")))
- {
- var doors = JsonConvert.DeserializeObject<List<TempDoor>>(StreamToString(r));
- foreach (TempDoor item in doors)
- {
- DoorService.Create(new DoorAmount
- {
- NumberOfDoors = item.NumberOfDoors
- });
- DoorService.Save();
- }
- }
- }
- return RedirectToAction("Index", "Home");
- }
- public ActionResult Purge()
- {
- // the order of the following is given because of the keying of the tables!
- ListingTimeService.PurgeAll();
- ImageService.PurgeAll();
- BookingService.PurgeAll();
- BookingAvailabilityService.PurgeAll();
- MessagesService.PurgeAll();
- WantedCarService.PurgeAll();
- ExtrasService.PurgeAll();
- AdvertisementService.PurgeAll();
- ModelService.PurgeAll();
- ManufacturerService.PurgeAll();
- EngineSizeService.PurgeAll();
- FuelTypeService.PurgeAll();
- ColourService.PurgeAll();
- SeatAmountService.PurgeAll();
- BodyTypeService.PurgeAll();
- DriveTrainService.PurgeAll();
- TransmissionService.PurgeAll();
- DoorService.PurgeAll();
- EquipmentService.PurgeAll();
- //
- //Identity tables' values are not needed to be deleted here
- Uow.Commit();
- return RedirectToAction("Index", "Home");
- }
- private string StreamToString(StreamReader stream)
- {
- return stream.ReadToEnd();
- }
- internal class TempValue
- {
- public string Value { get; set; }
- }
- internal class TempEngine
- {
- public decimal Size { get; set; }
- }
- internal class TempSeat
- {
- public decimal NumberOfSeats { get; set; }
- }
- internal class TempDoor
- {
- public int NumberOfDoors { get; set; }
- }
- internal class TempModel
- {
- public string Value { get; set; }
- public TempValue CarManufacturer { get; set; }
- }
- }
- }
- using CarAdvertiser.DAL.Identity;
- using CarAdvertiser.DTO;
- using CarAdvertiser.Models;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace CarAdvertiser.Controllers
- {
- public class HomeController : BaseController
- {
- [RequireHttps]
- public ActionResult Index()
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- CreateDefaultAdminUser();//so you can login as admin even when you have empty database
- //AddMessages();
- //CreatingTheValuesInDb();//when uncommenting this, make sure you also uncomment the DeletingTheValuesFromDb() method, so everytime you run the app, it will create all the values again
- //TestingTheValuesInDb();
- //DeletingTheValuesFromDb();
- FillSmallSearch();
- return View();
- }
- public ActionResult GetAllPremiumAdverts(int featured)
- {
- List<PremiumAdvertViewModel> result = new List<PremiumAdvertViewModel>();
- foreach (Advertisement item in AdvertisementService.GetRandomPremiumAdvert(featured))
- {
- PremiumAdvertViewModel model = new PremiumAdvertViewModel
- {
- Model = item.CarModel.Value,
- Colour = item.Colour.Value,
- Price = item.Price,
- Description = item.AdvertDescription,
- EngineSize = item.EngineSize.Size,
- FuelType = item.FuelType.Value,
- BodyType = item.BodyType.Value,
- AdvertId = item.Id,
- Make = item.CarModel.CarManufacturer.Value,
- RegYear = item.RegYear,
- SellerName = item.AppUser.Email,
- Images = item.Images.Select(x => x.ImageData)
- };
- result.Add(model);
- }
- return PartialView("_PremiumAdvertPartial", result);
- }
- [Authorize(Roles = "Admin")]
- public ActionResult About()
- {
- ViewBag.Message = "Your application description page.";
- return View();
- }
- [Authorize(Roles = "Admin")]
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
- return View();
- }
- private void CreateDefaultAdminUser()
- {
- string admin = "admin@caradvertiser.co.uk";
- if (!RepositoryAppRole.RoleExists("Admin"))
- {
- RepositoryAppRole.Create("Admin");
- RepositoryAppRole.Save();
- }
- if (RepositoryAppUserV2.FindByEmail(admin) == null)
- {
- var adminUser = RepositoryAppUserV2.RegisterAsync(new AppUserV2
- {
- UserName = admin,
- Email = admin
- }, "Aa,12345").Result;
- RepositoryAppRole.AddUsersToRoles(new[] { admin }, new[] { "Admin" });
- RepositoryAppRole.Save();
- }
- }
- private void FillSmallSearch()
- {
- ViewData["Make"] = ManufacturerService.GetAllNotDeleted().Select(x => new SelectListItem
- {
- Text = x.Value,
- Value = x.Id.ToString()
- });
- List<SelectListItem> fromYear = new List<SelectListItem>();
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- fromYear.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["FromYear"] = fromYear.OrderBy(x => x.Text);
- List<SelectListItem> toYear = new List<SelectListItem>();
- for (int i = 1960; i <= DateTime.Now.Year; i++)
- {
- toYear.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["ToYear"] = toYear.OrderByDescending(x => x.Text);
- List<SelectListItem> minPrice = new List<SelectListItem>();
- for (int i = 0; i < 50000; i += 500)
- {
- minPrice.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- ViewData["MinPrice"] = minPrice;
- List<SelectListItem> maxPrice = new List<SelectListItem>();
- for (int i = 0; i < 50000; i += 500)
- {
- {
- maxPrice.Add(new SelectListItem
- {
- Value = i.ToString(),
- Text = i.ToString()
- });
- }
- }
- ViewData["MaxPrice"] = maxPrice;
- }
- private void CreatingTheValuesInDb()
- {
- RepositoryAppRole.Create("Moderator");
- RepositoryAppRole.Create("Admin");
- RepositoryAppRole.Create("User");
- RepositoryAppRole.Save();
- IdentityResult a = RepositoryAppUserV2.RegisterAsync(new AppUserV2
- {
- UserName =
- "ATTILA.TOEROEK@gmail.com", //we always save username and email in lowercase (check AppUserV2 class)
- Email = "ATTILA.TOEROEk@gmail.com"
- }, "Aa,12345").Result;
- IdentityResult b = RepositoryAppUserV2.RegisterAsync(new AppUserV2
- {
- UserName = "test1@a.HU",
- Email = "test1@a.HU"
- }, "Aa,12345").Result;
- IdentityResult c = RepositoryAppUserV2.RegisterAsync(new AppUserV2
- {
- UserName = "test2@B.hu",
- Email = "test2@B.hu"
- }, "Aa,12345").Result;
- //RepositoryAppUserV2.Save();//no additional saving is needed, because RegisterAsync goes through the UserManager and not our Repository. That UserManager saves automatically.
- RepositoryAppRole.AddUsersToRoles(new string[] { "attila.toeroek@gmail.com", "test2@b.hu" }, new string[] { "Admin" });
- RepositoryAppRole.AddUsersToRoles(new string[] { "ATTILA.TOEROEK@gmail.com" }, new string[] { "Moderator" });
- RepositoryAppRole.Save();
- }
- private void TestingTheValuesInDb()
- {
- var a = RepositoryAppRole.IsUserInRole("test2@b.hu", "Admin");//true
- var b = RepositoryAppRole.IsUserInRole("test2@b.hu", "Moderator");//false
- var c = RepositoryAppRole.FindUsersInRole("Admin", ".hu");//1 results
- var d = RepositoryAppRole.GetRolesForUser("ATTILA.TOEROEK@gmail.com");//2 result
- var e = RepositoryAppRole.GetUsersInRole("Admin");//2 results
- }
- private void DeletingTheValuesFromDb()
- {
- RepositoryAppRole.Delete("Admin");
- RepositoryAppRole.Delete("Moderator");
- RepositoryAppRole.Delete("User");
- RepositoryAppRole.Save();
- RepositoryAppUserV2.Delete("ATTILA.toeroek@gmail.com");//just setting the IsDeleted flag
- RepositoryAppUserV2.Delete("test1@a.HU");
- RepositoryAppUserV2.Purge("test2@B.hu");//delete it forever
- RepositoryAppUserV2.Save();
- }
- private void AddMessages()
- {
- Messages message = MessagesService.Create(new Messages
- {
- SenderId = 8,
- ReceiverId = 9,
- MessageContent = "Siemaneczko, testujemy",
- IsRead = false,
- IsDeleted = false,
- CreatedDate = DateTime.Now,
- CreateUser = "Marcin"
- });
- Uow.Commit();
- }
- }
- }
- using CarAdvertiser.DAL.Identity;
- using CarAdvertiser.Models;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- using Microsoft.Owin.Security;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- using CarAdvertiser.DTO;
- namespace CarAdvertiser.Controllers
- {
- [Authorize]
- public class ManageController : BaseController
- {
- //private AppV2SignInManager _signInManager;
- //private AppUserV2Manager _userManager;
- public ManageController()
- {
- }
- //public ManageController(AppUserV2Manager userManager, AppV2SignInManager signInManager)
- //{
- // UserManager = userManager;
- // SignInManager = signInManager;
- //}
- //public AppV2SignInManager SignInManager
- //{
- // get
- // {
- // return _signInManager ?? HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- // }
- // private set
- // {
- // _signInManager = value;
- // }
- //}
- //public AppUserV2Manager UserManager
- //{
- // get
- // {
- // return _userManager ?? HttpContext.GetOwinContext().GetUserManager<AppUserV2Manager>();
- // }
- // private set
- // {
- // _userManager = value;
- // }
- //}
- public async Task<ActionResult> Index(ManageMessageId? message)
- {
- ViewBag.StatusMessage =
- message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
- : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
- : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
- : message == ManageMessageId.Error ? "An error has occurred."
- : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
- : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
- : "";
- var userId = User.Identity.GetUserId();
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var model = new IndexViewModel
- {
- HasPassword = HasPassword(),
- //PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
- //TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
- //Logins = await UserManager.GetLoginsAsync(userId),
- BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
- };
- return View(model);
- }
- //[HttpPost]
- //[ValidateAntiForgeryToken]
- //public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
- //{
- // ManageMessageId? message;
- // var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
- // if (result.Succeeded)
- // {
- // var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
- // if (user != null)
- // {
- // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- // }
- // message = ManageMessageId.RemoveLoginSuccess;
- // }
- // else
- // {
- // message = ManageMessageId.Error;
- // }
- // return RedirectToAction("ManageLogins", new { Message = message });
- //}
- public ActionResult AddPhoneNumber()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var code = await RepositoryAppUserV2.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId<int>(), model.Number);
- if (RepositoryAppUserV2.AppUserV2Manager.SmsService != null)
- {
- var message = new IdentityMessage
- {
- Destination = model.Number,
- Body = "Your security code is: " + code
- };
- await RepositoryAppUserV2.AppUserV2Manager.SmsService.SendAsync(message);
- }
- return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> EnableTwoFactorAuthentication()
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- await RepositoryAppUserV2.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), true);
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", "Manage");
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> DisableTwoFactorAuthentication()
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- await RepositoryAppUserV2.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), false);
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", "Manage");
- }
- public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var code = await RepositoryAppUserV2.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId<int>(), phoneNumber);
- return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.ChangePhoneNumberAsync(User.Identity.GetUserId<int>(), model.PhoneNumber, model.Code);
- if (result.Succeeded)
- {
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
- }
- ModelState.AddModelError("", "Failed to verify phone");
- return View(model);
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> RemovePhoneNumber()
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.SetPhoneNumberAsync(User.Identity.GetUserId<int>(), null);
- if (!result.Succeeded)
- {
- return RedirectToAction("Index", new { Message = ManageMessageId.Error });
- }
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
- }
- public ActionResult ChangePassword()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.ChangePasswordAsync(User.Identity.GetUserId<int>(), model.OldPassword, model.NewPassword);
- if (result.Succeeded)
- {
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
- }
- AddErrors(result);
- return View(model);
- }
- public ActionResult SetPassword()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
- {
- if (ModelState.IsValid)
- {
- RepositoryAppUserV2.AppUserV2Manager = HttpContext.GetOwinContext().Get<AppUserV2Manager>();
- RepositoryAppUserV2.AppV2SignInManager = HttpContext.GetOwinContext().Get<AppV2SignInManager>();
- var result = await RepositoryAppUserV2.AddPasswordAsync(User.Identity.GetUserId<int>(), model.NewPassword);
- if (result.Succeeded)
- {
- var user = await RepositoryAppUserV2.FindByIdAsync(User.Identity.GetUserId<int>());
- if (user != null)
- {
- await RepositoryAppUserV2.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- }
- return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
- }
- AddErrors(result);
- }
- return View(model);
- }
- //public async Task<ActionResult> ManageLogins(ManageMessageId? message)
- //{
- // ViewBag.StatusMessage =
- // message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
- // : message == ManageMessageId.Error ? "An error has occurred."
- // : "";
- // var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
- // if (user == null)
- // {
- // return View("Error");
- // }
- // var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
- // var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
- // ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
- // return View(new ManageLoginsViewModel
- // {
- // CurrentLogins = userLogins,
- // OtherLogins = otherLogins
- // });
- //}
- //[HttpPost]
- //[ValidateAntiForgeryToken]
- //public ActionResult LinkLogin(string provider)
- //{
- // return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
- //}
- //public async Task<ActionResult> LinkLoginCallback()
- //{
- // var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
- // if (loginInfo == null)
- // {
- // return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
- // }
- // var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
- // return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
- //}
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- //_userManager.Dispose();
- //_userManager = null;
- RepositoryAppUserV2?.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Helpers
- // Used for XSRF protection when adding external logins
- private const string XsrfKey = "XsrfId";
- private IAuthenticationManager AuthenticationManager
- {
- get
- {
- return HttpContext.GetOwinContext().Authentication;
- }
- }
- private void AddErrors(IdentityResult result)
- {
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError("", error);
- }
- }
- private bool HasPassword()
- {
- var user = RepositoryAppUserV2.AppUserV2Manager.FindById(User.Identity.GetUserId<int>());
- //var user = RepositoryAppUserV2.FindById(User.Identity.GetUserId());
- return user?.PasswordHash != null;
- }
- private bool HasPhoneNumber()
- {
- var user = RepositoryAppUserV2.FindById(User.Identity.GetUserId<int>());
- return user?.PhoneNumber != null;
- }
- public enum ManageMessageId
- {
- AddPhoneSuccess,
- ChangePasswordSuccess,
- SetTwoFactorSuccess,
- SetPasswordSuccess,
- RemoveLoginSuccess,
- RemovePhoneSuccess,
- Error
- }
- #endregion
- }
- }
- using System;
- using System.Net;
- using CarAdvertiser.Helpers;
- using System.Web.Mvc;
- using CarAdvertiser.DTO;
- using Microsoft.AspNet.Identity;
- namespace CarAdvertiser.Controllers
- {
- [Authorize]
- public class MessageController : BaseController
- {
- public ActionResult Index()
- {
- return View();
- }
- public JsonResult GetAllUnreadMessages()
- {
- return Json(MessageHelpers.GetAllUnreadMessages(User.Identity.GetUserId<int>()), JsonRequestBehavior.AllowGet);
- }
- public JsonResult GetAllUndeletedMessages()
- {
- return Json(MessageHelpers.GetAllUndeletedMessages(User.Identity.GetUserId<int>()), JsonRequestBehavior.AllowGet);
- }
- //[HttpPost]
- //public JsonResult SetReadMessage(int messageId)
- //{
- // MessagesService.SetRead(messageId);
- // Uow.Commit();
- // return Json(new {result = "OK"}, JsonRequestBehavior.AllowGet);
- //}
- [HttpPost]
- public JsonResult DeleteMessage(int messageId)
- {
- MessagesService.SetRead(messageId);
- MessagesService.Delete(messageId);
- Uow.Commit();
- return Json(new { result = "OK" }, JsonRequestBehavior.AllowGet);
- }
- [HttpPost]
- [Authorize]
- public ActionResult SendMessage(string message, int toId)
- {
- if (string.IsNullOrEmpty(message))
- {
- return new JsonErrorResult(HttpStatusCode.InternalServerError)
- {
- Data = "Missing message!",
- JsonRequestBehavior = JsonRequestBehavior.AllowGet
- };
- }
- try
- {
- MessagesService.Create(new Messages
- {
- MessageContent = message,
- ReceiverId = toId,
- SenderId = User.Identity.GetUserId<int>()
- });
- Uow.Commit();
- }
- catch (Exception ex)
- {
- return new JsonErrorResult(HttpStatusCode.InternalServerError)
- {
- Data = ex.Message,
- JsonRequestBehavior = JsonRequestBehavior.AllowGet
- };
- }
- return Json(new { result = "Message sent successfully" }, JsonRequestBehavior.AllowGet);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Mvc.Html;
- using CarAdvertiser.BLL.Services;
- using CarAdvertiser.DTO;
- using CarAdvertiser.Helpers;
- using CarAdvertiser.Models;
- using Microsoft.AspNet.Identity;
- using Newtonsoft.Json;
- namespace CarAdvertiser.Controllers
- {
- public class UserController : BaseController
- {
- // GET: User
- [Authorize]
- [HttpGet]
- public ActionResult UserPanel()
- {
- ViewBag.UserAdvertCount = AdvertisementService.GetAllActiveAdverts()
- .Where(x => x.AppUserId == User.Identity.GetUserId<int>()).Count();
- ViewBag.UserExpiredAdvertCount = AdvertisementService.GetAllExpiredAdverts()
- .Where(x => x.AppUserId == User.Identity.GetUserId<int>()).Count();
- ViewBag.UserSoldCars = AdvertisementService.GetAll()
- .Where(x => x.AppUserId == User.Identity.GetUserId<int>()).Where(x => x.IsSold == true).Count();
- return View();
- }
- [HttpGet]
- [Authorize]
- public ActionResult ManageAdverts()
- {
- IEnumerable<Advertisement> userAdverts = AdvertisementService.GetAllActiveAdverts().Where(x => x.AppUserId == User.Identity.GetUserId<int>());
- List<UserAdvertsViewModel> result = new List<UserAdvertsViewModel>();
- foreach (Advertisement item in userAdverts)
- {
- result.Add(new UserAdvertsViewModel
- {
- AdvertId = item.Id,
- Make = item.CarModel.CarManufacturer.Value,
- Model = item.CarModel.Value,
- Price = item.Price,
- ClosingDate = item.AdvertCloseDate,
- IsSold = item.IsSold
- });
- }
- return View("ManageAdverts", result);
- }
- //[HttpPost]
- [Authorize]
- [NoDirectAccess]
- [HttpGet]
- public ActionResult ExpiredAdverts()
- {
- IEnumerable<Advertisement> expiredAdverts = AdvertisementService.GetAllExpiredAdverts()
- .Where(x => x.AppUserId == User.Identity.GetUserId<int>());
- List<UserAdvertsViewModel> result = new List<UserAdvertsViewModel>();
- foreach (Advertisement item in expiredAdverts)
- {
- result.Add(new UserAdvertsViewModel
- {
- AdvertId = item.Id,
- Make = item.CarModel.CarManufacturer.Value,
- Model = item.CarModel.Value,
- Price = item.Price,
- ClosingDate = item.AdvertCloseDate,
- IsSold = item.IsSold
- });
- }
- return View(result);
- }
- [Authorize]
- [NoDirectAccess]
- [HttpGet]
- public ActionResult SoldCars()
- {
- IEnumerable<Advertisement> soldCars = AdvertisementService.GetAll()
- .Where(x => x.AppUserId == User.Identity.GetUserId<int>()).Where(x => x.IsSold);
- List<UserAdvertsViewModel> result = new List<UserAdvertsViewModel>();
- foreach (Advertisement item in soldCars)
- {
- result.Add(new UserAdvertsViewModel
- {
- AdvertId = item.Id,
- Make = item.CarModel.CarManufacturer.Value,
- Model = item.CarModel.Value,
- Price = item.Price,
- ClosingDate = item.AdvertCloseDate,
- IsSold = item.IsSold
- });
- }
- return View(result);
- }
- [HttpPost]
- public ActionResult SetAsSold(int id)
- {
- if (ModelState.IsValid)
- {
- Advertisement adv = AdvertisementService.FindById(id);
- adv.IsSold = true;
- AdvertisementService.Update(adv);
- Uow.Commit();
- }
- return View("UserPanel");
- }
- [Authorize]
- public ActionResult AdminPanel()
- {
- return View();
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace CarAdvertiser.Helpers
- {
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
- public sealed class NoDirectAccessAttribute : ActionFilterAttribute
- {
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- if (filterContext.HttpContext.Request.UrlReferrer == null ||
- filterContext.HttpContext.Request.Url?.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
- {
- filterContext.Result = new RedirectToRouteResult(new
- RouteValueDictionary(new { controller = "Home", action = "Index", area = "" }));
- }
- }
- }
- }
- using System.Net;
- using System.Web.Mvc;
- namespace CarAdvertiser.Helpers
- {
- public class JsonErrorResult : JsonResult
- {
- private readonly HttpStatusCode _statusCode;
- public JsonErrorResult(HttpStatusCode statusCode)
- {
- _statusCode = statusCode;
- }
- public override void ExecuteResult(ControllerContext context)
- {
- context.HttpContext.Response.StatusCode = (int) _statusCode;
- base.ExecuteResult(context);
- }
- }
- }
- using System;
- using CarAdvertiser.Hubs;
- using CarAdvertiser.Models;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Script.Serialization;
- namespace CarAdvertiser.Helpers
- {
- public static class MessageHelpers
- {
- public static string GetAllUnreadMessages(int userId)
- {
- using (SqlConnection connection =
- new SqlConnection(ConfigurationManager.ConnectionStrings["CarAdvertiser"].ConnectionString))
- {
- //always use 'dbo' prefix of database to trigger the change event!
- //always write down the selected columns and do not use SELECT *!
- using (SqlCommand cmd = new SqlCommand("SELECT [Id],SenderId,ReceiverId,MessageContent,IsRead FROM [dbo].[Messages] WHERE IsRead <> 1 AND ReceiverId=@receiverId", connection))
- {
- cmd.Parameters.AddWithValue("@receiverId", userId);
- cmd.Notification = null;
- SqlDependency dependency=new SqlDependency(cmd);
- dependency.OnChange += Dependency_OnChange;
- if (connection.State == ConnectionState.Closed) connection.Open();
- List<MessageViewModel> messages = new List<MessageViewModel>();
- using (SqlDataReader dr = cmd.ExecuteReader())
- {
- while (dr.Read())
- {
- messages.Add(new MessageViewModel
- {
- MessageId = (int)dr["Id"],
- SenderId = (int)dr["SenderId"],
- ReceiverId = (int)dr["ReceiverId"],
- Message = dr["MessageContent"].ToString(),
- IsRead = (bool)dr["IsRead"]
- });
- }
- dr.Close();
- }
- if (connection.State == ConnectionState.Open) connection.Close();
- var jsonSerialiser = new JavaScriptSerializer();
- var json = jsonSerialiser.Serialize(messages);
- return json;
- }
- }
- }
- public static string GetAllUndeletedMessages(int userId)
- {
- using (SqlConnection connection =
- new SqlConnection(ConfigurationManager.ConnectionStrings["CarAdvertiser"].ConnectionString))
- {
- //always use 'dbo' prefix of database to trigger the change event!
- //always write down the selected columns and do not use SELECT *!
- using (SqlCommand cmd = new SqlCommand("SELECT [Id],SenderId,ReceiverId,MessageContent,IsRead,CreatedDate,CreateUser FROM [dbo].[Messages] WHERE IsDeleted <> 1 AND ReceiverId=@receiverId", connection))
- {
- cmd.Parameters.AddWithValue("@receiverId", userId);
- cmd.Notification = null;
- SqlDependency dependency = new SqlDependency(cmd);
- dependency.OnChange += Dependency_OnChange;
- if (connection.State == ConnectionState.Closed) connection.Open();
- List<MessageViewModel> messages = new List<MessageViewModel>();
- using (SqlDataReader dr = cmd.ExecuteReader())
- {
- while (dr.Read())
- {
- messages.Add(new MessageViewModel
- {
- MessageId = (int)dr["Id"],
- SenderId = (int)dr["SenderId"],
- ReceiverId = (int)dr["ReceiverId"],
- Message = dr["MessageContent"].ToString(),
- IsRead = (bool)dr["IsRead"],
- SenderName = dr["CreateUser"].ToString(),
- ReceivedDate = ((DateTime)dr["CreatedDate"]).ToString("d")
- });
- }
- dr.Close();
- }
- if (connection.State == ConnectionState.Open) connection.Close();
- var jsonSerialiser = new JavaScriptSerializer();
- var json = jsonSerialiser.Serialize(messages);
- return json;
- }
- }
- }
- private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
- {
- if (e.Type == SqlNotificationType.Change)
- {
- CarAdvertiserHub.Show();
- }
- }
- }
- }
- using Microsoft.AspNet.SignalR;
- namespace CarAdvertiser.Hubs
- {
- public class CarAdvertiserHub : Hub
- {
- public static void Show()
- {
- IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CarAdvertiserHub>();
- context.Clients.All.displayMessage();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement