public async Task <EntrepreneurResponse> UpdateAsync(int id, Entrepreneur entrepreneur)
        {
            var existingEntrepreneur = await entrepreneurRepository.FindById(id);

            if (existingEntrepreneur == null)
            {
                return(new EntrepreneurResponse("User not found"));
            }

            existingEntrepreneur.Description = entrepreneur.Description;
            existingEntrepreneur.ImageUrl    = entrepreneur.ImageUrl;
            existingEntrepreneur.FirstName   = entrepreneur.FirstName;
            existingEntrepreneur.LastName    = entrepreneur.LastName;
            existingEntrepreneur.City        = entrepreneur.City;
            existingEntrepreneur.Occupation  = entrepreneur.Occupation;
            existingEntrepreneur.Description = entrepreneur.Description;

            try
            {
                entrepreneurRepository.Update(existingEntrepreneur);
                await unitOfWork.CompleteAsync();

                return(new EntrepreneurResponse(existingEntrepreneur));
            }
            catch (Exception ex)
            {
                return(new EntrepreneurResponse($"An error ocurred while updating the entrepreneur: {ex.Message}"));
            }
        }
        public async Task <IActionResult> CreateGuestAccount()
        {
            var business = new Business();

            business.Name = GenerateBusinessName();
            if (_context.Entrepreneurs.Any(s => s.UserName.ToLower() == business.Name))
            {
                business.Name += new Random().Next(1, 1000);
            }
            var user = new Entrepreneur()
            {
                Business           = business,
                EmailConfirmed     = true,
                LockoutEnabled     = false,
                TwoFactorEnabled   = false,
                UserName           = business.Name,
                NormalizedEmail    = business.Name.ToUpper(),
                NormalizedUserName = business.Name.ToUpper()
            };

            _context.Entrepreneurs.Add(user);
            await _context.SaveChangesAsync();

            await _signInManager.SignInAsync(user, true);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #3
0
        public async Task <IActionResult> Register(string token, string businessName)
        {
            if (token == null)
            {
                return(Unauthorized());
            }
            if (businessName == null)
            {
                return(StatusCode(400, "Need to include business name"));
            }

            try
            {
                var tokenHandler    = new JwtSecurityTokenHandler();
                var tokenParameters = new TokenValidationParameters()
                {
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config.GetValue <string>("JWT:Key"))),
                };
                tokenHandler.ValidateToken(token, tokenParameters, out SecurityToken validatedToken);
            }
            catch { return(Unauthorized()); }

            var authHeader      = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
            var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
            var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
            var username        = credentials[0];
            var password        = credentials[1];

            var user = new Entrepreneur
            {
                UserName = username,
                Email    = username,
                Business = new Business()
            };

            user.Business.Name = businessName;
            var result = await _signInManager.UserManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                _logger.LogInformation($"{username} account created.");
                var business = (await _context.Entrepreneurs
                                .Include(s => s.Business)
                                .SingleOrDefaultAsync(s => s.NormalizedEmail == username.ToUpper()))
                               .Business;

                return(Ok(Newtonsoft.Json.JsonConvert.SerializeObject(business)));
            }
            else
            {
                return(StatusCode(500));
            }
        }
        public string EntreprenuerCustomId(Entrepreneur model)
        {
            string customId     = string.Empty;
            string defaultValue = "EN";
            int    year         = DateTime.Now.Year;
            int    id           = _context.Entrepreneurs.Count() + 1;

            customId = defaultValue + year.ToString().Trim() + id.ToString().Trim().PadLeft(2, '0');
            return(customId);
        }
        public Paged <Entrepreneur> SearchPagination(int pageIndex, int pageSize, string query)
        {
            Paged <Entrepreneur> pagedResult = null;

            List <Entrepreneur> result = null;

            int totalCount = 0;

            _dataProvider.ExecuteCmd(
                "dbo.Entrepreneurs_Search",

                inputParamMapper : delegate(SqlParameterCollection parameterCollection)
            {
                parameterCollection.AddWithValue("@PageIndex", pageIndex);
                parameterCollection.AddWithValue("@PageSize", pageSize);
                parameterCollection.AddWithValue("@Query", query);
            },
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                Entrepreneur model         = new Entrepreneur();
                int index                  = 0;
                model.Id                   = reader.GetSafeInt32(index++);
                model.FirstName            = reader.GetSafeString(index++);
                model.LastName             = reader.GetSafeString(index++);
                model.Email                = reader.GetSafeString(index++);
                model.UserId               = reader.GetSafeInt32(index++);
                model.IndustryType         = new IndustryType();
                model.IndustryType.Id      = reader.GetSafeInt32(index++);
                model.IndustryType.Name    = reader.GetSafeString(index++);
                model.CompanyStatus        = new CompanyStatus();
                model.CompanyStatus.Id     = reader.GetSafeInt32(index++);
                model.CompanyStatus.Name   = reader.GetSafeString(index++);
                model.HasSecurityClearance = reader.GetSafeBool(index++);
                model.HasInsurance         = reader.GetSafeBool(index++);
                model.HasBonds             = reader.GetSafeBool(index++);
                model.SpecializedEquipment = reader.GetSafeString(index++);
                model.ImageUrl             = reader.GetSafeString(index++);
                totalCount                 = reader.GetSafeInt32(index++);

                if (result == null)
                {
                    result = new List <Entrepreneur>();
                }

                result.Add(model);
            }

                );
            if (result != null)
            {
                pagedResult = new Paged <Entrepreneur>(result, pageIndex, pageSize, totalCount);
            }
            return(pagedResult);
        }
        public Entrepreneur GetOwner(int projectId)
        {
            var          project      = _context.Projects.Where(x => x.Id == projectId).Include(x => x.Company).ThenInclude(x => x.Entrepreneur);
            Entrepreneur entrepreneur = new Entrepreneur();

            foreach (var item in project)
            {
                entrepreneur = item.Company.Entrepreneur;
            }
            return(entrepreneur);
        }
        public async Task <IActionResult> Index()
        {
            var          viewModel = new HomeIndexVM();
            Entrepreneur user      = null;

            if (User.Identity.IsAuthenticated)
            {
                user = await GetCurrentEntrepreneur();

                if (user.Business != null)
                {
                    var business = await _businessHelper.UpdateGainsSinceLastCheckIn(user.Business.Id);

                    business.Owner = await _entrepreneurHelper.UpdateEntrepreneurScore(user.Business.Id);

                    viewModel.Business = business;

                    viewModel.Purchasables = _context
                                             .Purchasables
                                             .Where(s => !s.IsUpgrade)
                                             .Include(s => s.Type)
                                             .Include(s => s.PurchasableUpgrade)
                                             .ThenInclude(s => s.PurchasableUpgrade) // Hard locks us into X number of upgrades, but I'm not sure of a better wya to accomplish this right now
                                             .OrderBy(s => s.IsSinglePurchase)
                                             .ThenBy(s => s.UnlocksAtTotalEarnings)
                                             .Select(s => PurchasableHelper.SwapPurchaseForUpgradeIfAlreadyBought(s, user.Business))
                                             .Select(s => PurchasableHelper.AdjustPurchasableCostWithSectorBonus(s, user.Business))
                                             .ToList();

                    viewModel.InvestmentsInBusiness = await _businessHelper.GetInvestmentsInCompany(business.Id);

                    viewModel.EspionagesAgainstBusiness = await _businessHelper.GetEspionagesAgainstCompany(business.Id);
                }
            }

            viewModel.MostSuccessfulBusinesses = _context.Business
                                                 .Include(s => s.Owner)
                                                 .Where(s => s.Cash != 0 && s.Name != null)
                                                 .OrderByDescending(s => s.Owner.Score).Take(5).ToList();
            viewModel.AvailableSectors = _context.Sectors.Select(s => new SelectListItem()
            {
                Value = s.Id.ToString(), Text = $"{s.Name} ({s.Description})"
            }).ToList();

            if (user != null && user.Business != null)
            {
                viewModel.PurchasedItems = user.Business.BusinessPurchases.Select(s => (s.Purchase, s.AmountOfPurchases)).ToList();
            }

            ViewData["DisplayMessageBadge"] = true;

            return(View(viewModel));
        }
        public Entrepreneur GetById(int id)
        {
            Entrepreneur model = null;

            _dataProvider.ExecuteCmd("dbo.Entrepreneurs_GetById_Details", inputParamMapper : delegate(SqlParameterCollection parms)
            {
                parms.AddWithValue("@Id", id);
            }, singleRecordMapper : delegate(IDataReader reader, short set)
            {
                model = EntrepreneurMapper(reader);
            });
            return(model);
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new Entrepreneur
                {
                    UserName = Input.Email,
                    Email    = Input.Email,
                    Business = new Business()
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        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>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public List <Entrepreneur> GetAll()
        {
            List <Entrepreneur> entrepreneursList = null;

            _dataProvider.ExecuteCmd("dbo.Entrepreneurs_GetAll_Details", inputParamMapper : null,
                                     singleRecordMapper : delegate(IDataReader reader, short set)
            {
                Entrepreneur model = EntrepreneurMapper(reader);
                if (entrepreneursList == null)
                {
                    entrepreneursList = new List <Entrepreneur>();
                }
                entrepreneursList.Add(model);
            });
            return(entrepreneursList);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Entrepreneur entrepreneur = new Entrepreneur();

            entrepreneur.CIN       = Convert.ToInt32(CINTextBox.Text);
            entrepreneur.Nom       = NomTextBox.Text;
            entrepreneur.Prenom    = PrenomTextBox.Text;
            entrepreneur.Adresse   = AdresseTextBox.Text;
            entrepreneur.Telephone = Convert.ToInt32(TelephoneTextBox.Text);
            entrepreneur.Email     = EmailTextBox.Text;
            if (service.AddEntrepreneur(entrepreneur))
            {
                Response.Write(service.GetFirstLetters(entrepreneur.Nom, entrepreneur.Prenom) + " a été ajouté");
            }
            else
            {
                Response.Write("L'ajout n'a pas été effecté");
            }
        }
Exemple #12
0
        public async Task <IActionResult> CreateGuestAccount()
        {
            var business = new Business();

            business.Name = GenerateBusinessName();
            var user = new Entrepreneur()
            {
                Business         = business,
                EmailConfirmed   = true,
                LockoutEnabled   = false,
                TwoFactorEnabled = false,
                UserName         = business.Name,
            };

            _context.Entrepreneurs.Add(user);
            await _context.SaveChangesAsync();

            await _signInManager.SignInAsync(user, true);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #13
0
        public async Task <IActionResult> Index()
        {
            var          viewModel = new HomeIndexVM();
            Entrepreneur user      = null;

            if (User.Identity.IsAuthenticated)
            {
                user = await GetCurrentEntrepreneur();

                if (user.Business != null)
                {
                    var business = await _businessHelper.UpdateGainsSinceLastCheckIn(user.Business.Id);

                    viewModel.Business = business;

                    viewModel.Purchasables = _context
                                             .Purchasables
                                             .Include(s => s.Type)
                                             .OrderBy(s => s.UnlocksAtTotalEarnings)
                                             .Select(s => PurchasableHelper.AdjustPurchasableCostWithSectorBonus(s, user.Business))
                                             .ToList();

                    viewModel.TotalInvestmentsInCompany = (await _businessHelper.GetInvestmentsInCompany(business.Id)).Count.ToString();
                }
            }

            viewModel.MostSuccessfulBusinesses = _context.Business.Where(s => s.Cash != 0 && s.Name != null).OrderByDescending(s => s.Cash).Take(5).ToList();
            viewModel.AvailableSectors         = _context.Sectors.Select(s => new SelectListItem()
            {
                Value = s.Id.ToString(), Text = $"{s.Name} ({s.Description})"
            }).ToList();

            if (user != null && user.Business != null)
            {
                viewModel.PurchasedItems = user.Business.BusinessPurchases.Select(s => (s.Purchase, s.AmountOfPurchases)).ToList();
            }

            return(View(viewModel));
        }
        public async Task <EntrepreneurResponse> SaveAsync(int userId, Entrepreneur entrepreneur)
        {
            var existingUser = await userRepository.FindById(userId);

            if (existingUser == null)
            {
                return(new EntrepreneurResponse("User not found"));
            }
            try
            {
                entrepreneur.UserId = userId;
                await entrepreneurRepository.AddAsync(entrepreneur);

                await unitOfWork.CompleteAsync();

                return(new EntrepreneurResponse(entrepreneur));
            }
            catch (Exception ex)
            {
                return(new EntrepreneurResponse($"An error ocurred while saving the entrepreneur: {ex.Message}"));
            }
        }
        private static Entrepreneur EntrepreneurMapper(IDataReader reader)
        {
            Entrepreneur model         = new Entrepreneur();
            int          startingIndex = 0;

            model.Id                   = reader.GetSafeInt32(startingIndex++);
            model.FirstName            = reader.GetSafeString(startingIndex++);
            model.LastName             = reader.GetSafeString(startingIndex++);
            model.Email                = reader.GetSafeString(startingIndex++);
            model.UserId               = reader.GetSafeInt32(startingIndex++);
            model.IndustryType         = new IndustryType();
            model.IndustryType.Id      = reader.GetSafeInt32(startingIndex++);
            model.IndustryType.Name    = reader.GetSafeString(startingIndex++);
            model.CompanyStatus        = new CompanyStatus();
            model.CompanyStatus.Id     = reader.GetSafeInt32(startingIndex++);
            model.CompanyStatus.Name   = reader.GetSafeString(startingIndex++);
            model.HasSecurityClearance = reader.GetSafeBool(startingIndex++);
            model.HasInsurance         = reader.GetSafeBool(startingIndex++);
            model.HasBonds             = reader.GetSafeBool(startingIndex++);
            model.SpecializedEquipment = reader.GetSafeString(startingIndex++);
            model.ImageUrl             = reader.GetSafeString(startingIndex++);
            return(model);
        }
Exemple #16
0
        public ActionResult <ItemResponse <Entrepreneur> > GetById(int id)
        {
            try
            {
                Entrepreneur entrepreneur = _entrepreneursService.GetById(id);

                if (entrepreneur == null)
                {
                    return(StatusCode(404, new ErrorResponse("Records Not Found")));
                }
                else
                {
                    ItemResponse <Entrepreneur> response = new ItemResponse <Entrepreneur>();
                    response.Item = entrepreneur;
                    return(Ok200(response));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.ToString());
                return(StatusCode(500, new ErrorResponse(ex.Message)));
            }
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string name, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                if (name == "Investor")
                {
                    var user = new Investor
                    {
                        UserName    = Input.Email,
                        Email       = Input.Email,
                        FName       = Input.FName,
                        LName       = Input.LName,
                        CountryId   = Input.Country,
                        DateofBirth = Input.DateOfBirth
                    };
                    user.InvestorCustomizedId = _customId.InvestorCustomId(user);
                    var result = await _userManager.CreateAsync(user);

                    await _userManager.AddToRoleAsync(user, "Investor");

                    if (result.Succeeded)
                    {
                        result = await _userManager.AddLoginAsync(user, info);

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

                            _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                            return(LocalRedirect(returnUrl));
                        }
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                else
                {
                    var user = new Entrepreneur
                    {
                        UserName    = Input.Email,
                        Email       = Input.Email,
                        FName       = Input.FName,
                        LName       = Input.LName,
                        CountryId   = Input.Country,
                        DateofBirth = Input.DateOfBirth
                    };
                    user.EntrepreneurCustomizedId = _customId.EntreprenuerCustomId(user);
                    var result = await _userManager.CreateAsync(user);

                    await _userManager.AddToRoleAsync(user, "Entreprenuer");

                    if (result.Succeeded)
                    {
                        result = await _userManager.AddLoginAsync(user, info);

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

                            _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                            return(LocalRedirect(returnUrl));
                        }
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
 public void Update(Entrepreneur entrepreneur)
 {
     _context.Entrepreneurs.Update(entrepreneur);
 }
 public async Task AddAsync(Entrepreneur entrepreneur)
 {
     await _context.Entrepreneurs.AddAsync(entrepreneur);
 }
        public async Task <IActionResult> OnPostAsync(string name, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/Identity/Account/Manage");
            if (ModelState.IsValid)
            {
                if (name == "Entreprenuer")
                {
                    var user = new Entrepreneur
                    {
                        UserName         = Input.Email,
                        Email            = Input.Email,
                        CountryId        = Input.CountryId,
                        NID              = Input.NID,
                        FName            = Input.FName,
                        LName            = Input.LName,
                        DateofBirth      = Input.DateofBirth,
                        PresentAddress   = Input.PresentAddress,
                        ParmanantAddress = Input.ParmanantAddress,
                    };
                    user.EntrepreneurCustomizedId = _customId.EntreprenuerCustomId(user);

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

                    await _userManager.AddToRoleAsync(user, "Entreprenuer");

                    if (result.Succeeded)
                    {
                        _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));
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                else
                {
                    var user = new Investor
                    {
                        UserName         = Input.Email,
                        Email            = Input.Email,
                        CountryId        = Input.CountryId,
                        NID              = Input.NID,
                        FName            = Input.FName,
                        LName            = Input.LName,
                        DateofBirth      = Input.DateofBirth,
                        PresentAddress   = Input.PresentAddress,
                        ParmanantAddress = Input.ParmanantAddress
                    };
                    user.InvestorCustomizedId = _customId.InvestorCustomId(user);
                    var result = await _userManager.CreateAsync(user, Input.Password);

                    await _userManager.AddToRoleAsync(user, "Investor");

                    if (result.Succeeded)
                    {
                        _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));
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }


            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #21
0
        public static void Initialize(CepikContext context)
        {
            context.Database.EnsureCreated();

            if (context.Entrepreneurs.Any())
            {
                return;   // DB has been seeded
            }

            var addresses = new Address[]
            {
                new Address {
                    City = "Warszawa", Commune = "Gmina Warszawa", HouseNumber = "23", PostalCode = "21-500", Street = "Mazowiecka", Voivodeship = "Mazowieckie"
                },
                new Address {
                    City = "Warszawa", Commune = "Gmina Warszawa", HouseNumber = "11", PostalCode = "21-500", Street = "Znana", Voivodeship = "Mazowieckie"
                },
                new Address {
                    City = "Warszawa", Commune = "Gmina Warszawa", HouseNumber = "3", PostalCode = "21-500", Street = "Secemińska", Voivodeship = "Mazowieckie"
                },
                new Address {
                    City = "Warszawa", Commune = "Gmina Warszawa", HouseNumber = "643", PostalCode = "21-500", Street = "Góralska", Voivodeship = "Mazowieckie"
                },
                new Address {
                    City = "Warszawa", Commune = "Gmina Warszawa", HouseNumber = "314", PostalCode = "21-500", Street = "Hala Wola", Voivodeship = "Mazowieckie"
                },
            };

            foreach (Address address in addresses)
            {
                context.Addresses.Add(address);
            }
            context.SaveChanges();

            var entrepreneurs = new Entrepreneur[]
            {
                new Entrepreneur {
                    NIP = 5423642344, Name = "Jan", Surname = "Kowalski", NumberInEnterpreneurRegister = 2332
                },
                new Entrepreneur {
                    NIP = 5423642000, Name = "Adam", Surname = "Kwiatkowski", NumberInEnterpreneurRegister = 23
                },
                new Entrepreneur {
                    NIP = 5423642001, Name = "Konrad", Surname = "Chmielewski", NumberInEnterpreneurRegister = 2353
                },
                new Entrepreneur {
                    NIP = 5423642002, Name = "Janina", Surname = "Chudzikiewicz", NumberInEnterpreneurRegister = 6423
                },
                new Entrepreneur {
                    NIP = 5423642003, Name = "Tomasz", Surname = "Chudy", NumberInEnterpreneurRegister = 5424
                },
            };

            foreach (Entrepreneur entrepreneur in entrepreneurs)
            {
                context.Entrepreneurs.Add(entrepreneur);
            }
            context.SaveChanges();

            var diagnosticians = new Diagnostician[]
            {
                new Diagnostician {
                    Name = "Ryszard", Surname = "Zieliński", NumberOfPremissions = 0321
                },
                new Diagnostician {
                    Name = "Robert", Surname = "Głębocki", NumberOfPremissions = 1324
                },
                new Diagnostician {
                    Name = "Damian", Surname = "Furtak", NumberOfPremissions = 3531
                },
                new Diagnostician {
                    Name = "Zenon", Surname = "Moszczyński", NumberOfPremissions = 5325
                },
                new Diagnostician {
                    Name = "Zbigniew", Surname = "Karwacki", NumberOfPremissions = 6342
                },
                new Diagnostician {
                    Name = "Harry", Surname = "Matejko", NumberOfPremissions = 3551
                },
                new Diagnostician {
                    Name = "Henryk", Surname = "Antonio", NumberOfPremissions = 5312
                },
                new Diagnostician {
                    Name = "Janusz", Surname = "Kacpszyk", NumberOfPremissions = 6532
                },
            };

            foreach (Diagnostician diagnostician in diagnosticians)
            {
                context.Diagnosticians.Add(diagnostician);
            }
            context.SaveChanges();

            var services = new Service[]
            {
                new Service {
                    Name = "Identyfikacja pojazdu, w tym: sprawdzenie cech identyfikacyjnych oraz ustalenie i porównanie zgodnoÊci faktycznych danych pojazdu z danymi zapisanymi w dowodzie rejestracyjnym lub odpowiadajàcym mu dokumencie"
                },
                new Service {
                    Name = "Identyfikacja pojazdu: sprawdzenie prawidΠowoÊci oznaczeƒ i stanu tablic rejestracyjnych pojazdu"
                },
                new Service {
                    Name = "Sprawdzenie i ocenę prawidłowości działania poszczególnych zespołów i układów pojazdu, w szczególności pod względem bezpieczeństwa jazdy i ochrony środowiska, w tym sprawdzenie i ocenę: stanu technicznego ogumienia"
                },
                new Service {
                    Name = "Sprawdzenie i ocenę prawidłowości działania poszczególnych zespołów i układów pojazdu, w szczególności pod względem bezpieczeństwa jazdy i ochrony środowiska, w tym sprawdzenie i ocenę: stanu technicznego zawieszenia"
                },
                new Service {
                    Name = "Sprawdzenie i ocenę prawidłowości działania poszczególnych zespołów i układów pojazdu, w szczególności pod względem bezpieczeństwa jazdy i ochrony środowiska, w tym sprawdzenie i ocenę: instalacji elektrycznej"
                },
            };

            foreach (Service service in services)
            {
                context.Services.Add(service);
                context.SaveChanges();
            }

            var vehicleControlStations = new VehicleControlStation[]
            {
                new VehicleControlStation {
                    Name = "U Romana", Address = addresses[0], Diagnosticians = { diagnosticians[0] }, Entrepreneur = entrepreneurs[0], NIP = 5423642344, Services = { services[0], services[2] }
                },
                new VehicleControlStation {
                    Name = "Stacja", Address = addresses[1], Diagnosticians = { diagnosticians[5], diagnosticians[6], diagnosticians[7] }, Entrepreneur = entrepreneurs[1], NIP = 5423642000, Services = { services[1], services[3] }
                },
                new VehicleControlStation {
                    Name = "Kontroli", Address = addresses[2], Diagnosticians = { diagnosticians[1] }, Entrepreneur = entrepreneurs[2], NIP = 5423642001, Services = { services[0], services[4] }
                },
                new VehicleControlStation {
                    Name = "Pojazdów", Address = addresses[3], Diagnosticians = { diagnosticians[2] }, Entrepreneur = entrepreneurs[3], NIP = 5423642002, Services = { services[2], services[3] }
                },
                new VehicleControlStation {
                    Name = "Zapraszamy", Address = addresses[4], Diagnosticians = { diagnosticians[4] }, Entrepreneur = entrepreneurs[4], NIP = 5423642003, Services = { services[0], services[3] }
                },
            };

            foreach (VehicleControlStation vehicleControlStation in vehicleControlStations)
            {
                context.VehicleControlStations.Add(vehicleControlStation);
            }
            context.SaveChanges();
        }
Exemple #22
0
 public bool AddEntrepreneur(Entrepreneur entrepreneur)
 {
     utOfWork.EntrepreneurRepository.Add(entrepreneur);
     utOfWork.Commit();
     return(true);
 }
Exemple #23
0
        private void Add()
        {
            var id = ReadString("Input entry name");

            if (_storage.FindData(id) != null)
            {
                Cancel("Person with this ID is already added. ");
                return;
            }

            Console.WriteLine("Input type:");
            Console.WriteLine("1: Student");
            Console.WriteLine("2: Baker");
            Console.WriteLine("3: Entrepreneur");
            var type = ReadNumber("Input type", 1, 3);

            var      firstName = ReadString("First name");
            var      lastName  = ReadString("Last name");
            var      birthDate = ReadString("Birth date");
            DateTime date;

            while (!DateTime.TryParse(birthDate, out date))
            {
                Console.WriteLine("Invalid date.");
                birthDate = ReadString("Birth date");
            }

            var canSkydive = ReadBool("Can skydive?");

            if (type == 1)
            {
                var grade = 0;
                while (grade < 1)
                {
                    grade = ReadNumber("Input grade", 0, 9);
                }

                var studId = ReadString("Student ID (dddd/wwwwww)");
                while (!Student.CheckStudentId(studId))
                {
                    Console.WriteLine(
                        "Invalid student ID. Valid format: dddd/wwwwww where d is [0-9] and w is [a-zA-Z]");
                    studId = ReadString("Student ID");
                }

                var stud = new Student(id);
                stud.FirstName = firstName;
                stud.LastName  = lastName;
                stud.BirthDate = date;
                stud.Grade     = (ushort)grade;
                stud.StudentId = studId;
                stud.CanDive   = canSkydive;
                _studentTable.WriteListContent(new[] { stud });

                var add = ReadBool("Confirm adding?");
                if (add)
                {
                    _storage.Add(stud);
                }
            }

            if (type == 2)
            {
                var baked = ReadNumber("Cakes baked", 0);
                var baker = new Baker(id);
                baker.FirstName  = firstName;
                baker.LastName   = lastName;
                baker.BirthDate  = date;
                baker.CakesBaked = baked;
                baker.CanDive    = canSkydive;
                _bakerTable.WriteListContent(new[] { baker });

                var add = ReadBool("Confirm adding?");
                if (add)
                {
                    _storage.Add(baker);
                }
            }

            if (type == 3)
            {
                var income       = ReadNumber("Monthly income");
                var entrepreneur = new Entrepreneur(id);
                entrepreneur.FirstName     = firstName;
                entrepreneur.LastName      = lastName;
                entrepreneur.BirthDate     = date;
                entrepreneur.MonthlyIncome = income;
                entrepreneur.CanDive       = canSkydive;
                _entrepreneurTable.WriteListContent(new[] { entrepreneur });

                var add = ReadBool("Confirm adding?");
                if (add)
                {
                    _storage.Add(entrepreneur);
                }
            }
        }