public async Task GetAllAsCollectionByCar()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository = new EfDeletableEntityRepository <CarUser>(new ApplicationDbContext(options.Options));

            var carUserOne = new CarUser {
                CarId = "123-098-hjk", UserId = "242hds-78dhgf-7823dsds"
            };
            var carUserTwo = new CarUser {
                CarId = "asd-123-rfv", UserId = "242tre-78dhgf-7823dsds"
            };

            await repository.AddAsync(carUserOne);

            await repository.AddAsync(carUserTwo);

            await repository.SaveChangesAsync();

            var usersService    = new Mock <IUsersService>();
            var carUsersService = new CarUsersService(repository, usersService.Object);

            AutoMapperConfig.RegisterMappings(typeof(CarUserViewModel).Assembly);
            var carUsers = await carUsersService.GetAllAsync <CarUserViewModel>(carUserOne.CarId);

            Assert.Single(carUsers);
        }
예제 #2
0
        } //End Page_Load

        protected void GetUser()
        {
            //Populate the form with the user info
            Int32 UserID = Convert.ToInt32(Request.QueryString["UserID"]);

            try
            {
                //Connect to db
                using (COMP2007Entities db = new COMP2007Entities())
                {
                    //Populate the user from the database
                    CarUser u = (from objs in db.CarUsers where objs.userID == UserID select objs).FirstOrDefault();

                    //Map the user info into the form
                    if (u != null)
                    {
                        txtFirstName.Text = u.firstName;
                        txtLastName.Text = u.lastName;
                        txtPhone.Text = u.phoneNum;
                        txtEmail.Text = u.email;
                        txtUsername.Text = u.userName;
                        txtOldPassHidden.Text = u.userPassword;
                    } //End IF
                } //End using
            } //End TRY
            //Catch any error and redirect to the error page
            catch (SystemException ex)
            {
                Response.Redirect("/error.aspx");
            } //End CATCH
        } //End GetUser
        public async Task <IHttpActionResult> PutCarUser(int id, CarUser carUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != carUser.CarId)
            {
                return(BadRequest());
            }

            db.Entry(carUser).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #4
0
        public ActionResult Assign(CarUser carUser, string drivers)
        {
            //Поиск водителя в базе, проверка соответствия
            var driversForSearch = (from o in _context.Employees
                                    select o).ToList().Where(e => !e.IsFirm);

            foreach (var item in driversForSearch)
            {
                if (item.FullName.Trim().ToUpper() == drivers.Trim().ToUpper())
                {
                    carUser.EmployeeId = item.Id;
                    break;
                }
            }

            var curDriver = (from d in _context.CarUsers
                             where d.EndUsingDate == null
                             select d).ToList();

            foreach (var item in curDriver)
            {
                item.EndUsingDate = carUser.StartUsingDate.AddMinutes(-10);
            }
            _context.CarUsers.Add(carUser);
            _context.SaveChanges();

            return(RedirectToAction("List", "CarUsers", new { carId = carUser.CarId }));
        }
예제 #5
0
        public ActionResult DeleteConfirmed(int id)
        {
            CarUser carUser = db.CarUsers.Find(id);

            db.CarUsers.Remove(carUser);
            db.SaveChanges();
            return(Json(new { success = true }));
        }
