Ejemplo n.º 1
0
        public async Task <ResourceResult <EmployeeResource> > UpsertAsync(EmployeeResource resource)
        {
            var result = new ResourceResult <EmployeeResource>();

            // Beautify before validation and make validation more succesfull
            BeautifyResource(resource);

            // save beautify effect effect
            result.Resource = resource;

            // Apply simple validation on attribute level
            ValidateAttributes(resource, result.Errors);

            // Apply complex business rules validation
            ValidateBusinessRules(resource, result.Errors);

            // Save is only usefull when error free
            if (result.Errors.Count == 0)
            {
                // Convert resource to entity
                var entity = mapper.Map <Employee>(resource);

                // save entity
                await EntityContext.UpsertAsync(entity);

                // convert save result back to resource and get database created values like auto incremental field and timestamps.
                result.Resource = mapper.Map <EmployeeResource>(entity);
            }

            return(result);
        }
Ejemplo n.º 2
0
        private String RemoveSensitiveFields(EmployeeResource resource)
        {
            // The dynamic Linq Select(params) works only on an IQueryable list
            // thats why 1 one item is added to a list
            var items = new List <EmployeeResource>(new[] { resource }).AsQueryable();

            // Find all property names
            var propertyNames = resource.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name).ToList();

            // Salary only visible to HR department
            if (!User.HasClaim("Department", "HR"))
            {
                propertyNames.Remove(nameof(EmployeeResource.Salary));
            }

            // Dynamic Linq supports dynamic selector
            var selector = $"new({String.Join(",", propertyNames)})";

            // Create dynamic object with authorized fields
            var reducedResource = items.Select(selector).First();

            // Create JSON
            var result = JsonConvert.SerializeObject(reducedResource, new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented
            });

            return(result);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] EmployeeResource resource)
        {
            try
            {
                // Create rescource
                var serviceResult = await ResourceService.InsertAsync(resource);

                // if return error message if needed
                if (serviceResult.Errors.Count > 0)
                {
                    return(BadRequest(serviceResult));
                }

                // On succes return url with id and newly created resource
                return(CreatedAtAction(nameof(Get), new { id = serviceResult.Resource.Id }, serviceResult.Resource));
            }
            catch (Exception ex)
            {
                var result = new ResourceResult <EmployeeResource>(resource);

                while (ex != null)
                {
                    result.Exceptions.Add(ex.Message);
                }

                return(BadRequest(result));
            }
        }
        public async Task <ActionResult <Employee> > UpdateEmployee(Guid id, EmployeeResource resource)
        {
            Employee employee = await _context.Employees
                                .Include(e => e.EmployeeSkill).ThenInclude(e => e.Skill)
                                .FirstOrDefaultAsync(e => e.Id == id);

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

            _mapper.Map(resource, employee);
            employee.FullName   = employee.Name + " " + employee.Surname;
            employee.UpdateDate = DateTime.Now;
            employee.Age        = DateTime.Today.Year - employee.DateOfBirth.Year;

            if (employee.EmployeeSkill.Count > 0)
            {
                _context.EmployeeSkills.RemoveRange(employee.EmployeeSkill);
            }

            if (resource.Skills.Count > 0)
            {
                foreach (var skill in resource.Skills)
                {
                    _context.EmployeeSkills.Add(new EmployeeSkill {
                        EmployeeId = employee.Id, SkillId = skill.Id
                    });
                }
            }

            await _context.SaveChangesAsync();

            return(Ok(employee));
        }
        public async Task <ActionResult <List <Employee> > > CreateEmployees(EmployeeResource resource)
        {
            var newEmployee = _mapper.Map <EmployeeResource, Employee>(resource);

            newEmployee.Id           = Guid.NewGuid();
            newEmployee.FullName     = newEmployee.Name + " " + newEmployee.Surname;
            newEmployee.CreationDate = DateTime.Now;
            newEmployee.UpdateDate   = DateTime.Now;
            newEmployee.Age          = DateTime.Today.Year - resource.DateOfBirth.Year;

            if (resource.Skills.Count > 0)
            {
                foreach (var skill in resource.Skills)
                {
                    _context.EmployeeSkills.Add(new EmployeeSkill {
                        EmployeeId = newEmployee.Id, SkillId = skill.Id
                    });
                }
            }

            await _context.AddAsync(newEmployee);

            await _context.SaveChangesAsync();

            return(Ok(newEmployee));
        }
