public static bool AddMembership(List<Models.GroupMembership> groupMemberships) { var group = new Models.Group(); var result = false; using (var uow = new DAL.UnitOfWork()) { foreach (var membership in groupMemberships.Where(membership => !uow.GroupMembershipRepository.Exists( g => g.ComputerId == membership.ComputerId && g.GroupId == membership.GroupId))) { uow.GroupMembershipRepository.Insert(membership); group = BLL.Group.GetGroup(membership.GroupId); } result = uow.Save(); } if (group.SetDefaultProperties == 1) { var groupProperty = BLL.GroupProperty.GetGroupProperty(group.Id); BLL.GroupProperty.UpdateComputerProperties(groupProperty); } if (group.SetDefaultBootMenu == 1) { var groupBootMenu = BLL.GroupBootMenu.GetGroupBootMenu(group.Id); BLL.GroupBootMenu.UpdateGroupMemberBootMenus(groupBootMenu); } return result; }
protected void gridView_Sorting(object sender, GridViewSortEventArgs e) { PopulateGrid(); List<Models.Group> listGroups = (List<Models.Group>)gvGroups.DataSource; switch (e.SortExpression) { case "Name": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.Name).ToList() : listGroups.OrderByDescending(g => g.Name).ToList(); break; case "Image": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.ImageId).ToList() : listGroups.OrderByDescending(g => g.ImageId).ToList(); break; case "Type": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.Type).ToList() : listGroups.OrderByDescending(g => g.Type).ToList(); break; } gvGroups.DataSource = listGroups; gvGroups.DataBind(); foreach (GridViewRow row in gvGroups.Rows) { var group = new Models.Group(); var lbl = row.FindControl("lblCount") as Label; var dataKey = gvGroups.DataKeys[row.RowIndex]; if (dataKey != null) group = BLL.Group.GetGroup(Convert.ToInt32(dataKey.Value)); if (lbl != null) lbl.Text = BLL.GroupMembership.GetGroupMemberCount(group.Id); } }
//Constructor For Starting Multicast For Group public Multicast(Models.Group group,int userId) { _computers = new List<Models.Computer>(); _multicastSession = new Models.ActiveMulticastSession(); _isOnDemand = false; _group = group; _userId = userId; }
//Constructor For Starting Multicast For On Demand public Multicast(Models.ImageProfile imageProfile, string clientCount, int userId) { _multicastSession = new Models.ActiveMulticastSession(); _isOnDemand = true; _imageProfile = imageProfile; _clientCount = clientCount; _group = new Models.Group{ImageProfileId = _imageProfile.Id}; _userId = userId; _multicastSession.ImageProfileId = imageProfile.Id; }
protected void btnSubmit_Click(object sender, EventArgs e) { RequiresAuthorizationOrManagedGroup(Authorizations.UpdateGroup, Group.Id); var group = new Group { Id = Group.Id, Name = txtGroupName.Text, Type = Group.Type, Description = txtGroupDesc.Text, }; var result = BLL.Group.UpdateGroup(group); EndUserMessage = !result.IsValid ? result.Message : "Successfully Updated Group"; }
protected void PopulateGrid() { gvGroups.DataSource = BLL.Group.SearchGroupsForUser(CloneDeployCurrentUser.Id,txtSearch.Text); gvGroups.DataBind(); foreach (GridViewRow row in gvGroups.Rows) { var group = new Models.Group(); var lbl = row.FindControl("lblCount") as Label; var dataKey = gvGroups.DataKeys[row.RowIndex]; if (dataKey != null) group = BLL.Group.GetGroup(Convert.ToInt32(dataKey.Value)); if (lbl != null) lbl.Text = BLL.GroupMembership.GetGroupMemberCount(group.Id); } lblTotal.Text = gvGroups.Rows.Count + " Result(s) / " + BLL.Group.GroupCountUser(CloneDeployCurrentUser.Id) + " Total Group(s)"; }
protected void Submit_Click(object sender, EventArgs e) { RequiresAuthorization(Authorizations.CreateGroup); if(ddlGroupType.Text == "smart") RequiresAuthorization(Authorizations.CreateSmart); var group = new Models.Group { Name = txtGroupName.Text, Description = txtGroupDesc.Text, Type = ddlGroupType.Text, }; var result = BLL.Group.AddGroup(group,CloneDeployCurrentUser.Id); if (!result.IsValid) EndUserMessage = result.Message; else { EndUserMessage = "Successfully Created Group"; Response.Redirect("~/views/groups/edit.aspx?groupid=" + group.Id); } }
public ActionResult Edit([Bind(Include = "id,title,parent_id,desc,flag")] Models.Group group_tmp) { try { if (ModelState.IsValid) { var group = db.Groups.Find(group_tmp.id); //Parents_ID if (group_tmp.parentId != "0") { var parent_id = Guid.Parse(group_tmp.parentId); var tmp = db.Groups.Where(d => d.id == parent_id && d.flag > 0).FirstOrDefault(); group.parentsId = tmp.parentsId + parent_id + ","; group.levels = tmp.levels + 1; } group.parentId = group_tmp.parentId; group.title = group_tmp.title; group.desc = group_tmp.desc; group.flag = group_tmp.flag; group.updatedBy = Common.Auth.getUser().id.ToString(); group.updatedAt = DateTime.Now; db.Entry(group).State = EntityState.Modified; db.SaveChanges(); this.success(TM.Common.Language.msgCreateSucsess); return(RedirectToAction("Index")); } else { this.danger(TM.Common.Language.msgError); } } catch (Exception ex) { this.danger(TM.Common.Language.msgCreateError); } return(RedirectToAction("Edit")); }
public Group(Models.Group model, Models.BaseContext context) { Id = model.Id; Name = model.Name; Description = model.Description; CreatedAt = model.CreatedAt; LastModified = model.LastModified; if (context != null) { var posts = context .Posts .ToList() .Where(x => x.GroupId == model.Id); Posts = new List <Post>(); foreach (Models.Post post in posts) { Posts.Add(new Views.Post(post, context)); } } }
protected override void ProcessRecord() { var groupsClient = Client.GetGroupsClient(); Models.Group group = null; Models.User user = null; try { group = groupsClient.Get(IdOrName); } catch (OktaException) { group = groupsClient.GetByName(IdOrName); } if (group != null) { var groupUsersClient = Client.GetGroupUsersClient(group); var usersClient = Client.GetUsersClient(); try { user = usersClient.Get(UserIdOrLogin); } catch (OktaException) { WriteWarning(string.Format("The user with ID or name {0} is invalid. Please try again.", UserIdOrLogin)); } if (user != null) { groupUsersClient.Remove(user); WriteObject(string.Format("User {0} was successfully removed from group {1}", user.Profile.Login, group.Profile.Name)); } } else { WriteWarning(string.Format("The group with id or name {0} seems to be invalid, please try with a different value", IdOrName)); } }
public ActionResult Create([Bind(Include = "title,parent_id,desc,flag")] Models.Group group) { try { if (ModelState.IsValid) { //ViewBag.group group.id = Guid.NewGuid(); //Parents_ID group.parentsId = ","; group.levels = 0; if (group.parentId != "0") { var parent_id = Guid.Parse(group.parentId); var tmp = db.Groups.Where(d => d.id == parent_id && d.flag > 0).FirstOrDefault(); group.parentsId = tmp.parentsId + parent_id + ","; group.levels = tmp.levels + 1; } group.appKey = AppKey.product; group.createdBy = Common.Auth.getUser().id.ToString(); group.createdAt = DateTime.Now; db.Groups.Add(group); db.SaveChanges(); this.success(TM.Common.Language.msgCreateSucsess); } else { this.danger(TM.Common.Language.msgError); } } catch (Exception ex) { this.danger(TM.Common.Language.msgCreateError); } return(RedirectToAction("Create")); }
protected void PopulateGrid() { gvGroups.DataSource = BLL.Group.SearchGroupsForUser(CloneDeployCurrentUser.Id, txtSearch.Text); gvGroups.DataBind(); foreach (GridViewRow row in gvGroups.Rows) { var group = new Models.Group(); var lbl = row.FindControl("lblCount") as Label; var dataKey = gvGroups.DataKeys[row.RowIndex]; if (dataKey != null) { group = BLL.Group.GetGroup(Convert.ToInt32(dataKey.Value)); } if (lbl != null) { lbl.Text = BLL.GroupMembership.GetGroupMemberCount(group.Id); } } lblTotal.Text = gvGroups.Rows.Count + " Result(s) / " + BLL.Group.GroupCountUser(CloneDeployCurrentUser.Id) + " Total Group(s)"; }
//gets info about the group public Models.Group GetbasicInfoAboutGroup(int teamID) { Models.Group group = new Models.Group(); SqlOpenConnection(); string sqlUse = "USE ProjectStyring;"; SqlCommand sqlUseQuery = new SqlCommand(sqlUse, connection); string query = string.Format("exec dbo.spTeam_GetSinglegroup {0}", teamID); SqlCommand sqlQuery = new SqlCommand(query, connection); try { sqlUseQuery.ExecuteNonQuery(); using (SqlDataReader reader = sqlQuery.ExecuteReader()) { while (reader.Read()) { try { //makes a group with the information from db with enddate group = new Models.Group(reader.GetString(1), reader.GetInt32(0), reader.GetString(5), reader.GetBoolean(4), reader.GetDateTime(2), reader.GetDateTime(3)); } catch { //makes a group with the information from db with no enddate group = new Models.Group(reader.GetString(1), reader.GetInt32(0), reader.GetString(5), reader.GetBoolean(4), reader.GetDateTime(2)); } } connection.Close(); } return(group); } catch { connection.Close(); return(null); } }
protected void gridView_Sorting(object sender, GridViewSortEventArgs e) { PopulateGrid(); List <Models.Group> listGroups = (List <Models.Group>)gvGroups.DataSource; switch (e.SortExpression) { case "Name": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.Name).ToList() : listGroups.OrderByDescending(g => g.Name).ToList(); break; case "Image": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.ImageId).ToList() : listGroups.OrderByDescending(g => g.ImageId).ToList(); break; case "Type": listGroups = GetSortDirection(e.SortExpression) == "Asc" ? listGroups.OrderBy(g => g.Type).ToList() : listGroups.OrderByDescending(g => g.Type).ToList(); break; } gvGroups.DataSource = listGroups; gvGroups.DataBind(); foreach (GridViewRow row in gvGroups.Rows) { var group = new Models.Group(); var lbl = row.FindControl("lblCount") as Label; var dataKey = gvGroups.DataKeys[row.RowIndex]; if (dataKey != null) { group = BLL.Group.GetGroup(Convert.ToInt32(dataKey.Value)); } if (lbl != null) { lbl.Text = BLL.GroupMembership.GetGroupMemberCount(group.Id); } } }
private void removeButton_Click(object sender, RoutedEventArgs e) { updateObject = (Models.Group)dtGroupAccount.SelectedItem; Models.ActionResultModelBinding result = null; try { var question = MessageBox.Show(Application.Current.FindResource("removeAccountWarning") as string, Application.Current.FindResource("warningTitle") as string, MessageBoxButton.YesNo); if (question == MessageBoxResult.Yes) { if (updateObject != null) { using (var controller = new Controllers.GroupController()) { result = controller.RemoveGroup(updateObject, true); } } } } catch (Exception c) { MessageBox.Show(c.Message); return; } finally { if (result != null) { MessageBox.Show(result.Message); if (result.Status == Models.ActionResult.Success) { GetGroupAccounts(); updateObject = null; } } } }
public async Task <IActionResult> Find([FromBody] Models.Group obj) { var bll_g = groupBusiness; var user = HttpContext.Items["EndUser"] as EF.EndUser; var o = this.mapper.Map <EF.Group>(obj); o.GroupCategory = new EF.GroupCategory { CommunityId = user.Member.CommunityId }; // Get group leader id var bll_m = memberBusiness; var glid = await bll_m.GetIdByName(obj.Leader ?? "", user.Member.CommunityId.Value); o.GroupLeader = glid; var res = from r in bll_g.Find(o) join m in bll_m.Find(new EF.Member { CommunityId = user.Member.CommunityId }) on r.GroupLeader equals m.Id select new { r.Id, r.GroupCategoryId, Category = r.GroupCategory.Name, r.Name, Members = r.GroupMember.Count, Leader = m.Name, LeaderMemberId = m.Id, isMember = r.GroupMember.Count(x => x.MemberId == user.MemberId) > 0, isLeader = user.MemberId == m.Id }; return(Json(await res.ToListAsync())); }
protected override void ProcessRecord() { var groupsClient = Client.GetGroupsClient(); Models.Group group = null; try { group = groupsClient.Get(IdOrName); } catch (OktaException) { group = groupsClient.GetByName(IdOrName); } if (group != null) { var groupUsersClient = Client.GetGroupUsersClient(group); var users = groupUsersClient.GetFilteredEnumerator(); WriteObject(users); } else { WriteWarning(string.Format("The group with ID or name {0} is invalid. Please try again", IdOrName)); } }
partial void CreateOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, Models.Group model);
public static IEnumerable <Models.Activity> GenerateSchedule (IEnumerable <Models.Group> modelGroups, IEnumerable <Models.Station> modelStations, IEnumerable <Models.SchedulingConstraint> modelConstraints, IEnumerable <Models.TimeSlot> modelTimeSlots) { InitializeData(); //The time slots passed in are supposed to be sorted, but it's better not to assume that IList <Models.TimeSlot> sortedTimeSlots = new List <Models.TimeSlot>(); foreach (Models.TimeSlot timeSlot in modelTimeSlots) { sortedTimeSlots.Add(timeSlot); } sortedTimeSlots.OrderBy(k => k.Start); modelStations = Shuffle(modelStations); initializeGroupStationVisitRange(modelConstraints, modelGroups, modelStations, ref groupStationVisitRange); initializeGroupPreferenceGiven(modelGroups, ref groupPreferenceGiven); initializeGroupStationAssignments(modelGroups, modelStations, ref groupStationAssignments); IList <Models.Activity> generatedSchedule = new List <Models.Activity>(); //initialize all groups and stations to be eligible for the next time slot foreach (Models.Group group in modelGroups) { nextTimeSlotUnassignedGroups.Add(group); } foreach (Models.Station station in modelStations) { nextTimeSlotUnassignedStations.Add(station); } foreach (Models.TimeSlot timeSlot in sortedTimeSlots) { if (timeSlot.isGeneral) { continue; } stationCapacities.Clear(); foreach (Models.Station station in modelStations) { stationCapacities.Add(station, station.Capacity); } //all groups that did not take an activity pin last time slot are unassigned //and all groups are eligible to be assigned to the next time slot //all stations that are available at this time slot minus those that //are currently having an activity pin unassignedGroups.Clear(); unassignedStations.Clear(); foreach (Models.Group group in nextTimeSlotUnassignedGroups) { unassignedGroups.Add(group); } foreach (Models.Station station in nextTimeSlotUnassignedStations) { unassignedStations.Add(station); } unassignedStations.Intersect(nextTimeSlotUnassignedStations); nextTimeSlotUnassignedGroups.Clear(); nextTimeSlotUnassignedStations.Clear(); foreach (Models.Group group in modelGroups) { nextTimeSlotUnassignedGroups.Add(group); } foreach (Models.Station station in modelStations) { nextTimeSlotUnassignedStations.Add(station); } unassignedGroups = Shuffle(unassignedGroups); for (int groupNum = 0; groupNum < unassignedGroups.Count; groupNum++) { Models.Group group = unassignedGroups[groupNum]; int? greatestNumVisits = 0; foreach (Models.Station station in unassignedStations) { int?currentNumVisits = groupStationVisitRange[group][station].numVisits; if (currentNumVisits > greatestNumVisits) { greatestNumVisits = currentNumVisits; eligibleStations.Clear(); eligibleStations.Add(station); } else if (currentNumVisits == greatestNumVisits && currentNumVisits > 0) { eligibleStations.Add(station); } } //don't assign activity pins to non-webelos filterEligibleStations(group, ref eligibleStations); //don't assign stations and categories visited on the same day removeSameDayStationsAndCategories(group, timeSlot, ref eligibleStations); //if the current group is still required to visit a station, then //assign them to one of those stations if (greatestNumVisits > 0 && eligibleStations.Count > 0) { if (assignStation(eligibleStations, group, timeSlot, sortedTimeSlots, generatedSchedule)) { groupNum--; } } } //for each group that was not required to visit one of the //remaining stations, assign them to their top station pick //no need to remove stations and categories visited on the same //day here because a group only receives their top preference one time for (int groupNum = 0; groupNum < unassignedGroups.Count; groupNum++) { Models.Group group = unassignedGroups[groupNum]; bool foundTopPick = false; for (int topStationPick = 0; topStationPick < 5; topStationPick++) { Models.Station topStation; if (topStationPick == 0) { topStation = group.Preference1; } else if (topStationPick == 1) { topStation = group.Preference2; } else if (topStationPick == 2) { topStation = group.Preference3; } else if (topStationPick == 3) { topStation = group.Preference4; } else { topStation = group.Preference5; } if (topStation == null) { continue; } foreach (Models.Station station in unassignedStations) { //if the group has not already been given their preference and they //are allowed to visit the station, then assign them to that station if (topStation == station && !groupPreferenceGiven[group][topStationPick] && groupCanVisitStationAgain(group, station)) { IList <Models.Station> eligibleStations = new List <Models.Station> { station }; //if the station is an activity pin and the group is not //a webelos rank, remove the station filterEligibleStations(group, ref eligibleStations); if (station.isActivityPin && generateAssignment( group, timeSlot, sortedTimeSlots, eligibleStations, generatedSchedule)) { groupNum--; foundTopPick = true; break; } else if (generateAssignment(group, timeSlot, sortedTimeSlots, eligibleStations, generatedSchedule)) { groupNum--; foundTopPick = true; break; } } } if (foundTopPick) { break; } } } //for each group that does not have a top station pick //remaining, assign them to their least assigned station for (int groupNum = 0; groupNum < unassignedGroups.Count; groupNum++) { eligibleStations.Clear(); Models.Group group = unassignedGroups[groupNum]; int leastGroupAssignmentNum = 0; if (unassignedStations.Count > 0) { leastGroupAssignmentNum = groupStationAssignments[group][unassignedStations[0]]; } foreach (Models.Station station in unassignedStations) { int groupAssignmentNum = groupStationAssignments[group][station]; if (groupAssignmentNum == leastGroupAssignmentNum && groupCanVisitStationAgain(group, station)) { eligibleStations.Add(station); } else if (groupAssignmentNum < leastGroupAssignmentNum && groupCanVisitStationAgain(group, station)) { leastGroupAssignmentNum = groupAssignmentNum; eligibleStations.Clear(); eligibleStations.Add(station); } } //only assign activity pin stations to webelos filterEligibleStations(group, ref eligibleStations); //don't assign stations and categories visited on the same day removeSameDayStationsAndCategories(group, timeSlot, ref eligibleStations); if (assignStation(eligibleStations, group, timeSlot, sortedTimeSlots, generatedSchedule)) { groupNum--; } } //at this point, there is no criteria left to assign a group to one //station over another, so assign them to a station that they can visit again for (int groupNum = 0; groupNum < unassignedGroups.Count; groupNum++) { Models.Group group = unassignedGroups[groupNum]; eligibleStations.Clear(); foreach (Models.Station station in unassignedStations) { if (groupCanVisitStationAgain(group, station)) { eligibleStations.Add(station); } } //only assign activity pins to webelos groups filterEligibleStations(group, ref eligibleStations); //don't assign stations and categories visited on the same day removeSameDayStationsAndCategories(group, timeSlot, ref eligibleStations); if (assignStation(eligibleStations, group, timeSlot, sortedTimeSlots, generatedSchedule)) { groupNum--; } } } return(generatedSchedule); }
private static bool groupCanVisitStationAgain(Models.Group group, Models.Station station) { return(groupStationVisitRange[group][station].numVisits > 0 || !groupStationVisitRange[group][station].numVisits.HasValue); }
public static bool generateAssignment( Models.Group assignedGroup, Models.TimeSlot timeSlot, IList <Models.TimeSlot> sortedTimeSlots, IList <Models.Station> eligibleStations, IList <Models.Activity> generatedSchedule) { if (eligibleStations.Count > 0) { int stationNumber = random.Next(eligibleStations.Count); Models.Station assignedStation = eligibleStations[stationNumber]; //we could be scheduling either an activity pin station or a regular station if (assignedStation.isActivityPin) { int timeSlotIndex = sortedTimeSlots.IndexOf(timeSlot); if (timeSlotIndex < 0 || sortedTimeSlots.Count <= (timeSlotIndex + 1)) { return(false); } int currentTimeSlotDayNum = sortedTimeSlots[timeSlotIndex].Start.DayOfYear; int nextTimeSlotDayNum = sortedTimeSlots[timeSlotIndex + 1].Start.DayOfYear; if (currentTimeSlotDayNum != nextTimeSlotDayNum || sortedTimeSlots[timeSlotIndex].isGeneral || sortedTimeSlots[timeSlotIndex + 1].isGeneral) { return(false); } activityNumber++; Models.Activity activity = new Models.Activity(); activity.ID = activityNumber; activity.Group = assignedGroup; activity.Station = assignedStation; activity.TimeSlot = sortedTimeSlots[timeSlotIndex]; generatedSchedule.Add(activity); Models.Activity activity1 = new Models.Activity(); activity1.ID = activityNumber; activity1.Group = assignedGroup; activity1.Station = assignedStation; activity1.TimeSlot = sortedTimeSlots[timeSlotIndex + 1]; generatedSchedule.Add(activity1); nextTimeSlotUnassignedStations.Remove(assignedStation); nextTimeSlotUnassignedGroups.Remove(assignedGroup); addAssignmentToDailyAssignments(activity); } else { activityNumber++; Models.Activity activity = new Models.Activity(); activity.ID = activityNumber; activity.Group = assignedGroup; activity.Station = assignedStation; activity.TimeSlot = timeSlot; generatedSchedule.Add(activity); addAssignmentToDailyAssignments(activity); } if (assignedGroup.Preference1 == assignedStation) { groupPreferenceGiven[assignedGroup][0] = true; } else if (assignedGroup.Preference2 == assignedStation) { groupPreferenceGiven[assignedGroup][1] = true; } else if (assignedGroup.Preference3 == assignedStation) { groupPreferenceGiven[assignedGroup][2] = true; } else if (assignedGroup.Preference4 == assignedStation) { groupPreferenceGiven[assignedGroup][3] = true; } else if (assignedGroup.Preference5 == assignedStation) { groupPreferenceGiven[assignedGroup][4] = true; } groupStationVisitRange[assignedGroup][assignedStation].decrementNumVisits(); groupStationAssignments[assignedGroup][assignedStation]++; unassignedGroups.Remove(assignedGroup); stationCapacities[assignedStation]--; if (stationCapacities[assignedStation] <= 0) { unassignedStations.Remove(assignedStation); } return(true); } return(false); }
public static int deductStationRevisitedOnSameDayScore( IEnumerable <Models.Activity> schedule, IEnumerable <Models.Group> groups, IEnumerable <Models.Station> stations, IEnumerable <Models.TimeSlot> timeSlots) { DateTime a = DateTime.Now; int revisitedPenalty = 0; //assignments for station categories on each day of camp //example: on day 3, Group "Knights1" has been assigned to //category "arts and crafts" twice and category "shooting" once IDictionary <int, Dictionary <Models.Group, Dictionary <string, int> > > dailyCategoryAssignments = new Dictionary <int, Dictionary <Models.Group, Dictionary <string, int> > >(); //assignments for stations on each day of camp //example: on day 2, Group "Knights2" has been assigned to station IDictionary <int, Dictionary <Models.Group, Dictionary <Models.Station, int> > > dailyStationAssignments = new Dictionary <int, Dictionary <Models.Group, Dictionary <Models.Station, int> > >(); foreach (Models.Activity activity in schedule) { Models.Group group = activity.Group; Models.Station station = activity.Station; string stationCategory = activity.Station.Category; if (stationCategory == null) { continue; } int dayNum = activity.TimeSlot.Start.DayOfYear; //check if the same station category has already been assigned on the same day if (dailyCategoryAssignments.ContainsKey(dayNum)) { if (dailyCategoryAssignments[dayNum].ContainsKey(group)) { if (dailyCategoryAssignments[dayNum][group].ContainsKey(stationCategory)) { int numVisits = dailyCategoryAssignments[dayNum][group][stationCategory]; revisitedPenalty += numVisits; dailyCategoryAssignments[dayNum][group][stationCategory]++; } else { dailyCategoryAssignments[dayNum][group].Add(stationCategory, 1); } } else { Dictionary <string, int> stationAssignmentValue = new Dictionary <string, int>(); stationAssignmentValue.Add(stationCategory, 1); dailyCategoryAssignments[dayNum].Add(group, stationAssignmentValue); } } else { Dictionary <Models.Group, Dictionary <string, int> > groupAssignments = new Dictionary <Models.Group, Dictionary <string, int> >(); Dictionary <string, int> stationAssignmentValue = new Dictionary <string, int>(); stationAssignmentValue.Add(stationCategory, 1); groupAssignments.Add(group, stationAssignmentValue); dailyCategoryAssignments.Add(dayNum, groupAssignments); } //check if the current station has already been assigned on the same day if (dailyStationAssignments.ContainsKey(dayNum)) { if (dailyStationAssignments[dayNum].ContainsKey(group)) { if (dailyStationAssignments[dayNum][group].ContainsKey(station)) { int numVisits = dailyStationAssignments[dayNum][group][station]; revisitedPenalty += numVisits; dailyStationAssignments[dayNum][group][station]++; } else { dailyStationAssignments[dayNum][group].Add(station, 1); } } else { Dictionary <Models.Station, int> stationAssignmentValue = new Dictionary <Models.Station, int>(); stationAssignmentValue.Add(station, 1); dailyStationAssignments[dayNum].Add(group, stationAssignmentValue); } } else { Dictionary <Models.Group, Dictionary <Models.Station, int> > groupAssignments = new Dictionary <Models.Group, Dictionary <Models.Station, int> >(); Dictionary <Models.Station, int> stationAssignmentValue = new Dictionary <Models.Station, int>(); stationAssignmentValue.Add(station, 1); groupAssignments.Add(group, stationAssignmentValue); dailyStationAssignments.Add(dayNum, groupAssignments); } } DateTime b = DateTime.Now; TimeSpan c = b.Subtract(a); return(revisitedPenalty * -90); }
// POST api/<controller> // // Add user to the database // public HttpResponseMessage Post([FromBody] JsonUser value) { if (value == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid user information")); } Models.Repository repository = new Models.Repository(); var user = repository.GetUserByEmail(value.Email); if (user != null) { return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "User with same email already exists")); } string groupCode = HttpContext.Current.Request.QueryString["code"]; Models.Group defaultGroup = repository.FindGroupByCode((string.IsNullOrEmpty(groupCode) ? "JYMF" : groupCode)); if (defaultGroup == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Group code not found")); } string userid; do { Random random = new Random(); userid = (!string.IsNullOrEmpty(value.UserId) ? value.UserId : System.Web.Security.Membership.GeneratePassword(16, 0)); userid = Regex.Replace(userid, @"[^a-zA-Z0-9]", m => random.Next(0, 9).ToString()); user = repository.GetUserById(userid); } while (user != null); MFUser fbUser = new MFUser { UserId = userid, Email = value.Email, Password = value.Password, FirstName = value.FirstName, LastName = value.LastName, Name = value.Name }; var mfUser = repository.CreateUser(fbUser); repository.SaveChanges(); if (repository.IsUserInGroup(mfUser, defaultGroup) == GroupRoleEnum.empty) { repository.DefaultGroup(mfUser, defaultGroup, GroupRoleEnum.member); repository.SaveChanges(); } // Send an email notification // var smtp = new SmtpClient(); // Settings in config file var message = new MailMessage("*****@*****.**", ConfigurationManager.AppSettings["AdminEmail"]); message.Subject = "JYMF RaceDay New User"; message.IsBodyHtml = true; message.Priority = MailPriority.High; message.Body = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/NewUser.txt")); message.Body = message.Body.Replace("@FIRSTNAME@", fbUser.FirstName) .Replace("@LASTNAME@", fbUser.LastName) .Replace("@EMAIL@", fbUser.Email); smtp.Send(message); return(Request.CreateResponse(HttpStatusCode.Created, "User added to application")); }
public async Task <IActionResult> PostAsync([FromRoute] string applicationId, [FromBody] Models.Group groupDto) { if (!(await ApplicationExistsAsync(applicationId).ConfigureAwait(false))) { return(NotFound()); } var group = Mapper.Map <Group>(groupDto); group.ApplicationId = applicationId; await CreateDocumentAsync(group).ConfigureAwait(false); return(Ok(groupDto)); }
partial void DeleteOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, System.Guid id, Models.Group model);
public override System.Threading.Tasks.Task <System.Web.Mvc.ActionResult> Delete(System.Guid id, Models.Group model) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Delete); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "id", id); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "model", model); DeleteOverride(callInfo, id, model); return(System.Threading.Tasks.Task.FromResult(callInfo as System.Web.Mvc.ActionResult)); }
public ActionResult <Models.Group> Create(Models.Group group) { _groupService.Create(group); return(CreatedAtRoute("GetUserGroup", new { id = group.Id.ToString() }, group)); }
public IActionResult New(string name, int prefcurr) { // If the group exists for this user then return error // Security.Authorization DbRetriever = new Security.Authorization(DbContext, HttpContext); Models.User currUser = DbRetriever.GetUserFrom(HttpContext); // If the UserID in session doesn't reflects an actual user // Redirect to the sign up page // if (currUser == null) { return(RedirectToAction("Index", "Home")); } // If a group with the same name, bound to this user exists // Redirect to user's home page with errors set // if (currUser.Groups.Where(g => g.Name == name).FirstOrDefault() != null) { AddErrorMessage(TempData, "A group with the same name already exists"); return(RedirectToAction("Home", "Account")); } // Make new group model with the given name // Models.Group newGroup = new Models.Group() { Name = name, UserID = currUser.UserID, PrefCurrID = prefcurr }; // Try to validate new model // If it fails redirect to user home page passing the newGroup model to display errors // if (TryValidateModel(newGroup) == false) { AddErrorMessage(TempData, "Model is not valid"); return(RedirectToAction("Home", "Account")); } // Try to make new database record // try { DbContext.Groups.Add(newGroup); DbContext.SaveChanges(); // If everything is okay go to user's home page // AddOkMessage(TempData, "New group created successfully!"); } catch { // If it fails to add new record to db // Redirect to users home page // AddErrorMessage(TempData, "Error while creating your group!"); } return(RedirectToAction("Home", "Account")); }
public void Update(Models.Group group) { context.Entry(group).State = EntityState.Modified; }
public Group(Models.Group group) { Id = group.Id; Default = group.Default ? 1 : 0; Name = group.Name; }
//makes a group //returns the id of the group public int MakeGroup(Models.Group group) { return sql.MakeGroup(group); }
public Models.Group FindGroupByIdIncludeAgents(int id) { Models.Group group = context.Groups.Include(gr => gr.Agents).FirstOrDefault(gr => gr.Id == id); return(group); }
public ActionResult New(string username, string password) { // If the user is already authenticated no need to show the sign up page // if (IsLogged(HttpContext)) { return(RedirectToAction("Index", "Home")); } // // User is not logged in // // Check if username already exists // if (DbContext.Users.Where(u => u.Username == username).FirstOrDefault() != null) { AddErrorMessage(TempData, "This username already exists!"); return(View()); // Username exists } // // Username does note exist in the database // // Make new model for the new user // Pass the username and password provided by the user // Models.User newUser = new Models.User() { Username = username, Password = password }; // Try to validate the new model // if (TryValidateModel(newUser) == false) { return(View(newUser)); } // Model not valid // // Model is valid // // Secure the password through hashing // newUser.SecurePassword(); // Try to make new database record from new model // try { DbContext.Users.Add(newUser); DbContext.SaveChanges(); // // New record added successfully // // Add the default Group to the new User // Models.Group defGroup = new Models.Group() { Name = "MyGroup" }; defGroup.UserID = DbContext.Users.Last().UserID; DbContext.Groups.Add(defGroup); DbContext.SaveChanges(); // Set a welcoming/helping message // AddOkMessage(TempData, "You successfully signed up for the best expenses tracker! You can now login and start tracking!", "Welcome to ShopTracker!"); // Redirect to the login page // return(RedirectToAction("Login")); } catch (Exception ex) { // Something went wrong // Redirect user to a new sign up form // AddErrorMessage(TempData, ex.ToString()); AddErrorMessage(TempData, "Error while making a new record!"); return(RedirectToAction("New")); } }
public void AddGroupEditedEvent(Models.Group group, Models.User authorUser) { var @event = new Event(EventType.GroupEdited, authorUser, group); _eventStore.AddToBus(@event); }
public async Task <Models.Group> FindGroupByIdIncludeAgentsAsync(int?id) { Models.Group group = await context.Groups.Include(gr => gr.Agents).FirstOrDefaultAsync(gr => gr.Id == id); return(group); }
public async Task <IActionResult> PutAsync([FromRoute] string applicationId, string id, [FromBody] Models.Group groupDto) { var group = await GetDocumentAsync(applicationId, id).ConfigureAwait(false); if (group == null) { return(NotFound()); } group.Name = groupDto.Name; await UpdateDocumentAsync(group).ConfigureAwait(false); return(Ok(groupDto)); }
public void Create(Models.Group group) { context.Groups.Add(group); }