예제 #6
0
        public ActionResult DeleteConfirmed(int id)
        {
            CarUser carUser = db.CarUsers.Find(id);

            db.CarUsers.Remove(carUser);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public async Task <IHttpActionResult> GetCarUser(int id)
        {
            CarUser carUser = await db.CarUsers.FindAsync(id);

            if (carUser == null)
            {
                return(NotFound());
            }

            return(Ok(carUser));
        }
예제 #8
0
        public async Task GetDetailsAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository = new EfDeletableEntityRepository <Car>(new ApplicationDbContext(options.Options));

            var carOne = new Car {
                Model = "Форд Фиеста", LicensePlate = "CO1212KA", CompanyId = "72804eudajhkhfvs-dasfa", FuelType = PatniListi.Data.Models.Enums.Fuel.Дизел, TankCapacity = 55, AverageConsumption = 4, InitialFuel = 10, StartKilometers = 234987
            };
            var carUserOne = new CarUser {
                CarId = carOne.Id, UserId = "242hds-78dsd-7823dsds"
            };

            carOne.CarUsers.Add(carUserOne);
            var carTwo = new Car {
                Model = "Форд Фиеста", LicensePlate = "CO4312KA", CompanyId = "72804eud-3464-hfvs-dasfa", FuelType = PatniListi.Data.Models.Enums.Fuel.Бензин, TankCapacity = 55, AverageConsumption = 6, InitialFuel = 10, StartKilometers = 230444
            };
            var carUserTwo = new CarUser {
                CarId = carTwo.Id, UserId = "242hds-78dhgf-7823dsds"
            };

            carTwo.CarUsers.Add(carUserTwo);
            var carUserTwoOne = new CarUser {
                CarId = carTwo.Id, UserId = "242tre-78dhgf-7823dsds"
            };

            carTwo.CarUsers.Add(carUserTwoOne);
            var carThree = new Car {
                Model = "Форд Фиеста 8", LicensePlate = "CO9812KA", CompanyId = "72804eudajhkhfvs-dasfa", FuelType = PatniListi.Data.Models.Enums.Fuel.Дизел, TankCapacity = 55, AverageConsumption = 5, InitialFuel = 10, StartKilometers = 234957
            };
            var carUserThree = new CarUser {
                CarId = carThree.Id, UserId = "242tre-78dhgf-7823dsds"
            };

            carThree.CarUsers.Add(carUserThree);

            await repository.AddAsync(carOne);

            await repository.AddAsync(carTwo);

            await repository.AddAsync(carThree);

            await repository.SaveChangesAsync();

            var carsService = new CarsService(repository);

            AutoMapperConfig.RegisterMappings(typeof(CarDetailsViewModel).Assembly);
            var car = await carsService.GetDetailsAsync <CarDetailsViewModel>(carThree.Id);

            Assert.Equal(carThree.Model, car.Model);
            Assert.Equal(carThree.LicensePlate, car.LicensePlate);
            Assert.Equal(carThree.CarUsers.Count(), car.AllDrivers.Count());
        }
예제 #9
0
 public ActionResult Edit([Bind(Include = "CarUseID,DriverID,CarID,StartDate,EndDate")] CarUser carUser)
 {
     if (ModelState.IsValid)
     {
         db.Entry(carUser).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.CarID    = new SelectList(db.Cars, "CarID", "Make", carUser.CarID);
     ViewBag.DriverID = new SelectList(db.Drivers, "DriverID", "FirstName", carUser.DriverID);
     return(View(carUser));
 }
        public async Task <IHttpActionResult> PostCarUser(CarUser carUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.CarUsers.Add(carUser);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = carUser.CarId }, carUser));
        }
예제 #11
0
        } //end Page_Load


        protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //Store the selected row
            Int32 selectedRow = e.RowIndex;

            //Get the data key, in this case the UserID
            Int32 userID = Convert.ToInt32(grdUsers.DataKeys[selectedRow].Values["UserID"]);



            //Connect To Entity Framework
            using (COMP2007Entities db = new COMP2007Entities())
            {
                //Count the number of postings
                int count = (from cars in db.Cars
                             where cars.userID == userID
                             select cars).Count();

                if (count != 0)
                {
                    Response.Write(@"<script language='javascript'>alert('Please delete your postings first!');</script>");
                }
                else
                {
                    //Select the user by using the UserID
                    CarUser u = (from objs in db.CarUsers where objs.userID == userID select objs).FirstOrDefault();


                    //Delete it from our CarUsers table
                    db.CarUsers.Remove(u);
                    db.SaveChanges();

                    //Find our user in the ASP.Net Idenity user table
                    var userStore = new UserStore<IdentityUser>();
                    var userManager = new UserManager<IdentityUser>(userStore);
                    var user = userManager.Find(u.userName, u.userPassword);

                    //Delete that user from Idenity user table
                    userManager.Delete(user);


                    //Sign the deleted user out
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    authenticationManager.SignOut();

                    //Redirect
                    Response.Redirect("/default.aspx");
                }
            } //End using


        } //End grdUsers_RowDeleting
예제 #12
0
        // GET: CarUsers/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarUser carUser = db.CarUsers.Find(id);

            if (carUser == null)
            {
                return(HttpNotFound());
            }
            return(View(carUser));
        }
        public async Task <IHttpActionResult> DeleteCarUser(int id)
        {
            CarUser carUser = await db.CarUsers.FindAsync(id);

            if (carUser == null)
            {
                return(NotFound());
            }

            db.CarUsers.Remove(carUser);
            await db.SaveChangesAsync();

            return(Ok(carUser));
        }