Ejemplo n.º 6
0
        // Werte setzen
        public void InitialSet()
        {
            UpdateFunctionList();

            // Wenn keine personelle Ressource ausgewählt: Erstellen
            if (selectedVEmployeeResource == null)
            {
                CreateFieldsEnabled = true;
                SetFieldsEnabled    = false;

                btnCreateOrSetEmployeeResourceName = "Erstellen";
            }
            else
            {
                // Wenn personelle Ressource ausgewählt: Updaten
                CreateFieldsEnabled = false;
                SetFieldsEnabled    = true;

                // View Obj in richtiges EmployeeResource umwandeln
                selectedEmployeeResource = new EmployeeResource(selectedVEmployeeResource.Id, selectedVEmployeeResource.BudgetTime, selectedVEmployeeResource.EffectiveTime, selectedVEmployeeResource.Deviation, selectedVEmployeeResource.FunctionId, selectedVEmployeeResource.ActivityId);

                txtPlannedTime   = selectedEmployeeResource.BudgetTime;
                txtEffectiveTime = selectedEmployeeResource.EffectiveTime;
                txtDeviation     = selectedEmployeeResource.Deviation;

                btnCreateOrSetEmployeeResourceName = "Setzen";
            }
        }
        public async Task <EmployeeResource> ReplaceAsync(int id, EmployeeResource resource)
        {
            Employee entity = await FindAsync(id);

            Mapper.Map(resource, entity);
            await _db.SaveChangesAsync();

            return(ToResource(entity));
        }
        public async Task <EmployeeResource> AddAsync(EmployeeResource resource)
        {
            Employee entity = ToEntity(resource);

            _db.Employees.Add(entity);
            await _db.SaveChangesAsync();

            return(ToResource(entity));
        }
Ejemplo n.º 9
0
        public EmployeeResource Create()
        {
            var result = new EmployeeResource()
            {
                Id = Guid.NewGuid()
            };

            return(result);
        }
Ejemplo n.º 10
0
        public async Task <IHttpActionResult> PostEmployee(EmployeeResource resoure)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            EmployeeResource result = await _employeesService.AddAsync(resoure);

            return(CreatedAtRoute("DefaultApi", new { id = result.Id }, result));
        }
Ejemplo n.º 11
0
        /// <summary>
        ///  Perform basic validation
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="errors"></param>
        protected void ValidateAttributes(EmployeeResource resource, IList <ValidationError> errors)
        {
            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(resource);
            var validationResults = new List <ValidationResult>();;

            Validator.TryValidateObject(resource, validationContext, validationResults, true);

            foreach (var item in validationResults)
            {
                errors.Add(new ValidationError(item.ErrorMessage, item.MemberNames?.FirstOrDefault() ?? ""));
            }
        }
Ejemplo n.º 12
0
        public async Task <ResourceResult <EmployeeResource> > InsertAsync(EmployeeResource resource)
        {
            // Fields are set by persistance service
            resource.CreatedBy = null;

            resource.ModifiedAt = null;
            resource.ModifiedBy = null;

            resource.RowVersion = null;

            return(await UpsertAsync(resource));
        }
