public EmployeeEditForm(EmployeeModel _dataModel) { InitializeComponent(); this.dataModel = _dataModel; this.cbManagerID.Items.Add(""); this.cbManagerID.Items.AddRange(dataModel.getIDItemArray("HR.Employees", 0, 1)); }
//TODO public CheckResult ValidateEmployee(SmartCRMEntitiesModel context, EmployeeModel model) { CheckResult result = CheckResult.Default; if (string.IsNullOrWhiteSpace(model.FirstName)) { result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<EmployeeModel>(x => x.FirstName), "Enter First Name!")); } if (string.IsNullOrWhiteSpace(model.LastName)) { result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<EmployeeModel>(x => x.LastName), "Enter Last Name!")); } //if (model.Username.Length < MinimumUsernameLength) //{ // result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Username), "Minimum required length of the Username is 3 symbols!")); //} //if (model.Password.Length < MinimumPasswordLength) //{ // result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Password), "Minimum required length of the Password is 6 symbols!")); //} return result; }
public static void Map(Employee source, EmployeeModel destination) { Mapper.Map(source, destination); destination.Gender = (GenderType)source.Gender; // destination.Photo = source.Photo; // destination.PhotoImage = ImagesHelper.ByteArrayToImage(source.Photo); }
public void CanSerializerSingleton() { // Arrange const string expect = "{" + "\"@odata.context\":\"http://localhost/odata/$metadata#Boss\"," + "\"@odata.id\":\"http://localhost/odata/Boss\"," + "\"@odata.editLink\":\"http://localhost/odata/Boss\"," + "\"EmployeeId\":987,\"EmployeeName\":\"John Mountain\"}"; IEdmModel model = GetEdmModel(); IEdmSingleton singleton = model.EntityContainer.FindSingleton("Boss"); HttpRequestMessage request = GetRequest(model, singleton); ODataSerializerContext readContext = new ODataSerializerContext() { Url = new UrlHelper(request), Path = request.ODataProperties().Path, Model = model, NavigationSource = singleton }; ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider(); EmployeeModel boss = new EmployeeModel {EmployeeId = 987, EmployeeName = "John Mountain"}; MemoryStream bufferedStream = new MemoryStream(); // Act ODataEntityTypeSerializer serializer = new ODataEntityTypeSerializer(serializerProvider); serializer.WriteObject(boss, typeof(EmployeeModel), GetODataMessageWriter(model, bufferedStream), readContext); // Assert string result = Encoding.UTF8.GetString(bufferedStream.ToArray()); Assert.Equal(expect, result); }
//Method to parse the input file data into list object public List<EmployeeModel> ParseFileData(string FileInfo) { EmployeeModel EmpMdlObj = new EmployeeModel(); var EmployeeModelList = new List<EmployeeModel>(); try { var lines = File.ReadAllLines(FileInfo); foreach (var line in lines) { var linedata = line.Split(','); EmpMdlObj.EmployeeID = linedata[0]; EmpMdlObj.EmployeeName = linedata[1]; EmpMdlObj.EmployeeDOB = Convert.ToDateTime(linedata[2]); EmpMdlObj.EmployeeCity = linedata[3]; EmployeeModelList.Add(EmpMdlObj); } return EmployeeModelList; } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } }
public static int Insert(EmployeeModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { Employee emp = new Employee(); emp.Id = model.ID; emp.EmployeeName = model.EmployeeName; emp.Username = model.Username; emp.Password = model.Password; emp.Creater = model.Creater; emp.CreateDate = model.CreateDate; emp.Modifier = model.Modifier; emp.ModifyDate = model.ModifyDate; dc.Employees.InsertOnSubmit(emp); dc.SubmitChanges(); } return 1; } catch (Exception) { return 0; } }
public ChatMessageModel(int id, EmployeeModel author, string message, DateTime created) { Id = id; Author = author; Message = message; Created = created; }
public SimplifiedEmployeeViewModel(EmployeeModel employee) { Id = employee.Id; Name = employee.Name; Surname = employee.Surname; Position = Enum.GetName(typeof(Roles), employee.Position); }
private void InsertEmployee(SmartCRMEntitiesModel db, EmployeeModel employeeModel) { Employee pocoEmployee = new Employee(); MapHelper.Map(employeeModel, pocoEmployee); db.Add(pocoEmployee); db.FlushChanges(); employeeModel.Id = pocoEmployee.Id; }
private void InsertAccount(SmartCRMEntitiesModel db, UserModel userModel, EmployeeModel employeeModel) { User pocoUser = new User(); MapHelper.Map(userModel, pocoUser); Employee pocoEmployee = new Employee(); MapHelper.Map(employeeModel, pocoEmployee); pocoUser.Employee = pocoEmployee; db.Add(pocoUser); }
private void UpdateEmployee(SmartCRMEntitiesModel db, EmployeeModel employeeModel) { var pocoEmployee = db.Employees.FirstOrDefault(x => x.Id.Equals(employeeModel.Id)); if (pocoEmployee == null) { throw new NullReferenceException("Missing employee!"); } MapHelper.Map(employeeModel, pocoEmployee); }
public void SaveAccount(SmartCRMEntitiesModel db, UserModel userModel, EmployeeModel employeeModel) { if (userModel.IsNew) { this.InsertAccount(db, userModel, employeeModel); } else { this.UpdateAccount(db, userModel, employeeModel); } }
public static ChatRoomModel CreateChat(EmployeeModel with) { using (var connection = new MySqlConnection(Settings.Default.ConnectionString)) { connection.Open(); //New Chatroom var query = "INSERT INTO ChatRoom VALUES(null, @topic)"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.Parameters.Add(new MySqlParameter("@topic", MySqlDbType.String)); cmd.Prepare(); cmd.Parameters["@topic"].Value = $"Chat between {EmployeeModel.CurrentEmployee.Name} and {with.Name}"; cmd.ExecuteNonQuery(); //Get Chatroom-ID query = "SELECT LAST_INSERT_ID() as Id"; cmd = new MySqlCommand(query, connection); var reader = cmd.ExecuteReader(); int chatId = 0; if (reader.Read()) { chatId = reader.GetInt32("Id"); } reader.Close(); //New ChatMember cmd.CommandText = "INSERT INTO ChatMember VALUES(null, @member, @chatroom)"; cmd.Parameters.Add(new MySqlParameter("@member", MySqlDbType.Int32)); cmd.Parameters.Add(new MySqlParameter("@chatroom", MySqlDbType.Int32)); cmd.Prepare(); cmd.Parameters["@chatroom"].Value = chatId; //Add me cmd.Parameters["@member"].Value = EmployeeModel.CurrentEmployee.Id; cmd.ExecuteNonQuery(); //Add with cmd.Parameters["@member"].Value = with.Id; cmd.ExecuteNonQuery(); var newChatModel = new ChatRoomModel { Id = chatId }; newChatModel.Load(); return newChatModel; } }
public void SaveEmployee(SmartCRMEntitiesModel db, EmployeeModel employeeModel) { if (employeeModel.Id == 0) { this.InsertEmployee(db, employeeModel); } else { this.UpdateEmployee(db, employeeModel); } }
private void UpdateAccount(SmartCRMEntitiesModel db, UserModel userModel, EmployeeModel employeeModel) { var pocoUser = db.Users.FirstOrDefault(x => x.UserId.Equals(userModel.UserId)); if (pocoUser == null) { throw new NullReferenceException("Missing user!"); } MapHelper.Map(userModel, pocoUser); MapHelper.Map(employeeModel, pocoUser.Employee); }
public static EmployeeModel SelectOne(EmployeeModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { Employee item = dc.Employees.Where(a => a.Id == model.ID).SingleOrDefault(); return new EmployeeModel(item.Id, item.EmployeeName, item.RoleId.ToString(), item.Username, item.Password, item.Creater, item.CreateDate, item.Modifier, item.ModifyDate); } } catch (Exception) { return new EmployeeModel(); } }
public void AddUser(EmployeeModel user) { using (var connection = new MySqlConnection(Settings.Default.ConnectionString)) { connection.Open(); var query = "INSERT INTO ChatMember VALUES(null, @member, @chatroom)"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.Parameters.Add(new MySqlParameter("@member", MySqlDbType.Int32)); cmd.Parameters.Add(new MySqlParameter("@chatroom", MySqlDbType.Int32)); cmd.Prepare(); cmd.Parameters["@chatroom"].Value = Chat.Id; cmd.Parameters["@member"].Value = user.Id; cmd.ExecuteNonQuery(); Chat.Load(); } }
public CheckResult DeleteEmployee(EmployeeModel focusedUser) { CheckResult check = CheckResult.Default; //using (var db = DbManager.CreateInstance()) //{ // try // { // UserRepository rep = new UserRepository(); // rep.DeleteUser(db, focusedUser); // db.SaveChanges(); // this.Users.Remove(focusedUser); // } // catch (Exception ex) // { // check.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, "InvalidDeletion", "Cannot delete this user!")); // return check; // } // return check; //} return check; }
public bool checkEmployee(string strWhere) { this.em = new EmployeeDal(); this.dbo = new DB_OPT(); return (this.em.GetList(strWhere, this.dbo).Tables[0].Rows.Count > 0); }
public void Update(EmployeeModel modelEmployee) { _employeesRepository.Update(modelEmployee.ToEntity()); }
// // GET: /Employee/ public ActionResult Index() { EmployeeModel objEmpModel = new EmployeeModel(); return(View(objEmpModel)); }
public bool Create([FromBody] EmployeeModel employee) { var data = EmployeeDataAccessLayer.SaveEmployee(employee); return(data); }
public void Set(EmployeeModel model) { _cache[model.Id] = model; }
public int CreateEmployee(EmployeeModel empModel) { return(_CreateEmployeeRepository.CreateEmployee(empModel)); }
public void MarkAsModified(EmployeeModel item) { Entry(item).State = EntityState.Modified; }
public void Init() { var employees = new List <EmployeeModel>() { new EmployeeModel { Id = 1, Birth = DateTime.Now.AddYears(-10), FirstName = "John", LastName = "Doe", Salary = 1000, TaxNumber = "1234", WorkingPosition = "Developer" }, new EmployeeModel { Id = 2, Birth = DateTime.Now.AddYears(-20), FirstName = "Edward", LastName = "Kovalsky", Salary = 2000, TaxNumber = "0987", WorkingPosition = "CEO" } }; var pagedList = new PagedDataList <EmployeeModel>(employees, 0, 0, 0); var employeesForList = new List <EmployeeForListDto>() { new EmployeeForListDto { Id = 1, Age = 10, FirstName = "John", LastName = "Doe", Salary = 1000, TaxNumber = "1234", WorkingPosition = "Developer" }, new EmployeeForListDto { Id = 2, Age = 20, FirstName = "Edward", LastName = "Kovalsky", Salary = 2000, TaxNumber = "0987", WorkingPosition = "CEO" } }; var employee = new EmployeeModel { Id = 1, Birth = DateTime.Now.AddYears(-10), FirstName = "John", LastName = "Doe", Salary = 1000, TaxNumber = "1234", WorkingPosition = "Developer" }; var employeeForList = new EmployeeForListDto { Id = 1, Age = 10, FirstName = "John", LastName = "Doe", Salary = 1000, TaxNumber = "1234", WorkingPosition = "Developer" }; var eRMock = new Mock <IEmployeesRepository>(MockBehavior.Strict); eRMock.Setup(m => m.Get(null)).Returns(Task.FromResult(pagedList)); eRMock.Setup(m => m.Get(1)).Returns(Task.FromResult(employee)); eRMock.Setup(m => m.Save()).Returns(Task.FromResult(true)); eRMock.Setup(m => m.Update(It.IsAny <EmployeeModel>(), It.IsAny <EmployeeModel>())); eRMock.Setup(m => m.Add(It.IsAny <EmployeeModel>())); eRMock.Setup(m => m.Delete(It.IsAny <EmployeeModel>())); var mapMock = new Mock <IMapper>(MockBehavior.Strict); mapMock.Setup(m => m.Map <IEnumerable <EmployeeForListDto> >(It.IsAny <EmployeeModel>())).Returns(employeesForList); mapMock.Setup(m => m.Map <EmployeeForListDto>(It.IsAny <EmployeeModel>())).Returns(employeeForList); mapMock.Setup(m => m.Map <IEnumerable <EmployeeForListDto> >(It.IsAny <PagedDataList <EmployeeModel> >())).Returns(employeesForList); this.employeesRepository = eRMock; this.mapper = mapMock; }
public async Task <IHttpActionResult> GetEmployee(int EmpId) { try { using (MaxMasterDbEntities db = new MaxMasterDbEntities()) { Employee emp = await db.Employees.FindAsync(EmpId); var employee = new EmployeeModel(); employee.FirstName = emp.FirstName; employee.MiddleName = emp.MiddleName; employee.LastName = emp.LastName; employee.Email = emp.Email; employee.PrimaryPhoneNum = emp.PrimaryPhone; employee.SecondaryPhoneNum = emp.SecondaryPhone; employee.Gender = emp.Gender; employee.BloodGroup = emp.BloodGroup; employee.Aadhar = emp.Aadhar; employee.Pan = emp.PAN; employee.AddressLine1 = emp.AddressLine1; employee.AddressLine2 = emp.AddressLine2; if (emp.City_Id != 0) { employee.CityId = emp.City_Id; employee.CityName = emp.City.Name; employee.StateId = emp.City.State_Id; employee.StateName = emp.City.State.Name; employee.Country = emp.City.State.Country_Id; employee.CountryName = emp.City.State.Country.Name; } if (emp.Shift_Id != null) { employee.ShiftId = emp.Shift_Id; employee.ShiftTimings = (emp.Shift.InTime).ToString(@"hh\:mm") + "-" + (emp.Shift.OutTime).ToString(@"hh\:mm"); } employee.DOB = emp.DOB.ToString("yyyy-MM-dd"); employee.DOJ = emp.DOJ.ToString("yyyy-MM-dd"); employee.ZIP = emp.ZIP; employee.EmploymentType = emp.EmploymentType; employee.DesgId = emp.Designation_Id; employee.DesgName = emp.Designation.Name; employee.DeptId = emp.Department_Id; employee.DeptName = emp.Department.Name; employee.RoleId = emp.Role_Id; employee.RoleName = emp.AspNetRole.Name; employee.OrgId = emp.OrgId; employee.OrgName = emp.Organisation.OrgName; employee.PhotoUrl = emp.PhotoURL; var manager = emp.Manager_Id; if (manager != null) { employee.ManagerId = emp.Manager_Id; employee.ManagerName = db.Employees.Where(x => x.Id == emp.Manager_Id).Select(x => x.FirstName + " " + x.LastName).FirstOrDefault(); } employee.ProvisionalPeriod = emp.ProvisionalPeriod; return(Content(HttpStatusCode.OK, new { employee })); } } catch (Exception ex) { new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace); return(Content(HttpStatusCode.InternalServerError, "An error occured , please try again later")); } }
public async Task UpdateProfile(ProfileEditViewModel model) { if (model.EmployeeImage != null) { var employeeImage = new EmployeeImageModel { ImageId = model.ImageId, EmployeeId = model.EmployeeId, }; using (var memoryStream = new MemoryStream()) { await model.EmployeeImage.CopyToAsync(memoryStream); employeeImage.Images = memoryStream.ToArray(); } var existingImage = await _employeeImageService.ExistsAsync(model.EmployeeId); if (existingImage) { await _employeeImageService.UpdateAsync(employeeImage); } else { await _employeeImageService.AddAsync(employeeImage); } } // update employee var employee = new EmployeeModel { EmployeeId = model.EmployeeId, GlobalId = model.GlobalId, CardId = model.CardId, Title = model.Title, TitleThai = model.TitleThai, EmployeeType = model.EmployeeType, FirstName = model.FirstName, LastName = model.LastName, FirstNameThai = model.FirstNameThai, LastNameThai = model.LastNameThai, Gender = model.Gender, BirthDate = model.BirthDate, HireDate = model.HireDate, AvailableFlag = true, ChangedDate = DateTime.Now, }; await _employeeService.UpdateAsync(employee); // add or update employee state var employeeState = new EmployeeStateModel { EmployeeId = model.EmployeeId, DepartmentId = model.DepartmentId, SectionId = model.SectionId, ShiftId = (byte)model.ShiftId, LevelId = model.LevelId, PositionId = model.JobPositionId, JobFunctionId = model.JobFunctionId, BusStationId = model.BusStationId, JoinDate = model.JoinDate, ChangedDate = DateTime.Now }; var existEmployeeState = await _employeeStateService.ExistsAsync(model.EmployeeId); if (existEmployeeState) { await _employeeStateService.UpdateAsync(employeeState); } else { await _employeeStateService.AddAsync(employeeState); } // add or update address var address = new EmployeeAddressModel { EmployeeAddressId = model.EmployeeAddressId, EmployeeId = model.EmployeeId, HomeAddress = model.HomeAddress, City = model.City, Country = model.Country, PostalCode = model.PostalCode, PhoneNumber = model.PhoneNumber, EmailAddress = model.EmailAddress, ChangedDate = DateTime.Now }; if (address.EmployeeAddressId > 0) { await _employeeAddressService.UpdateAsync(address); } else { await _employeeAddressService.AddAsync(address); } }
public ActionResult Sample3FilterSearch(EmployeeModel objModel, int page = 1, int pageSize = 10) { BindSample3(objModel, page, pageSize); return(PartialView("Sample3List", objModel)); }
public IHttpActionResult GetAllEmployeeByCompanyId(int id) { EmployeeModel model = new EmployeeModel(); return(Content(HttpStatusCode.OK, model.GetAllByCompanyId(id))); }
public static void Map(EmployeeModel source, Employee destination) { Mapper.Map(source, destination); destination.Gender = (short)source.Gender; // destination.Photo = source.Photo; //ImagesHelper.ImageToByteArray(source.PhotoImage); }
protected void loadData() { string currentFilter ; if (IsPostBack == false) { Session["emp_filter"] = "jobStatus=1 "; currentFilter = "jobStatus=1 "; } else currentFilter = (string)Session["emp_filter"]; //this.scriptLb.Text = currentFilter; EmployeeParser newParser = new EmployeeParser(); this.dataModel = new EmployeeModel(this.gvEmployees, @".\SQL2008", 1433, "TSQLFundamentals2008","sa", "123456", "HR.Employees", newParser); newParser.DataModel = this.dataModel; try { this.dataModel.resetControl(currentFilter); if (this.IsPostBack == false) this.loadEmpIDS(); } catch(Exception ex) { Session["current_error"] = ex.Message; Response.Redirect("serverError.aspx"); } }
public CheckResult DeleteEmployee(EmployeeModel focusedEmployee) { CheckResult check = CheckResult.Default; using (var db = DbManager.CreateInstance()) { try { EmployeeRepository rep = new EmployeeRepository(); rep.DeleteEmployee(db, focusedEmployee); db.SaveChanges(); this.Employees.Remove(focusedEmployee); } catch (NullReferenceException nREx) { //TODO Log check.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, "", nREx.Message)); return check; } catch (DataStoreException) { check.Details.Add( new CheckResultDetail( CheckResultDetail.ErrorType.Error, "InvalidDeletion", Messages.CannotDeleteLinkedItem)); return check; } catch (Exception) { //TODO Log check.Details.Add( new CheckResultDetail( CheckResultDetail.ErrorType.Error, "InvalidDeletion", "Deletion failed!")); return check; } return check; } }
static void Main(string[] args) { //string whatIdid; //int i; //double totalHours; //double ttl = 0; //double myTimeInHours; //List<TimeSheetEntry> ents = new List<TimeSheetEntry>(); //TimeSheetEntry ent = new TimeSheetEntry(); //what job do you do //how long do you do it for //check the value given by the user //add the data as an entry to the TimeSheetEntry //ask for more time - if yes repeat, - if no continue //check if worked for acme //send email to acme //calculate total bill for Acme //check if worked for ABC //send email to ABC //calculate total bill for ABC //calculate pay and overtime //end application //Console.Write("Enter what you did and for Acme or ABC?: "); //whatIdid = Console.ReadLine(); //Console.Write("How many hours did you do it for: "); //string myHours = Console.ReadLine(); //checkHoursValid(myHours); ////t = int.Parse(Console.ReadLine()); //ent.WorkDone = whatIdid; //ent.WorkedHours = myTimeInHours; //ents.Add(ent); //Console.Write("Do you want to enter more time:"); ////bool cont = bool.Parse(Console.ReadLine()); //string answer = Console.ReadLine(); //checkMoreTimeValid(answer); //while (cont == true) //{ // Console.Write("Enter what you did and for Acme or ABC?: "); // whatIdid = Console.ReadLine(); // Console.Write("How many hours did you do it for: "); // //t = int.Parse(Console.ReadLine()); // myHours = Console.ReadLine(); // checkHoursValid(myHours); // ent = new TimeSheetEntry(); //this is a new instance, not a ref to the old one // ent.WorkedHours = myTimeInHours; // ent.WorkDone = whatIdid; // ents.Add(ent); // Console.Write("Do you want to enter more time:"); // //cont = bool.Parse(Console.ReadLine()); // answer = Console.ReadLine(); // checkMoreTimeValid(answer); // //cont = false; //} //REFACTORED creation of new method LoadTimeSheets List <TimeSheetEntry> timeSheets = LoadTimeSheets(); //pull a EmployeeModel reference to a certain employee and call if currentEmployee EmployeeModel currentEmployee = DataAccess.GetCurrentEmployee(); //get me a list of customers we'll call customers of type "CustomerModel" populated by the method DataAccess.GetCustomer() List <CustomerModel> customers = DataAccess.GetCustomers(); //(in one line) //Bill each customer in the TimeSheets and send them an email customers.ForEach(x => BillCustomer(timeSheets, x)); //OR (standard way) //foreach(var customer in customers) //{ // //BillCustomer(timeSheets, customer.CustomerName, customer.HourlyRateToBill); // //REFACTORED BillCustomer to just take in the CustomerModel so it can access those properties // BillCustomer(timeSheets, customer); //} //totalHours = TimeSheetProcessing.GetHoursWorkedForCompany(timeSheets, "Acme"); //Console.WriteLine(); //Console.WriteLine("Simulating Sending email to Acme"); //Console.WriteLine("Your bill is $" + totalHours * 150 + " for the hours worked."); //BillCustomer(timeSheets, "Acme", 150); //totalHours = TimeSheetProcessing.GetHoursWorkedForCompany(timeSheets, "ABC"); //Console.WriteLine(); //Console.WriteLine("Simulating Sending email to ABC"); //Console.WriteLine("Your bill is $" + totalHours * 125 + " for the hours worked."); //BillCustomer(timeSheets, "ABC", 125); //totalHours = 0; //for (i = 0; i < timeSheets.Count; i++) //{ // totalHours += timeSheets[i].WorkedHours; //} //if (totalHours > 40) //{ // Console.WriteLine("You will get paid $" + ((40 * 10) + ((totalHours - 40) * 15)) + " for your work."); //} //else //{ // Console.WriteLine("You will get paid $" + totalHours * 10 + " for your time."); //} //Pay the employee based on the time sheet entry and the current employees pay rate PayEmployee(timeSheets, currentEmployee); Console.WriteLine(); Console.Write("Press any key to exit application..."); Console.ReadKey(); }
public static IEmployee ToEntity(this EmployeeModel source) { return(Mapper.Map <EmployeeModel, IEmployee>(source)); }
public void DeleteEmployee(SmartCRMEntitiesModel db, EmployeeModel employeeModel) { Employee pocoEmployee = db.Employees.FirstOrDefault(x => x.Id == employeeModel.Id); if (pocoEmployee == null) { throw new NullReferenceException("Missing employee in database!"); } db.Delete(pocoEmployee); }
public int UpdateEmployeeDetails(EmployeeModel empModel) { return(_UpdateEmployeeRepository.UpdateEmployeeDetails(empModel)); }
private IEmployeeModel PopulateEmployeeModelFromInterface() { var employee = new EmployeeModel { Address = address.Text, BankAccount = bankAccount.Text, BankName = bankName.Text, BirthDate = birthDate.Value, City = cityName.Text, CreatedBy = createdBy.Text, CreatedDate = createdDate.Value, FirstName = firstName.Text, Gender = gender.Text, HiredDate = hireDate.Value, Id = Convert.ToInt32(recordId.Text), LastName = lastName.Text, ModifiedBy = modifiedBy.Text, ModifiedDate = modifiedDate.Value, MaritalStatus = maritalStatus.Text, MiddleName = middleName.Text, NationalIDNumber = nationalIdNumber.Text, PayrollGroupCode = payrollGroupCode.Text, PositionName = positionName.Text, PostalCode = postalCode.Text, State = stateName.Text, Title = titleName.Text, EmployeeID = employeeId.Text }; bool b; Boolean.TryParse(isTerminate.Text, out b); employee.IsTerminate = b; employee.TerminateDate = terminateDate.Checked ? (DateTime?)terminateDate.Value : null; employee.TerminateDescription = terminateDescription.Text; return employee; }
public static void ReplaceReferences(ObservableCollection <DepartmentModel> collection, EmployeeModel selectedEmployee) { if (collection.Count > 0) { for (int i = collection.Count - 1; i >= 0; i--) { if (selectedEmployee.Department.Name == collection[i].Name && !ReferenceEquals(selectedEmployee.Department.Name, collection[i].Name)) { collection.Add(selectedEmployee.Department); collection.Remove(collection[i]); } } } }
public ActionResult AddEmployee(EmployeeModel model) { ViewBag.Class = "display-hide"; try { if (ModelState.IsValid) { model.CreatedBy = UserManager.user.UserId; model.Archived = "NonArchive"; string path = Server.MapPath("~/UploadDocuments/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (model.ImageFile != null) { string Imagepath = Server.MapPath("~/Images/UserImages/"); if (!Directory.Exists(Imagepath)) { Directory.CreateDirectory(Imagepath); } string fileName = Path.GetFileName(model.ImageFile.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.ImageFile.FileName); model.ImageFile.SaveAs(Imagepath + fileName); model.Image = fileName; model.ImageFile = null; } if (model.IDCardFirst_File != null) { string fileName = Path.GetFileName(model.IDCardFirst_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.IDCardFirst_File.FileName); model.IDCardFirst_File.SaveAs(path + fileName); model.IDCardFirst = fileName; model.IDCardFirst_File = null; } if (model.IDCardSecond_AddressProof_File != null) { string fileName = Path.GetFileName(model.IDCardSecond_AddressProof_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.IDCardSecond_AddressProof_File.FileName); model.IDCardSecond_AddressProof_File.SaveAs(path + fileName); model.IDCardSecond_AddressProof_ = fileName; model.IDCardSecond_AddressProof_File = null; } if (model.CV_File != null) { string fileName = Path.GetFileName(model.CV_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.CV_File.FileName); model.CV_File.SaveAs(path + fileName); model.CV = fileName; model.CV_File = null; } if (model.ExperienceCertificate_File != null) { string fileName = Path.GetFileName(model.ExperienceCertificate_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.ExperienceCertificate_File.FileName); model.ExperienceCertificate_File.SaveAs(path + fileName); model.ExperienceCertificate = fileName; model.ExperienceCertificate_File = null; } if (model.AppointementLetter_File != null) { string fileName = Path.GetFileName(model.AppointementLetter_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.AppointementLetter_File.FileName); model.AppointementLetter_File.SaveAs(path + fileName); model.AppointementLetter = fileName; model.AppointementLetter_File = null; } if (model.AggrementDocument_File != null) { string fileName = Path.GetFileName(model.AggrementDocument_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.AggrementDocument_File.FileName); model.AggrementDocument_File.SaveAs(path + fileName); model.AggrementDocument = fileName; model.AggrementDocument_File = null; } if (model.OtherDocument_File != null) { string fileName = Path.GetFileName(model.OtherDocument_File.FileName); fileName = "test" + Guid.NewGuid().ToString() + Path.GetExtension(model.OtherDocument_File.FileName); model.OtherDocument_File.SaveAs(path + fileName); model.OtherDocument = fileName; model.OtherDocument_File = null; } if (!string.IsNullOrWhiteSpace(model.DOB)) { model.DateOfBirth = DateTime.ParseExact(model.DOB, "dd/MM/yyyy", null); } //model.DateOfBirth = Convert.ToDateTime(model.DOB); var serialized = JsonConvert.SerializeObject(model); var client = new HttpClient(); var content = new StringContent(serialized, System.Text.Encoding.UTF8, "application/json"); client.BaseAddress = new Uri(HttpContext.Request.Url.AbsoluteUri); var result = client.PostAsync(BaseURL + "/api/Management/AddUpdateEmployee", content).Result; if (result.StatusCode == HttpStatusCode.OK) { var contents = result.Content.ReadAsStringAsync().Result; var Response = JsonConvert.DeserializeObject <ResponseModel>(contents); ModelState.Clear(); ModelState.AddModelError("CustomError", Response.response); ViewBag.Class = "alert-success"; model = new EmployeeModel(); } else if (result.StatusCode == HttpStatusCode.Unauthorized) { var contents = result.Content.ReadAsStringAsync().Result; var Response = JsonConvert.DeserializeObject <ResponseModel>(contents); ModelState.AddModelError("CustomError", Response.response); ViewBag.Class = "alert-danger"; } else { ModelState.AddModelError("CustomError", "Error occurred"); ViewBag.Class = "alert-danger"; } } } catch (Exception ex) { ModelState.AddModelError("CustomError", ex.Message); ViewBag.Class = "alert-danger"; } model.listDepartment = GetDepartments(); model.listDepartment = model.listDepartment.Where(s => s.IsActive == true).ToList(); if (model.DepartmentId > 0) { model.listDesignation = GetDesignations(model.DepartmentId); } var list = new List <SelectListItem> { new SelectListItem { Text = "Admin", Value = "Admin" }, new SelectListItem { Text = "HR", Value = "HR" }, new SelectListItem { Text = "Project Manager", Value = "Project Manager" }, new SelectListItem { Text = "Network Admin", Value = "Network Admin" }, new SelectListItem { Text = "Team Leader", Value = "Team Leader" }, new SelectListItem { Text = "Employee", Value = "Employee" } }; ViewData["ddlRole"] = list; return(View(model)); }
public bool Edit([FromBody] EmployeeModel employee) { var data = EmployeeDataAccessLayer.UpdateEmployee(employee); return(data); }
public ActionResult Create(EmployeeModel employee) { _dal.AddEmployee(_mapper.MapToBEModel(employee)); return(RedirectToAction("Index")); }
public void Add(EmployeeModel employee) { _employeesRepository.Add(employee.ToEntity()); }
public void GetMapEmployeeBOL_ShouldReturnException() { var model = new EmployeeModel(); Assert.ThrowsException <NullReferenceException>(() => model.GetMapEmployeeBOL(null)); }
public ActionResult AddEmployee(EmployeeModel Emp, FormCollection image) { //var clientPath = Path.GetDirectoryName(photo.FileName); //var filename = Path.GetFileName(photo.FileName); //var fileName = Path.GetDirectoryName(photo.FileName); //var fileName2 = Path.GetFullPath(photo.FileName); ////HttpPostedFileBase photo = Request.Files["photo"]; ////string ss = form["photo"].ToString(); ////var file2 = Request.Files[0]; try { if (ModelState.IsValid) { //EmpRepository EmpRepo = new EmpRepository(); //if (photo != null && photo.ContentLength > 0) //{ // var fileName = Path.GetFileName(photo.FileName); // var path = Path.Combine(Server.MapPath("~/TempFile/"), fileName); photo.SaveAs(path); // UploadImage_URL(path, fileName); // var fullPath = Server.MapPath("~/TempFile/" + fileName); // if (System.IO.File.Exists(fullPath)) // { // System.IO.File.Delete(fullPath); // //ViewBag.deleteSuccess = "true"; // } //} HttpPostedFileBase fileNameglobal = null; foreach (string item in Request.Files) { HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase; fileNameglobal = file; if (file.ContentLength == 0) { continue; } if (file.ContentLength > 0) { CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer(); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(file.FileName); blob.UploadFromStream(file.InputStream); } } //var fileName = Path.GetFileName(photo.FileName); var fileName = Path.GetFileName(fileNameglobal.FileName); EmpRepository EmpRepo = new EmpRepository(); Emp.ImagePath = fileName; EmpRepo.AddEmployee(Emp); ViewBag.Message = "Records added successfully."; } //return View(); return(RedirectToAction("GetAllEmpDetails")); } catch (Exception ex) { return(View()); } }
/// <summary> /// Sets the current employee and accept changes /// </summary> /// <param name="employee">Employee</param> public void SetEmployee(EmployeeModel employee) { this.CurrentEmployee = employee; if (this.CurrentEmployee != null) { this.CurrentEmployee.PropertyChanged += this.CurrentAccount_PropertyChanged; if (!this.CurrentEmployee.IsNew) { this.CurrentEmployee.AcceptChanges(); } else { this.InvokeAccountChangedEvent(); } } }
public ActionResult Create(EmployeeModel objemployeemodel) { try { DynamicParameters param = new DynamicParameters(); param.Add("@UserId", objemployeemodel.EmployeeUserName); param.Add("@Pass", objemployeemodel.EmployeePassword); IEnumerable <EmployeeModel> Employeedata = SqlHelper.QuerySP <EmployeeModel>("AdminLogIn", param, null); if (Employeedata != null && Employeedata.ToList().Count() > 0) { if (Employeedata.Where(x => x.EmployeeUserName == objemployeemodel.EmployeeUserName && x.EmployeePassword == objemployeemodel.EmployeePassword).Count() > 0) { EmployeeModel objemp = new EmployeeModel(); objemp = Employeedata.Where(x => x.EmployeeUserName == objemployeemodel.EmployeeUserName && x.EmployeePassword == objemployeemodel.EmployeePassword).FirstOrDefault(); if (objemp.DesignationId == 1) { Session["Employee"] = objemp; //Response.Redirect("~/Admin/Admin.aspx"); TempData["ErrorMessage"] = null; return(RedirectToAction("Index", "Dashboard")); } else if (objemp.DesignationId == 2) { Session["Employee"] = objemp; //Response.Redirect("~/Manager/Manager.aspx"); TempData["ErrorMessage"] = null; return(RedirectToAction("Index", "Dashboard")); } else if (objemp.DesignationId == 3) { Session["Employee"] = objemp; //Response.Redirect("./Chef.aspx"); TempData["ErrorMessage"] = null; return(RedirectToAction("Index", "Dashboard")); } else { TempData["ErrorMessage"] = "Error Encountered."; return(View("Index")); } } else { TempData["ErrorMessage"] = "Invalid Username or Password."; return(View("Index")); } } else { //TempData["ErrorMessage"] = "Not a single user is registered."; //return View("Index"); DynamicParameters param1 = new DynamicParameters(); IEnumerable <TableInformationModel> tabledata = SqlHelper.QuerySP <TableInformationModel>("usp_GetTableInfo", param1, null); if (tabledata.Count() > 0) { if (tabledata.ToList().Where(x => x.TableName == objemployeemodel.EmployeeUserName && x.TablePassword == objemployeemodel.EmployeePassword).Count() > 0) { Session["TableInfo"] = tabledata.ToList().Where(x => x.TableName == objemployeemodel.EmployeeUserName && x.TablePassword == objemployeemodel.EmployeePassword).FirstOrDefault(); return(RedirectToAction("Index", "Home")); } else { TempData["ErrorMessage"] = "Not a single user is registered."; return(View("Index")); } } else { TempData["ErrorMessage"] = "Not a single user is registered."; return(View("Index")); } } } catch { return(View()); } }
public ChatViewModel(EmployeeModel employee) { Chat = ChatRoomModel.CreateChat(employee); }
public ActionResult Edit(EmployeeModel employee) { _dal.UpdateEmployee(_mapper.MapToBEModel(employee)); return(RedirectToAction("Index")); }
public Task <EmployeeModel> Update(EmployeeModel model) { throw new NotImplementedException(); }
public IActionResult Post() { var payload = ReadPayload(); _logger.LogInformation("Received a webhook"); var signatureHeader = Request.Headers["x-xero-signature"].FirstOrDefault(); _logger.LogInformation("Verifying the signature to confirm that the payload is from Xero."); var isValid = _signatureVerifier.VerifySignature(payload, signatureHeader); if (!isValid) { _logger.LogWarning("The signature is incorrect. Responding with HTTP 401 Unauthorised."); return(Unauthorized()); } _logger.LogInformation("The signature is correct. Saving the payload for processing later (so that we can respond as quickly as possible)."); if (!payload.Contains("resourceId")) // hand-shake { return(Ok()); } // _payloadQueue.Enqueue(payload); // var update = JsonConvert.DeserializeXNode(payload); var objectToUpdate = JsonConvert.DeserializeObject <Payload>(payload); var @event = objectToUpdate.Events.FirstOrDefault(); if (@event != null) { return(Ok()); } var model = new EmployeeModel { ContactId = @event.ResourceId }; switch (@event.EventType) { case "UPDATE": _employeeService.Update(model); break; case "ADD": _employeeService.Add(model); break; } _contactObservable.AddActivity( new Activity { Id = model.Id, PersonName = model.FullName, Status = @event.EventType }); _logger.LogInformation("Webhook is saved. Returning an empty 200 OK"); return(Ok()); }
public ActionResult UpdateProject(ProjectListEdit EPL) { try { JavaScriptSerializer json_serializer = new JavaScriptSerializer(); var modifiedOrNewEmpList = json_serializer.Deserialize <EmployeeProjectList[]>(EPL.EmployeeProjectList); StringBuilder errorMessage = new StringBuilder(); if (EPL.Theme.HasValue) { var eligibleThemeGrants = ConfigurationManager.AppSettings["ThemeGrandCodes"].ToString().Split(',').ToList(); var themeMstType = Convert.ToInt32(ConfigurationManager.AppSettings["TypeGrant"]); var themes = DB.MasterData.Where(x => x.MstTypeID == themeMstType && eligibleThemeGrants.Contains(x.MstCode)).Select(x => x.MstID); if (!themes.Contains(EPL.ProjectGrant)) { EPL.Theme = null; } } if (EPL.IsRDProject == 1) { IEnumerable <EmployeeProjectList> GetDetails = DB.Database.SqlQuery <EmployeeProjectList>( @"exec " + Constants.P_UpdateProjectList + " @ProjectName,@ProjectId,@ProjectCode,@StartDate,@EndDate,@InternalOrder,@ProjectGrant,@IsRDProject,@Theme,@ResearchArea,@TypeofResearch,@CostCenter,@ProjectDesc", new object[] { new SqlParameter("@ProjectName", EPL.ProjectName), new SqlParameter("@ProjectId", EPL.ProjectID), new SqlParameter("@ProjectCode", EPL.ProjectCode), new SqlParameter("@StartDate", EPL.StartDate), new SqlParameter("@EndDate", EPL.EndDate), new SqlParameter("@InternalOrder", EPL.InternalOrder), new SqlParameter("@ProjectGrant", EPL.ProjectGrant), new SqlParameter("@ResearchArea", EPL.ResearchArea), new SqlParameter("@TypeofResearch", EPL.TypeofResearch), new SqlParameter("@IsRDProject", EPL.IsRDProject), new SqlParameter("@CostCenter", EPL.CostCentre), new SqlParameter("@ProjectDesc", EPL.ProjectDesc ?? ""), new SqlParameter("@Theme", (object)EPL.Theme ?? DBNull.Value), }).ToList().Distinct(); } else { IEnumerable <EmployeeProjectList> GetDetails = DB.Database.SqlQuery <EmployeeProjectList>( @"exec " + Constants.P_UpdateProjectList + " @ProjectName,@ProjectId,@ProjectCode,@StartDate,@EndDate,@InternalOrder,@ProjectGrant,@IsRDProject,@Theme,null,null,@CostCenter,@ProjectDesc", new object[] { new SqlParameter("@ProjectName", EPL.ProjectName), new SqlParameter("@ProjectId", EPL.ProjectID), new SqlParameter("@ProjectCode", EPL.ProjectCode), new SqlParameter("@StartDate", EPL.StartDate), new SqlParameter("@EndDate", EPL.EndDate), new SqlParameter("@InternalOrder", EPL.InternalOrder), new SqlParameter("@ProjectGrant", EPL.ProjectGrant), new SqlParameter("@IsRDProject", EPL.IsRDProject), new SqlParameter("@Theme", (object)EPL.Theme ?? DBNull.Value), new SqlParameter("@CostCenter", EPL.CostCentre), new SqlParameter("@ProjectDesc", EPL.ProjectDesc ?? ""), }).ToList().Distinct(); } List <ProjectEmployeesModel> projectMembers = DB.ProjectEmployee.Where(x => x.ProjectID == EPL.ProjectID).ToList(); foreach (ProjectEmployeesModel item in projectMembers) { if (item.EndDate > EPL.EndDate) { item.EndDate = EPL.EndDate; DB.Entry(item).State = System.Data.Entity.EntityState.Modified; DB.SaveChanges(); } } foreach (var item in modifiedOrNewEmpList) { if (!DB.ProjectEmployee.Any(x => x.ProjectID == EPL.ProjectID && x.EmployeeID == item.EmployeeID)) { EmployeeModel refRole = DB.Employee.FirstOrDefault(x => x.EmployeeID == item.EmployeeID); List <EmployeeProjectList> GetDetails2 = DB.Database.SqlQuery <EmployeeProjectList>( @"exec " + Constants.P_InsertProjectEmployee + " @ProjectId,@EmployeeID,@CheckRole,@InvPercentage,@RefRole,@StartDate,@EndDate,@Grant,@IsActive,@CreatedBy", new object[] { new SqlParameter("@ProjectId", EPL.ProjectID), new SqlParameter("@EmployeeID", item.EmployeeID), new SqlParameter("@CheckRole", item.IsManager), new SqlParameter("@InvPercentage", item.InvPercentage), new SqlParameter("@RefRole", EPL.IsRDProject == 1 ? (refRole.RoleID ?? 0) : 0), new SqlParameter("@StartDate", item.StartDate), new SqlParameter("@EndDate", item.EndDate), new SqlParameter("@Grant", Convert.ToInt64(EPL.ProjectGrant)), new SqlParameter("@IsActive", 1), new SqlParameter("@CreatedBy", Session["EmployeeId"].ToString()) }).ToList(); if (EPL.IsRDProject == 1 && refRole.RoleID == null) { ViewBag.Message = ViewBag.Message + $"line Employee { SCTimeSheet.Models.Common.GetName(refRole.EmpFirstName, refRole.EmpLastName, refRole.EmpMiddleName) } Role is blank, please modify manually or contact administrator"; } if (!string.IsNullOrEmpty(refRole.Email)) { if (!DB.User.Any(x => x.Email == refRole.Email)) { UserModel user = new UserModel { Email = refRole.Email, CreatedBy = 1, CreatedDate = DateTime.Now, IsActive = true, Password = "******", RoleID = item.IsManager ? Convert.ToInt64(ReadConfig.GetValue("RolePM")) : Convert.ToInt64(ReadConfig.GetValue("RoleEmployee")) }; DB.User.Add(user); DB.SaveChanges(); refRole.UserID = user.UserID; DB.Employee.Attach(refRole); DB.Entry(refRole).State = System.Data.Entity.EntityState.Modified; DB.SaveChanges(); } } else { ViewBag.Message = ViewBag.Message + $"line Employee { SCTimeSheet.Models.Common.GetName(refRole.EmpFirstName, refRole.EmpLastName, refRole.EmpMiddleName) } email is blank, please contact administrator"; } } else { var emp = DB.ProjectEmployee.FirstOrDefault(x => x.ProjectID == EPL.ProjectID && x.EmployeeID == item.EmployeeID); emp.InvPercentage = item.InvPercentage; emp.StartDate = item.StartDate; emp.EndDate = item.EndDate; emp.CheckRole = item.IsManager; emp.RefRole = item.EmpRole; DB.Entry(emp).State = System.Data.Entity.EntityState.Modified; DB.SaveChanges(); } } // return RedirectToAction("Index", "ProjectMain"); ViewBag.Message = ViewBag.Message + $"line {EPL.ProjectName } is updated successfully"; GetDefaults(); ViewBag.ProjectId = EPL.ProjectID; ViewBag.GrantID = EPL.ProjectGrant; ViewBag.ReasearchID = EPL.ResearchArea; ViewBag.TypeID = EPL.TypeofResearch; //EPL.ProjectMembers = string.Join(",", empPercentageStatus.Select(x => x.Key.Key)); //EPL.ProjectMembersNames = string.Join(",", empPercentageStatus.Select(x => x.Key.Value)); EPL.EmpSearchText = ""; return(View("ProjectEdit", EPL)); } catch (Exception ex) { LogHelper.ErrorLog(ex); throw ex; } }
public static void InviteToChat(EmployeeModel employee, ChatRoomModel chatRoom) { throw new NotImplementedException(); }
public ActionResult Save(ProjectMasterModelNew model) { try { GetDefaults(); JavaScriptSerializer json_serializer = new JavaScriptSerializer(); var modifiedOrNewEmpList = json_serializer.Deserialize <EmployeeProjectList[]>(model.EmployeeProjectList); ModelState.Remove("ProjectID"); // model.ValidateModel(ModelState); model.MemberProjectGrant = model.ProjectGrant; Session["ProjectGrant"] = model.ProjectGrant; model.IsActive = true; if (model.Theme.HasValue) { var eligibleThemeGrants = ConfigurationManager.AppSettings["ThemeGrandCodes"].ToString().Split(',').ToList(); var themeMstType = Convert.ToInt32(ConfigurationManager.AppSettings["TypeGrant"]); var themes = DB.MasterData.Where(x => x.MstTypeID == themeMstType && eligibleThemeGrants.Contains(x.MstCode)).Select(x => x.MstID); if (!themes.Contains(model.ProjectGrant)) { model.Theme = null; } } ProjectMasterModel newModel = new ProjectMasterModel { ProjectID = model.ProjectID, ProjectCode = model.ProjectCode, ProjectName = model.ProjectName, ProjectDesc = model.ProjectDesc, InternalOrder = model.InternalOrder, CostCentre = model.CostCentre, ProjectGrant = model.ProjectGrant, ResearchArea = model.ResearchArea, TypeofResearch = model.TypeofResearch, StartDate = model.StartDate, EndDate = model.EndDate, ProjectDuration = model.ProjectDuration, IsActive = true, IsRDProject = model.IsRDProject, Theme = model.Theme }; DB.ProjectMaster.Add(newModel); DB.SaveChanges(); long projectId = DB.ProjectMaster.Where(x => x.ProjectCode == model.ProjectCode).Select(x => x.ProjectID).FirstOrDefault(); string projectName = DB.ProjectMaster.Where(x => x.ProjectCode == model.ProjectCode).Select(x => x.ProjectName).FirstOrDefault(); Session["pId"] = projectId; Session["pName"] = projectName; TempData["projectid"] = 1; TempData["Success"] = ResourceMessage.NewProjectAdd; Session["ProjectGrant"] = model.ProjectGrant; if (modifiedOrNewEmpList.Any()) { model.ProjectID = projectId; model.IsActive = true; foreach (var item in modifiedOrNewEmpList) { EmployeeModel refRole = DB.Employee.FirstOrDefault(x => x.EmployeeID == item.EmployeeID); List <EmployeeProjectList> GetDetails = DB.Database.SqlQuery <EmployeeProjectList>( @"exec " + Constants.P_InsertProjectEmployee + " @ProjectId,@EmployeeID,@CheckRole,@InvPercentage,@RefRole,@StartDate,@EndDate,@Grant,@IsActive,@CreatedBy", new object[] { new SqlParameter("@ProjectId", model.ProjectID), new SqlParameter("@EmployeeID", item.EmployeeID), new SqlParameter("@CheckRole", item.IsManager), new SqlParameter("@InvPercentage", item.InvPercentage), new SqlParameter("@RefRole", model.IsRDProject == 1 ? (refRole.RoleID ?? 0) : 0), new SqlParameter("@StartDate", item.StartDate), new SqlParameter("@EndDate", item.EndDate), new SqlParameter("@Grant", model.ProjectGrant), new SqlParameter("@IsActive", model.IsActive), new SqlParameter("@CreatedBy", Session["EmployeeId"].ToString()) }).ToList(); if (model.IsRDProject == 1 && refRole.RoleID == null) { ViewBag.Message = ViewBag.Message + $"line Employee { SCTimeSheet.Models.Common.GetName(refRole.EmpFirstName, refRole.EmpLastName, refRole.EmpMiddleName) } Role is blank, please modify manually or contact administrator"; } if (!string.IsNullOrEmpty(refRole.Email)) { if (!DB.User.Any(x => x.Email == refRole.Email)) { UserModel user = new UserModel { Email = refRole.Email, CreatedBy = 1, CreatedDate = DateTime.Now, IsActive = true, Password = "******", RoleID = item.IsManager ? Convert.ToInt64(ReadConfig.GetValue("RolePM")) : Convert.ToInt64(ReadConfig.GetValue("RoleEmployee")) }; DB.User.Add(user); DB.SaveChanges(); refRole.UserID = user.UserID; DB.Employee.Attach(refRole); DB.Entry(refRole).State = System.Data.Entity.EntityState.Modified; DB.SaveChanges(); } } else { ViewBag.Message = ViewBag.Message + $"line Employee { SCTimeSheet.Models.Common.GetName(refRole.EmpFirstName, refRole.EmpLastName, refRole.EmpMiddleName) } email is blank, please contact administrator"; } } } TempData.Add("ProjectCreated", $"{model.ProjectName } is created successfully"); return(RedirectToAction("Index", "ProjectMain")); } catch (Exception ex) { TempData["Error"] = ex.ToString(); LogHelper.ErrorLog(ex); } return(View("Index", model)); }
private void BuildEmployeeModel(EmployeeModel employeeModel) { employeeModel.ActionMethod = ActionMethod.Edit; employeeModel.DepartmentModelList = _departmentService.GetAll().Select(x => _mapper.Map <Department, DepartmentModel>(x)).ToList(); }
public void RemoveEmployee(EmployeeModel focusedEmployee) { this.Employees.Remove(focusedEmployee); }
public void SetEmployee(EmployeeModel employee) { this.CurrentEmployee = employee; }
public EmployeeViewModel(EmployeeModel model) { Model = model; IsChecked = model.IsChecked; EmpName = model.EmpName; }
private void EmployeeDataBind(string strPK) { try { this.dbo = new DB_OPT(); this.dbo.Open(); this.em = new EmployeeDal(); DataSet list = new DataSet(); list = this.em.GetList(" pk_corp='" + strPK + "'", this.dbo); if ((list != null) && (list.Tables[0].Rows.Count > 0)) { this.gv_Employee.DataSource = list; this.gv_Employee.DataBind(); } else { DataTable table = new DataTable(); table = list.Tables[0]; DataRow row = table.NewRow(); table.Rows.Add(row); this.gv_Employee.DataSource = table.DefaultView; this.gv_Employee.DataBind(); } } catch (Exception exception) { this.el = new ExceptionLog.ExceptionLog(); this.el.ErrClassName = base.GetType().ToString(); this.el.ErrMessage = exception.Message.ToString(); this.el.ErrMethod = "EmployeeDataBind()"; this.el.WriteExceptionLog(true); Const.OpenErrorPage("获取数据失败,请联系系统管理员!", this.Page); } finally { if (this.dbo != null) { this.dbo.Close(); } } }
public async Task <IActionResult> Edit([FromForm] EmployeeModel model) { if (!ModelState.IsValid) { PartialView(); } // Map model to resource var resource = mapper.Map <EmployeeResource>(model); // save resource to Json var resourceDocument = JsonConvert.SerializeObject(resource); using (var content = new StringContent(resourceDocument, Encoding.UTF8, "application/json")) { using (var client = restClient.CreateClient(User)) { // determen call update or insert Upsert upsert = client.PutAsync; // no RowVersion indicates insert if (model.RowVersion.IsNullOrEmpty()) { upsert = client.PostAsync; } using (var response = await upsert(apiUrl, content)) { // init result var result = new ResourceResult <EmployeeResource>(resource); // read result from RESTful service var responseDocument = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) { // Fetch created or updated resource from response result.Resource = JsonConvert.DeserializeObject <EmployeeResource>(responseDocument);; } else { // fetch errors and or exceptions result = JsonConvert.DeserializeObject <ResourceResult <EmployeeResource> >(responseDocument); } // Set error message for concurrency error if (response.StatusCode == HttpStatusCode.Conflict) { result.Errors.Clear(); result.Errors.Add(new ValidationError("This record is modified by another user")); result.Errors.Add(new ValidationError("Your work is not saved and replaced with new content")); result.Errors.Add(new ValidationError("Please review the new content and if required edit and save again")); } if (response.StatusCode.IsInSet(HttpStatusCode.OK, HttpStatusCode.Created, HttpStatusCode.Conflict)) { return(StatusCode(response.StatusCode.ToInt32(), result)); } // copy errors so they will be rendered in edit form foreach (var error in result.Errors) { ModelState.AddModelError(error.MemberName ?? "", error.Message); } // Update model with Beautify effect(s) and make it visible in the partial view IEnumerable <PropertyInfo> properties = model.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { var rawValue = property.GetValue(model); var attemptedValue = rawValue == null ? "" : Convert.ToString(rawValue, CultureInfo.InvariantCulture); ModelState.SetModelValue(property.Name, rawValue, attemptedValue); } // No need to specify model here, it has no effect on the render process :-( return(PartialView()); } } } }