예제 #14
0
        public ActionResult Edit([Bind(Include = "CarId,DisplayName,Make,LicenseNumber,Color,Type,PurchaseYear,Default")] CarUser carUser)
        {
            carUser.UserId = User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                db.Entry(carUser).State = EntityState.Modified;
                db.SaveChanges();

                return(Json(new { success = true }));
            }
            //ViewBag.Type = new SelectList(db.CarTypes, "Id", "Description", carUser.Type);

            return(PartialView("Edit", carUser));
        }
        public async Task UpdateAsyncAddNewUsersToCar()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository      = new EfDeletableEntityRepository <CarUser>(new ApplicationDbContext(options.Options));
            var usersRepository = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));
            var carsRepository  = new EfDeletableEntityRepository <Car>(new ApplicationDbContext(options.Options));

            var carTwo = new Car {
                Model = "Форд Фиеста", LicensePlate = "CO4312KA", CompanyId = "72804eud-3464-hfvs-dasfa", FuelType = PatniListi.Data.Models.Enums.Fuel.Бензин, TankCapacity = 55, AverageConsumption = 6, InitialFuel = 10, StartKilometers = 230444
            };
            var user = new ApplicationUser {
                UserName = "******", Email = "*****@*****.**", CompanyId = "7480-32141-3274983", FullName = "Петър Петров", LastLoggingDate = DateTime.UtcNow
            };
            var userOne = new ApplicationUser {
                UserName = "******", Email = "*****@*****.**", CompanyId = "7sd0-32141-3274983", FullName = "Мая Маринова", LastLoggingDate = DateTime.UtcNow
            };
            await usersRepository.AddAsync(user);

            await usersRepository.AddAsync(userOne);

            await usersRepository.SaveChangesAsync();

            var carUserTwo = new CarUser {
                CarId = carTwo.Id, UserId = user.Id
            };

            carTwo.CarUsers.Add(carUserTwo);

            await carsRepository.AddAsync(carTwo);

            await carsRepository.SaveChangesAsync();

            IEnumerable <string> drivers = new List <string>()
            {
                "Мая Маринова",
                "Петър Петров",
            };

            var usersService    = new Mock <IUsersService>();
            var carUsersService = new CarUsersService(repository, usersService.Object);

            AutoMapperConfig.RegisterMappings(typeof(UserCarViewModel).Assembly);
            await carUsersService.UpdateAsync(carTwo.Id, carTwo.CompanyId, drivers);

            Assert.Equal(2, carTwo.CarUsers.Count);
        }
예제 #16
0
        // GET: CarUsers/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarUser carUser = db.CarUsers.Find(id);

            if (carUser == null)
            {
                return(HttpNotFound());
            }
            //ViewBag.Type = new SelectList(db.CarTypes, "Id", "Description", carUser.Type);

            return(PartialView("Edit", carUser));
        }
예제 #17
0
        // GET: CarUsers/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarUser carUser = db.CarUsers.Find(id);

            if (carUser == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CarID    = new SelectList(db.Cars, "CarID", "Make", carUser.CarID);
            ViewBag.DriverID = new SelectList(db.Drivers, "DriverID", "FirstName", carUser.DriverID);
            return(View(carUser));
        }
예제 #18
0
        } //End btnSave_Click

        protected void saveEditUser()
        {
            try
            {
                //Connect to EF
                using (COMP2007Entities db = new COMP2007Entities())
                {
                    //Initialized a new CarUser
                    CarUser u = new CarUser();
                    Int32 UserID = 0;

                    //Check he query string for an ID so we know to add or edit
                    if (Request.QueryString["UserID"] != null)
                    {
                        //Get the ID from url
                        UserID = Convert.ToInt32(Request.QueryString["UserID"]);

                        //Get the current user from EF
                        u = (from objs in db.CarUsers where objs.userID == UserID select objs).FirstOrDefault();
                    } //End IF

                    //Set the CarUser field to the form feild

                    u.firstName = txtFirstName.Text;
                    u.lastName = txtLastName.Text;
                    u.email = txtEmail.Text;
                    u.phoneNum = txtPhone.Text;
                    u.userName = txtUsername.Text;
                    u.userPassword = txtPassword.Text;

                    //If the user ID is 0 - We are adding
                    if (UserID == 0)
                    {
                        db.CarUsers.Add(u);
                    } //End IF

                    //Save the changes done to the database
                    db.SaveChanges();
                } //End using
            } //End TRY
            //Catch any error and redirect to the error page
            catch (SystemException ex)
            {
                Response.Redirect("/error.aspx");
            } //End CATCH
        } //End saveEditUser
