protected override void Up(MigrationBuilder migrationBuilder)
 {
     using (var db = new TimesheetContext()) {
         foreach (var b in new [] {
             new { code = "5H", name = "5 hrs", length = 300 },
             new { code = "HH", name = "1/2 hr", length = 30 },
             new { code = "1H", name = "1 hr", length = 60 },
             new { code = "1.5H", name = "1 1/2 hr", length = 90 },
             new { code = "2H", name = "2 hrs", length = 120 },
             new { code = "15M", name = "15 min", length = 15 },
             new { code = "45M", name = "45 min", length = 45 },
             new { code = "1H15M", name = "1 hr 15 min", length = 75 },
             new { code = "1H45M", name = "1 hr 45 min", length = 105 },
             new { code = "2H15M", name = "2 hrs 15 min", length = 135 },
             new { code = "2H30M", name = "2 hrs 30 min", length = 150 },
             new { code = "2H45M", name = "2 hrs 45 min", length = 165 },
             new { code = "3H0M", name = "3 hrs ", length = 180 },
             new { code = "3H15M", name = "3 hrs 15 min", length = 195 },
             new { code = "3H30M", name = "3 hrs 30 min", length = 210 },
             new { code = "3H45M", name = "3 hrs 45 min", length = 225 },
             new { code = "4H0M", name = "4 hrs ", length = 240 },
             new { code = "4H15M", name = "4 hrs 15 min", length = 255 },
             new { code = "4H30M", name = "4 hrs 30 min", length = 270 },
             new { code = "4H45M", name = "4 hrs 45 min", length = 285 },
         })
         {
             db.Breaks.Add(new Break(b.code, b.name, b.length));
         }
         db.SaveChanges();
     };
 }
