Esempio n. 1
0
 public ActionResult Create(Departments dep)
 {
     //Contso.Data.ContsoMVC db = new Contso.Data.ContsoMVC();
     //ViewBag.Instructorid = new SelectList(db.Instructor, "id", "id");
     departmentService.Create(dep);
     return(RedirectToAction("Index"));
 }
Esempio n. 2
0
        public DepartmentsControllerTests()
        {
            var list = new List <Department>
            {
                new Department {
                    Id = 1, Name = "test 1", OfferingId = 2
                },
                new Department {
                    Id = 2, Name = "test 2", OfferingId = 1
                }
            }.AsQueryable();

            var mockContext          = Substitute.For <TtContext>();
            var departmentRepository = Substitute.For <Repository <Department> >(mockContext);
            var offeringRepository   = Substitute.For <Repository <Offering> >(mockContext);

            _service = Substitute.For <DepartmentService>(departmentRepository, offeringRepository);
            _service.GetList().Returns(list);
            _service.GetItem(Arg.Any <int>()).Returns(new Department {
                Id = 1, Name = "test 1", OfferingId = 1
            });
            _service.Create(Arg.Any <Department>());
            _service.Update(Arg.Any <int>(), Arg.Any <Department>());
            _service.Delete(Arg.Any <int>());

            var mockLogger = Substitute.For <ILoggerFactory>();

            _controller = new DepartmentsController(_service, mockLogger);
        }
        public ActionResult Create(Department department)
        {
            DepartmentService service = new DepartmentService();

            service.Create(department);
            return(RedirectToAction("Index"));
        }
Esempio n. 4
0
        public void the_entity_should_be_initialized_with_default_values()
        {
            var s = new DepartmentService();
            var d = s.Create();

            Assert.AreEqual("New Department", d.Name, "OnCreate was not called.");
        }
Esempio n. 5
0
		public void DepartmentCreate()
		{		
			Department instance1 = new Department();
			Assert.IsNotNull(instance1, "DepartmentTest.DepartmentNew: Unable to create instance using new()");
			Department instance2 = DepartmentService.Create();
			Assert.IsNotNull(instance2, "DepartmentTest.DepartmentCreate: Unable to create instance");
		}
Esempio n. 6
0
        public void the_entity_should_not_be_null()
        {
            var s = new DepartmentService();
            var d = s.Create();

            Assert.IsNotNull(d, "The entity was not created.");
        }
Esempio n. 7
0
        public ActionResult Create(CreateForm form)
        {
            if (ModelState.IsValid)
            {
                C.Department Department = new C.Department(form.Title, DateTime.Now, form.Description, SessionUser.GetUser().Id, true);

                int?DepId = DepartmentService.Create(Department, SessionUser.GetUser().Id);
                if (DepId != null)
                {
                    if (DepartmentService.ChangeHeadOfDepartment((int)DepId, form.SelectedHeadOfDepartmentId, SessionUser.GetUser().Id))
                    {
                        return(RedirectToAction("Index"));
                    }
                }
                IEnumerable <C.Employee> Employees = EmployeeService.GetAllActive();
                List <SelectListItem>    HeadOfDepartmentCandidates = new List <SelectListItem>();
                foreach (C.Employee emp in Employees)
                {
                    HeadOfDepartmentCandidates.Add(new SelectListItem()
                    {
                        Text  = emp.FirstName + " " + emp.LastName + " (" + emp.Email + ")",
                        Value = emp.Employee_Id.ToString()
                    });
                }
                form.HeadOfDepartmentCandidateList = HeadOfDepartmentCandidates;
            }
            return(View(form));
        }
        public void CreateTest()
        {
            var item = new Department();

            _service.Create(item);
            _departmentRepository.Received(1).Create(item);
        }
        protected void btnOk_Click(object sender, EventArgs e)
        {
            DepartmentService departmentService = new DepartmentService();
            Department        department        = new Department
            {
                DepartmentName = txtDepartmentName.Text,
                Description    = txtDescription.Text,
                ParentId       = int.Parse(ddlParent.SelectedValue),
                LeaderId       = int.Parse(ddlLeader.SelectedValue),
                SortCode       = departmentService.GetSortCode(int.Parse(ddlParent.SelectedValue))
            };
            int id;

            if (int.TryParse(Request["id"], out id))
            {
                department.DepartmentId = id;
                departmentService.Update(department);
            }
            else
            {
                departmentService.Create(department);
            }

            PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
        }
