Example #1
0
        public async Task Should_create_company_employee_profile_success()
        {
            var        client     = GetClient();
            CompanyDto companyDto = new CompanyDto();

            companyDto.Name      = "IBM";
            companyDto.Employees = new List <EmployeeDto>()
            {
                new EmployeeDto()
                {
                    Name = "Tom",
                    Age  = 19
                }
            };

            companyDto.Profile = new ProfileDto()
            {
                RegisteredCapital = 100010,
                CertId            = "100",
            };

            var           httpContent = JsonConvert.SerializeObject(companyDto);
            StringContent content     = new StringContent(httpContent, Encoding.UTF8, MediaTypeNames.Application.Json);
            await client.PostAsync("/companies", content);

            var allCompaniesResponse = await client.GetAsync("/companies");

            var body = await allCompaniesResponse.Content.ReadAsStringAsync();

            var returnCompanies = JsonConvert.DeserializeObject <List <CompanyDto> >(body);

            Assert.Equal(1, returnCompanies.Count);
            Assert.Equal(companyDto.Employees.Count, returnCompanies[0].Employees.Count);
            Assert.Equal(companyDto.Employees[0].Age, returnCompanies[0].Employees[0].Age);
            Assert.Equal(companyDto.Employees[0].Name, returnCompanies[0].Employees[0].Name);
            Assert.Equal(companyDto.Profile.CertId, returnCompanies[0].Profile.CertId);
            Assert.Equal(companyDto.Profile.RegisteredCapital, returnCompanies[0].Profile.RegisteredCapital);

            var scope                = Factory.Services.CreateScope();
            var scopedServices       = scope.ServiceProvider;
            CompanyDbContext context = scopedServices.GetRequiredService <CompanyDbContext>();

            Assert.Equal(1, context.Companies.ToList().Count);
            var firstCompany = await context.Companies
                               .Include(company => company.Profile)
                               .FirstOrDefaultAsync();

            Assert.Equal(companyDto.Profile.CertId, firstCompany.Profile.CertId);
        }
        public void PromoteEmployeeToManager(int id, Department department)
        {
            using (var db = new CompanyDbContext())
            {
                var user = db.Users.SingleOrDefault(x => x.Id == id);
                if (user == null)
                {
                    throw new Exception("Employee with given Id does not exist");
                }
                user.DepartmentId = department.Id;
                user.UserType     = UserType.Manager;

                db.SaveChanges();
            }
        }
        public User LogIn(string username, string password)
        {
            User user;

            using (var ctx = new CompanyDbContext())
            {
                user = ctx.Users.SingleOrDefault(x => x.UserName.Equals(username) && x.Password.Equals(password));

                if (user != null)
                {
                    return(user);
                }
                return(null);
            }
        }
        public List <Project> GetAllProjectsByEmployeeWithDepartmentAndManager(int employeeId)
        {
            using (var ctx = new CompanyDbContext())
            {
                List <Project> projects = new List <Project>();
                List <Task>    tasks    = ctx.Tasks.Where(y => y.EmployeeID.Equals(employeeId)).ToList();

                foreach (Task t in tasks)
                {
                    Project pr = GetProjectByID(t.ProjectID);
                    projects.Add(pr);
                }
                return(projects);
            }
        }
 //public Department GetDepartmentById(int id)
 //{
 //    using (var db = new CompanyDbContext())
 //    {
 //        return db.Departmants.SingleOrDefault(x => x.Id == id);
 //    }
 //}
 public void AddNewDepartmentWeb(string name, string description, int?managerId)
 {
     using (var db = new CompanyDbContext())
     {
         var departments = new Department
         {
             Name               = name,
             Description        = description,
             ManagerId          = managerId,
             IsDepartmentActive = true
         };
         db.Departmants.Add(departments);
         db.SaveChanges();
     }
 }
Example #6
0
 public void deleteLeave()
 {
     using (var context = new CompanyDbContext())
     {
         Console.WriteLine("Delete EmployeeLeave:");
         Console.Write("Enter Employee_Name:");
         string name = Console.ReadLine();
         var    b    = context.Employees.Single(t => t.EmployeeName == name);
         leave.EmployeeId = b.EmployeeId;
         var l = context.EmployeeLeave.Single(t => t.EmployeeId == leave.EmployeeId);
         leave.LeaveId = l.LeaveId;
         EmployeeLeave.Remove(leave);
         SaveChanges();
     }
 }