Пример #2
0
        // Delete/Archive
        public string DeletePersonByID(int id)
        {
            string result;

            using (TimesheetContext context = new TimesheetContext())
            {
                // archive this person throw error if they arent found
                Person target = context.Persons.Where(x => x.ID == id && x.Archive == false).SingleOrDefault();
                if (target == null)
                {
                    throw new Exception($"Person with ID: {id} was not found.");
                }
                target.Archive = true;
                // archive this persons employee record
                Employee targetEmployee = context.Employees.Where(x => x.PersonID == target.ID).SingleOrDefault();
                targetEmployee.Archive = true;
                // loop through and archive all projects for this person
                List <Project> targetProjects = context.Projects.Where(x => x.EmployeeID == targetEmployee.ID).ToList();
                foreach (Project targetProject in targetProjects)
                {
                    targetProject.Archive = true;
                }
                context.SaveChanges();
                result = "Your account has been archived. We may store data for records (this will not be publicly available)";
            }
            return(result);
        }
        // Get a list of projects based on employeeID of student, for student to view their projects
        public List <ProjectDTO> GetProjectListForStudent(int employeeID)
        {
            List <ProjectDTO> studentProjects;
            List <Project>    projectList;

            using (TimesheetContext context = new TimesheetContext())
            {
                // Filter the project for matching employee ID & unarchived projects only
                projectList = context.Projects.Where(x => x.EmployeeID == employeeID && x.Archive == false).ToList();

                // calculate total hours for each project
                studentProjects = projectList.Select(x => new ProjectDTO()
                {
                    ID                = x.ID,
                    ProjectName       = x.ProjectName,
                    DueDate           = x.DueDate,
                    DateCreated       = x.DateCreated,
                    DateCompleted     = x.DateCompleted,
                    DesignHours       = x.DesignHours,
                    DoingHours        = x.DoingHours,
                    CodeReviewHours   = x.CodeReviewHours,
                    TestingHours      = x.TestingHours,
                    DeliverablesHours = x.DeliverablesHours
                }).ToList();

                return(studentProjects);
            }
        }
        public async Task <ActionResult> Start(RegistrationModel model)
        {
            using (var db = new TimesheetContext())
            {
                // Create a new temporary tenant.
                var registration = db.RegistrationRequests.Add(new RegistrationRequest
                {
                    Id               = Guid.NewGuid(),
                    CreatedOn        = DateTime.UtcNow,
                    SignupToken      = Guid.NewGuid().ToString(),
                    AdminConsented   = model.EnableForMyOrganization,
                    OrganizationName = model.OrganizationName
                });
                await db.SaveChangesAsync();

                // Build the redirect to the consent page.
                var authorizationRequest = String.Format(OnboardingUrl,
                                                         Uri.EscapeDataString(ConfigurationManager.AppSettings["AzureAD:ClientID"]),
                                                         Uri.EscapeDataString("https://graph.windows.net"),
                                                         Uri.EscapeDataString(Request.Url.GetLeftPart(UriPartial.Authority) + "/registration/complete"),
                                                         Uri.EscapeDataString(registration.SignupToken));
                if (model.EnableForMyOrganization)
                {
                    authorizationRequest += String.Format("&prompt={0}", Uri.EscapeDataString("admin_consent"));
                }
                return(Redirect(authorizationRequest));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ManagerDashboardHelper"/> class.
 /// </summary>
 /// <param name="context">The timesheet context.</param>
 /// <param name="repositoryAccessors">The instance of repository accessors.</param>
 /// <param name="userGraphService">The instance of user Graph service to access logged-in user's reportees and manager.</param>
 /// <param name="managerDashboardMapper">The instance of manager dashboard mapper.</param>
 public ManagerDashboardHelper(TimesheetContext context, IRepositoryAccessors repositoryAccessors, IUsersService userGraphService, IManagerDashboardMapper managerDashboardMapper)
 {
     this.context                = context;
     this.repositoryAccessors    = repositoryAccessors;
     this.userGraphService       = userGraphService;
     this.managerDashboardMapper = managerDashboardMapper;
 }
        // Create project cohort
        public void CreateProjectForCohort(string projectName, DateTime dueDate, float cohort)
        {
            List <Employee> cohortList;

            using (TimesheetContext context = new TimesheetContext())
            {
                // Filter Cohort First
                cohortList = context.Employees.Where(x => x.Cohort == cohort).ToList();

                // Assigned filtered cohort with assignments using foreach loop.
                foreach (Employee student in cohortList)
                {
                    Project newProject = new Project()
                    {
                        ProjectName = projectName,
                        DueDate     = dueDate,
                        EmployeeID  = student.ID,
                        DateCreated = DateTime.Now
                    };

                    context.Add(newProject);
                    context.SaveChanges();
                }
            }
        }
        public void AddTime_Success()
        {
            // Setup
            TimesheetContext db   = new TimesheetContext();
            User             user = db.Users.First();
            int  maxTimeId        = db.Times.Select(t => t.Id).Max();
            Time time             = new Time()
            {
                Date = DateTime.Today, HoursWorked = 5, UserId = user.Id
            };

            // Test action
            TimesheetRepository repository = new TimesheetRepository();

            repository.AddTime(time);

            // Assertions
            Time newTime = db.Times.First(t => t.Id > maxTimeId);

            Assert.IsNotNull(newTime);
            Assert.AreEqual(time.Date, newTime.Date);

            // Cleanup
            db.Times.Remove(newTime);
        }
 public TokenService(int timeout, TokenServiceType type, TimesheetContext context, ILogger <TokenService> logger)
 {
     _timeoutSeconds = timeout;
     _type           = type;
     _context        = context;
     _logger         = logger;
 }
        // Read
        // Get a list of employees based on input: all, intructor, student
        public List <EmployeeDTO> GetAllEmployees(string input)
        {
            using (TimesheetContext context = new TimesheetContext())
            {
                switch (input)
                {
                case "instructor":
                    if (!context.Employees.Any(x => x.Instructor == true))
                    {
                        throw new ArgumentNullException("No instructor recorded in the employee database.");
                    }
                    else
                    {
                        return(GetAll().Where(x => x.Instructor == true).ToList());
                    }

                case "student":
                    if (!context.Employees.Any(x => x.Instructor == false))
                    {
                        throw new ArgumentException("No student recorded in the employee database.");
                    }
                    else
                    {
                        return(GetAll().Where(x => x.Instructor == false).ToList());
                    }

                default:
                    return(GetAll());
                }
            }
        }
        // Read
        // Get all list of the projects and students for instructors, it can further filtered by: project name, studentID, duedate, ordered by total hours
        public List <ProjectDTO> GetAllProjects()
        {
            List <ProjectDTO> target;

            using (TimesheetContext context = new TimesheetContext())
            {
                target = context.Projects.Where(x => x.Archive == false).Select(x => new ProjectDTO()
                {
                    ID                = x.ID,
                    ProjectName       = x.ProjectName,
                    FullName          = $"{x.Employee.Person.FirstName} {x.Employee.Person.LastName}",
                    DueDate           = x.DueDate,
                    DateCreated       = x.DateCreated,
                    DateCompleted     = x.DateCompleted,
                    DesignHours       = x.DesignHours,
                    DoingHours        = x.DoingHours,
                    CodeReviewHours   = x.CodeReviewHours,
                    TestingHours      = x.TestingHours,
                    DeliverablesHours = x.DeliverablesHours,
                    Cohort            = x.Employee.Cohort
                }
                                                                                ).ToList();
            }
            return(target);
        }
Пример #11
0
        public async Task <ActionResult> Callback(string returnUrl)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (externalIdentity == null)
            {
                throw new Exception("Could not get the external identity. Please check your Auth0 configuration settings and ensure that " +
                                    "you configured UseCookieAuthentication and UseExternalSignInCookie in the OWIN Startup class. " +
                                    "Also make sure you are not calling setting the callbackOnLocationHash option on the JavaScript login widget.");
            }

            // Create or update the user.
            using (var db = new TimesheetContext())
            {
                var givenNameClaim  = externalIdentity.Claims.FirstOrDefault(c => c.Type == "given_name");
                var familyNameClaim = externalIdentity.Claims.FirstOrDefault(c => c.Type == "family_name");
                var providerClaim   = externalIdentity.Claims.FirstOrDefault(c => c.Type == "provider");
                var identifierClaim = externalIdentity.Claims.FirstOrDefault(c => c.Type == "user_id");
                var tenantClaim     = externalIdentity.Claims.FirstOrDefault(c => c.Type == "tenantid");
                var upnClaim        = externalIdentity.Claims.FirstOrDefault(c => c.Type == "upn");

                // Check if the user already exists.
                var user = await db.Users.FirstOrDefaultAsync(u => u.Provider == providerClaim.Value && u.Identifier == identifierClaim.Value);

                if (user == null && tenantClaim != null && upnClaim != null)
                {
                    user = await db.Users.FirstOrDefaultAsync(u => u.AzureTenantId == tenantClaim.Value && u.AzureUpn == upnClaim.Value);
                }

                // New user.
                if (user == null)
                {
                    user = db.Users.Add(new User {
                        Id = Guid.NewGuid(), CreatedOn = DateTime.UtcNow
                    });
                }

                // Update user profile.
                user.Identifier    = identifierClaim.Value;
                user.Provider      = providerClaim.Value;
                user.Firstname     = givenNameClaim != null ? givenNameClaim.Value : null;
                user.Lastname      = familyNameClaim != null ? familyNameClaim.Value : null;
                user.AzureTenantId = tenantClaim != null ? tenantClaim.Value : null;
                user.AzureUpn      = upnClaim != null ? upnClaim.Value : null;

                await db.SaveChangesAsync();

                // Login.
                var applicationIdentity = CreateIdentity(externalIdentity, user);
                AuthenticationManager.SignIn(new AuthenticationProperties {
                    IsPersistent = false
                }, applicationIdentity);
            }

            // Optional: Redirect new users to page where they can complete their profile.
            return(RedirectToLocal(returnUrl ?? Url.Action("Index", "TimesheetEntries")));
        }
Пример #12
0
 public TimesheetController(TimesheetContext context, IConfiguration config)
 {
     _db             = context;
     _config         = config;
     cacheConnection = _config.GetValue <string>("CacheConnection").ToString();
     lazy            = new Lazy <ConnectionMultiplexer>(() =>
     {
         return(ConnectionMultiplexer.Connect(cacheConnection));
     });
 }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProjectHelper"/> class.
 /// </summary>
 /// <param name="context">The timesheet database context.</param>
 /// <param name="repositoryAccessors">The instance of repository accessors.</param>
 /// <param name="projectMapper">The instance of project model mapper.</param>
 /// <param name="memberMapper">Instance of member mapper.</param>
 /// <param name="taskMapper">Instance of task mapper.</param>
 public ProjectHelper(
     TimesheetContext context,
     IRepositoryAccessors repositoryAccessors,
     IProjectMapper projectMapper,
     IMemberMapper memberMapper,
     ITaskMapper taskMapper)
 {
     this.context             = context;
     this.repositoryAccessors = repositoryAccessors;
     this.projectMapper       = projectMapper;
     this.memberMapper        = memberMapper;
     this.taskMapper          = taskMapper;
 }
Пример #14
0
        // READ
        // Authenticate
        // return a personDTO whose authentication info matches or throw an error
        public PersonDTO Authenticate(string email, string password)
        {
            using (TimesheetContext context = new TimesheetContext())
            {
                Person returnUser = context.Persons.Where(x => x.Email == email && x.Archive == false).SingleOrDefault();

                // check if username exist
                if (returnUser == null)
                {
                    return(null);
                }

                // if user isnt authenticated, return null
                if (!Hasher.ValidatePassword(password, returnUser.PasswordSalt, returnUser.PasswordHash))
                {
                    return(null);
                }

                // if we get to this point, then the user was authenticated
                // create a JWT token and add it to the user
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, returnUser.ID.ToString()),
                        new Claim(ClaimTypes.Role, returnUser.Role)
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);


                PersonDTO authenticatedUser = new PersonDTO()
                {
                    ID        = returnUser.ID,
                    Email     = returnUser.Email,
                    FirstName = returnUser.FirstName,
                    LastName  = returnUser.LastName,
                    //Cohort = employeeInfo.Cohort,
                    //Instructor = employeeInfo.Instructor,
                    //Projects = GET a list of projects belonging to this person,
                    Token = tokenHandler.WriteToken(token)
                };

                // authentication successful
                return(authenticatedUser);
            }
        }
        public void GetSubordinatesForUser_Success()
        {
            // Setup
            TimesheetContext db   = new TimesheetContext();
            User             user = db.Users.First(u => u.ManagerId.HasValue);

            // Test action
            TimesheetRepository repository = new TimesheetRepository();
            var subordinates = repository.GetSubordinatesForUser(user.Id);

            // Assertions
            Assert.IsNotNull(subordinates);
            Assert.IsTrue(subordinates.Any());
        }
        public void GetTimesForUser_Success()
        {
            // Setup
            TimesheetContext db   = new TimesheetContext();
            User             user = db.Times.First().User;

            // Test action
            TimesheetRepository repository = new TimesheetRepository();
            var times = repository.GetTimesForUser(user.Id);

            // Assertions
            Assert.IsNotNull(times);
            Assert.IsTrue(times.Any());
        }
        public void GetUser_Success()
        {
            // Setup
            TimesheetContext db   = new TimesheetContext();
            User             user = db.Users.First();

            // Test action
            TimesheetRepository repository = new TimesheetRepository();
            var authenticatedUser          = repository.GetUser(user.Login, user.Password);

            // Assertions
            Assert.IsNotNull(authenticatedUser);
            Assert.AreEqual(user.Login, authenticatedUser.Login);
        }
        // This template is from 4.1-ReactAPI project @link: https://github.com/TECHCareers-by-Manpower/4.1-ReactAPI/tree/master/Controllers
        // Create project for individual person
        // Create project with parameters, project name, due date, date creation, employee_id
        public int CreateProject(string projectName, DateTime dueDate, int employeeID)
        {
            int target;

            // Create Validation Exception to catch any exceptions that is related to database error such as taken email, taken id, and taken name.
            ValidationExceptions exception = new ValidationExceptions();

            using (TimesheetContext context = new TimesheetContext())
            {
                // The project cannot be assigned to employee twice
                // Only instructor can make projects and assign projects
                // Example: JavaScript Assignment cannot be assigned twice
                // Any employee that have that project assigned, the project cannot be created and an response will be created.

                // Find the employee first
                if (!context.Employees.Any(x => x.ID == employeeID))
                {
                    exception.SubExceptions.Add(new ArgumentException($"The student with ID of {employeeID} cannot be found in the database."));
                }
                else
                if (context.Projects.Where(x => x.EmployeeID == employeeID).Any(x => x.ProjectName == projectName))
                {
                    // If the employee alreaddy has a project that matches the project being assigned, throw error
                    exception.SubExceptions.Add(new ArgumentException($"This project, {projectName} has been assigned to this student with ID: {employeeID}."));
                }

                if (exception.SubExceptions.Count > 0)
                {
                    throw exception;
                }
                else
                {
                    // If no exceptions are thrown, the project will be created for the student, and will return a project ID integer.
                    Project newProject = new Project()
                    {
                        ProjectName = projectName,
                        DueDate     = dueDate,
                        EmployeeID  = employeeID,
                        DateCreated = DateTime.Now
                    };

                    context.Add(newProject);
                    context.SaveChanges();
                    target = newProject.ID;
                }
            }
            // This will return a projectID number.
            return(target);
        }
 // Get all the list with model DTO to generate
 public List <EmployeeDTO> GetAll()
 {
     using (TimesheetContext context = new TimesheetContext())
     {
         return(context.Employees.Include(x => x.Person).Select(x => new EmployeeDTO
         {
             ID = x.ID,
             FirstName = x.Person.FirstName,
             LastName = x.Person.LastName,
             Email = x.Person.Email,
             Instructor = x.Instructor,
             Cohort = x.Cohort,
             Archive = x.Archive
         }).ToList());
     }
 }
        public Employee GetEmployeeIDByPersonID(int personID)
        {
            Employee target;

            using (TimesheetContext context = new TimesheetContext())
            {
                if (!context.Employees.Any(x => x.PersonID == personID))
                {
                    throw new ArgumentException($"No employee with ID,{personID} recorded in the employee database.");
                }
                else
                {
                    target = context.Employees.Where(x => x.PersonID == personID).Single();
                }
            }
            return(target);
        }
        // Complete a project
        public int Complete(int projectID)
        {
            Project target;

            using (TimesheetContext context = new TimesheetContext())
            {
                if (!context.Projects.Any(x => x.ID == projectID))
                {
                    throw new ArgumentNullException($"No project with ID {projectID} found.");
                }
                else
                {
                    target = context.Projects.Where(x => x.ID == projectID).Single();
                    target.DateCompleted = DateTime.Now;
                    context.SaveChanges();
                }
                return(target.ID);
            }
        }
