public ActionResult Create() { CheckCookies(); Ticket model = new Ticket(); model.DueDate = DateTimeOffset.UtcNow.AddDays(10); model.HoursToComplete = 1; UserRolesHelper helper = new UserRolesHelper(); var id = User.Identity.GetUserId(); var roles = helper.ListUserRoles(id); var highest = helper.GetHighestRole(id); ViewBag.HighestUserRole = highest; // Do this in every GET action... var uModel = ProjectsHelper.LoadUserModel(); ViewBag.UserModel = uModel; // If user is Submitter only (or has no role), don't allow Skill, Due Date, or HoursToComplete to show ViewBag.BaseOptionsOnly = (roles == null || ((roles.Count == 1) && (roles[0] == R.Submitter))) ? true : false; // If Admin, allow to select Developer when creating the ticket if (uModel.IsAdmin || uModel.IsPM) { var roleDev = db.Roles.FirstOrDefault(r => r.Name == R.Developer); ViewBag.CanAssignDeveloper = true; if (roleDev != null) { ViewBag.AssignedToDevId = new SelectList(db.Users .Where(d => d.Roles.FirstOrDefault(r => r.RoleId == roleDev.Id) != null), "Id", "UserName"); } else ViewBag.AssignedToDevId = Enumerable.Empty<SelectListItem>(); } else { ViewBag.AssignedToDevId = Enumerable.Empty<SelectListItem>(); ViewBag.CanAssignDeveloper = false; } ViewBag.OwnerUserId = new SelectList(db.Users, "Id", "FirstName"); ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name"); ViewBag.SkillRequiredId = new SelectList(db.SkillLevels, "Id", "Name"); ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name"); ViewBag.TicketStatusId = new SelectList(db.TicketStatuses, "Id", "Name"); ViewBag.TicketTypeId = new SelectList(db.TicketTypes, "Id", "Name"); return View(model); }
public ActionResult Create(int? id, string anchor, int? page, int? cid = null) { // Do this in every GET action... ViewBag.UserModel = ProjectsHelper.LoadUserModel(); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } // Creating comment for main ticket ViewBag.id = (int)id; ViewBag.anchor = anchor; ViewBag.page = page; TicketComment newComment = new TicketComment(); var user = new UserRolesHelper().GetCurrentUser(); newComment.UserId = user.Id; newComment.DisplayName = user.DisplayName != "" ? user.DisplayName : user.UserName; if (cid == null) { newComment.ParentCommentId = null; newComment.TicketId = (int)id; newComment.Level = 0; } else { TicketComment oldComment = db.TicketComments.Find(cid); newComment.ParentCommentId = oldComment.Id; newComment.TicketId = oldComment.TicketId; newComment.Level = oldComment.Level + 1 ?? 1; } ViewBag.Ticket = db.Tickets.Find(newComment.TicketId); ViewBag.Parent = db.TicketComments.Find(newComment.ParentCommentId); return View(newComment); }
// GET: Tickets public ActionResult Index(string scope) { // First, get this user... UserRolesHelper helper = new UserRolesHelper(); var userId = helper.GetCurrentUserId(); // Do this in every GET action... ViewBag.UserModel = ProjectsHelper.LoadUserModel(); if (string.IsNullOrEmpty(scope)) scope = "My"; ViewBag.Scope = scope; CheckCookies(); DateTimeOffset now = DateTimeOffset.UtcNow; DateTimeOffset start, end; switch (scope) { case "My": // Need to track all places where User could be attached to a ticket: // - as PM (then follow ticket chain) // - as Developer (follow ticket chain) // - as ticket creator // - as ticket commenter var myTickets = db.Users.Find(userId).TicketsAssigned .Union(db.Users.Find(userId).TicketsOwned); return View(myTickets.ToList()); case "All": // Come here for all tickets var allTickets = db.Tickets.Include(t => t.AssignedToDev).Include(t => t.OwnerUser).Include(t => t.Project).Include(t => t.SkillRequired).Include(t => t.TicketPriority).Include(t => t.TicketStatus).Include(t => t.TicketType); return View(allTickets.ToList()); case "NotAssigned": // Come here for all not yet assigned var notTickets = db.Tickets .Where(tic => tic.AssignedToDevId == null) .Include(t => t.AssignedToDev).Include(t => t.OwnerUser).Include(t => t.Project).Include(t => t.SkillRequired).Include(t => t.TicketPriority).Include(t => t.TicketStatus).Include(t => t.TicketType); return View(notTickets.ToList()); case "Problem": // Come here for tickets that don't look right (i.e., not assigned by status too low) DateTimeOffset oneYear = DateTimeOffset.UtcNow.AddYears(-1); var problems = db.Tickets .Where(tic => (tic.TicketStatus.Step <= 30 && tic.AssignedToDevId != null) || (tic.TicketStatus.Step >= 40 && tic.AssignedToDevId == null) || tic.DueDate == DateTimeOffset.MinValue || tic.HoursToComplete == 0 || tic.DueDate <= oneYear || tic.TicketStatusId == (int)TS.Status.Deferred || tic.TicketStatusId == (int)TS.Status.UnableToReproduce) .OrderByDescending(tic => tic.TicketStatusId).ThenBy(tic => tic.Id); return View(problems.ToList()); case "MyNew": var newTickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId == (int)TS.Status.AssignedToDev); return View(newTickets.ToList()); case "MyDue7": end = now.AddDays(7); var due7Tickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId != (int)TS.Status.Resolved && t.DueDate >= now && t.DueDate < end); return View(due7Tickets.ToList()); case "MyDue24": end = now.AddDays(1); var due24Tickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId != (int)TS.Status.Resolved && t.DueDate >= now && t.DueDate < end); return View(due24Tickets.ToList()); case "MyDue30": end = now.AddDays(30); var due30Tickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId != (int)TS.Status.Resolved && t.DueDate >= now && t.DueDate < end); return View(due30Tickets.ToList()); case "MyOverdue": start = now.AddDays(-1); var overdueTickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.DueDate >= start && t.DueDate < now); return View(overdueTickets.ToList()); case "MyInDevelopment": var devTickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId == (int)TS.Status.InDevelopment); return View(devTickets.ToList()); case "MyTesting": var testingTickets = db.Tickets .Where(t => t.AssignedToDevId == userId && t.TicketStatusId >= (int)TS.Status.ReadyToTest && t.TicketStatusId != (int)TS.Status.Resolved); return View(testingTickets.ToList()); case "Resolved": // This is for Admin to see which tickets might have been accidentally resolved too early // Allows for them to be adjusted var resolvedTickets = db.Tickets .Where(t => t.TicketStatusId == (int)TS.Status.Resolved); return View(resolvedTickets.ToList()); default: // For all other scopes, come here var tickets = db.Tickets .Where(tic => tic.TicketStatus.Name == scope) .Include(t => t.AssignedToDev).Include(t => t.OwnerUser).Include(t => t.Project).Include(t => t.SkillRequired).Include(t => t.TicketPriority).Include(t => t.TicketStatus).Include(t => t.TicketType); return View(tickets.ToList()); } }
public ActionResult Edit([Bind(Include = "Id,ProjectId,TicketTypeId,TicketPriorityId,TicketStatusId,AssignedToDevId,SkillRequiredId,Title,Created,Description,DueDate,HoursToComplete")] Ticket ticket, string submit) { CheckCookies(); if (ModelState.IsValid) { Ticket origTicket = db.Tickets.Find(ticket.Id); // Check each field to see if changed. If so, copy new value to origTicket and create TicketHistory // But first, remember the current Developer... string origDevId = origTicket.AssignedToDevId; if (submit == "Ready for Testing") { // Update status... origTicket.TicketStatusId = (int)TS.Status.ReadyToTest; } // WasChanged updates all the fields, origTicket is new version... DateTimeOffset dtChanged = ticket.WasChanged(db, origTicket); // If the current user is not the assigned Dev, need to send notification // Get current user... var helper = new UserRolesHelper(); if (ticket.AssignedToDevId != helper.GetCurrentUserId()) TicketNotification.Notify(db, origTicket, dtChanged, TicketNotification.EType.TicketModified); if (dtChanged != DateTimeOffset.MinValue) { origTicket.SetUpdated(dtChanged); db.Entry(origTicket).State = EntityState.Modified; db.SaveChanges(); // Need to see if the Assigned Dev was changed... if so, send out // one notification to previous Dev, two notifications to new Dev if (origTicket.AssignedToDevId != origDevId) { // Remember the current Dev, swap vars in order to remove... string newDevId = origTicket.AssignedToDevId; origTicket.AssignedToDevId = origDevId; TicketNotification.Notify(db, origTicket, origTicket.Updated.Value, TicketNotification.EType.RemovedFromTicket); // And now reset to correct new Dev and issue notifications origTicket.AssignedToDevId = newDevId; TicketNotification.Notify(db, origTicket, origTicket.Updated.Value, TicketNotification.EType.AssignedToTicket); TicketNotification.Notify(db, origTicket, origTicket.Updated.Value, TicketNotification.EType.TicketModified); } } return RedirectToAction("Index", new { scope = "My" }); } // Do this in every GET action... ViewBag.UserModel = ProjectsHelper.LoadUserModel(); ViewBag.AssignedToDevId = new SelectList(db.Users, "Id", "FirstName", ticket.AssignedToDevId); ViewBag.OwnerUserId = new SelectList(db.Users, "Id", "FirstName", ticket.OwnerUserId); ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name", ticket.ProjectId); ViewBag.SkillRequiredId = new SelectList(db.SkillLevels, "Id", "Name", ticket.SkillRequiredId); ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name", ticket.TicketPriorityId); ViewBag.TicketStatusId = new SelectList(db.TicketStatuses, "Id", "Name", ticket.TicketStatusId); ViewBag.TicketTypeId = new SelectList(db.TicketTypes, "Id", "Name", ticket.TicketTypeId); return View(ticket); }
// GET: Tickets/Edit/5 public ActionResult Edit(int? id) { CheckCookies(); // Do this in every GET action... var uModel = ProjectsHelper.LoadUserModel(); ViewBag.UserModel = uModel; if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Ticket ticket = db.Tickets.Find(id); if (ticket == null) { return HttpNotFound(); } UserRolesHelper helper = new UserRolesHelper(); var userId = helper.GetCurrentUserId(); var roles = helper.ListUserRoles(userId); // If Admin, allow to select Developer when creating the ticket if (uModel.IsAdmin || uModel.IsPM) { var roleDev = db.Roles.FirstOrDefault(r => r.Name == R.Developer); ViewBag.CanAssignDeveloper = true; if (roleDev != null) { var dev = new SelectList(db.Users .Where(d => d.Roles.Any(r => r.RoleId == roleDev.Id)), "Id", "UserName", ticket.AssignedToDevId); ViewBag.AssignedToDevId = dev; } else ViewBag.AssignedToDevId = Enumerable.Empty<SelectListItem>(); } else { ViewBag.AssignedToDevId = Enumerable.Empty<SelectListItem>(); ViewBag.CanAssignDeveloper = false; } ViewBag.OwnerUserId = new SelectList(db.Users, "Id", "FirstName", ticket.OwnerUserId); ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name", ticket.ProjectId); ViewBag.SkillRequiredId = new SelectList(db.SkillLevels, "Id", "Name", ticket.SkillRequiredId); ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name", ticket.TicketPriorityId); ViewBag.TicketStatusId = new SelectList(db.TicketStatuses, "Id", "Name", ticket.TicketStatusId); ViewBag.TicketTypeId = new SelectList(db.TicketTypes, "Id", "Name", ticket.TicketTypeId); return View(ticket); }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); // // IMPORTANT NOTE: The first parameter above (model.Email) is really the UserName... the PasswordSignInAsync function // expects the UserName here, and NOT the email. So don't try to match up the email in the code below or it will fail! switch (result) { case SignInStatus.Success: // If user has multiple roles, ask which one should become the active one ApplicationDbContext db = new ApplicationDbContext(); var user = db.Users.FirstOrDefault(u => u.UserName == model.Email); // See IMPORTANT NOTE above! (this is really UserName) UserRolesHelper helper = new UserRolesHelper(); var userRoles = helper.ListUserRoles(user.Id); string role = ""; switch (userRoles.Count()) { case 0: user.ActiveRole = R.NewUser; break; case 1: user.ActiveRole = userRoles[0]; break; default: // More than one role, so show modal to allow user to select the login role // But first, set the highest role as the active one... user.ActiveRole = helper.GetHighestRole(user.Id); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); // Now send the roles (concatenated)... for (int i = 0; i < userRoles.Count; i++) role += "-" + userRoles[i]; return RedirectToAction("Index", "Home", new { myRoles = role }); } // For just one role, finish up here db.Entry(user).State = EntityState.Modified; db.SaveChanges(); if (returnUrl == null) return RedirectToAction("Dashboard", "Home"); return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Let's make this user a Submitter... UserRolesHelper helper = new UserRolesHelper(); helper.AddUserToRole(user.Id, R.Submitter); await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
// GET: TicketNotifications public ActionResult Index(string scope) { ViewBag.UserModel = ProjectsHelper.LoadUserModel(); ViewBag.Scope = scope ?? "My"; // First, get this user... UserRolesHelper helper = new UserRolesHelper(); var userId = helper.GetCurrentUserId(); switch (scope) { case "My": // Now get My notifications... var My = db.TicketNotifications.Where(n => n.UserId == userId) .OrderBy(n => n.HasBeenRead).ThenByDescending(n => n.Created); return View(My.ToList()); case "All": var All = db.TicketNotifications.Include(t => t.Ticket).Include(t => t.User) .OrderBy(n => n.HasBeenRead).ThenByDescending(n => n.Created); return View(All.ToList()); case "MyAssignedToTicket": var MyAssignedToTicket = db.TicketNotifications .Where(n => n.UserId == userId && n.Type == TicketNotification.EType.AssignedToTicket); return View(MyAssignedToTicket.ToList()); case "MyRemovedFromTicket": var MyRemovedFromTicket = db.TicketNotifications .Where(n => n.UserId == userId && n.Type == TicketNotification.EType.RemovedFromTicket); return View(MyRemovedFromTicket.ToList()); case "MyTicketModified": var MyTicketModified = db.TicketNotifications .Where(n => n.UserId == userId && n.Type == TicketNotification.EType.TicketModified); return View(MyTicketModified.ToList()); case "MyComments": var MyComments = db.TicketNotifications .Where(n => n.UserId == userId && (n.Type == TicketNotification.EType.CommentCreated || n.Type == TicketNotification.EType.CommentDeleted || n.Type == TicketNotification.EType.CommentModified)); return View(MyComments.ToList()); case "MyAttachments": var MyAttachments = db.TicketNotifications .Where(n => n.UserId == userId && (n.Type == TicketNotification.EType.AttachmentCreated || n.Type == TicketNotification.EType.AttachmentDeleted || n.Type == TicketNotification.EType.AttachmentModified)); return View(MyAttachments.ToList()); default: // A normal type without "My" in front TicketNotification.EType type = TicketNotification.EType.AssignedToTicket; bool gotIt = Enum.TryParse<TicketNotification.EType>(scope, out type); if (gotIt) { var ticketNotifications = db.TicketNotifications.Where(n => n.Type == type); return View(ticketNotifications.ToList()); } else { var noneHere = db.TicketNotifications.Where(n => n.TicketId == -1); return View(noneHere.ToList()); } } }
private int AddNewUsers() { int nUsers = 0; // Process each row, create new user int row; string[] colData; bool skip = false; row = Start-1; UserRolesHelper helper = new UserRolesHelper(); var store = new UserStore<ApplicationUser>(db); UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(store); string defaultPassword = "******"; while (++row < (Count + Start)) { skip = false; if (Source[row][0] != ';') { // Valid row to process, so get columns // // DON'T TRIM THE ROW!! If it's trimmed, the column positions will NOT line up with // what is expected, resulting in a crash! // colData = Source[row].Split('\t'); // Create a new User object, fill in the data int nRequireds = 0; // Used to show all required fields exist string data; ApplicationUser user = new ApplicationUser(); // FirstName if (this.HeadingOffsets[(int)H.U_FirstName] >= 0) { if ((user.FirstName = colData[HeadingOffsets[(int)H.U_FirstName]]) != "") { nRequireds++; } } // LastName if (this.HeadingOffsets[(int)H.U_LastName] >= 0) { if ((user.LastName = colData[HeadingOffsets[(int)H.U_LastName]]) != "") { nRequireds++; } } // If we don't have either a First or Last name, show error.. if (nRequireds == 0) { Section.LogErr(db, "Row " + (row+1) + " needs either FirstName or LastName -- cannot process this row"); skip = false; } // UserName if (this.HeadingOffsets[(int)H.U_UserName] >= 0) { if ((user.UserName = colData[HeadingOffsets[(int)H.U_UserName]]) == "") { // If there's no UserName, exit now! Section.LogErr(db, "Row " + row + " must have a unique UserName -- cannot process this row"); skip = false; } } // DisplayName if (this.HeadingOffsets[(int)H.U_DisplayName] >= 0) { // If no display name, use UserName if ((data = colData[HeadingOffsets[(int)H.U_DisplayName]]) == "") data = user.UserName; user.DisplayName = data; } // SkillLevel if (this.HeadingOffsets[(int)H.U_SkillLevel] >= 0) { // Setup SkillLevel data = colData[HeadingOffsets[(int)H.U_SkillLevel]]; int pos = FindPos(data, Skills.ToList()); if (pos < 0) { // Not valid, show error Section.LogAlert(db, "Row " + (row+1) + ": setting default SkillLevel to Junior"); pos = 0; } user.SkillLevelId = pos + 1; } else user.SkillLevelId = 1; // Email if (this.HeadingOffsets[(int)H.U_Email] >= 0) { if ((user.Email = colData[HeadingOffsets[(int)H.U_Email]]) == "") { Section.LogErr(db, "Row " + (row+1) + " must have a valid Email -- cannot process this row"); skip = true; } } // PhoneNumber if (this.HeadingOffsets[(int)H.U_Phone] >= 0) { user.PhoneNumber = user.TextMsgNumber = colData[HeadingOffsets[(int)H.U_Phone]]; } // User is complete, so save if unique if (!skip) { // Before creating an account, see if this user name is already being used var x2 = db.Users.FirstOrDefault(u => u.UserName == user.UserName); if (x2 == null) { // OK to continue, this will be a new user bool addedUser = false; try { manager.Create(user, defaultPassword); addedUser = true; } catch (Exception e) { skip = true; addedUser = false; } // Need to ensure the user was created try { // See if user is in the db... if not, save again! var x = db.Users.FirstOrDefault(u => u.UserName == user.UserName); if (x == null) { var u = db.Users.Add(user); db.SaveChanges(); addedUser = true; } } catch (Exception e) { string msg = "Row " + (row + 1) + " could not be processed"; LogErr(db, msg); skip = true; addedUser = false; } if (addedUser) nUsers++; // Now add any user roles specified... if (!skip) { LogSuccess(db, "Added User [" + user.UserName + "] from row " + (row + 1)); int nRoles = 0; // Admin if (this.HeadingOffsets[(int)H.U_RoleAdmin] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleAdmin]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Admin)) { helper.AddUserToRole(user.Id, R.Admin); nRoles++; } } } // PM if (this.HeadingOffsets[(int)H.U_RoleProjectManager] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleProjectManager]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.PM)) { helper.AddUserToRole(user.Id, R.PM); nRoles++; } } } // Dev if (this.HeadingOffsets[(int)H.U_RoleDeveloper] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleDeveloper]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Dev)) { helper.AddUserToRole(user.Id, R.Dev); nRoles++; } } } // Submitter if (this.HeadingOffsets[(int)H.U_RoleSubmitter] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleSubmitter]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Submitter)) { helper.AddUserToRole(user.Id, R.Submitter); nRoles++; } } } // If no roles, add Submitter if (nRoles == 0) if (!helper.IsUserInRole(user.Id, R.Submitter)) helper.AddUserToRole(user.Id, R.Submitter); } } else { Section.LogAlert(db, "UserName [" + user.UserName + "] on row " + (row + 1) + " already in database, will be skipped"); } } } } return nUsers; }
private int AddNewTickets() { // Process each row, create new user int nTickets = 0; int row; string[] colData; string Creator, Dev, Name, Desc; row = Start - 1; UserRolesHelper helper = new UserRolesHelper(); var statuses = db.TicketStatuses.ToList(); var priorities = db.TicketPriorities.ToList(); var types = db.TicketTypes.ToList(); var skills = db.SkillLevels.ToList(); bool devOk = false; // Set to true if validated and ready to add to ticket // Use same time stamp for all tickets DateTimeOffset now = DateTimeOffset.UtcNow; // First, make sure all needed columns are present if (HeadingOffsets[(int)H.T_Title] < 0 || HeadingOffsets[(int)H.T_Description] < 0) { Section.LogErr(db, "Ticket on row " + (row + 1) + " is missing a column " + "(Title and Description are required) -- cannot process any Tickets"); return 0; } while (++row < (Count + Start)) { if (Source[row][0] != ';') { // Valid row to process, so get columns // // DON'T TRIM THE ROW!! If it's trimmed, the column positions will NOT line up with // what is expected, resulting in a crash! // colData = Source[row].Split('\t'); // These rules must be followed: // [] Title and Description must be non-empty // [] No uniqueness test -- OK to enter tickets with same Title/Description(??) // [] Developer must be in database // [] Developer must be in Developer role // [] TicketCreator must be in database // [] If ProjectTitle/Description cannot be found, leave as null // [] Parse DateCreated - default is Now // [] Parse DueDate - default is Now + 1 day // [] Parse HoursToComplete - default is 1 // [] Parse Type, Priority, Status, Skill - default is 1 // - load all values from db, find the match, if not found use default // // If rules not followed, show error and skip Ticket ticket = new Ticket(); ticket.Title = colData[HeadingOffsets[(int)H.T_Title]]; ticket.Description = colData[HeadingOffsets[(int)H.T_Description]]; Dev = colData[HeadingOffsets[(int)H.T_AssignedDeveloperUserName]]; Creator = colData[HeadingOffsets[(int)H.T_TicketCreatorUserName]]; ApplicationUser user = null; // Test column requirements now... if (ticket.Title.Length == 0 || ticket.Description.Length == 0) { Section.LogErr(db, "Ticket on row " + (row + 1) + " needs both a Title and a Description -- will be skipped"); continue; } // Validate Developer user = db.Users.FirstOrDefault(u => u.UserName == Dev); if (user == null) { if (Dev != "") Section.LogAlert(db, "DeveloperUser on row " + (row + 1) + " has UserName [" + Dev + "] not in database -- leaving field blank, will continue"); } else { // Dev is in database, now check role if (!helper.IsUserInRole(user.Id, R.Developer)) { Section.LogErr(db, "Ticket on row " + (row + 1) + " has AssignedDeveloper [" + user.UserName + "] not in 'Developer' role -- leaving field blank, will continue"); } else { devOk = true; // Flags us to create Notification if/when ticket added to table ticket.AssignedToDevId = user.Id; } } // Validate Creator user = db.Users.FirstOrDefault(u => u.UserName == Creator); if (user == null) { Section.LogAlert(db, "TicketCreator on row " + (row + 1) + " has UserName [" + Dev + "] not in database -- using name of current user for this Ticket"); ticket.OwnerUserId = helper.GetCurrentUserId(); } else { ticket.OwnerUserId = user.Id; } // Validate Project -- if not found, leave as null Name = colData[HeadingOffsets[(int)H.T_ProjectName]]; Desc = colData[HeadingOffsets[(int)H.T_ProjectDescription]]; var project = db.Projects.FirstOrDefault(p => p.Name == Name && p.Description == Desc); if (project != null) ticket.ProjectId = project.Id; else { if (Name != "" && Desc != "") Section.LogAlert(db, "Ticket on row " + (row + 1) + " has project not found in Projects table -- setting to null, will continue"); } // Check HoursToComplete int num; int.TryParse(colData[HeadingOffsets[(int)H.T_HoursToComplete]], out num); ticket.HoursToComplete = num < 1 ? 1 : num; // Parse Dates... DateTimeOffset date; DateTimeOffset.TryParse(colData[HeadingOffsets[(int)H.T_DateCreated]], out date); if (date == DateTimeOffset.MinValue) { ticket.Created = ticket.MostRecentUpdate = now; Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid DateCreated -- using today's date"); } else ticket.Created = date; DateTimeOffset.TryParse(colData[HeadingOffsets[(int)H.T_DueDate]], out date); if (date == DateTimeOffset.MinValue) { ticket.DueDate = now.AddDays(10); Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid DueDate -- set default date to 10 days from now"); } else ticket.DueDate = date; // Validate Type, Priority, Status, Skill -- set to 1 as default // Type string type = colData[HeadingOffsets[(int)H.T_TicketType]].ToUpper(); var tempType = types.Where(t => t.Name.ToUpper().Contains(type)); if (tempType.Count() == 1) ticket.TicketTypeId = tempType.ElementAt(0).Id; else { // Set to default, issue alert if invalid type specified ticket.TicketTypeId = 1; if (type != "") Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid TicketType -- set to Bug"); } // Priority string priority = colData[HeadingOffsets[(int)H.T_TicketPriority]].ToUpper(); var tempPriority = priorities.Where(t => t.Name.ToUpper().Contains(priority)); if (tempPriority.Count() == 1) ticket.TicketPriorityId = tempPriority.ElementAt(0).Id; else { // Set to default, issue alert if invalid type specified ticket.TicketPriorityId = 3; if (type != "") Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid TicketPriority -- set to Essential"); } // Status string status = colData[HeadingOffsets[(int)H.T_TicketStatus]].ToUpper(); var tempStatus = statuses.Where(t => t.Name.ToUpper().Contains(status)); if (tempStatus.Count() == 1) ticket.TicketStatusId = tempStatus.ElementAt(0).Id; else { // Set to default, issue alert if invalid type specified ticket.TicketStatusId = 1; if (type != "") Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid TicketStatus -- set to New"); } // Skill string skill = colData[HeadingOffsets[(int)H.T_SkillRequired]].ToUpper(); var tempSkill = skills.Where(s => s.Name.ToUpper().Contains(skill)); if (tempSkill.Count() == 1) ticket.SkillRequiredId = tempSkill.ElementAt(0).Id; else { // Set to default, issue alert if invalid type specified ticket.SkillRequiredId = 1; if (type != "") Section.LogAlert(db, "Ticket on row " + (row + 1) + " had invalid SkillRequired -- set to Junior"); } // Last check... if ticket.StatusId is "New" and a developer is assigned, change to "AssignedToDev" if (ticket.AssignedToDev != null && ticket.TicketStatusId == (int)TS.Status.New) { Section.LogAlert(db, "Ticket on row " + (row + 1) + " has assigned developer -- set to AssignedToDev"); ticket.TicketStatusId = (int)TS.Status.AssignedToDev; } // We can add the Ticket now db.Tickets.Add(ticket); db.SaveChanges(); if (devOk) ticket.NotifyNewTicket(db); LogSuccess(db, "Added Ticket from row " + (row + 1)); nTickets++; } } return nTickets; }
private int AddNewProjects() { int nProjects = 0; // Process each row, create new Project int row; string[] colData; string PM; row = Start-1; UserRolesHelper helper = new UserRolesHelper(); // First, make sure all needed columns are present if (HeadingOffsets[(int)H.P_ProjectName] < 0 || HeadingOffsets[(int)H.P_Description] < 0 || HeadingOffsets[(int)H.P_ProjectManagerUserName] < 0) { Section.LogErr(db, "Project on row " + (row + 1) + " is missing a column " + "(ProjectName, Description, and ProjectManagerUserName are required) -- cannot process any projects"); return 0; } while (++row < (Count + Start)) { if (Source[row][0] != ';') { // Valid row to process, so get columns // // DON'T TRIM THE ROW!! If it's trimmed, the column positions will NOT line up with // what is expected, resulting in a crash! // colData = Source[row].Split('\t'); // These rules must be followed: // [] All three columns (ProjectName, Description, and ProjectManagerUserName) must exist // [] ProjectManager must be in database // [] ProjectManager must be in PM role // [] There can be no other project having the same Title+Description // // If rules not followed, show error and skip Project project = new Project(); project.Name = colData[HeadingOffsets[(int)H.P_ProjectName]]; project.Description = colData[HeadingOffsets[(int)H.P_Description]]; PM = colData[HeadingOffsets[(int)H.P_ProjectManagerUserName]]; ApplicationUser user = null; // Test requirements now... if (project.Name.Length == 0 || project.Description.Length == 0 || PM.Length == 0) { Section.LogErr(db, "Project on row " + (row + 1) + " is missing data in a column -- cannot process"); continue; } user = db.Users.FirstOrDefault(u => u.UserName == PM); if (user == null) { Section.LogErr(db, "Project on row " + (row+1) + " has UserName [" + PM + "] not in database -- cannot process"); continue; } else { // PM is in database, now check role if (!helper.IsUserInRole(user.Id, R.PM)) { Section.LogErr(db, "Project on row " + (row+1) + " has UserName [" + user.UserName + "] not in 'ProjectManager' role -- cannot process"); continue; } } // Make sure Title and Description are unique var proj = db.Projects.FirstOrDefault(p => p.Name == project.Name && p.Description == project.Description); if (proj != null) { Section.LogErr(db, "Project on row " + (row + 1) + " has same name and description as project # " + proj.Id + " in Projects table -- cannot process"); continue; } // We can create the project now db.Projects.Add(project); project.Users.Add(db.Users.Find(user.Id)); db.SaveChanges(); LogSuccess(db, "Added Project from row " + (row + 1)); nProjects++; } } return nProjects; }
private int AddNewProjDevs() { int nDevs = 0; // Process each row, add Developer to Project int row; string[] colData; string Name, Desc, Dev; row = Start - 1; UserRolesHelper helper = new UserRolesHelper(); // First, make sure all needed columns are present if (HeadingOffsets[(int)H.PD_ProjectName] < 0 || HeadingOffsets[(int)H.PD_Description] < 0 || HeadingOffsets[(int)H.PD_DeveloperUserName] < 0) { Section.LogErr(db, "ProjectDeveloper on row " + (row + 1) + " is missing a column " + "(ProjectName, Description, and DeveloperUserName are required) -- cannot process any ProjectDevelopers"); return 0; } while (++row < (Count + Start)) { if (Source[row][0] != ';') { // Valid row to process, so get columns // // DON'T TRIM THE ROW!! If it's trimmed, the column positions will NOT line up with // what is expected, resulting in a crash! // colData = Source[row].Split('\t'); // These rules must be followed: // [] All three columns (ProjectName, Description, and DeveloperUserName) must exist // [] ProjectName/Description must be in database // [] Developer must be in Developer role // [] There can be no other project having the same Title+Description // // If rules not followed, show error and skip Name = colData[HeadingOffsets[(int)H.PD_ProjectName]]; Desc = colData[HeadingOffsets[(int)H.PD_Description]]; Dev = colData[HeadingOffsets[(int)H.PD_DeveloperUserName]]; ApplicationUser user = null; // Test requirements now... if (Name.Length == 0 || Desc.Length == 0 || Dev.Length == 0) { Section.LogErr(db, "ProjectDeveloper info on row " + (row + 1) + " is missing data in a column -- cannot process"); continue; } user = db.Users.FirstOrDefault(u => u.UserName == Dev); if (user == null) { Section.LogErr(db, "DeveloperUser on row " + (row + 1) + " has UserName [" + Dev + "] not in database -- cannot process"); continue; } else { // Dev is in database, now check role if (!helper.IsUserInRole(user.Id, R.Developer)) { Section.LogErr(db, "Project on row " + (row + 1) + " has UserName [" + user.UserName + "] not in 'Developer' role -- cannot process"); continue; } } // Make sure there is a unique ProjectTitle/Description... var project = db.Projects.FirstOrDefault(p => p.Name == Name && p.Description == Desc); if (project == null) { Section.LogErr(db, "Project on row " + (row + 1) + " not found in Projects table -- cannot add DeveloperUser to project"); continue; } // We can add the Developer now if (ProjectsHelper.AddUserToProject(user.Id, project.Id)) { LogSuccess(db, "Added Developer from row " + (row + 1)); nDevs++; } else LogAlert(db, "Developer on row " + (row + 1) + " already on Project"); } } return nDevs; }
public ActionResult SelectRole(string MyRole) { // Strip out any extra portion... MyRole = MyRole.Replace(" (default)", ""); // User has selected a role, so make it active ApplicationDbContext db = new ApplicationDbContext(); UserRolesHelper helper = new UserRolesHelper(); var user = db.Users.Find(helper.GetCurrentUserId()); user.ActiveRole = MyRole; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); // Do this in every GET action... ViewBag.UserModel = ProjectsHelper.LoadUserModel(); return RedirectToAction("Dashboard"); }
public ActionResult ManageUsers(string submit, string[] Select) { if (submit == "Cancel") return RedirectToAction("Index"); if (ModelState.IsValid) { // Make sure there is still somebody with Admin privileges!! // So, scoop everything up first and recreate the original model if (Select != null) { // The first string should be the actions, to parse it string[] roles = Select[0].Split('~'); // Find where Admin is so we can make sure somebody is still Admin! int posAdmin = Array.IndexOf(roles, R.Admin); int nRoles; List<ManageUsersData> muList = new List<ManageUsersData>(); bool isAdminChecked = false; if (posAdmin > -1) { // We found the Admin role, assume at this point the list of roles is correct nRoles = roles.Count() - 1; // Now, each User is represented by his Id, followed by a T or F for each role he is // currently enrolled in. So now, reconvert all the data back to the original mode, with // the new int index = 1; while (index < Select.Length) { // Scoop up all the returned data ManageUsersData mu = new ManageUsersData(nRoles); // Get the user Id mu.Id = Select[index++]; // Now get all the original settings for roles... for (int z = 0; z < nRoles; z++) { mu.OrigRoles[z] = Select[index][z] == 'T' ? true : false; } index++; // Advance to next line // Now get any checked roles... int num; while (index < Select.Length && Select[index].Length < 32) { // The next char is an index represented a selected role if (Int32.TryParse(Select[index], out num)) { mu.NewRoles[num] = true; index++; } else { break; } } if (mu.NewRoles[posAdmin]) { isAdminChecked = true; } // Add this mu to the list muList.Add(mu); } if (!isAdminChecked) { // Need to keep an Admin! return RedirectToAction("NeedAdmin"); } // Now, we are ready to update all the roles for each user UserRolesHelper helper = new UserRolesHelper(); foreach (var mu in muList) { // See if any role changed... for (int i = 0; i < nRoles; i++) { if (mu.NewRoles[i] != mu.OrigRoles[i]) { // Role changed... if (mu.NewRoles[i]) { helper.AddUserToRole(mu.Id, roles[i]); } else { helper.RemoveUserFromRole(mu.Id, roles[i]); } } } } // All went according to plan, so return to Main Menu! return RedirectToAction("Index"); } } } return RedirectToAction("UsersPostError"); }
public ActionResult ManageUsers() { ViewBag.Message = "Manage users."; UserRolesHelper helper = new UserRolesHelper(); // Create list of all roles List<string> roles = db.Roles.Select(r => r.Name).ToList(); // We don't need Guest or NewUser, so remove them roles.Remove(R.Guest); roles.Remove(R.NewUser); int nRoles = roles.Count; // Create list of users List<ManageUsersData> users = db.Users .Where(u => u.UserName != R.GuestUserName) .Select(u => new ManageUsersData() { Id = u.Id, UserName = u.UserName, Email = u.Email, DisplayName = u.DisplayName, First = u.FirstName, Last = u.LastName }) .ToList(); // And for each user, create list of roles and generate foreach (var user in users) { user.OrigRoles = new bool[nRoles]; user.NewRoles = new bool[nRoles]; var userRoles = helper.ListUserRoles(user.Id); for (var i = 0; i < nRoles; i++) user.OrigRoles[i] = user.NewRoles[i] = userRoles.Contains(roles[i]); } // Now for each user, get list of roles and create origRoles data ViewBag.UsersAndRoles = users; ViewBag.Roles = roles; // Do this in every GET action... ViewBag.UserModel = ProjectsHelper.LoadUserModel(); return View(new ManageUsersModel(users, roles)); }