Ejemplo n.º 13
0
        public async Task <IHttpActionResult> PutEmployee(int id, EmployeeResource resource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            resource.Id = id;

            await _employeesService.ReplaceAsync(id, resource);

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 14
0
        public async Task <IHttpActionResult> GetEmployee(int id)
        {
            try
            {
                EmployeeResource resource = await _employeesService.SingleAsync(id);

                return(Ok(resource));
            }
            catch (KeyNotFoundException)
            {
                return(NotFound());
            }
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> CreateEmployee([FromBody] EmployeeResource employeeResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var employee = mapper.Map <EmployeeResource, Employee>(employeeResource);

            context.Employees.Add(employee);
            await context.SaveChangesAsync();

            return(Ok(employee));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Edit(int id, [FromForm] EmployeeResource employeeResource)
        {
            if (!ModelState.IsValid)
            {
                return(View(employeeResource));
            }
            var response = await _service.Put(id, employeeResource, _appSetings.RestApiUrl);

            if (!response.Success)
            {
                ModelState.AddModelError("Email", response.Message);
                return(View(employeeResource));
            }
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> UpdateEmployee(int id, [FromBody] EmployeeResource employeeResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var employee = await context.Employees.FindAsync(id);

            if (employee == null)
            {
                return(NotFound());
            }
            mapper.Map <EmployeeResource, Employee>(employeeResource, employee);
            await context.SaveChangesAsync();

            return(Ok(employee));
        }
Ejemplo n.º 18
0
        public void CreateEmployee(UserResource createdUser)
        {
            var siteId = GetSiteID();

            var siteAssignments     = CreateEmployeeSiteAssignmentCollection(createdUser, StartDate, siteId);
            var jobAssignments      = CreateEmployeeJobAssignments(createdUser, StartDate, siteId);
            var employeeStatuses    = CreateEmployeeStatusCollection(createdUser, siteId, StartDate);
            var scheduleConstraints = CreateEmployeeScheduleConstraintsList(createdUser, siteId);

            var employee = new EmployeeResource
            {
                SeniorityDate       = StartDate,
                MinorStatus         = "NotMinor",
                PunchValidationCode = "NoScheduleValidation",
                GenerateException   = true,
                EmployeeSiteAssignmentCollection = siteAssignments,
                IsManagement           = false,
                EmployeeJobAssignments = jobAssignments,
                ManagerInSchedule      = false,
                ID                          = createdUser.ID,
                BadgeNumber                 = createdUser.ID.ToString(),
                SchoolDistrictID            = null,
                SchedulingTypeCode          = "Manual",
                IgnoreBiometricValidation   = false,
                PayGroupID                  = null,
                CanWorkUnassignedJobs       = false,
                PayrollSystemNumber         = null,
                ManagerPassword             = null,
                GenerateAlerts              = false,
                BirthDate                   = "1992-09-02T00:00:00",
                EmployeeStatuses            = employeeStatuses,
                EmployeeScheduleConstraints = scheduleConstraints,
                HireDate                    = StartDate
            };

            try
            {
                _Client.Create(HttpMethod.Post, EmployeeApi, employee).Wait();
                Console.WriteLine("Employee " + createdUser.Name.FirstName + " " + createdUser.Name.LastName + " was created");
            }
            catch (AggregateException aggregateException)
            {
                aggregateException.Handle(HandleCreationException);
            }
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> AddEmployee([FromBody] EmployeeResource empResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }
            var isEmailUsed = await _service.FindEmployeeByEmail(empResource.Email);

            if (isEmailUsed.Success)
            {
                return(Conflict("Esse email já foi utilizado."));
            }
            var employee = _converter.ConvertToModel(empResource);
            var result   = await _service.AddEmployee(employee);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }
            return(Ok(result.Employee));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Put([FromBody] EmployeeResource resource)
        {
            try
            {
                var currentResource = await ResourceService.FindAsync(resource.Id);

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

                var serviceResult = await ResourceService.UpdateAsync(resource);

                if (serviceResult.Errors.Count > 0)
                {
                    return(BadRequest(serviceResult));
                }

                return(Ok(serviceResult.Resource));
            }
            catch (Exception ex)
            {
                var result = new ResourceResult <EmployeeResource>(resource);

                while (ex != null)
                {
                    result.Exceptions.Add(ex.Message);

                    if (ex is ConcurrencyException)
                    {
                        return(StatusCode(HttpStatusCode.Conflict.ToInt32(), result));
                    }

                    ex = ex.InnerException;
                }

                return(BadRequest(result));
            }
        }
Ejemplo n.º 21
0
 protected virtual void ValidateDelete(EmployeeResource resource, IList <ValidationError> errors)
 {
 }
Ejemplo n.º 22
0
        public async Task <IEnumerable <EmployeeResource> > GetEmployee(EmployeeResource employeeResource)
        {
            var employee = await context.Employees.ToListAsync();

            return(mapper.Map <IEnumerable <Employee>, IEnumerable <EmployeeResource> >(employee));
        }
Ejemplo n.º 23
0
 public async Task <ResourceResult <EmployeeResource> > UpdateAsync(EmployeeResource resource)
 {
     return(await UpsertAsync(resource));
 }
Ejemplo n.º 24
0
 protected virtual void BeautifyResource(EmployeeResource resource)
 {
 }
Ejemplo n.º 25
0
 protected virtual void ValidateBusinessRules(EmployeeResource resource, IList <ValidationError> errors)
 {
 }
 private static Employee ToEntity(EmployeeResource resource)
 {
     return(Mapper.Map <Employee>(resource));
 }
 public void RunBeforeTests()
 {
     _resource = new EmployeeResource(_token);
 }