Esempio n. 10
0
        public ActionResult Create([Bind(Include = "Id,DepartmentName")] Department department)
        {
            if (ModelState.IsValid)
            {
                _departmentService.Create(department);
                return(RedirectToAction("Index"));
            }

            return(View(department));
        }
        public async Task <IActionResult> Post([FromBody] Department model)
        {
            string message = await _service.Validate(new DepartmentGetOptions { FullName = model.FullName });

            if (!string.IsNullOrEmpty(message))
            {
                return(BadRequest(new { message }));
            }
            return(Ok(await _service.Create(model)));
        }
Esempio n. 12
0
        public void it_should_call_OnSaving_for_added_entities()
        {
            using (var work = Create.Work())
            {
                var s = new DepartmentService(work);
                var d = s.Create();
                d.Name = bad_department_name;
                s.Add(d);

                work.Save();
            }
        }
        public void it_should_call_OnSaving_for_added_entities()
        {
            using (var work = Create.Work())
            {
                var s = new DepartmentService(work);
                var d = s.Create();
                d.Name = bad_department_name;
                s.Add(d);

                work.Save();
            }
        }
Esempio n. 14
0
        public void Test_CreateDepartment()
        {
            IDepartmentService service = new DepartmentService(Settings.Default.connString);
            Department         dep1    = new Department()
            {
                name      = "工程部",
                remark    = "工程部们",
                companyId = 1
            };

            Assert.IsTrue(service.Create(dep1));

            Department dep2 = new Department()
            {
                name      = "人事部",
                remark    = "人事部门",
                companyId = 2
            };

            Assert.IsTrue(service.Create(dep2));
        }
Esempio n. 15
0
        public ActionResult Create(DepartmentViewModel departmentViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(departmentViewModel));
            }

            var departmentModel = departmentViewModel.GetDepartmentModelByDepartmentViewModel();

            departmentService.Create(departmentModel);

            return(RedirectToAction("Index", "Department"));
        }
Esempio n. 16
0
        public void SetUp()
        {
            // create the test entity, using a guid string for its name
            using (var work = Ignorance.Create.Work())
            {
                var service = new DepartmentService(work);

                this.Dept           = service.Create();
                this.Dept.Name      = Guid.NewGuid().ToString();
                this.Dept.GroupName = Guid.NewGuid().ToString();
                service.Add(this.Dept);

                work.Save();
            }
        }
Esempio n. 17
0
        public ActionResult Create([FromBody] Department department)
        {
            // Validate departmentCode
            if (_departmentService.GetByOne(department.DepartmentCode) == null)
            {
                var dept = _departmentService.Create(department);

                if (dept == null)
                {
                    return(BadRequest());
                }

                return(Ok(dept.Id));
            }
            else
            {
                return(BadRequest("Department Code is existed"));
            }
        }
        public async void Create_department_valid_parameters_must_have_called_add()
        {
            //Arrange
            var repository  = A.Fake <IRepository>();
            var department  = new Department(0, 0, 20, 0, "Department3");
            var departments = new List <Department>()
            {
                new Department(0, 0, 0, 10, "Department1"),
                new Department(0, 0, 10, 20, "Department2")
            };

            A.CallTo(() => repository.ListAsync <Department>()).Returns(departments);
            var service = new DepartmentService(repository);

            //Act
            await service.Create(department);

            //Assert
            A.CallTo(() => repository.Add <Department>(department)).MustHaveHappenedOnceExactly();
        }
Esempio n. 19
0
        public async void Create()
        {
            var mock  = new ServiceMockFacade <IDepartmentRepository>();
            var model = new ApiDepartmentRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Department>())).Returns(Task.FromResult(new Department()));
            var service = new DepartmentService(mock.LoggerMock.Object,
                                                mock.RepositoryMock.Object,
                                                mock.ModelValidatorMockFactory.DepartmentModelValidatorMock.Object,
                                                mock.BOLMapperMockFactory.BOLDepartmentMapperMock,
                                                mock.DALMapperMockFactory.DALDepartmentMapperMock,
                                                mock.BOLMapperMockFactory.BOLEmployeeDepartmentHistoryMapperMock,
                                                mock.DALMapperMockFactory.DALEmployeeDepartmentHistoryMapperMock);

            CreateResponse <ApiDepartmentResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            mock.ModelValidatorMockFactory.DepartmentModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiDepartmentRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Department>()));
        }