예제 #19
0
        public async Task UpdateAsync(string carId, string companyId, IEnumerable <string> collection)
        {
            var newDrivers = new List <UserViewModel>();

            if (collection.Any())
            {
                foreach (var name in collection)
                {
                    var user = await this.usersService.GetByNameAsync <UserViewModel>(name, companyId);

                    newDrivers.Add(user);
                }

                var carUsers = await this.GetAllAsync <UserCarViewModel>(carId);

                if (carUsers.Any())
                {
                    foreach (var cu in carUsers)
                    {
                        var carUser = new CarUser
                        {
                            CarId  = cu.CarId,
                            UserId = cu.UserId,
                        };

                        this.carUsersRepository.HardDelete(carUser);

                        await this.carUsersRepository.SaveChangesAsync();
                    }
                }

                foreach (var user in newDrivers)
                {
                    var carUser = new CarUser
                    {
                        CarId  = carId,
                        UserId = user.Id,
                    };

                    await this.carUsersRepository.AddAsync(carUser);
                }

                await this.carUsersRepository.SaveChangesAsync();
            }
        }
예제 #20
0
        public ActionResult Create([Bind(Include = "CarId,DisplayName,Make,LicenseNumber,Color,Type,PurchaseYear,Default")] CarUser carUser)
        {
            carUser.UserId = User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                if (Session["NewServiceGarageId"] != null)
                {
                    carUser.GarageId = Convert.ToInt32(Session["NewServiceGarageId"]);
                }
                db.CarUsers.Add(carUser);
                db.SaveChanges();
                return(Json(new { success = true }));
            }

            //ViewBag.Type = new SelectList(db.CarTypes, "Id", "Description", carUser.Type);

            return(PartialView("Create", carUser));
        }
예제 #21
0
        // GET: CarUsers/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarUser carUser = db.CarUsers.Find(id);

            if (carUser == null)
            {
                return(HttpNotFound());
            }
            else
            {
                ViewBag.Message = "Do You want to delete this car ?";
            }
            return(PartialView("Delete", carUser));
        }
예제 #22
0
        public async Task SetIsDeletedAsync(string carId, string fullName)
        {
            var carUsersFromDb = await this.GetAllAsync <UserCarViewModel>(carId);

            if (carUsersFromDb != null)
            {
                foreach (var cu in carUsersFromDb)
                {
                    var carUser = new CarUser
                    {
                        CarId  = cu.CarId,
                        UserId = cu.UserId,
                    };

                    carUser.ModifiedBy = fullName;
                    this.carUsersRepository.Delete(carUser);

                    await this.carUsersRepository.SaveChangesAsync();
                }
            }
        }
예제 #23
0
        public ActionResult Renewal(int id, bool cancel)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarUser carUser = db.CarUsers.Find(id);

            if (carUser == null)
            {
                return(HttpNotFound());
            }
            if (cancel)
            {
                ViewBag.Message = "Renewal cancellation would mean next week onwards the no more amount would be automatically deducted. Do you agree to the terms and conditions?";
            }
            else
            {
                ViewBag.Message = "Renewal would mean next week onwards the amount would be automatically deducted. Do you agree to the terms and conditions?";
            }
            return(PartialView("Renewal", carUser));
        }
예제 #24
0
        private ICollection <CarUser> GetCarsUsers(Car car, ICollection <User> users)
        {
            ICollection <CarUser> carsUsers = new List <CarUser>();

            foreach (var user in users)
            {
                var carUserFromDb = this.unitOfWork.CarsUsers.GetByCarIdAndUserId(car.CarId, user.UserId);
                if (carUserFromDb != null)
                {
                    carsUsers.Add(carUserFromDb);
                }
                else
                {
                    var carUser = new CarUser
                    {
                        Car  = car,
                        User = user
                    };
                    carsUsers.Add(carUser);
                }
            }
            return(carsUsers);
        }
예제 #25
0
 public IResult Delete(CarUser user)
 {
     _carUserDal.Delete(user);
     return(new SuccessResult());
 }
예제 #26
0
 public IResult Update(CarUser user)
 {
     _carUserDal.Update(user);
     return(new SuccessResult());
 }