Example #7
0
        public void CheckQueryFiltersAreAppliedToEntityClassesOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <CompanyDbContext>();

            using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("accessKey")))
            {
                var entities = context.Model.GetEntityTypes().ToList();

                //ATTEMPT
                var queryFilterErrs = entities.CheckEntitiesHasAQueryFilter().ToList();

                //VERIFY
                queryFilterErrs.Any().ShouldBeFalse(string.Join('\n', queryFilterErrs));
            }
        }
        public async Task <IEnumerable <Customer> > GetAllCustomersMapped()
        {
            IEnumerable <Entity.Models.Customer> customers = null;

            using (CompanyDbContext context = new CompanyDbContext())
            {
                customers = await context.Customer.Include(c => c.Orders)
                            .ThenInclude(o => o.OrderItems)
                            .ThenInclude(oi => oi.Product)
                            .ThenInclude(p => p.Supplier)
                            .AsNoTracking()
                            .ToListAsync();
            }

            return(_mapper.Map <IEnumerable <Customer> >(customers));
        }
        public void TestCreateCompany()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <CompanyDbContext>();

            using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider(null)))
            {
                context.Database.EnsureCreated();

                //ATTEMPT
                var company = Company.AddTenantToDatabaseWithSaveChanges("TestCompany", PaidForModules.None, context);

                //VERIFY
                company.DataKey.ShouldNotBeNull();
            }
        }
Example #10
0
        public async Task <IEnumerable <DepartmentListModel> > GetDepartmentList()
        {
            using (var context = new CompanyDbContext())
            {
                var department = await context.Department
                                 .Include(d => d.Employee)
                                 .Select(d => new DepartmentListModel()
                {
                    Id             = d.Id,
                    DepartmentName = d.DepartmentName
                })
                                 .ToListAsync();

                return(department);
            }
        }
Example #11
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args)
                       .Build();


            using (var scope = host.Services.CreateScope())
            {
                var serviceProvider = scope.ServiceProvider;
                var config          = serviceProvider.GetRequiredService <IConfiguration>();

                CompanyDbContext.CreateDefaultAccounts(serviceProvider, config).Wait();
            }

            host.RunAsync().Wait();
        }
Example #12
0
        public ActionResult Edit(Product product)
        {
            CompanyDbContext db = new CompanyDbContext();
            Product          existingProduct = db.Products.Where(p => p.ProductID == product.ProductID).FirstOrDefault();

            existingProduct.ProductName        = product.ProductName;
            existingProduct.Price              = product.Price;
            existingProduct.DateOfPurchase     = product.DateOfPurchase;
            existingProduct.BrandID            = product.BrandID;
            existingProduct.CategoryID         = product.CategoryID;
            existingProduct.AvailabilityStatus = product.AvailabilityStatus;
            existingProduct.Active             = product.Active;
            //TODO: grab the photo from the form and update it in the database
            db.SaveChanges();
            return(RedirectToAction("index", "Products"));
        }
        public async Task <bool> InviteDeveloperToProject(int developerId, int projectId)
        {
            using (CompanyDbContext context = CompanyDbContext.Create())
            {
                var entity = new ProjectDeveloper
                {
                    DeveloperId = developerId,
                    ProjectId   = projectId
                };

                context.ProjectDeveloper.Add(entity);
                await context.SaveChangesAsync();

                return(true);
            }
        }
Example #14
0
 public void EditTask(int id, int estimatedTime, int remainingTime, TaskState taskState, string taskComment)
 {
     using (var db = new CompanyDbContext())
     {
         var tasks = db.Tasks.SingleOrDefault(x => x.Id == id);
         if (tasks == null)
         {
             throw new Exception("Task with given Id doesn't exist");
         }
         tasks.EstimatedWorkingTime = estimatedTime;
         tasks.RemainingWorkingTime = remainingTime;
         tasks.TaskState            = taskState;
         tasks.TaskComment          = taskComment;
         db.SaveChanges();
     }
 }
 public override void Set(string key, string value)
 {
     base.Set(key, value);
     using (var db = new CompanyDbContext(defaultValue.GetValue <DbConfigs>("DbConfigs")))
     {
         var config = db.Config.FirstOrDefault(a => a.Name == key);
         if (config == null)
         {
             config = new Config {
                 Name = key
             };
             db.Config.Add(config);
         }
         config.Value = value;
         db.SaveChanges();
     }
 }