Esempio n. 20
0
        //[MenuHightlight(CurrentItem = "depart_tt", CurrentParentItem = "user_home")]
        public ActionResult Create(DepartmentViewModel viewModel)
        {
            var areas = _areaService.Get(properties: new[] { "Id", "AreaName" }).Select(p => new SelectListItem
            {
                Text  = p.AreaName,
                Value = p.Id.ToString(),
            }).ToList();

            ViewData["Areas"] = areas;

            var expression = new[]
            {
                new ExpressionCriteria {
                    PropertyName = "DEPT_INFO_ISDEL", Value = 0, Operate = Operator.Equal
                },
            };
            var deps = _departmentService.Get(expression).Select(p => new SelectListItem
            {
                Text  = p.Name,
                Value = p.Id.ToString(),
            }).ToList();

            ViewData["Departments"] = deps;

            if (viewModel.DepartmentContract.AreaId == default(Guid))
            {
                ModelState.AddModelError("", "请选择区域");
            }
            else if (viewModel.DepartmentContract.IsValid())
            {
                var rs = _departmentService.Create(viewModel.DepartmentContract);
                if (rs != ResultStatus.Success)
                {
                    ModelState.AddModelError("", rs == ResultStatus.Duplicate ? "记录已经存在" : "添加失败");
                    return(View(new DepartmentViewModel(viewModel.DepartmentContract)));
                }
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", viewModel.DepartmentContract.ErrorMessage);
            return(View(new DepartmentViewModel(viewModel.DepartmentContract)));
        }
        public void added_entities_should_not_persist()
        {
            var guidName = Guid.NewGuid().ToString();
            // using Service API, Add a record
            using (var work = Ignorance.Create.Work())
            {
                var s = new DepartmentService(work);
                var d = s.Create();
                d.Name = guidName;
                s.Add(d);

                // but do NOT call Save on Work.
            }

            // test (using straight EF) that the record still exists.
            using (var db = new AdventureWorksEntities())
            {
                var d = db.Departments.FirstOrDefault(p => p.Name == guidName);
                Assert.IsNull(d, "Add was persisted without Work.Save().");
            }
        }
Esempio n. 22
0
        public void added_entities_should_not_persist()
        {
            var guidName = Guid.NewGuid().ToString();

            // using Service API, Add a record
            using (var work = Ignorance.Create.Work())
            {
                var s = new DepartmentService(work);
                var d = s.Create();
                d.Name = guidName;
                s.Add(d);

                // but do NOT call Save on Work.
            }

            // test (using straight EF) that the record still exists.
            using (var db = new AdventureWorksEntities())
            {
                var d = db.Departments.FirstOrDefault(p => p.Name == guidName);
                Assert.IsNull(d, "Add was persisted without Work.Save().");
            }
        }
Esempio n. 23
0
        public static int Run(
            ILogger logger,
            DepartmentService departmentService
            )
        {
            try
            {
                string folderName      = "Seed";
                string contentRootPath = Directory.GetCurrentDirectory();
                string folderPath      = Path.Combine(contentRootPath, folderName);
                if (!Directory.Exists(folderPath))
                {
                    throw new IOException("Папка с файлами инициализации базы данных не найдена.");
                }
                #region Seed faculties
                string facultiesFilePath = Path.Combine(folderPath, "faculties.json");
                if (!File.Exists(facultiesFilePath))
                {
                    throw new IOException("Файл инициализации факультетов не найден.");
                }
                List <Department> faculties = JsonConvert.DeserializeObject <List <Department> >(File.ReadAllText(facultiesFilePath));

                foreach (var faculty in faculties)
                {
                    departmentService.Create(faculty).Wait();
                }

                #endregion
                return(0);
            }
            catch (Exception exception)
            {
                logger.LogError(exception.Message);
                return(1);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 导入
        /// </summary>
        /// <returns></returns>
        public ImportMessage Import()
        {
            ImportMessage msg = new ImportMessage()
            {
                Success = true
            };

            try
            {
                FileInfo fileInfo = new FileInfo(this.FilePath);
                List <DepartmentExcelModel> records = new List <DepartmentExcelModel>();
                string sheetName = "Tmp";
                /// 读取excel文件
                using (ExcelPackage ep = new ExcelPackage(fileInfo))
                {
                    if (ep.Workbook.Worksheets.Count > 0)
                    {
                        ExcelWorksheet ws = ep.Workbook.Worksheets.First();
                        sheetName = ws.Name;
                        for (int i = 2; i <= ws.Dimension.End.Row; i++)
                        {
                            records.Add(new DepartmentExcelModel()
                            {
                                Name   = ws.Cells[i, 1].Value == null ? string.Empty : ws.Cells[i, 1].Value.ToString(),
                                Remark = ws.Cells[i, 2].Value == null ? string.Empty : ws.Cells[i, 2].Value.ToString(),
                                ParentDepartmentName = ws.Cells[i, 3].Value == null ? string.Empty : ws.Cells[i, 3].Value.ToString(),
                                CompanyName          = ws.Cells[i, 4].Value == null ? string.Empty : ws.Cells[i, 4].Value.ToString()
                            });
                        }
                    }
                    else
                    {
                        msg.Success = false;
                        msg.Content = "文件不包含数据表,请检查";
                    }
                }
                if (msg.Success)
                {
                    /// 验证数据
                    if (records.Count > 0)
                    {
                        Validates(records);
                        if (records.Where(s => s.ValidateMessage.Success == false).Count() > 0)
                        {
                            /// 创建错误文件
                            msg.Success = false;
                            /// 写入文件夹,然后返回
                            string tmpFile = FileHelper.CreateFullTmpFilePath(Path.GetFileName(this.FilePath), true);
                            msg.Content       = FileHelper.GetDownloadTmpFilePath(tmpFile);
                            msg.ErrorFileFeed = true;

                            FileInfo tmpFileInfo = new FileInfo(tmpFile);
                            using (ExcelPackage ep = new ExcelPackage(tmpFileInfo))
                            {
                                ExcelWorksheet sheet = ep.Workbook.Worksheets.Add(sheetName);
                                ///写入Header
                                for (int i = 0; i < DepartmentExcelModel.Headers.Count(); i++)
                                {
                                    sheet.Cells[1, i + 1].Value = DepartmentExcelModel.Headers[i];
                                }
                                ///写入错误数据
                                for (int i = 0; i < records.Count(); i++)
                                {
                                    sheet.Cells[i + 2, 1].Value = records[i].Name;
                                    sheet.Cells[i + 2, 2].Value = records[i].Remark;
                                    sheet.Cells[i + 2, 3].Value = records[i].ParentDepartmentName;
                                    sheet.Cells[i + 2, 4].Value = records[i].CompanyName;
                                    sheet.Cells[i + 2, 5].Value = records[i].ValidateMessage.ToString();
                                }

                                /// 保存
                                ep.Save();
                            }
                        }
                        else
                        {
                            foreach (var r in records)
                            {
                                IDepartmentService ds = new DepartmentService(this.DbString);

                                if (!string.IsNullOrEmpty(r.ParentDepartmentName))
                                {
                                    BlueHrLib.Data.Department pd = ds.FindByIdWithCompanyId(r.Company.id, r.ParentDepartmentName);
                                    if (pd == null)
                                    {
                                    }
                                    else
                                    {
                                        BlueHrLib.Data.Department d = ds.FindByIdWithCompanyIdAndParentId(r.Company.id, r.Name, pd.id);

                                        if (d == null)
                                        {
                                            r.ParentDepartment = pd;

                                            BlueHrLib.Data.Department dd = new BlueHrLib.Data.Department();
                                            dd.name      = r.Name;
                                            dd.remark    = r.Remark;
                                            dd.companyId = r.Company.id;
                                            dd.parentId  = r.ParentDepartment.id;
                                            ds.Create(dd);
                                        }
                                    }
                                }
                                else
                                {
                                    BlueHrLib.Data.Department d = ds.FindByIdWithCompanyId(r.Company.id, r.Name);
                                    if (d == null)
                                    {
                                        BlueHrLib.Data.Department dd = new BlueHrLib.Data.Department();
                                        dd.name      = r.Name;
                                        dd.remark    = r.Remark;
                                        dd.companyId = r.Company.id;

                                        ds.Create(dd);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        msg.Success = false;
                        msg.Content = "文件不包含数据,请检查";
                    }
                }
            }
            catch (Exception e)
            {
                msg.Success = false;
                msg.Content = "导入失败:" + e.Message + ",请联系系统管理员";
                LogUtil.Logger.Error(e.Message);
                LogUtil.Logger.Error(e.StackTrace);
            }
            return(msg);
        }
 public void the_entity_should_not_be_null()
 {
     var s = new DepartmentService();
     var d = s.Create();
     Assert.IsNotNull(d, "The entity was not created.");
 }
 public void the_entity_should_be_initialized_with_default_values()
 {
     var s = new DepartmentService();
     var d = s.Create();
     Assert.AreEqual("New Department", d.Name, "OnCreate was not called.");
 }
Esempio n. 27
0
        public ActionResult Create(mgt_Department model)
        {
            var result = service.Create(model);

            return(Json(result));
        }
 public ResultView Create([FromBody] DepartmentView view)
 {
     return(_Service.Create(view, LogonInfo));
 }