public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/Manage/");
            if (ModelState.IsValid)
            {
                var user = new DealerEmployeeLoginCredential {
                    UserName = Input.Email,
                    Email    = Input.Email
                };

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    Dealer dealer = new Dealer
                    {
                        Name         = Input.Name,
                        Address      = Input.Address,
                        AddressLine2 = Input.AddressLine2,
                        City         = Input.City,
                        State        = Input.State,
                        Zip          = Input.Zip,
                        PhoneNumber  = Input.PhoneNumber,
                        Website      = Input.Website
                    };

                    Dealer found = _outdoorPowerRepository.GetDealer(dealer);

                    if (found == null)
                    {
                        _outdoorPowerRepository.AddDealer(dealer);

                        if (!await _outdoorPowerRepository.SaveChangesAsync())
                        {
                            ModelState.AddModelError("Save Failed", "Unable to save the dealer.");
                        }
                        else
                        {
                            found = dealer;
                        }
                    }

                    DealerEmployee dealerEmployee = new DealerEmployee
                    {
                        FirstName = Input.FirstName,
                        LastName  = Input.LastName,
                        DealerId  = found.Id,
                        DealerEmployeeLoginCredentialsId = new Guid(user.Id)
                    };

                    _outdoorPowerRepository.AddDealerEmployee(dealerEmployee);
                    if (!await _outdoorPowerRepository.SaveChangesAsync())
                    {
                        ModelState.AddModelError("Save Failed", "Unable to save the user information.");
                    }
                    else
                    {
                        IEnumerable <Claim> claims = new List <Claim>(
                            new Claim[] {
                            new Claim("DealerId", found.Id.ToString()),
                            new Claim("EditAccess", "DealerOwner")
                        }
                            );

                        var identityResult = await _userManager.AddClaimsAsync(
                            user,
                            claims
                            );
                    }


                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                else
                {
                    bool duplicate = false;

                    foreach (var error in result.Errors)
                    {
                        if (error.Code == "DuplicateUserName" || error.Code == "DuplicateEmail")
                        {
                            duplicate = true;
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }

                    if (duplicate)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #2
0
        public async Task <IActionResult> Inventory(ManageAddInventoryViewModel manageAddInventoryViewModel)
        {
            manageAddInventoryViewModel.DatePosted = DateTime.Now;

            if (ModelState.IsValid)
            {
                DealerInventory dealerInventory = Mapper.Map <DealerInventory>(manageAddInventoryViewModel);
                string          dealerId        = User.Claims.FirstOrDefault(x => x.Type == "DealerId").Value;
                dealerInventory.DealerId = Int32.Parse(dealerId);

                if (dealerInventory.ZipCode == null)
                {
                    Dealer dealer = _userRepository.GetDealer(dealerInventory.DealerId);
                    dealerInventory.ZipCode = dealer.Zip;
                }

                _outdoorPowerRepository.AddDealerInventory(dealerInventory);

                if (!await _outdoorPowerRepository.SaveChangesAsync())
                {
                    ModelState.AddModelError("Save Failed", "Unable to save to the dealer inventory table.");
                }
                else
                {
                    // Add Entry to Metrics Inventory Table
                    Models.Metrics.Inventory metricInventory = Mapper.Map <Models.Metrics.Inventory>(manageAddInventoryViewModel);
                    if (!await _metricRepository.SaveChangesAsync())
                    {
                        ModelState.AddModelError("Metric Save Failed", "Unable to save information to the metrics database.");
                    }

                    if (manageAddInventoryViewModel.Images != null)
                    {
                        foreach (var Image in manageAddInventoryViewModel.Images)
                        {
                            if (Image != null && Image.Length > 0)
                            {
                                var uploadPath = Path.Combine(
                                    _environment.WebRootPath,
                                    "images\\dealer\\" + dealerId.ToString() + "\\inventory\\" + dealerInventory.Id.ToString()
                                    );

                                string webPath = Path.Combine(
                                    "/images/dealer/" + dealerId.ToString() + "/inventory/" + dealerInventory.Id.ToString()
                                    );

                                if (!Directory.Exists(uploadPath))
                                {
                                    Directory.CreateDirectory(uploadPath);
                                }

                                if (Image.Length > 0 && !System.IO.File.Exists(Path.Combine(uploadPath, Image.FileName)))
                                {
                                    var fileName = ContentDispositionHeaderValue.Parse
                                                       (Image.ContentDisposition).FileName.Trim('"');

                                    System.Console.WriteLine(fileName);
                                    using (var fileStream = new FileStream(Path.Combine(uploadPath, Image.FileName), FileMode.Create))
                                    {
                                        await Image.CopyToAsync(fileStream);
                                    }

                                    DealerInventoryImage dealerInventoryImage = new DealerInventoryImage();
                                    dealerInventoryImage.Path              = uploadPath + "\\" + fileName;
                                    dealerInventoryImage.WebPath           = webPath + "/" + fileName;
                                    dealerInventoryImage.DealerInventoryId = dealerInventory.Id;
                                    _outdoorPowerRepository.AddDealerInventoryImages(dealerInventoryImage);
                                }
                            }
                        }
                    }

                    if (!await _outdoorPowerRepository.SaveChangesAsync())
                    {
                        ModelState.AddModelError("Save Failed", "Unable to save to the images.");
                    }

                    return(LocalRedirect("/manage/inventory?id=" + dealerInventory.Id));
                }
            }

            manageAddInventoryViewModel.TypeList = _outdoorPowerRepository.GetInventoryTypes().Select(
                pt => new SelectListItem
            {
                Value = pt.Id.ToString(),
                Text  = pt.Name
            }).ToList();

            manageAddInventoryViewModel.MakeList = _outdoorPowerRepository.GetInventoryMakes().Select(
                pt => new SelectListItem
            {
                Value = pt.Id.ToString(),
                Text  = pt.Name
            }).ToList();

            manageAddInventoryViewModel.MakeList.Add(new SelectListItem
            {
                Value = "-2",
                Text  = "Other"
            });

            if (manageAddInventoryViewModel.QInventoryMakeId > 0 && manageAddInventoryViewModel.QInventoryTypeId > 0)
            {
                manageAddInventoryViewModel.ModelList = _outdoorPowerRepository.GetInventoryModels(
                    (int)manageAddInventoryViewModel.QInventoryMakeId,
                    manageAddInventoryViewModel.QInventoryTypeId
                    ).Select(
                    pt => new SelectListItem
                {
                    Value = pt.Id.ToString(),
                    Text  = pt.Name
                }).ToList();

                manageAddInventoryViewModel.ModelList.Add(new SelectListItem
                {
                    Value = "-2",
                    Text  = "Other"
                });

                if (manageAddInventoryViewModel.QInventoryModelId > 0)
                {
                    manageAddInventoryViewModel.ModelOptionList = _outdoorPowerRepository.GetInventoryModelOptions((int)manageAddInventoryViewModel.QInventoryModelId).Select(
                        pt => new SelectListItem
                    {
                        Value = pt.Id.ToString(),
                        Text  = pt.Name
                    }).ToList();

                    manageAddInventoryViewModel.ModelOptionList.Add(new SelectListItem
                    {
                        Value = "-2",
                        Text  = "Other"
                    });
                }
            }
            else
            {
                manageAddInventoryViewModel.ModelList       = new List <SelectListItem>();
                manageAddInventoryViewModel.ModelOptionList = new List <SelectListItem>();
            }

            manageAddInventoryViewModel.YearList = new List <SelectListItem>();

            int year = DateTime.UtcNow.Year;

            do
            {
                manageAddInventoryViewModel.YearList.Add(
                    new SelectListItem()
                {
                    Text  = year.ToString(),
                    Value = year.ToString()
                }
                    );
                year -= 1;
            } while (year > 1995);

            manageAddInventoryViewModel.EngineBrandList = _outdoorPowerRepository.GetEngineBrands().Select(
                pt => new SelectListItem
            {
                Value = pt,
                Text  = pt
            }
                ).ToList();

            if (!String.IsNullOrEmpty(manageAddInventoryViewModel.EngineBrand))
            {
                manageAddInventoryViewModel.EngineHorsePowerList = _outdoorPowerRepository.GetEngineHorsePower(
                    manageAddInventoryViewModel.EngineBrand
                    ).Select(
                    pt => new SelectListItem
                {
                    Value = pt,
                    Text  = pt
                }
                    ).ToList();
            }
            else
            {
                manageAddInventoryViewModel.EngineHorsePowerList = new List <SelectListItem>();
            }

            return(View(manageAddInventoryViewModel));
        }