Example #16
0
        public async Task <IEnumerable <ProjectsListModel> > GetProjectsList()
        {
            using (var context = new CompanyDbContext())
            {
                var projects = await context.Project
                               .Include(p => p.EmployeeProject)
                               .Select(p => new ProjectsListModel()
                {
                    Id       = p.Id,
                    Name     = p.ProjectName,
                    Duration = p.Duration
                })
                               .ToListAsync();

                return(projects);
            }
        }
Example #17
0
        public async Task <Developer> CreateAsync(string firstName, string lastName, DateTime workedFrom)
        {
            using (CompanyDbContext context = CompanyDbContext.Create())
            {
                var entity = new Dal.Entitites.Developer
                {
                    FirstName  = firstName,
                    LastName   = lastName,
                    WorkedFrom = workedFrom
                };

                context.Developer.Add(entity);
                await context.SaveChangesAsync();

                return(ToDomain(entity));
            }
        }
Example #18
0
 public void addProjects()
 {
     using (var context = new CompanyDbContext())
     {
         Console.WriteLine("Add Projects:");
         Console.Write("Enter Project_Name:");
         project.ProjectName = Console.ReadLine();
         Console.Write("Enter DeadLine:");
         project.Deadline = System.DateTime.Parse(Console.ReadLine());
         Console.Write("Enter BusinessUnitName:");
         string bname = Console.ReadLine();
         var    obj   = context.BusinessUnits.Single(t => t.UnitName == bname);
         project.BusinessUnitId = obj.BusinessUnitId;
         Projects.Add(project);
         SaveChanges();
     }
 }
        public Department InsertDepartment(string name, string description, int company)
        {
            var department = new Department
            {
                Name               = name,
                Description        = description,
                isDepartmentActive = true,
                ComapanyID         = company
            };

            using (var ctx = new CompanyDbContext())
            {
                var newDepartment = ctx.Departments.Add(department);
                ctx.SaveChanges();
                return(newDepartment);
            }
        }
Example #20
0
        public async Task <IEnumerable <LaptopListModel> > GetLaptopList()
        {
            using (var context = new CompanyDbContext())
            {
                var laptops = await context.Laptop
                              .Include(l => l.Employee)
                              .Select(d => new LaptopListModel()
                {
                    Id           = d.Id,
                    BrandName    = d.BrandName,
                    EmployeeName = context.Employee.FirstOrDefault(e => e.Id == d.EmployeeId).FirstName + " " + context.Employee.FirstOrDefault(e => e.Id == d.EmployeeId).LastName
                })
                              .ToListAsync();

                return(laptops);
            }
        }
        public void EditDepartment(int id, string name, string description, int?managerId, bool isDepartmentActive)
        {
            using (var db = new CompanyDbContext())
            {
                var department = db.Departmants.SingleOrDefault(x => x.Id == id);
                if (department == null)
                {
                    throw new Exception("There is no department with given id");
                }
                department.Name               = name;
                department.Description        = description;
                department.ManagerId          = managerId;
                department.IsDepartmentActive = isDepartmentActive;

                db.SaveChanges();
            }
        }
Example #22
0
 public void addUnits()
 {
     using (var context = new CompanyDbContext())
     {
         Console.WriteLine("Add Business Units:");
         Console.Write("Enter UnitName:");
         unit.UnitName = Console.ReadLine();
         Console.Write("Enter CompanyId");
         unit.CompanyId = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter NumberOfProjects:");
         unit.NumberOfProjects = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter NumberOfEmployees:");
         unit.NumberOfEmployees = Convert.ToInt32(Console.ReadLine());
         BusinessUnits.Add(unit);
         SaveChanges();
     }
 }
        public void deleteProject(Project project)
        {
            using (var ctx = new CompanyDbContext())
            {
                var deleteProject = ctx.Projects.SingleOrDefault(x => x.Id.Equals(project.Id));
                if (deleteProject == null)
                {
                    throw new Exception("Project with given Id does not exist");
                }

                var deleteTasksOnProject = ctx.Tasks.Where(y => y.ProjectID.Equals(project.Id)).ToList();
                deleteTasksOnProject.ForEach(x => x.StateOfTask = "Canceled");

                deleteProject.StateOfProject = "Canceled";
                ctx.SaveChanges();
            }
        }
        public async Task <bool> DeleteDeveloperFromProject(int developerId, int projectId)
        {
            using (CompanyDbContext context = CompanyDbContext.Create())
            {
                var entity = await context.ProjectDeveloper.SingleOrDefaultAsync(item => item.DeveloperId == developerId && item.ProjectId == projectId);

                if (entity == null)
                {
                    return(false);
                }

                context.ProjectDeveloper.Remove(entity);

                await context.SaveChangesAsync();

                return(true);
            }
        }
