public async Task <IActionResult> PutDepartment([FromRoute] int id, [FromBody] Department department)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != department.Id)
            {
                return(BadRequest());
            }

            _context.Entry(department).State = EntityState.Modified;

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

            return(NoContent());
        }
Esempio n. 2
0
        public async Task <IActionResult> Create([Bind("Id,First,Last,Month,Year,EmployeeTypeID")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                //
                if (employee.EmployeeTypeID == 2)
                {
                    Manager manager = new Manager
                    {
                        Id             = employee.Id,
                        First          = employee.First,
                        Last           = employee.Last,
                        Month          = employee.Month,
                        Year           = employee.Year,
                        EmployeeTypeID = employee.EmployeeTypeID,
                        EmployeeType   = employee.EmployeeType
                    };
                    _context.Add(manager);
                }
                else
                {
                    _context.Add(employee);
                }

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["EmployeeTypeID"] = new SelectList(_context.EmployeeType, "EmployeeTypeID", "EmployeeDiscription", employee.EmployeeTypeID);
            return(View(employee));
        }
Esempio n. 3
0
        public async Task <IActionResult> Edit(int id, [Bind("DeptId,DeptName")] Department department)
        {
            if (id != department.DeptId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (var context = new EmployeeManagementContext())
                    {
                        context.Update(department);
                        await context.SaveChangesAsync();
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DepartmentExists(department.DeptId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            //return View(author);
            return(RedirectToAction("Index"));
        }
        private async void btnSave_Click(object sender, EventArgs e)
        {
            string id           = txtIdNo.Text;
            string name         = txtFullName.Text;
            string address      = txtAddress.Text;
            string contactNo    = txtContact.Text;
            string email        = txtEmail.Text;
            string desigination = txtDesignation.Text;
            string department   = comboBoxDepartment.Text;
            string dateOfJoin   = dateTimePicker.Text;
            string wageRate     = txtWage.Text;
            string hourWorked   = txtWorkedHour.Text;

            using (EmployeeManagementContext context = new EmployeeManagementContext())
            {
                Employee emp = new Employee(id, name, address, contactNo, email, desigination, department, dateOfJoin, wageRate, hourWorked);
                context.Employees.Add(emp);
                await context.SaveChangesAsync();
            }

            //instance event args and value has been passed
            IdentityEventArgs args = new IdentityEventArgs(id, name, address, contactNo, email, desigination, department, dateOfJoin, wageRate, hourWorked);

            //Event has be raised with update arguments of delegate
            IdentityUpdated?.Invoke(this, args);

            this.Hide();
        }
        public async Task <IActionResult> Create([Bind("Name,Surname,Address,Qualification,ContactNumber, DeptId")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                using (var _context = new EmployeeManagementContext())
                {
                    _context.Add(employee);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            using (var _context = new EmployeeManagementContext())
            {
                var departments = await _context.Departments.Select(a => new SelectListItem
                {
                    Value = a.DeptId.ToString(),
                    Text  = $"{a.DeptName}"
                }).ToListAsync();

                ViewBag.Departments = departments;
                //ViewData["DeptId"] = new SelectList(_context.Departments, "DeptId", "DeptId", employee.DeptId);
            }
            return(View(employee));
        }
Esempio n. 6
0
        public async Task <EmployeeModel> CreateEmployee(EmployeeModel empModel)
        {
            try
            {
                Employee employee       = mapper.Map <Employee>(empModel);
                var      responseResult = await databaseContext.Employee.AddAsync(employee);

                await databaseContext.SaveChangesAsync();

                //write logic to send mail
                SendMailOnEmployeeCreateOrDelete(responseResult.Entity, "Created");
                return(mapper.Map <EmployeeModel>(responseResult.Entity));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <Employee> AddEmployee(EmployeeViewModel employee)
        {
            try
            {
                Employee newEmployee = mapper.Map <Employee>(employee);
                var      result      = await dbContext.Employees.AddAsync(newEmployee);

                await dbContext.SaveChangesAsync();

                SendMail(result.Entity, RecordStatus.Created);
                return(result.Entity);
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> AddGroup(AddGroupViewModel model)
        {
            ViewBag.Department = context.Departments.Select(c => new SelectListItem
            {
                Text  = c.Name,
                Value = c.Name
            });

            if (ModelState.IsValid)
            {
                var dep   = context.Departments.Where(s => s.Name == model.DepartmentValue).FirstOrDefault();
                var group = new Group()
                {
                    Name        = model.Name,
                    Email       = model.Email,
                    Description = model.Description,
                    Department  = dep
                };

                await context.Groups.AddAsync(group);

                int changesCount = await context.SaveChangesAsync();

                if (changesCount > 0)
                {
                    var appLogType = context.AppLogTypes.Where(c => c.TypeName == "GroupAdded").FirstOrDefault();

                    var appLog = new AppLog()
                    {
                        Created    = DateTime.Now,
                        AppLogType = appLogType,
                        Message    = $"Добавлена новая группа. ID: {group.Id}, Наименование: {group.Name}"
                    };

                    await context.AppLogs.AddAsync(appLog);

                    await context.SaveChangesAsync();
                }
                return(RedirectToAction("Index", "Group"));
            }

            return(View());
        }
Esempio n. 9
0
        public async Task <IActionResult> AddDepartment(AddDepartmentViewModel model)
        {
            if (ModelState.IsValid)
            {
                var depFromDb = await context.Departments.Where(d => d.Name == model.Name).FirstOrDefaultAsync();

                if (depFromDb == null)
                {
                    var dep = new Department()
                    {
                        Name        = model.Name,
                        Email       = model.Email,
                        Description = model.Description
                    };

                    await context.Departments.AddAsync(dep);

                    int changesCount = await context.SaveChangesAsync();

                    if (changesCount > 0)
                    {
                        var appLogType = context.AppLogTypes.Where(c => c.TypeName == "DepartmentAdded").FirstOrDefault();

                        var appLog = new AppLog()
                        {
                            Created    = DateTime.Now,
                            AppLogType = appLogType,
                            Message    = $"Добавлен новый отдел. ID: {dep.Id}, Наименование: {dep.Name}"
                        };

                        await context.AppLogs.AddAsync(appLog);

                        await context.SaveChangesAsync();
                    }
                    return(RedirectToAction("Index", "Department"));
                }
                else
                {
                    ModelState.AddModelError("", "Указанный отдел уже присутствует в базе данных. Укажите другой.");
                }
            }
            return(View());
        }
Esempio n. 10
0
        public async Task <IActionResult> Create([Bind("FirstName,LastName,Gender,Birth,Department,Address,Phone,Email")] Employee employee)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(employee);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(employee));
        }
        public async Task <IActionResult> PostEmployee([FromBody] EmployeeViewModel employee)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Employee emp = new Employee();

            emp.Gender     = employee.Gender;
            emp.Name       = employee.Name;
            emp.Salary     = employee.Salary;
            emp.ProfilePic = employee.ProfilePic;
            emp.Department = _context.Departments.First(x => x.Id == employee.DepartmentId);

            _context.Employees.Add(emp);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetEmployee", new { id = employee.Id }, employee));
        }
Esempio n. 12
0
        public async Task <IActionResult> AddPosition(AddPositionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var posFromDb = await context.Positions.Where(p => p.Name == model.Name).FirstOrDefaultAsync();

                if (posFromDb == null)
                {
                    var position = new Position()
                    {
                        Name = model.Name
                    };

                    await context.Positions.AddAsync(position);

                    int changesCount = await context.SaveChangesAsync();

                    if (changesCount > 0)
                    {
                        var appLogType = context.AppLogTypes.Where(c => c.TypeName == "PositionAdded").FirstOrDefault();

                        var appLog = new AppLog()
                        {
                            Created    = DateTime.Now,
                            AppLogType = appLogType,
                            Message    = $"Добавлена новая должность. ID: {position.Id}, Наименование: {position.Name}"
                        };

                        await context.AppLogs.AddAsync(appLog);

                        await context.SaveChangesAsync();
                    }
                    return(RedirectToAction("Index", "Position"));
                }
                else
                {
                    ModelState.AddModelError("", "Данная должность уже присутствует в базе данных. Укажите другую.");
                }
            }
            return(View());
        }
Esempio n. 13
0
 public async Task <IActionResult> Create([Bind("DeptName")] Department department)
 {
     using (var context = new EmployeeManagementContext())
     {
         if (ModelState.IsValid)
         {
             context.Add(department);
             await context.SaveChangesAsync();
         }
         return(RedirectToAction("Index"));
     }
 }
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            using (var _context = new EmployeeManagementContext())
            {
                var employee = await _context.Employees.FindAsync(id);

                _context.Employees.Remove(employee);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
        }
        public async Task <string> AddEmployee(Employees employee)
        {
            try
            {
                await _context.Employees.AddAsync(employee);

                await _context.SaveChangesAsync();

                return("Employee Added Sucessfully");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            using (var context = new EmployeeManagementContext())
            {
                //var department = await context.Departments.FindAsync(id);
                var department = await context.Departments.Include(a => a.Employees).FirstOrDefaultAsync(m => m.DeptId == id);

                if (department.Employees.Count == 0)
                {
                    context.Departments.Remove(department);
                    await context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    ViewBag.Message = "Record can not deleted foreign key violation";
                    return(View());
                    //throw new Exception("Record can not deleted foreign key violation");
                    //return RedirectToAction(nameof(Index));
                }
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("EmpId,Name,Surname,Address,Qualification,ContactNumber,DeptId")] Employee employee)
        {
            if (id != employee.EmpId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (var _context = new EmployeeManagementContext())
                    {
                        _context.Update(employee);
                        await _context.SaveChangesAsync();
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeeExists(employee.EmpId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            using (var _context = new EmployeeManagementContext())
            {
                ViewData["DeptId"] = new SelectList(_context.Departments, "DeptId", "DeptId", employee.DeptId);
            }
            return(View(employee));
        }
Esempio n. 18
0
        /**
         *
         * This method will help to import CSV file and set the values on dataGridView
         *
         * **/
        public async void ImportEmployeeFromCsv()
        {
            using (var openFileDialog1 = new OpenFileDialog()
            {
                Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false
            })
            {
                if (openFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                const char sepChar      = ',';
                const char quoteChar    = '"';
                var        employeeList = new List <string[]>();
                try
                {
                    using (Stream stream = null)
                    {
                        var rows = File.ReadAllLines(openFileDialog1.FileName);
                        foreach (var csvRow in rows)
                        {
                            var inQuotes = false;
                            var fields   = new List <string>();
                            var field    = "";
                            for (var i = 0; i < csvRow.Length; i++)
                            {
                                if (inQuotes)
                                {
                                    if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)
                                    {
                                        i      = i++;
                                        field += quoteChar;
                                    }
                                    else if (csvRow[i] == quoteChar)
                                    {
                                        inQuotes = false;
                                    }
                                    else
                                    {
                                        if (csvRow[i - 1] == quoteChar)
                                        {
                                            field  = "";
                                            field += csvRow[i];
                                        }
                                        else
                                        {
                                            field += csvRow[i];
                                        }
                                    }
                                }
                                else
                                {
                                    if (csvRow[i] == quoteChar)
                                    {
                                        inQuotes = true;
                                    }
                                    if (csvRow[i] == sepChar)
                                    {
                                        fields.Add(field);
                                        field = "";
                                    }
                                    else
                                    {
                                        field += csvRow[i];
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(field))
                            {
                                fields.Add(field);
                                field = "";
                            }
                            employeeList.Add(fields.ToArray());
                        }
                    }
                }
                catch (Exception er)
                {
                    MessageBox.Show(er.Message, "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                foreach (var value in employeeList)
                {
                    using (var context = new EmployeeManagementContext())
                    {
                        dataGridView.Rows.Add(value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], value[8], value[9]);
                        var emp = new Employee(value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], value[8], value[9]);
                        context.Employees.Add(emp);
                        try
                        {
                            await context.SaveChangesAsync();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        public async Task <IActionResult> AddEmployee(AddEmployeeViewModel model)
        {
            ViewBag.Group = context.Groups.Select(c => new SelectListItem
            {
                Text  = c.Name,
                Value = c.Name
            });

            ViewBag.Position = context.Positions.Select(c => new SelectListItem
            {
                Text  = c.Name,
                Value = c.Name
            });

            if (ModelState.IsValid)
            {
                var group = await context.Groups.Where(c => c.Name == model.GroupValue).FirstOrDefaultAsync();

                var position = await context.Positions.Where(c => c.Name == model.PositionValue).FirstOrDefaultAsync();

                var employee = new Employee()
                {
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    MiddleName     = model.MiddleName,
                    Login          = model.Login,
                    Email          = model.Email,
                    ExtensionPhone = model.ExtensionPhone,
                    BirthDate      = model.BirthDate,
                    EmploymentDate = model.EmploymentDate,
                    IsActive       = true,
                    Group          = group
                };

                var mobile = new MobilePhone()
                {
                    Employee = employee,
                    Number   = model.MobilePhone
                };

                var emplPosition = new EmployeePosition()
                {
                    Position = position,
                    Employee = employee
                };

                await context.Employees.AddAsync(employee);

                await context.MobilePhones.AddAsync(mobile);

                await context.EmployeePositions.AddAsync(emplPosition);

                int changesCount = await context.SaveChangesAsync();

                if (changesCount > 0)
                {
                    var appLogType = await context.AppLogTypes.Where(c => c.TypeName == "EmployeeAdded").FirstOrDefaultAsync();

                    var appLog = new AppLog()
                    {
                        Created    = DateTime.Now,
                        AppLogType = appLogType,
                        Message    = $"Добавлен новый пользователь. ID: {employee.Id}, ФИО: {employee.LastName} {employee.FirstName} {employee.MiddleName}"
                    };

                    await context.AppLogs.AddAsync(appLog);

                    await context.SaveChangesAsync();
                }
                return(RedirectToAction("EmployeeDetails", "Employee", new { id = employee.Id }));
            }
            return(View());
        }