예제 #27
0
        protected void btnPost_Click(object sender, EventArgs e)
        {
            if (checkClasses())
            {
                string userName = User.Identity.Name;
                Int32 carID = 0;
                CarUser carUser = new CarUser();
                Car car = new Car();
                CarClass cClass = new CarClass();

                try
                {
                    //use EF to connect to SQL seer
                    using (COMP2007Entities db = new COMP2007Entities())
                    {
                        //check he query string for ID some we know add or edit
                        if (Request.QueryString["carID"] != null)
                        {
                            //Get the id from url
                            carID = Convert.ToInt32(Request.QueryString["carID"]);
                            car = (from objs in db.Cars where objs.carID == carID select objs).FirstOrDefault();
                            cClass = (from objs in db.CarClasses where objs.carID == carID select objs).FirstOrDefault();
                        }

                        //The URL is empty, get the userID of the logged in user.
                        else
                        {
                            carUser = (from objs in db.CarUsers where objs.userName == userName select objs).FirstOrDefault();
                            car.userID = carUser.userID;
                        }

                        car.engineID = Convert.ToInt32(ddlEngine.SelectedValue);
                        car.modelYear = Convert.ToInt32(ddlYear.SelectedValue);
                        car.transmission = ddlTransmission.SelectedItem.Text;

                        if (rblNewUsed.SelectedValue == "New")
                            car.@new = true;
                        else
                            car.@new = false;

                        car.color = txtColour.Text;
                        car.cost = Convert.ToDecimal(txtCost.Text);
                        car.location = txtLocation.Text;
                        car.kilometer = Convert.ToInt32(txtKM.Text);
                        car.listedDate = DateTime.Today;

                        if (carID == 0)
                        {
                            db.Cars.Add(car);
                        }

                        db.SaveChanges();

                        cClass.modelID = Convert.ToInt32(ddlModel.SelectedValue);

                        cClass.@class = carClass;

                        if (carID == 0)
                        {
                            cClass.carID = car.carID;
                            db.CarClasses.Add(cClass);
                        }

                        db.SaveChanges();
                    }
                } //End TRY
                catch (SystemException ex)
                {
                    Debug.WriteLine("ERROR MESSAGE: " + ex.Message);
                    Response.Redirect("/error.aspx");
                } //End CATCH
            }
            else
            {
                lblClass.Text = "Please pick a class";
            }
            Response.Redirect("/admin/account.aspx");
        }//End btnPost_Click
예제 #28
0
        } //End getAccount


        protected void getPosts()
        {
            //Get the user name of the logged in user
            string userName = User.Identity.Name;
            //Create some objects
            Int32 userID = 0;
            CarUser carUser = new CarUser();
            Car car = new Car();
            CarClass cClass = new CarClass();

            try
            {
                //Connect to EF
                using (COMP2007Entities db = new COMP2007Entities())
                {

                    //Cherck the URL for ID
                    if (Request.QueryString["UserID"] != null)
                    {
                        //Get the id from url
                        userID = Convert.ToInt32(Request.QueryString["userID"]);

                        //Get that records from the database
                        carUser = (from objs in db.CarUsers where objs.userID == userID select objs).FirstOrDefault();
                    }

                    //The URL is empty, get the userID of the logged in user.
                    else
                    {
                        carUser = (from objs in db.CarUsers where objs.userName == userName select objs).FirstOrDefault();
                    }

                    userID = carUser.userID;

                    //Count the number of postings
                    int count = (from cars in db.Cars
                                 where cars.userID == userID
                                 select cars).Count();

                    //If its greater that 0 them them
                    if (count > 0)
                    {
                        var objE = (from cars in db.Cars
                                    join cu in db.CarUsers on cars.userID equals cu.userID
                                    join carE in db.CarEngines on cars.engineID equals carE.engineID
                                    join carclass in db.CarClasses on cars.carID equals carclass.carID
                                    join model in db.CarModels on carclass.modelID equals model.modelID
                                    join make in db.CarMakes on model.makeID equals make.makeID
                                    where cars.userID == userID
                                    select new { make.make, model.model, carclass.@class, cars.modelYear, cars.transmission, carE.fuelType, cars.@new, cars.cost, cars.kilometer, cars.carID });

                        grdPosts.DataSource = objE.ToList();
                        grdPosts.DataBind();
                    }

                    //If there is none ask if they want to make one
                    else
                    {
                        grdPosts.Visible = false;
                        pnlAdPost.Visible = true;
                    }
                }
            } //End TRY
            //Catch any error and redirect to the error page
            catch (SystemException ex)
            {
                Response.Redirect("/error.aspx");
            } //End CATCH
        }
예제 #29
0
 public IResult Add(CarUser user)
 {
     _carUserDal.Add(user);
     return(new SuccessResult());
 }