Example #25
0
        public ActionResult Edit(Product product)
        {
            CompanyDbContext db = new CompanyDbContext();

            Product product1 = db.Products.Where(x => x.ProductID == product.ProductID).FirstOrDefault();

            product1.ProductName        = product.ProductName;
            product1.Price              = product.Price;
            product1.DateOfPurchase     = product.DateOfPurchase;
            product1.CategoryID         = product.CategoryID;
            product1.BrandID            = product.BrandID;
            product1.AvailabilityStatus = product.AvailabilityStatus;
            product1.Active             = product.Active;

            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
Example #26
0
        public void EditUser(int id, string name, string lastName, DateTime dayOfBirth, Gender gender, Department department)
        {
            using (var db = new CompanyDbContext())
            {
                var user = db.Users.Single(x => x.Id == id);
                if (user == null)
                {
                    throw new Exception("Specified user doesn't exist");
                }
                user.Name       = name;
                user.LastName   = lastName;
                user.DayOfBirth = dayOfBirth;
                user.Gender     = gender;
                user.Department = department;

                db.SaveChanges();
            }
        }
Example #27
0
 public void CreateAdmin(string username, string password, string name, string lastName, DateTime dayOfBirth, Gender gender)
 {
     using (var db = new CompanyDbContext())
     {
         var user = new User
         {
             DayOfBirth = dayOfBirth,
             Name       = name,
             LastName   = lastName,
             Password   = password,
             Username   = username,
             Gender     = gender,
             UserType   = UserType.Administrator
         };
         db.Users.Add(user);
         db.SaveChanges();
     }
 }
Example #28
0
        public async Task <bool> DeleteAsync(int id)
        {
            using (CompanyDbContext context = CompanyDbContext.Create())
            {
                var entity = await context.Project.SingleOrDefaultAsync(item => item.Id == id);

                if (entity == null)
                {
                    return(false);
                }

                context.Project.Remove(entity);

                await context.SaveChangesAsync();

                return(true);
            }
        }
Example #29
0
        public async Task <Project> CreateAsync(string name, string description, DateTime startAt)
        {
            using (CompanyDbContext context = CompanyDbContext.Create())
            {
                var entity = new Dal.Entitites.Project
                {
                    Description = description,
                    Name        = name,
                    StartAt     = startAt
                };

                context.Project.Add(entity);

                await context.SaveChangesAsync();

                return(ToDomain(entity));
            }
        }
Example #30
0
 public void AddNewProject(string projectName, int projectPrice, string projectDescription, DateTime projectStartDate, DateTime projectEndDate)
 {
     using (var db = new CompanyDbContext())
     {
         var project = new ProjectClass.Project
         {
             ProjectName        = projectName,
             ProjectPrice       = projectPrice,
             ProjectDescription = projectDescription,
             ProjectStartDate   = projectStartDate,
             ProjectEndDate     = projectEndDate,
             DepartmentId       = (int)Company.Instance.CurrentUser.DepartmentId,
             ProjectManagerId   = Company.Instance.CurrentUser.Id,
         };
         db.Projects.Add(project);
         db.SaveChanges();
     }
 }
Example #31
0
        //[ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                string org_name = model.CompanyName.Replace(' ', '_');
                FileWorker.CreateCompanyRepo(org_name);
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = org_name, RegisterDate = DateTime.Now, NextPayment = DateTime.Now.AddMonths(1) };
                var result = await UserManager.CreateAsync(user, model.Password);

                var CompanyDb = new CompanyDbContext(org_name);
                var fio = model.FIO.Split(' ');
                CompanyDb.Employees.Add(new Employee() { Surname = fio[0], Name = fio[1], Patronymic = fio[2], Login = model.Email, Password = "" });
                CompanyDb.SaveChanges();

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                    // Отправка сообщения электронной почты с этой ссылкой
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");

                    return  Json(Url.Action("Index", "MainPage"));
                }
             
            }         
            return GetErrors();
        }