Пример #22
0
        internal static void Initialize(TimesheetContext context)
        {
            var initializer = new DataInitializer();

            var departments = initializer.GetDepartments();

            foreach (var department in departments)
            {
                context.Departments.Add(department);
            }
            context.SaveChanges();

            var timesheets = initializer.GetTimesheetsMock();

            foreach (var timesheet in timesheets)
            {
                context.Timesheets.Add(timesheet);
            }
            context.SaveChanges();
        }
        // Archive
        public int Archive(int projectID)
        {
            Project target;

            using (TimesheetContext context = new TimesheetContext())
            {
                if (!context.Projects.Any(x => x.ID == projectID))
                {
                    throw new ArgumentNullException($"No project with {projectID} recorded in the employee database.");
                }
                else
                {
                    target             = context.Projects.Where(x => x.ID == projectID).Single();
                    target.Archive     = true;
                    target.DateArchive = DateTime.Now;
                    context.SaveChanges();
                }
                return(target.ID);
            }
        }
        // Create
        // id: person_id, instructor: true/false, cohort: float such as 4.1
        public int CreateEmployee(int personID, bool instructor, float cohort)
        {
            Employee target;

            using (TimesheetContext context = new TimesheetContext())
            {
                // has to validate that Employee cannot be created twice for the same PersonID
                if (context.Employees.Any(x => x.PersonID == personID))
                {
                    throw new ArgumentException($"This person with ID, {personID} is already an employee of the database.");
                }

                if (instructor == true)
                {
                    // if instructor is TRUE, create newInstructor and cohort set to zero
                    Employee newInstructor = new Employee()
                    {
                        PersonID   = personID,
                        Instructor = true,
                        Cohort     = 0
                    };
                    context.Add(newInstructor);
                    context.SaveChanges();
                    target = newInstructor;
                }
                else
                {
                    // if instrutor is FALSE, create newEmployee and cohort is set to the cohort entered
                    Employee newEmployee = new Employee()
                    {
                        PersonID   = personID,
                        Instructor = false,
                        Cohort     = cohort
                    };
                    context.Add(newEmployee);
                    context.SaveChanges();
                    target = newEmployee;
                }
                return(target.ID);
            }
        }
        // Update
        // Student update hours based on the type of hours
        // Student must have asignments to add hours to project
        // Only student can add hours to their project, such as JavaScript

        public Project UpdateHours(int projectID, float design, float doing, float codeReview, float testing, float deliverables)
        {
            Project project;

            using (TimesheetContext context = new TimesheetContext())
            {
                project                    = context.Projects.Where(x => x.ID == projectID).Single();
                project.DesignHours       += design;
                project.DoingHours        += doing;
                project.CodeReviewHours   += codeReview;
                project.TestingHours      += testing;
                project.DeliverablesHours += deliverables;

                // if any of the values are less than zero, set them to 0 ( no negative values)
                if (project.DesignHours < 0)
                {
                    project.DesignHours = 0;
                }
                if (project.DoingHours < 0)
                {
                    project.DoingHours = 0;
                }
                if (project.CodeReviewHours < 0)
                {
                    project.CodeReviewHours = 0;
                }
                if (project.TestingHours < 0)
                {
                    project.TestingHours = 0;
                }
                if (project.DeliverablesHours < 0)
                {
                    project.DeliverablesHours = 0;
                }

                context.SaveChanges();
            }

            return(project);
        }
Пример #26
0
#pragma warning restore CA1506

        /// <summary>
        /// Configure the application request pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">Hosting Environment.</param>
        /// <param name="timesheetContext">The timesheet context.</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TimesheetContext timesheetContext)
        {
            app.UseRequestLocalization();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseMvc();
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.EnvironmentName.ToUpperInvariant() == "DEVELOPMENT")
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });

#pragma warning disable CA1062 // The 'timesheetContext' will be available through dependency injection.
            timesheetContext.Database.Migrate();
#pragma warning restore CA1062 // The 'timesheetContext' will be available through dependency injection.
        }
 public TimesheetController(TimesheetContext context, IConfiguration config)
 {
     _db     = context;
     _config = config;
 }
 public AccountController(TimesheetContext context, IEmailTokenService emailTokenService, ILogger <AccountController> logger)
 {
     _context           = context;
     _emailTokenService = emailTokenService;
     _logger            = logger;
 }
Пример #29
0
 public EmployeesController(TimesheetContext context, IConfiguration config)
 {
     _context = context;
     _config  = config;
 }
Пример #30
0
 public DeveloperController(TimesheetContext context)
 {
     _db = context;
 }