/// <summary> /// Displays the detail form for an existing occurrence. /// </summary> /// <param name="rockContext">The DbContext.</param> /// <param name="occurrenceId">The ID of the occurrence to display.</param> /// <param name="group">The group the occurrence belongs to.</param> private void ShowExistingOccurrence(RockContext rockContext, int occurrenceId, Group group) { pnlEdit.Visible = false; pnlDetails.Visible = true; pnlAttendees.Visible = true; BindFilter(); var groupType = new GroupTypeService(rockContext).Get(group.GroupTypeId); var occurrence = new AttendanceOccurrenceService(rockContext).Get(occurrenceId); lOccurrenceName.Text = occurrence.Name; tbOccurrenceName.Text = occurrence.Name; lOccurrenceDate.Text = occurrence.OccurrenceDate.ToShortDateString(); dpOccurrenceDate.SelectedDate = occurrence.OccurrenceDate; heAcceptMessage.Text = occurrence.AcceptConfirmationMessage; heDeclineMessage.Text = occurrence.DeclineConfirmationMessage; rcbShowDeclineReasons.Checked = occurrence.ShowDeclineReasons; cblDeclineReason.Visible = occurrence.ShowDeclineReasons; List <int> selectedDeclineReasons = occurrence.DeclineReasonValueIds.SplitDelimitedValues().Select(int.Parse).ToList(); foreach (int declineReasonId in selectedDeclineReasons) { foreach (ListItem liItem in rcblAvailableDeclineReasons.Items) { if (liItem.Value == declineReasonId.ToString()) { liItem.Selected = true; } } } if (occurrence.LocationId.HasValue) { var location = occurrence.Location; if (location == null) { location = new LocationService(rockContext).Get(occurrence.LocationId.Value); } lLocation.Visible = true; lLocation.Text = location.ToString(); locpLocation.Location = location; } else { lLocation.Visible = false; lLocation.Text = string.Empty; locpLocation.Location = null; } if (occurrence.ScheduleId.HasValue && occurrence.Schedule == null) { occurrence.Schedule = new ScheduleService(rockContext).GetNoTracking(occurrence.ScheduleId.Value); } if (occurrence.Schedule == null) { lSchedule.Visible = false; lSchedule.Text = string.Empty; lScheduleText.Text = string.Empty; spSchedule.SetValue(null); } else { lSchedule.Visible = true; lSchedule.Text = occurrence.Schedule.FriendlyScheduleText; lScheduleText.Text = occurrence.Schedule.FriendlyScheduleText; spSchedule.SetValue(occurrence.Schedule); } BindAttendeeGridAndChart(); }
/// <summary> /// Shows the filters. /// </summary> private void BindFilter() { ScheduleService scheduleService = new ScheduleService(new RockContext()); var customSettings = CheckinManagerHelper.GetCheckinManagerConfigurationFromCookie().CustomSettings; var scheduleIdsFilter = customSettings.GetValueOrNull(CustomSettingKey.EnRouteScheduleIdsFilter); var pickedGroupIdsFilter = customSettings.GetValueOrNull(CustomSettingKey.EnRoutePickedGroupIdsFilter); var includeChildGroupsFilter = customSettings.GetValueOrNull(CustomSettingKey.EnRouteIncludeChildGroupsFilter); var selectedScheduleIds = scheduleIdsFilter.SplitDelimitedValues().AsIntegerList(); // limit Schedules to ones that are Active, have a CheckInStartOffsetMinutes, and are Named schedules var scheduleQry = scheduleService.Queryable().Where(a => a.IsActive && a.CheckInStartOffsetMinutes != null && a.Name != null && a.Name != string.Empty); var scheduleList = scheduleQry.ToList().OrderBy(a => a.Name).ToList(); var sortedScheduleList = scheduleList.OrderByOrderAndNextScheduledDateTime(); lbSchedules.Items.Clear(); foreach (var schedule in sortedScheduleList) { var listItem = new ListItem(); if (schedule.Name.IsNotNullOrWhiteSpace()) { listItem.Text = schedule.Name; } else { listItem.Text = schedule.FriendlyScheduleText; } listItem.Value = schedule.Id.ToString(); listItem.Selected = selectedScheduleIds.Contains(schedule.Id); lbSchedules.Items.Add(listItem); } IEnumerable <CheckinAreaPath> checkinAreasPaths; var checkinAreaFilter = CheckinManagerHelper.GetCheckinAreaFilter(this); if (checkinAreaFilter != null) { checkinAreasPaths = new GroupTypeService(new RockContext()).GetCheckinAreaDescendantsPath(checkinAreaFilter.Id); } else { checkinAreasPaths = new GroupTypeService(new RockContext()).GetAllCheckinAreaPaths(); } var checkinGroupTypeIdsToShow = checkinAreasPaths.Select(a => a.GroupTypeId).Distinct().ToList(); gpGroups.IncludedGroupTypeIds = checkinGroupTypeIdsToShow; var selectedGroupIds = pickedGroupIdsFilter.SplitDelimitedValues().AsIntegerList(); gpGroups.SetValues(selectedGroupIds); if (GetAttributeValue(AttributeKey.AlwaysShowChildGroups).AsBoolean()) { cbIncludeChildGroups.Visible = false; lblIncludeChildGroups.Visible = true; cbIncludeChildGroups.Checked = true; } else { cbIncludeChildGroups.Visible = true; lblIncludeChildGroups.Visible = false; cbIncludeChildGroups.Checked = includeChildGroupsFilter.AsBoolean(); } }
private void Map() { string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: 8px; }} </style>"; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); string settingGroupTypeId = GetAttributeValue("GroupType"); string queryStringGroupTypeId = PageParameter("GroupTypeId"); if ((string.IsNullOrWhiteSpace(settingGroupTypeId) && string.IsNullOrWhiteSpace(queryStringGroupTypeId))) { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display as a block setting or pass a GroupTypeId as a query parameter.</div>"; } else { var rockContext = new RockContext(); pnlMap.Visible = true; int groupsMapped = 0; int groupsWithNoGeo = 0; StringBuilder sbGroupJson = new StringBuilder(); StringBuilder sbGroupsWithNoGeo = new StringBuilder(); Guid?groupType = null; int groupTypeId = -1; if (!string.IsNullOrWhiteSpace(settingGroupTypeId)) { groupType = new Guid(settingGroupTypeId); } else { if (!string.IsNullOrWhiteSpace(queryStringGroupTypeId) && Int32.TryParse(queryStringGroupTypeId, out groupTypeId)) { groupType = new GroupTypeService(rockContext).Get(groupTypeId).Guid; } } if (groupType != null) { Template template = null; if (GetAttributeValue("ShowMapInfoWindow").AsBoolean()) { template = Template.Parse(GetAttributeValue("InfoWindowContents").Trim()); } else { template = Template.Parse(string.Empty); } var groupPageRef = new PageReference(GetAttributeValue("GroupDetailPage")); // create group detail link for use in map's info window var personPageParams = new Dictionary <string, string>(); personPageParams.Add("PersonId", string.Empty); var personProfilePage = LinkedPageUrl("PersonProfilePage", personPageParams); var groupEntityType = EntityTypeCache.Read(typeof(Group)); var dynamicGroups = new List <dynamic>(); // Create query to get attribute values for selected attribute keys. var attributeKeys = GetAttributeValue("Attributes").SplitDelimitedValues().ToList(); var attributeValues = new AttributeValueService(rockContext).Queryable("Attribute") .Where(v => v.Attribute.EntityTypeId == groupEntityType.Id && attributeKeys.Contains(v.Attribute.Key)); GroupService groupService = new GroupService(rockContext); var groups = groupService.Queryable() .Where(g => g.GroupType.Guid == groupType) .Select(g => new { Group = g, GroupId = g.Id, GroupName = g.Name, GroupGuid = g.Guid, GroupMemberTerm = g.GroupType.GroupMemberTerm, GroupCampus = g.Campus.Name, IsActive = g.IsActive, GroupLocation = g.GroupLocations .Where(l => l.Location.GeoPoint != null) .Select(l => new { l.Location.Street1, l.Location.Street2, l.Location.City, l.Location.State, PostalCode = l.Location.PostalCode, Latitude = l.Location.GeoPoint.Latitude, Longitude = l.Location.GeoPoint.Longitude, Name = l.GroupLocationTypeValue.Value }).FirstOrDefault(), GroupMembers = g.Members, AttributeValues = attributeValues .Where(v => v.EntityId == g.Id) }); if (GetAttributeValue("IncludeInactiveGroups").AsBoolean() == false) { groups = groups.Where(g => g.IsActive == true); } // Create dynamic object to include attribute values foreach (var group in groups) { dynamic dynGroup = new ExpandoObject(); dynGroup.GroupId = group.GroupId; dynGroup.GroupName = group.GroupName; // create group detail link for use in map's info window if (groupPageRef.PageId > 0) { var groupPageParams = new Dictionary <string, string>(); groupPageParams.Add("GroupId", group.GroupId.ToString()); groupPageRef.Parameters = groupPageParams; dynGroup.GroupDetailPage = groupPageRef.BuildUrl(); } else { dynGroup.GroupDetailPage = string.Empty; } dynGroup.PersonProfilePage = personProfilePage; dynGroup.GroupMemberTerm = group.GroupMemberTerm; dynGroup.GroupCampus = group.GroupCampus; dynGroup.GroupLocation = group.GroupLocation; var groupAttributes = new List <dynamic>(); foreach (AttributeValue value in group.AttributeValues) { var attrCache = AttributeCache.Read(value.AttributeId); var dictAttribute = new Dictionary <string, object>(); dictAttribute.Add("Key", attrCache.Key); dictAttribute.Add("Name", attrCache.Name); if (attrCache != null) { dictAttribute.Add("Value", attrCache.FieldType.Field.FormatValueAsHtml(null, value.Value, attrCache.QualifierValues, false)); } else { dictAttribute.Add("Value", value.Value); } groupAttributes.Add(dictAttribute); } dynGroup.Attributes = groupAttributes; var groupMembers = new List <dynamic>(); foreach (GroupMember member in group.GroupMembers) { var dictMember = new Dictionary <string, object>(); dictMember.Add("Id", member.Person.Id); dictMember.Add("GuidP", member.Person.Guid); dictMember.Add("NickName", member.Person.NickName); dictMember.Add("LastName", member.Person.LastName); dictMember.Add("RoleName", member.GroupRole.Name); dictMember.Add("Email", member.Person.Email); dictMember.Add("PhotoGuid", member.Person.Photo != null ? member.Person.Photo.Guid : Guid.Empty); var phoneTypes = new List <dynamic>(); foreach (PhoneNumber p in member.Person.PhoneNumbers) { var dictPhoneNumber = new Dictionary <string, object>(); dictPhoneNumber.Add("Name", p.NumberTypeValue.Value); dictPhoneNumber.Add("Number", p.ToString()); phoneTypes.Add(dictPhoneNumber); } dictMember.Add("PhoneTypes", phoneTypes); groupMembers.Add(dictMember); } dynGroup.GroupMembers = groupMembers; dynamicGroups.Add(dynGroup); } // enable showing debug info if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT)) { lDebug.Visible = true; lDebug.Text = dynamicGroups.Take(5).lavaDebugInfo(); } else { lDebug.Visible = false; lDebug.Text = string.Empty; } foreach (var group in dynamicGroups) { if (group.GroupLocation != null && group.GroupLocation.Latitude != null) { groupsMapped++; var groupDict = group as IDictionary <string, object>; string infoWindow = template.Render(Hash.FromDictionary(groupDict)).Replace("\n", string.Empty); sbGroupJson.Append(string.Format( @"{{ ""name"":""{0}"" , ""latitude"":""{1}"", ""longitude"":""{2}"", ""infowindow"":""{3}"" }},", HttpUtility.HtmlEncode(group.GroupName), group.GroupLocation.Latitude, group.GroupLocation.Longitude, HttpUtility.HtmlEncode(infoWindow))); } else { groupsWithNoGeo++; if (!string.IsNullOrWhiteSpace(group.GroupDetailPage)) { sbGroupsWithNoGeo.Append(string.Format(@"<li><a href='{0}'>{1}</a></li>", group.GroupDetailPage, group.GroupName)); } else { sbGroupsWithNoGeo.Append(string.Format(@"<li>{0}</li>", group.GroupName)); } } } string groupJson = sbGroupJson.ToString(); // remove last comma if (groupJson.Length > 0) { groupJson = groupJson.Substring(0, groupJson.Length - 1); } // add styling to map string styleCode = "null"; string markerColor = "FE7569"; DefinedValueCache dvcMapStyle = DefinedValueCache.Read(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (colors.Any()) { markerColor = colors.First().Replace("#", ""); } } // write script to page string mapScriptFormat = @" <script> Sys.Application.add_load(function () {{ var groupData = JSON.parse('{{ ""groups"" : [ {0} ]}}'); var showInfoWindow = {1}; var mapStyle = {2}; var pinColor = '{3}'; var pinImage = new google.maps.MarkerImage('http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + pinColor, new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34)); var pinShadow = new google.maps.MarkerImage('http://chart.googleapis.com/chart?chst=d_map_pin_shadow', new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35)); initializeMap(); function initializeMap() {{ console.log(mapStyle); var map; var bounds = new google.maps.LatLngBounds(); var mapOptions = {{ mapTypeId: 'roadmap', styles: mapStyle }}; // Display a map on the page map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); map.setTilt(45); // Display multiple markers on a map if (showInfoWindow) {{ var infoWindow = new google.maps.InfoWindow(), marker, i; }} // Loop through our array of markers & place each one on the map $.each(groupData.groups, function (i, group) {{ var position = new google.maps.LatLng(group.latitude, group.longitude); bounds.extend(position); marker = new google.maps.Marker({{ position: position, map: map, title: htmlDecode(group.name), icon: pinImage, shadow: pinShadow }}); // Allow each marker to have an info window if (showInfoWindow) {{ google.maps.event.addListener(marker, 'click', (function (marker, i) {{ return function () {{ infoWindow.setContent(htmlDecode(groupData.groups[i].infowindow)); infoWindow.open(map, marker); }} }})(marker, i)); }} map.fitBounds(bounds); }}); // Override our map zoom level once our fitBounds function runs (Make sure it only runs once) var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {{ google.maps.event.removeListener(boundsListener); }}); }} function htmlDecode(input) {{ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue; }} }}); </script>"; string mapScript = string.Format( mapScriptFormat, groupJson, GetAttributeValue("ShowMapInfoWindow").AsBoolean().ToString().ToLower(), styleCode, markerColor); ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-mapper-script", mapScript, false); if (groupsMapped == 0) { pnlMap.Visible = false; lMessages.Text = @" <p> <div class='alert alert-warning fade in'>No groups were able to be mapped. You may want to check your configuration.</div> </p>"; } else { // output any warnings if (groupsWithNoGeo > 0) { string messagesFormat = @" <p> <div class='alert alert-warning fade in'>Some groups could not be mapped. <button type='button' class='close' data-dismiss='alert' aria-hidden='true'><i class='fa fa-times'></i></button> <small><a data-toggle='collapse' data-parent='#accordion' href='#map-error-details'>Show Details</a></small> <div id='map-error-details' class='collapse'> <p class='margin-t-sm'> <strong>Groups That Could Not Be Mapped</strong> <ul> {0} </ul> </p> </div> </div> </p>"; lMessages.Text = string.Format(messagesFormat, sbGroupsWithNoGeo.ToString()); } } } else { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display and a location type to use.</div>"; } } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var registrationRegistrantService = new RegistrationRegistrantService(rockContext); var eiogmService = new EventItemOccurrenceGroupMapService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var signatureDocumentServce = new SignatureDocumentService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); int[] signatureDocumentIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates"))) { signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); var group = new GroupService(rockContext).Get(bbGroup); if (group.Name.Contains("Week 2")) { cmpCampus.Visible = true; } Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid(); int? hsmGroupTypeId = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id; var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList(); hlGroup.NavigateUrl = "/group/" + group.Id; var attributeIds = attributeService.Queryable() .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) || (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) || (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue))) .Select(a => a.Id).ToList(); var gmTmpqry = groupMemberService.Queryable() .Where(gm => (gm.GroupId == group.Id)); var qry = gmTmpqry .Join(registrationRegistrantService.Queryable(), obj => obj.Id, rr => rr.GroupMemberId, (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 }, av => new { PersonId = av.EntityId, av.AttributeId }, (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() }) .GroupJoin(attributeValueService.Queryable(), obj => obj.GroupMember.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }); var qry2 = gmTmpqry .GroupJoin( groupMemberService.Queryable() .Join(groupService.Queryable(), gm => new { Id = gm.GroupId, GroupTypeId = 10 }, g => new { g.Id, g.GroupTypeId }, (gm, g) => new { GroupMember = gm, Group = g }) .Join(groupLocationService.Queryable(), obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 }, gl => new { gl.GroupId, gl.GroupLocationTypeValueId }, (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl }) .Join(locationService.Queryable(), obj => obj.GroupLocation.LocationId, l => l.Id, (obj, l) => new { GroupMember = obj.GroupMember, Location = l }), gm => gm.PersonId, glgm => glgm.GroupMember.PersonId, (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() } ) .GroupJoin(signatureDocumentServce.Queryable() .Join(personAliasService.Queryable(), sd => sd.AppliesToPersonAliasId, pa => pa.Id, (sd, pa) => new { SignatureDocument = sd, Alias = pa }), obj => obj.GroupMember.PersonId, sd => sd.Alias.PersonId, (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds }) .GroupJoin(phoneNumberService.Queryable(), obj => obj.GroupMember.PersonId, p => p.PersonId, (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn }); if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix)))) { string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower(); qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable(); } decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); if (lowerVal != null && upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue)) { if (group.Name.Contains("Week 2")) { qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).AsQueryable(); } } var stopwatch = new Stopwatch(); stopwatch.Start(); var tmp = qry.ToList(); var tmp2 = qry2.ToList(); lStats.Text = "Query Runtime: " + stopwatch.Elapsed; stopwatch.Reset(); stopwatch.Start(); var newQry = tmp.Select(g => new { Id = g.GroupMember.Id, RegisteredBy = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person), Registrant = new ModelValue <Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.RegistrationId, Group = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group), DOB = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "", Address = new ModelValue <Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()), Email = g.Person.Email, Gender = g.Person.Gender, // (B & B Registration) GraduationYearProfile = g.Person.GraduationYear, // (Person Profile) HomePhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), CellPhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), GroupMemberData = new Func <GroupMemberAttributes>(() => { GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues); return(gma); })(), RegistrantData = new Func <RegistrantAttributes>(() => { RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues); return(row); })(), School = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Read(g.School.AsGuid()) != null?DefinedValueCache.Read(g.School.AsGuid()).Value:"", LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(), Departure = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(), Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", // MSMGroup = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()), Person = g.Person, AddressStreet = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(), AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(), RegistrantName = g.Person.FullName, }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable(); lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed; stopwatch.Stop(); gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields; var mergeFields = new List <String>(); mergeFields.Add("Id"); mergeFields.Add("RegisteredBy"); mergeFields.Add("Group"); mergeFields.Add("Registrant"); mergeFields.Add("Age"); mergeFields.Add("GraduationYear"); mergeFields.Add("DOB"); mergeFields.Add("Address"); mergeFields.Add("Email"); mergeFields.Add("Gender"); mergeFields.Add("GraduationYearProfile"); mergeFields.Add("HomePhone"); mergeFields.Add("CellPhone"); mergeFields.Add("GroupMemberData"); mergeFields.Add("RegistrantData"); mergeFields.Add("LegalRelease"); mergeFields.Add("Departure"); mergeFields.Add("Campus"); mergeFields.Add("Role"); mergeFields.Add("MSMGroup"); gReport.CommunicateMergeFields = mergeFields; /* * if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix)))) * { * string poa = GetUserPreference(string.Format("{0}POA", keyPrefix)); * if (poa == "[Blank]") * { * poa = ""; * } * newQry = newQry.Where(q => q.GroupMemberData.POA == poa); * } */ SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName)); } gReport.DataBind(); }
/// <summary> /// Renders the specified writer. /// </summary> /// <param name="badge">The badge.</param> /// <param name="writer">The writer.</param> public override void Render(PersonBadgeCache badge, System.Web.UI.HtmlTextWriter writer) { if (!String.IsNullOrEmpty(GetAttributeValue(badge, "GroupType"))) { string badgeColor = "#0ab4dd"; if (!String.IsNullOrEmpty(GetAttributeValue(badge, "BadgeColor"))) { badgeColor = GetAttributeValue(badge, "BadgeColor"); } Guid groupTypeGuid = GetAttributeValue(badge, "GroupType").AsGuid(); if (groupTypeGuid != Guid.Empty) { var rockContext = new RockContext(); // get group type info GroupType groupType = new GroupTypeService(rockContext).Get(groupTypeGuid); if (groupType != null) { // get descendant group info GroupService groupService = new GroupService(rockContext); var groupsOfGroupType = groupService.Queryable().Where(g => g.GroupType.Guid == groupTypeGuid); List <int> groupIds = groupsOfGroupType.Select(g => g.Id).ToList(); foreach (var group in groupsOfGroupType) { groupIds.AddRange(groupService.GetAllDescendents(group.Id).Select(g => g.Id)); } // determine if person is in this type of group GroupMemberService groupMemberService = new GroupMemberService(rockContext); GroupMember groupMember = groupMemberService.Queryable("Person,GroupRole,Group") .Where(t => groupIds.Contains(t.GroupId) && t.PersonId == Person.Id && t.GroupMemberStatus == GroupMemberStatus.Active && t.Group.IsActive) .OrderBy(g => g.GroupRole.Order) .FirstOrDefault(); var badgeHtml = ""; var labelText = ""; if (groupMember != null) { badgeHtml = String.Format("<i class='badge-icon {0}' style='color: {1}'></i>", groupType.IconCssClass, badgeColor); labelText = String.Format("{0} is in a descendant of a {1}", Person.NickName, groupType.Name); } else { badgeHtml = String.Format("<i class='badge-icon badge-disabled {0}'></i>", groupType.IconCssClass); labelText = String.Format("{0} is not in a descendant of a {1}", Person.NickName, groupType.Name); } writer.Write(String.Format(@"<div class='badge badge-ingroupoftype badge-id-{0}' data-toggle='tooltip' data-original-title='{1}'>{2}</div>" , badge.Id, labelText, badgeHtml)); } } } }
private void SortRows(string eventParam, string[] values) { var groupTypeIds = new List <int>(); using (var rockContext = new RockContext()) { if (eventParam.Equals("re-order-area")) { Guid groupTypeGuid = new Guid(values[0]); int newIndex = int.Parse(values[1]); var allRows = phRows.ControlsOfTypeRecursive <CheckinAreaRow>(); var sortedRow = allRows.FirstOrDefault(a => a.GroupTypeGuid.Equals(groupTypeGuid)); if (sortedRow != null) { Control parentControl = sortedRow.Parent; var siblingRows = allRows .Where(a => a.Parent.ClientID == sortedRow.Parent.ClientID) .ToList(); int oldIndex = siblingRows.IndexOf(sortedRow); var groupTypeService = new GroupTypeService(rockContext); var groupTypes = new List <GroupType>(); foreach (var siblingGuid in siblingRows.Select(a => a.GroupTypeGuid)) { var groupType = groupTypeService.Get(siblingGuid); if (groupType != null) { groupTypes.Add(groupType); groupTypeIds.Add(groupType.Id); } } groupTypeService.Reorder(groupTypes, oldIndex, newIndex); } } else if (eventParam.Equals("re-order-group")) { Guid groupGuid = new Guid(values[0]); int newIndex = int.Parse(values[1]); var allRows = phRows.ControlsOfTypeRecursive <CheckinGroupRow>(); var sortedRow = allRows.FirstOrDefault(a => a.GroupGuid.Equals(groupGuid)); if (sortedRow != null) { Control parentControl = sortedRow.Parent; var siblingRows = allRows .Where(a => a.Parent.ClientID == sortedRow.Parent.ClientID) .ToList(); int oldIndex = siblingRows.IndexOf(sortedRow); var groupService = new GroupService(rockContext); var groups = new List <Group>(); foreach (var siblingGuid in siblingRows.Select(a => a.GroupGuid)) { var group = groupService.Get(siblingGuid); if (group != null) { groups.Add(group); } } groupService.Reorder(groups, oldIndex, newIndex); } } rockContext.SaveChanges(); } Rock.CheckIn.KioskDevice.Clear(); BuildRows(); }
/// <summary> /// Sets the selection. /// </summary> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection(System.Web.UI.Control[] controls, string selection) { var groupType = new GroupTypeService(new RockContext()).Get(selection.AsGuid()); (controls[0] as GroupTypePicker).SetValue(groupType != null ? groupType.Id : (int?)null); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="groupTypeId">The groupType identifier.</param> public void ShowDetail(int groupTypeId) { pnlDetails.Visible = false; bool editAllowed = true; GroupType groupType = null; if (!groupTypeId.Equals(0)) { groupType = new GroupTypeService(new RockContext()).Get(groupTypeId); pdAuditDetails.SetEntity(groupType, ResolveRockUrl("~")); } if (groupType == null) { groupType = new GroupType { Id = 0 }; var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid()); if (templatePurpose != null) { groupType.GroupTypePurposeValueId = templatePurpose.Id; } // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } if (groupType != null) { editAllowed = groupType.IsAuthorized(Authorization.EDIT, CurrentPerson); pnlDetails.Visible = true; hfGroupTypeId.Value = groupType.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!editAllowed || !IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(GroupType.FriendlyTypeName); } if (readOnly) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails(groupType); } else { btnEdit.Visible = true; btnDelete.Visible = true; if (groupType.Id > 0) { ShowReadonlyDetails(groupType); } else { ShowEditDetails(groupType); } } } }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="groupType">The groupType.</param> private void ShowReadonlyDetails(GroupType groupType) { SetEditMode(false); if (groupType != null) { hfGroupTypeId.SetValue(groupType.Id); lReadOnlyTitle.Text = groupType.ToString().FormatAsHtmlTitle(); lDescription.Text = groupType.Description; groupType.LoadAttributes(); hlType.Text = groupType.GetAttributeValue("CheckInType"); hlType.Visible = true; DescriptionList mainDetailsDescList = new DescriptionList(); DescriptionList leftDetailsDescList = new DescriptionList(); DescriptionList rightDetailsDescList = new DescriptionList(); string scheduleList = string.Empty; using (var rockContext = new RockContext()) { var descendantGroupTypeIds = new GroupTypeService(rockContext).GetAllAssociatedDescendents(groupType.Id).Select(a => a.Id); scheduleList = new GroupLocationService(rockContext) .Queryable().AsNoTracking() .Where(a => a.Group.GroupType.Id == groupType.Id || descendantGroupTypeIds.Contains(a.Group.GroupTypeId)) .SelectMany(a => a.Schedules) .Select(s => s.Name) .Distinct() .OrderBy(s => s) .ToList() .AsDelimited(", "); } if (!string.IsNullOrWhiteSpace(scheduleList)) { mainDetailsDescList.Add("Scheduled Times", scheduleList); } groupType.LoadAttributes(); if (groupType.AttributeValues.ContainsKey("core_checkin_CheckInType")) { leftDetailsDescList.Add("Check-in Type", groupType.AttributeValues["core_checkin_CheckInType"].ValueFormatted); } if (groupType.AttributeValues.ContainsKey("core_checkin_SearchType")) { var searchType = groupType.AttributeValues["core_checkin_SearchType"]; rightDetailsDescList.Add("Search Type", searchType.ValueFormatted); var searchTypeGuid = searchType.Value.AsGuid(); if (searchTypeGuid.Equals(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME_AND_PHONE.AsGuid()) || searchTypeGuid.Equals(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER.AsGuid())) { rightDetailsDescList.Add("Phone Number Compare", groupType.AttributeValues["core_checkin_PhoneSearchType"].ValueFormatted); } } lblMainDetails.Text = mainDetailsDescList.Html; lblLeftDetails.Text = leftDetailsDescList.Html; lblRightDetails.Text = rightDetailsDescList.Html; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (HasFilterErrors()) { return; } var checkinAreaFilter = CheckinManagerHelper.GetCheckinAreaFilter(this); CampusCache campus = GetCampusFromContext(); var selectedScheduleIds = lbSchedules.SelectedValues.AsIntegerList(); if (selectedScheduleIds.Any()) { btnShowFilter.AddCssClass("criteria-exists bg-warning"); } else { btnShowFilter.RemoveCssClass("criteria-exists bg-warning"); } CheckinManagerHelper.SaveRoomListFilterToCookie(selectedScheduleIds.ToArray()); var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); IEnumerable <CheckinAreaPath> checkinAreaPaths; if (checkinAreaFilter != null) { checkinAreaPaths = groupTypeService.GetCheckinAreaDescendantsPath(checkinAreaFilter.Id); } else { checkinAreaPaths = groupTypeService.GetAllCheckinAreaPaths(); } var selectedGroupTypeIds = checkinAreaPaths.Select(a => a.GroupTypeId).Distinct().ToArray(); var groupLocationService = new GroupLocationService(rockContext); var groupLocationsQuery = groupLocationService.Queryable() .Where(gl => selectedGroupTypeIds.Contains(gl.Group.GroupTypeId) && gl.Group.IsActive && (!gl.Group.IsArchived)); var parentLocationIdParameter = PageParameter(PageParameterKey.ParentLocationId).AsIntegerOrNull(); var locationIdParameter = PageParameter(PageParameterKey.LocationId).AsIntegerOrNull(); var locationGridField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lRoomName"); if (locationGridField != null && !locationGridField.Visible) { locationGridField.Visible = true; } List <int> locationIds; if (locationIdParameter.HasValue) { // If LocationId is specified in the URL, list only items for the specified location. // Also, hide the Location Grid Column and set the PanelTitle as the location's name // This will take precedence over the selected campus+locations and/or <seealso cref="ParentLocationId"/> var locationService = new LocationService(rockContext); lPanelTitle.Text = locationService.GetSelect(locationIdParameter.Value, s => s.Name); locationIds = new List <int>(); locationIds.Add(locationIdParameter.Value); if (locationGridField != null) { // since a LocationId parameter was specified, the LocationGrid field doesn't need to be shown locationGridField.Visible = false; } } else if (parentLocationIdParameter.HasValue) { // If parentLocationId is specified, show the direct (first level) child locations of the specified ParentLocationId. // This will take precedence over the selected campus+locations. var locationService = new LocationService(rockContext); locationIds = locationService.Queryable() .Where(a => a.ParentLocationId.HasValue && a.ParentLocationId.Value == parentLocationIdParameter.Value) .Select(a => a.Id).ToList(); lPanelTitle.Text = string.Format("{0} Child Locations", locationService.GetSelect(parentLocationIdParameter.Value, s => s.Name)); } else { // Limit locations (rooms) to locations within the selected campus. locationIds = new LocationService(rockContext).GetAllDescendentIds(campus.LocationId.Value).ToList(); locationIds.Add(campus.LocationId.Value, true); lPanelTitle.Text = "Room List"; } groupLocationsQuery = groupLocationsQuery.Where(a => locationIds.Contains(a.LocationId)); if (selectedScheduleIds.Any()) { groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue && selectedScheduleIds.Contains(s.Id))); } else { groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue)); } var groupLocationList = groupLocationsQuery.Select(a => new GroupLocationInfo { LocationId = a.LocationId, LocationName = a.Location.Name, ParentGroupId = a.Group.ParentGroupId, ParentGroupName = a.Group.ParentGroup.Name, GroupId = a.Group.Id, GroupName = a.Group.Name, GroupTypeId = a.Group.GroupTypeId }).ToList(); var startDateTime = RockDateTime.Today; DateTime currentDateTime; if (campus != null) { currentDateTime = campus.CurrentDateTime; } else { currentDateTime = RockDateTime.Now; } // Get all Attendance records for the current day and location. var attendanceQuery = new AttendanceService(rockContext).Queryable().Where(a => a.StartDateTime >= startDateTime && a.DidAttend == true && a.StartDateTime <= currentDateTime && a.PersonAliasId.HasValue && a.Occurrence.GroupId.HasValue && a.Occurrence.LocationId.HasValue && a.Occurrence.ScheduleId.HasValue); // Limit attendances (rooms) to the groupLocations' LocationId and GroupIds that we'll be showing var groupLocationLocationIds = groupLocationList.Select(a => a.LocationId).Distinct().ToList(); var groupLocationGroupsIds = groupLocationList.Select(a => a.GroupId).Distinct().ToList(); attendanceQuery = attendanceQuery.Where(a => groupLocationLocationIds.Contains(a.Occurrence.LocationId.Value) && groupLocationGroupsIds.Contains(a.Occurrence.GroupId.Value)); attendanceQuery = attendanceQuery.Where(a => selectedGroupTypeIds.Contains(a.Occurrence.Group.GroupTypeId)); if (selectedScheduleIds.Any()) { attendanceQuery = attendanceQuery.Where(a => selectedScheduleIds.Contains(a.Occurrence.ScheduleId.Value)); } var rosterAttendeeAttendanceList = RosterAttendeeAttendance.Select(attendanceQuery).ToList(); var groupTypeIdsWithAllowCheckout = selectedGroupTypeIds .Select(a => GroupTypeCache.Get(a)) .Where(a => a != null) .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ALLOW_CHECKOUT).AsBoolean()) .Select(a => a.Id) .Distinct().ToList(); var groupTypeIdsWithEnablePresence = selectedGroupTypeIds .Select(a => GroupTypeCache.Get(a)) .Where(a => a != null) .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ENABLE_PRESENCE).AsBoolean()) .Select(a => a.Id) .Distinct(); var scheduleIds = rosterAttendeeAttendanceList.Select(a => a.ScheduleId.Value).Distinct().ToList(); var scheduleList = new ScheduleService(rockContext).GetByIds(scheduleIds).ToList(); var scheduleIdsWasScheduleOrCheckInActiveForCheckOut = new HashSet <int>(scheduleList.Where(a => a.WasScheduleOrCheckInActiveForCheckOut(currentDateTime)).Select(a => a.Id).ToList()); rosterAttendeeAttendanceList = rosterAttendeeAttendanceList.Where(a => { var allowCheckout = groupTypeIdsWithAllowCheckout.Contains(a.GroupTypeId); if (!allowCheckout) { /* * If AllowCheckout is false, remove all Attendees whose schedules are not currently active. Per the 'WasSchedule...ActiveForCheckOut()' * method below: "Check-out can happen while check-in is active or until the event ends (start time + duration)." This will help to keep * the list of 'Present' attendees cleaned up and accurate, based on the room schedules, since the volunteers have no way to manually mark * an Attendee as 'Checked-out'. * * If, on the other hand, AllowCheckout is true, it will be the volunteers' responsibility to click the [Check-out] button when an * Attendee leaves the room, in order to keep the list of 'Present' Attendees in order. This will also allow the volunteers to continue * 'Checking-out' Attendees in the case that the parents are running late in picking them up. */ return(scheduleIdsWasScheduleOrCheckInActiveForCheckOut.Contains(a.ScheduleId.Value)); } else { return(true); } }).ToList(); var attendancesByLocationId = rosterAttendeeAttendanceList .GroupBy(a => a.LocationId.Value).ToDictionary(k => k.Key, v => v.ToList()); _attendancesByLocationIdAndGroupId = attendancesByLocationId.ToDictionary( k => k.Key, v => v.Value.GroupBy(x => x.GroupId.Value).ToDictionary(x => x.Key, xx => xx.ToList())); _checkinAreaPathsLookupByGroupTypeId = checkinAreaPaths.ToDictionary(k => k.GroupTypeId, v => v); _showOnlyParentGroup = this.GetAttributeValue(AttributeKey.ShowOnlyParentGroup).AsBoolean(); var roomList = new List <RoomInfo>(); foreach (var groupLocation in groupLocationList) { AddToRoomList(roomList, groupLocation); } List <RoomInfo> sortedRoomList; if (_showOnlyParentGroup) { sortedRoomList = roomList.OrderBy(a => a.LocationName).ToList(); } else { sortedRoomList = new List <RoomInfo>(); sortedRoomList.AddRange(roomList.OfType <RoomInfoByGroup>().OrderBy(a => a.LocationName).ThenBy(a => a.GroupName).ToList()); } var checkedInCountField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedInCount"); var presentCountField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lPresentCount"); var checkedOutCountField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedOutCount"); checkedOutCountField.Visible = groupTypeIdsWithAllowCheckout.Any(); // Always show Present Count regardless of the 'Enable Presence' setting. (A person gets automatically marked present if 'Enable Presence' is disabled.) presentCountField.Visible = true; if (groupTypeIdsWithEnablePresence.Any()) { // Presence is enabled, so records could be in the 'Checked-in' state // and Present column should be labeled 'Present'. checkedInCountField.Visible = true; presentCountField.HeaderText = "Present"; } else { // https://app.asana.com/0/0/1199637795718017/f // 'Enable Presence' is disabled, so a person automatically gets marked present. // So, no records will be in the 'Checked-In (but no present)' state. // Also, a user thinks of 'Present' as 'Checked-In' if they don't use the 'Enable Presence' feature checkedInCountField.Visible = false; presentCountField.HeaderText = "Checked-In"; } if (_showOnlyParentGroup) { gRoomList.DataKeyNames = new string[1] { "LocationId" }; } else { gRoomList.DataKeyNames = new string[2] { "LocationId", "GroupId" }; } gRoomList.DataSource = sortedRoomList; gRoomList.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } GroupType groupType = null; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); int?groupTypeId = hfGroupTypeId.ValueAsInt(); if (groupTypeId.HasValue && groupTypeId.Value > 0) { groupType = groupTypeService.Get(groupTypeId.Value); } bool newGroupType = false; if (groupType == null) { groupType = new GroupType(); groupTypeService.Add(groupType); var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid()); if (templatePurpose != null) { groupType.GroupTypePurposeValueId = templatePurpose.Id; } newGroupType = true; } if (groupType != null) { groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.IconCssClass = tbIconCssClass.Text; groupType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType); groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString()); groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString()); groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString()); groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString()); groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString()); groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue); groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString()); groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString()); groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString()); groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text); groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text); groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text); groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString()); groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue); groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text); groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text); groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString()); var searchType = DefinedValueCache.Get(ddlSearchType.SelectedValueAsInt() ?? 0); if (searchType != null) { groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString()); } else { groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER); } groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text); groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text); groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text); groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString()); groupType.SetAttributeValue("core_checkin_AllowCheckout", cbAllowCheckout.Checked.ToString()); groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text); groupType.SetAttributeValue("core_checkin_AutoSelectOptions", ddlAutoSelectOptions.SelectedValueAsInt()); // Registration Settings groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS, cbRegistrationDisplayAlternateIdFieldForAdults.Checked.ToTrueFalse()); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN, cbRegistrationDisplayAlternateIdFieldForChildren.Checked.ToTrueFalse()); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON, cbRegistrationDisplaySmsEnabled.Checked.ToTrueFalse()); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED, cbRegistrationSmsEnabledByDefault.Checked.ToTrueFalse()); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS, lbRegistrationRequiredAttributesForAdults.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS, lbRegistrationOptionalAttributesForAdults.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN, lbRegistrationRequiredAttributesForChildren.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN, lbRegistrationOptionalAttributesForChildren.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES, lbRegistrationRequiredAttributesForFamilies.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES, lbRegistrationOptionalAttributesForFamilies.SelectedValues.AsDelimited(",")); Guid?defaultPersonConnectionStatusValueGuid = null; var defaultPersonConnectionStatusValueId = dvpRegistrationDefaultPersonConnectionStatus.SelectedValue.AsIntegerOrNull(); if (defaultPersonConnectionStatusValueId.HasValue) { var defaultPersonConnectionStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueId.Value); if (defaultPersonConnectionStatusValue != null) { defaultPersonConnectionStatusValueGuid = defaultPersonConnectionStatusValue.Guid; } } groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS, defaultPersonConnectionStatusValueGuid.ToString()); var workflowTypeService = new WorkflowTypeService(rockContext); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES, workflowTypeService.GetByIds(wftpRegistrationAddFamilyWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(",")); groupType.SetAttributeValue( Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES, workflowTypeService.GetByIds(wftpRegistrationAddPersonWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(",")); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION, cbEnableCheckInAfterRegistration.Checked.ToTrueFalse()); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES, lbKnownRelationshipTypes.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES, lbSameFamilyKnownRelationshipTypes.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES, lbCanCheckInKnownRelationshipTypes.SelectedValues.AsDelimited(",")); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE, ceStartTemplate.Text); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE, ceFamilySelectTemplate.Text); groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE, ceSuccessTemplate.Text); // Save group type and attributes rockContext.WrapTransaction(() => { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); }); if (newGroupType) { var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId); pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString()); NavigateToPage(pageRef); } else { groupType = groupTypeService.Get(groupType.Id); ShowReadonlyDetails(groupType); } Rock.CheckIn.KioskDevice.Clear(); } }
/// <summary> /// Private method called by Execute() to process the job. This method should be wrapped in a try/catch block to ensure than any exceptions are sent to the /// <see cref="ExceptionLogService"/>. /// </summary> /// <param name="context">The job's execution context.</param> private void ProcessJob(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; RockContext rockContext = new RockContext(); // Make sure GroupType job attribute was assigned. Guid? groupTypeGuid = dataMap.GetString(AttributeKey.GroupType).AsGuidOrNull(); List <GroupType> rsvpGroupTypes = new List <GroupType>(); if (groupTypeGuid != null) { // Verify GroupType exists. var groupType = new GroupTypeService(rockContext).Get(groupTypeGuid.Value); if (groupType == null) { context.Result = "Job Exited: The selected Group Type does not exist."; return; } // Verify GroupType has RSVP enabled. if (!groupType.EnableRSVP) { context.Result = "Job Exited: The selected Group Type does not have RSVP enabled."; return; } rsvpGroupTypes.Add(groupType); } else { rsvpGroupTypes = new GroupTypeService(rockContext).Queryable().AsNoTracking().Where(gt => gt.EnableRSVP).ToList(); } var sbResults = new StringBuilder(); foreach (var groupType in rsvpGroupTypes) { // Retrieve RSVP settings from GroupType. var systemCommunicationService = new SystemCommunicationService(rockContext); SystemCommunication groupTypeReminder = GetGroupTypeRsvpReminder(groupType, systemCommunicationService); int?groupTypeOffset = GetGroupTypeOffset(groupType); // Get RSVP enabled groups which have an RSVP Reminder set, and verify that there is at least one group to process. var groups = GetRsvpReminderEligibleGroups(groupType, rockContext, groupType.RSVPReminderSystemCommunicationId.HasValue); if (!groups.Any()) { sbResults.AppendLine($"The Group Type {groupType.Name} does not contain any groups with RSVP reminder communications."); continue; } // Process groups and get the response. This is where the actual work starts. sbResults.Append(ProcessGroups(groups, groupTypeReminder, groupTypeOffset, rockContext)); } // Job complete! Record results of the job to the context. var jobResult = sbResults.ToString(); if (string.IsNullOrEmpty(jobResult)) { jobResult = "Job completed successfully, but no reminders were sent."; } context.Result = jobResult; }
private string BuildHierarchy(List <int> groupTypeIds, int?campusId) { GroupTypeService groupTypeService = new GroupTypeService(_rockContext); var groupTypes = groupTypeService .Queryable().AsNoTracking() .Where(t => groupTypeIds.Contains(t.Id)) .OrderBy(t => t.Order) .ThenBy(t => t.Name) .ToList(); var content = new StringBuilder(); foreach (var groupType in groupTypes) { if (!_addedGroupTypeIds.Contains(groupType.Id)) { _addedGroupTypeIds.Add(groupType.Id); if (groupType.GroupTypePurposeValueId == null || groupType.Groups.Count > 0) { string groupTypeContent = string.Empty; if (groupType.ChildGroupTypes.Count > 0) { groupTypeContent = BuildHierarchy(groupType.ChildGroupTypes.Select(t => t.Id).ToList(), campusId); } var groupContent = new StringBuilder(); foreach (var group in groupType.Groups) { if (!_addedGroupIds.Contains(group.Id) && (!campusId.HasValue || !group.CampusId.HasValue || campusId.Value == group.CampusId.Value)) { _addedGroupIds.Add(group.Id); var groupName = group.IsActive ? group.Name : group.Name + " (Inactive)"; if (!string.IsNullOrWhiteSpace(GetAttributeValue("GroupDetailPage"))) { var groupPageParams = new Dictionary <string, string>(); if (Request["GroupTypeIds"] != null) { groupPageParams.Add("GroupTypeIds", Request["GroupTypeIds"]); } groupPageParams.Add("GroupId", group.Id.ToString()); groupContent.Append(string.Format("<li><a href='{0}'>{1}</a></li>", LinkedPageUrl("GroupDetailPage", groupPageParams), groupName)); } else { groupContent.Append(string.Format("<li>{0}</li>", groupName)); } } } if (!string.IsNullOrWhiteSpace(groupTypeContent) || groupContent.Length > 0) { content.Append("<ul>"); content.Append(string.Format("<li><strong>{0}</strong></li>", groupType.Name)); content.Append(groupTypeContent); if (groupContent.Length > 0) { content.Append("<ul>"); content.Append(groupContent.ToString()); content.Append("</ul>"); } content.Append("</ul>"); } } else { if (groupType.ChildGroupTypes.Count > 0) { content.Append(BuildHierarchy(groupType.ChildGroupTypes.Select(t => t.Id).ToList(), campusId)); } } } } return(content.ToString()); }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService(rockContext); var groupTypeService = new GroupTypeService(rockContext); IEnumerable <GroupTypePath> groupPaths = new List <GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable(); int groupTypeId; // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter int?groupTypeIdPageParam = this.PageParameter("groupTypeId").AsIntegerOrNull(); if (groupTypeIdPageParam.HasValue) { groupTypeId = groupTypeIdPageParam ?? Rock.Constants.All.Id; } else { groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id; } if (groupTypeId != Rock.Constants.All.Id) { var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents(groupTypeId).Select(a => a.Id); // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor) groupLocationQry = groupLocationQry.Where(a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains(a.Group.GroupTypeId)); groupPaths = groupTypeService.GetAllAssociatedDescendentsPath(groupTypeId); } else { // if no specific GroupType is specified, show all GroupTypes with GroupTypePurpose of Checkin Template and their descendents (since this blocktype is specifically for Checkin) int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE)).Id; List <int> descendantGroupTypeIds = new List <int>(); foreach (var templateGroupType in groupTypeService.Queryable().Where(a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId)) { foreach (var childGroupType in groupTypeService.GetChildGroupTypes(templateGroupType.Id)) { descendantGroupTypeIds.Add(childGroupType.Id); descendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(childGroupType.Id).Select(a => a.Id).ToList()); } } groupLocationQry = groupLocationQry.Where(a => descendantGroupTypeIds.Contains(a.Group.GroupTypeId)); } if (gGroupLocationSchedule.SortProperty != null) { groupLocationQry = groupLocationQry.Sort(gGroupLocationSchedule.SortProperty); } else { groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name); } var qryList = groupLocationQry.Select(a => new { GroupLocationId = a.Id, GroupName = a.Group.Name, LocationName = a.Location.Name, ScheduleIdList = a.Schedules.Select(s => s.Id), a.LocationId, GroupTypeId = a.Group.GroupTypeId }).ToList(); int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id; if (parentLocationId != Rock.Constants.All.Id) { var descendantLocationIds = new LocationService(rockContext).GetAllDescendents(parentLocationId).Select(a => a.Id); qryList = qryList.Where(a => descendantLocationIds.Contains(a.LocationId)).ToList(); } // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add("GroupLocationId"); dataTable.Columns.Add("GroupName"); dataTable.Columns.Add("LocationName"); dataTable.Columns.Add("Path"); foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { dataTable.Columns.Add(field.DataField, typeof(bool)); } foreach (var row in qryList) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = row.GroupName; dataRow["LocationName"] = row.LocationName; dataRow["Path"] = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault(); foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty)); dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId); } dataTable.Rows.Add(dataRow); } gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { GroupType groupType; GroupTypeService groupTypeService = new GroupTypeService(); int groupTypeId = int.Parse(hfGroupTypeId.Value); if (groupTypeId == 0) { groupType = new GroupType(); groupTypeService.Add(groupType, CurrentPersonId); } else { groupType = groupTypeService.Get(groupTypeId); } groupType.Name = tbName.Text; if (ddlDefaultGroupRole.SelectedValue.Equals(None.Id.ToString())) { groupType.DefaultGroupRoleId = null; } else { groupType.DefaultGroupRoleId = int.Parse(ddlDefaultGroupRole.SelectedValue); } groupType.Description = tbDescription.Text; groupType.ChildGroupTypes = new List <GroupType>(); groupType.ChildGroupTypes.Clear(); foreach (var item in ChildGroupTypesDictionary) { var childGroupType = groupTypeService.Get(item.Key); if (childGroupType != null) { groupType.ChildGroupTypes.Add(childGroupType); } } DefinedValueService definedValueService = new DefinedValueService(); groupType.LocationTypes = new List <GroupTypeLocationType>(); groupType.LocationTypes.Clear(); foreach (var item in LocationTypesDictionary) { var locationType = definedValueService.Get(item.Key); if (locationType != null) { groupType.LocationTypes.Add(new GroupTypeLocationType { LocationTypeValueId = locationType.Id }); } } // check for duplicates if (groupTypeService.Queryable().Count(a => a.Name.Equals(groupType.Name, StringComparison.OrdinalIgnoreCase) && !a.Id.Equals(groupType.Id)) > 0) { tbName.ShowErrorMessage(WarningMessage.DuplicateFoundMessage("name", GroupType.FriendlyTypeName)); return; } if (!groupType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { groupTypeService.Save(groupType, CurrentPersonId); }); BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; }
/// <summary> /// Builds an expression for an attribute field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The entity field.</param> /// <param name="values">The filter parameter values: FieldName, <see cref="ComparisonType">Comparison Type</see>, (optional) Comparison Value(s)</param> /// <returns></returns> public static Expression GetAttributeExpression(IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List <string> values) { if (!values.Any()) { // if no filter parameter values where specified, don't filter return(new NoAttributeFilterExpression()); } var service = new AttributeValueService(( RockContext )serviceInstance.Context); var attributeValues = service.Queryable().Where(v => v.EntityId.HasValue); AttributeCache attributeCache = null; if (entityField.AttributeGuid.HasValue) { attributeCache = AttributeCache.Get(entityField.AttributeGuid.Value); var attributeId = attributeCache != null ? attributeCache.Id : 0; attributeValues = attributeValues.Where(v => v.AttributeId == attributeId); } else { attributeValues = attributeValues.Where(v => v.Attribute.Key == entityField.Name && v.Attribute.FieldTypeId == entityField.FieldType.Id); } ParameterExpression attributeValueParameterExpression = Expression.Parameter(typeof(AttributeValue), "v"); // Determine the appropriate comparison type to use for this Expression. // Attribute Value records only exist for Entities that have a value specified for the Attribute. // Therefore, if the specified comparison works by excluding certain values we must invert our filter logic: // first we find the Attribute Values that match those values and then we exclude the associated Entities from the result set. ComparisonType?comparisonType = ComparisonType.EqualTo; ComparisonType?evaluatedComparisonType = comparisonType; // If Values.Count >= 2, then Values[0] is ComparisonType, and Values[1] is a CompareToValue. Otherwise, Values[0] is a CompareToValue (for example, a SingleSelect attribute) if (values.Count >= 2) { comparisonType = values[0].ConvertToEnumOrNull <ComparisonType>(); switch (comparisonType) { case ComparisonType.DoesNotContain: evaluatedComparisonType = ComparisonType.Contains; break; case ComparisonType.IsBlank: evaluatedComparisonType = ComparisonType.IsNotBlank; break; case ComparisonType.LessThan: evaluatedComparisonType = ComparisonType.GreaterThanOrEqualTo; break; case ComparisonType.LessThanOrEqualTo: evaluatedComparisonType = ComparisonType.GreaterThan; break; case ComparisonType.NotEqualTo: evaluatedComparisonType = ComparisonType.EqualTo; break; default: evaluatedComparisonType = comparisonType; break; } values[0] = evaluatedComparisonType.ToString(); } var filterExpression = entityField.FieldType.Field.AttributeFilterExpression(entityField.FieldConfig, values, attributeValueParameterExpression); if (filterExpression != null) { if (filterExpression is NoAttributeFilterExpression) { // Special Case: If AttributeFilterExpression returns NoAttributeFilterExpression, just return the NoAttributeFilterExpression. // For example, If this is a CampusFieldType and they didn't pick any campus, we don't want to do any filtering for this DataFilter. return(filterExpression); } else { attributeValues = attributeValues.Where(attributeValueParameterExpression, filterExpression, null); } } else { // AttributeFilterExpression returned NULL ( the FieldType didn't specify any additional filter on AttributeValue), // ideally the FieldType should have returned a NoAttributeFilterExpression, but just in case, don't filter System.Diagnostics.Debug.WriteLine($"Unexpected NULL result from FieldType.Field.AttributeFilterExpression for { entityField.FieldType }"); return(new NoAttributeFilterExpression()); } IQueryable <int> ids = attributeValues.Select(v => v.EntityId.Value); MemberExpression propertyExpression = Expression.Property(parameterExpression, "Id"); ConstantExpression idsExpression = Expression.Constant(ids.AsQueryable(), typeof(IQueryable <int>)); Expression expression = Expression.Call(typeof(Queryable), "Contains", new Type[] { typeof(int) }, idsExpression, propertyExpression); if (attributeCache != null) { // Test the default value against the expression filter. If it pass, then we can include all the attribute values with no value. var comparedToDefault = IsComparedToValue(attributeValueParameterExpression, filterExpression, attributeCache.DefaultValue); if (comparedToDefault) { var allAttributeValueIds = service.Queryable().Where(v => v.Attribute.Id == attributeCache.Id && v.EntityId.HasValue && !string.IsNullOrEmpty(v.Value)).Select(a => a.EntityId.Value); ConstantExpression allIdsExpression = Expression.Constant(allAttributeValueIds.AsQueryable(), typeof(IQueryable <int>)); Expression notContainsExpression = Expression.Not(Expression.Call(typeof(Queryable), "Contains", new Type[] { typeof(int) }, allIdsExpression, propertyExpression)); expression = Expression.Or(expression, notContainsExpression); } // If there is an EntityTypeQualifierColumn/Value on this attribute, also narrow down the entity query to the ones with matching QualifierColumn/Value if (attributeCache.EntityTypeQualifierColumn.IsNotNullOrWhiteSpace() && attributeCache.EntityTypeQualifierValue.IsNotNullOrWhiteSpace()) { Expression qualifierParameterExpression = null; PropertyInfo qualifierColumnProperty = parameterExpression.Type.GetProperty(attributeCache.EntityTypeQualifierColumn); // make sure the QualifierColumn is an actual mapped property on the Entity if (qualifierColumnProperty != null && qualifierColumnProperty.GetCustomAttribute <NotMappedAttribute>() == null) { qualifierParameterExpression = parameterExpression; } else { if (attributeCache.EntityTypeQualifierColumn == "GroupTypeId" && parameterExpression.Type == typeof(Rock.Model.GroupMember)) { // Special Case for GroupMember with Qualifier of 'GroupTypeId' (which is really Group.GroupTypeId) qualifierParameterExpression = Expression.Property(parameterExpression, "Group"); } else if (attributeCache.EntityTypeQualifierColumn == "RegistrationTemplateId" && parameterExpression.Type == typeof(Rock.Model.RegistrationRegistrant)) { // Special Case for RegistrationRegistrant with Qualifier of 'RegistrationTemplateId' (which is really Registration.RegistrationInstance.RegistrationTemplateId) qualifierParameterExpression = Expression.Property(parameterExpression, "Registration"); qualifierParameterExpression = Expression.Property(qualifierParameterExpression, "RegistrationInstance"); } else { // Unable to determine how the EntityTypeQualiferColumn relates to the Entity. Probably will be OK, but spit out a debug message System.Diagnostics.Debug.WriteLine($"Unable to determine how the EntityTypeQualiferColumn {attributeCache.EntityTypeQualifierColumn} relates to entity {parameterExpression.Type} on attribute {attributeCache.Name}:{attributeCache.Guid}"); } } if (qualifierParameterExpression != null) { // if we figured out the EntityQualifierColumn/Value expression, apply it // This would effectively add something like 'WHERE [GroupTypeId] = 10' to the WHERE clause MemberExpression entityQualiferColumnExpression = Expression.Property(qualifierParameterExpression, attributeCache.EntityTypeQualifierColumn); object entityTypeQualifierValueAsType = Convert.ChangeType(attributeCache.EntityTypeQualifierValue, entityQualiferColumnExpression.Type); Expression entityQualiferColumnEqualExpression = Expression.Equal(entityQualiferColumnExpression, Expression.Constant(entityTypeQualifierValueAsType, entityQualiferColumnExpression.Type)); // If the qualifier Column is GroupTypeId, we'll have to do an OR clause of all the GroupTypes that inherit from this // This would effectively add something like 'WHERE ([GroupTypeId] = 10) OR ([GroupTypeId] = 12) OR ([GroupTypeId] = 17)' to the WHERE clause if (attributeCache.EntityTypeQualifierColumn == "GroupTypeId" && attributeCache.EntityTypeQualifierValue.AsIntegerOrNull().HasValue) { var qualifierGroupTypeId = attributeCache.EntityTypeQualifierValue.AsInteger(); List <int> inheritedGroupTypeIds = null; using (var rockContext = new RockContext()) { var groupType = new GroupTypeService(rockContext).Get(qualifierGroupTypeId); inheritedGroupTypeIds = groupType.GetAllDependentGroupTypeIds(rockContext); } if (inheritedGroupTypeIds != null) { foreach (var inheritedGroupTypeId in inheritedGroupTypeIds) { Expression inheritedEntityQualiferColumnEqualExpression = Expression.Equal(entityQualiferColumnExpression, Expression.Constant(inheritedGroupTypeId)); entityQualiferColumnEqualExpression = Expression.Or(entityQualiferColumnEqualExpression, inheritedEntityQualiferColumnEqualExpression); } } } expression = Expression.And(entityQualiferColumnEqualExpression, expression); } } } // If we have used an inverted comparison type for the evaluation, invert the Expression so that it excludes the matching Entities. if (comparisonType != evaluatedComparisonType) { return(Expression.Not(expression)); } else { return(expression); } }
protected void btnSave_Click(object sender, EventArgs e) { hfAreaGroupClicked.Value = "true"; using (var rockContext = new RockContext()) { var attributeService = new AttributeService(rockContext); if (checkinArea.Visible) { var groupTypeService = new GroupTypeService(rockContext); var groupType = groupTypeService.Get(checkinArea.GroupTypeGuid); if (groupType != null) { groupType.LoadAttributes(rockContext); checkinArea.GetGroupTypeValues(groupType); if (groupType.IsValid) { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes)) { var attribute = attributeService.Get(labelAttribute.Value.Guid); attributeService.Delete(attribute); } // Make sure default role is set if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any()) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; int binaryFileFieldTypeID = FieldTypeCache.Get(Rock.SystemGuid.FieldType.LABEL.AsGuid()).Id; foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupType.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if (!attribute.IsValid) { return; } attributeService.Add(attribute); } rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.Clear(); nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults(groupType.ValidationResults); } } } if (checkinGroup.Visible) { var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var group = groupService.Get(checkinGroup.GroupGuid); if (group != null) { group.LoadAttributes(rockContext); checkinGroup.GetGroupValues(group); // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList(); foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList()) { groupLocationService.Delete(groupLocation); group.GroupLocations.Remove(groupLocation); } var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList(); foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList()) { var groupLocation = new GroupLocation(); groupLocation.LocationId = item.LocationId; group.GroupLocations.Add(groupLocation); } // Set the new order foreach (var item in checkinGroup.Locations.OrderBy(l => l.Order).ToList()) { var groupLocation = group.GroupLocations.FirstOrDefault(gl => gl.LocationId == item.LocationId); groupLocation.Order = item.Order ?? 0; } if (group.IsValid) { rockContext.SaveChanges(); group.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.Clear(); nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults(group.ValidationResults); } } } } hfIsDirty.Value = "false"; }
/// <summary> /// Gets the list source. /// </summary> /// <value> /// The list source. /// </value> internal override Dictionary <string, string> GetListSource(Dictionary <string, ConfigurationValue> configurationValues) { GroupTypeService groupTypeService = new GroupTypeService(new RockContext()); return(groupTypeService.Queryable().OrderBy(a => a.Name).ToDictionary(k => k.Guid.ToString(), v => v.Name)); }
protected void btnSave_Click(object sender, EventArgs e) { KioskType kioskType = null; var rockContext = new RockContext(); var kioskTypeService = new KioskTypeService(rockContext); var attributeService = new AttributeService(rockContext); var locationService = new LocationService(rockContext); var scheduleService = new ScheduleService(rockContext); var groupTypeService = new GroupTypeService(rockContext); int kioskTypeId = int.Parse(hfKioskTypeId.Value); if (kioskTypeId != 0) { kioskType = kioskTypeService.Get(kioskTypeId); } if (kioskType == null) { kioskType = new KioskType(); kioskTypeService.Add(kioskType); } if (kioskType != null) { kioskType.Name = tbName.Text; kioskType.Description = tbDescription.Text; kioskType.Message = tbMessage.Text; kioskType.IsMobile = cbIsMobile.Checked; kioskType.MinutesValid = tbMinutesValid.Text.AsIntegerOrNull(); kioskType.GraceMinutes = tbGraceMinutes.Text.AsIntegerOrNull(); kioskType.Theme = ddlTheme.SelectedValue; if (!kioskType.IsValid || !Page.IsValid) { // Controls will render the error messages return; } // Remove any deleted locations foreach (var location in kioskType.Locations .Where(l => !Locations.Keys.Contains(l.Id)) .ToList()) { kioskType.Locations.Remove(location); } // Remove any deleted schedules foreach (var schedule in kioskType.Schedules .Where(s => !Schedules.Keys.Contains(s.Id)) .ToList()) { kioskType.Schedules.Remove(schedule); } // Add any new locations var existingLocationIDs = kioskType.Locations.Select(l => l.Id).ToList(); foreach (var location in locationService.Queryable() .Where(l => Locations.Keys.Contains(l.Id) && !existingLocationIDs.Contains(l.Id))) { kioskType.Locations.Add(location); } // Add any new schedules var existingScheduleIDs = kioskType.Schedules.Select(s => s.Id).ToList(); foreach (var schedule in scheduleService.Queryable() .Where(s => Schedules.Keys.Contains(s.Id) && !existingScheduleIDs.Contains(s.Id))) { kioskType.Schedules.Add(schedule); } //Save checkin template kioskType.CheckinTemplateId = ddlTemplates.SelectedValue.AsInteger(); var GroupTypes = kioskType.GroupTypes; GroupTypes.Clear(); foreach (ListItem item in cblPrimaryGroupTypes.Items) { if (item.Selected) { GroupTypes.Add(groupTypeService.Get(item.Value.AsInteger())); } } kioskType.CampusId = ddlCampus.SelectedCampusId; rockContext.SaveChanges(); KioskTypeCache.Remove(kioskType.Id); KioskTypeCache.Get(kioskType.Id); KioskDeviceHelpers.Clear(kioskType.GroupTypes.Select(gt => gt.Id).ToList()); NavigateToParentPage(); } }
/// <summary> /// Handels the Delete button click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnDelete_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { if (checkinArea.Visible) { GroupTypeService groupTypeService = new GroupTypeService(rockContext); GroupType groupType = groupTypeService.Get(checkinArea.GroupTypeGuid); if (groupType != null) { if (IsInheritedGroupTypeRecursive(groupType, groupTypeService)) { nbDeleteWarning.Text = "WARNING - Cannot delete. This group type or one of its child group types is assigned as an inherited group type."; nbDeleteWarning.Visible = true; return; } string errorMessage; if (!groupTypeService.CanDelete(groupType, out errorMessage)) { nbDeleteWarning.Text = "WARNING - Cannot Delete: " + errorMessage; nbDeleteWarning.Visible = true; return; } int id = groupType.Id; groupType.ParentGroupTypes.Clear(); groupType.ChildGroupTypes.Clear(); groupTypeService.Delete(groupType); rockContext.SaveChanges(); GroupTypeCache.Flush(id); Rock.CheckIn.KioskDevice.FlushAll(); } SelectArea(null); } if (checkinGroup.Visible) { GroupService groupService = new GroupService(rockContext); Group group = groupService.Get(checkinGroup.GroupGuid); if (group != null) { string errorMessage; if (!groupService.CanDelete(group, out errorMessage)) { nbDeleteWarning.Text = "WARNING - Cannot Delete: " + errorMessage; nbDeleteWarning.Visible = true; return; } groupService.Delete(group); //Delete if group isn't active rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.FlushAll(); SelectGroup(null); } } } BuildRows(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); hfLimitToSecurityRoleGroups.Value = GetAttributeValue("LimittoSecurityRoleGroups"); hfRootGroupId.Value = GetAttributeValue("Group"); // limit GroupType selection to what Block Attributes allow List <Guid> groupTypeGuids = GetAttributeValue("GroupTypes").SplitDelimitedValues().Select(Guid.Parse).ToList(); string groupTypeIds = "0"; if (groupTypeGuids.Any()) { groupTypeIds = new GroupTypeService().Queryable().Where(a => groupTypeGuids.Contains(a.Guid)).Select(a => a.Id).ToList().AsDelimited(","); groupTypeIds = string.IsNullOrWhiteSpace(groupTypeIds) ? "0" : groupTypeIds; } hfGroupTypes.Value = groupTypeIds; if (!string.IsNullOrWhiteSpace(_groupId)) { hfInitialGroupId.Value = _groupId; hfSelectedGroupId.Value = _groupId; Group group = (new GroupService()).Get(int.Parse(_groupId)); if (group != null) { // show the Add button if the selected Group's GroupType can have children lbAddGroupChild.Enabled = group.GroupType.ChildGroupTypes.Count > 0; } else { // hide the Add Button when adding a new Group lbAddGroupChild.Enabled = false; } // get the parents of the selected item so we can tell the treeview to expand those List <string> parentIdList = new List <string>(); while (group != null) { group = group.ParentGroup; if (group != null) { parentIdList.Insert(0, group.Id.ToString()); } } // also get any additional expanded nodes that were sent in the Post string postedExpandedIds = this.Request.Params["expandedIds"]; if (!string.IsNullOrWhiteSpace(postedExpandedIds)) { var postedExpandedIdList = postedExpandedIds.Split(',').ToList(); foreach (var id in postedExpandedIdList) { if (!parentIdList.Contains(id)) { parentIdList.Add(id); } } } hfInitialGroupParentIds.Value = parentIdList.AsDelimited(","); } else { // let the Add button be visible if there is nothing selected lbAddGroupChild.Enabled = true; } // disable add child group if no group is selected int selectedGroupId = hfSelectedGroupId.ValueAsInt(); if (selectedGroupId == 0) { lbAddGroupChild.Enabled = false; } }
/// <summary> /// Maps the RLC data to rooms, locations & classes -- Mapping RLC Names as groups under check-in /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapRLC(IQueryable <Row> tableData) { var lookupContext = new RockContext(); // Add an Attribute for the unique F1 Ministry Id //int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id; //var rlcAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId // && a.Key == "F1RLCId").Select(a => a.Id).FirstOrDefault(); //if (rlcAttributeId == 0) //{ // var newRLCAttribute = new Rock.Model.Attribute(); // newRLCAttribute.Key = "F1RLCId"; // newRLCAttribute.Name = "F1 RLC Id"; // newRLCAttribute.FieldTypeId = IntegerFieldTypeId; // newRLCAttribute.EntityTypeId = groupEntityTypeId; // newRLCAttribute.EntityTypeQualifierValue = string.Empty; // newRLCAttribute.EntityTypeQualifierColumn = string.Empty; // newRLCAttribute.Description = "The FellowshipOne identifier for the RLC Group that was imported"; // newRLCAttribute.DefaultValue = string.Empty; // newRLCAttribute.IsMultiValue = false; // newRLCAttribute.IsRequired = false; // newRLCAttribute.Order = 0; // lookupContext.Attributes.Add(newRLCAttribute); // lookupContext.SaveChanges(DisableAudit); // rlcAttributeId = newRLCAttribute.Id; //} // Get previously imported Ministries //var importedRLCs = new AttributeValueService(lookupContext).GetByAttributeId(rlcAttributeId) // .Select(av => new { RLCId = av.Value.AsType<int?>(), RLCName = av.ForeignId }) // .ToDictionary(t => t.RLCId, t => t.RLCName); //List<AttributeValue> importedRLCAVList = new AttributeValueService( lookupContext ).GetByAttributeId( rlcAttributeId ).ToList(); //Not in use var newRLCGroupList = new List <Group>(); var rlcAttributeValueList = new List <AttributeValue>(); //Need a list of GroupTypes var gtService = new GroupTypeService(lookupContext); var existingGroupTypes = new List <GroupType>(); existingGroupTypes = gtService.Queryable().ToList(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying RLC Group import ({0:N0} found).", totalRows)); foreach (var row in tableData) { int? rlcId = row["RLC_ID"] as int?; string rlcName = row["RLC_Name"] as string; string rlcStringId = Convert.ToString(rlcId); int?importedRLCs = new GroupService(lookupContext).Queryable().Where(a => a.ForeignId == rlcStringId).Select(a => a.Id).FirstOrDefault(); if (rlcId != null && importedRLCs == 0) { if (rlcName != null) { bool? rlcIsActive = row["Is_Active"] as bool?; string roomName = row["Room_Name"] as string; string maxCapacity = row["Max_Capacity"] as string; string roomDescription = row["Room_Name"] as string; string roomCode = row["Room_Code"] as string; DateTime?startAgeDate = row["Start_Age_Date"] as DateTime?; DateTime?endAgeDate = row["End_Age_Date"] as DateTime?; int? activityId = row["Activity_ID"] as int?; //Searches for Parent ActivityId string activityStringId = activityId.ToString(); GroupType parentActivityArea = existingGroupTypes.Where(gt => gt.ForeignId == activityStringId).FirstOrDefault(); if (String.IsNullOrWhiteSpace(rlcName)) { ReportProgress(0, string.Format(".")); rlcName = "Excavator Test"; } var rlcGroup = new Group(); bool rlcIsActiveBool = (bool)rlcIsActive; //Sets the Group values for RLC rlcGroup.IsSystem = false; rlcGroup.Name = rlcName.Trim(); rlcGroup.Order = 0; //rlcGroup.Guid = new Guid(); rlcGroup.GroupTypeId = parentActivityArea.Id; rlcGroup.IsActive = rlcIsActiveBool; rlcGroup.Description = roomDescription; rlcGroup.ForeignId = rlcStringId; //rlcGroup.GroupLocations = new List<GroupLocation>(); //rlcGroup.GroupLocations.Add( CheckLocation( roomDescription ) ); var rlcAttributeValue = new AttributeValue(); //Sets the Attribute Values for RLC //rlcAttributeValue.IsSystem = false; //rlcAttributeValue.AttributeId = rlcAttributeId; //rlcAttributeValue.Value = rlcStringId; //rlcAttributeValue.ForeignId = rlcName.Trim(); //rlcAttributeValueList.Add(rlcAttributeValue); newRLCGroupList.Add(rlcGroup); completed++; // Adds rlcGroup to newRLCGroup list ReportProgress(0, string.Format("Parent Activity/Area: {1} Group Added: {0} IsActive: {2}.", rlcGroup.Name, parentActivityArea.Name, rlcGroup.IsActive)); if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} RLC/Groups imported ({1}% complete). ", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange(rlcAttributeValueList); rockContext.Groups.AddRange(newRLCGroupList); rockContext.SaveChanges(DisableAudit); newRLCGroupList.Clear(); rlcAttributeValueList.Clear(); }); ReportPartialProgress(); } } } } if (newRLCGroupList.Any()) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange(rlcAttributeValueList); rockContext.Groups.AddRange(newRLCGroupList); rockContext.SaveChanges(DisableAudit); newRLCGroupList.Clear(); rlcAttributeValueList.Clear(); }); } ReportProgress(100, string.Format("Finished ministry and activity import: {0:N0} imported.", completed)); }
/// <summary> /// Checks the settings. If false is returned, it's expected that the caller will make /// the nbNotice visible to inform the user of the "settings" error. /// </summary> /// <returns>true if settings are valid; false otherwise</returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _mode = GetAttributeValue("Mode"); _autoFill = GetAttributeValue("AutoFillForm").AsBoolean(); var groupService = new GroupService(_rockContext); bool groupIsFromQryString = true; Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull(); if (groupGuid.HasValue) { _group = groupService.Get(groupGuid.Value); groupIsFromQryString = false; } if (_group == null) { groupGuid = PageParameter("GroupGuid").AsGuidOrNull(); if (groupGuid.HasValue) { _group = groupService.Get(groupGuid.Value); } } if (_group == null && GetAttributeValue("EnablePassingGroupId").AsBoolean(false)) { int?groupId = PageParameter("GroupId").AsIntegerOrNull(); if (groupId.HasValue) { _group = groupService.Get(groupId.Value); } } if (_group == null) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group identifying parameter and there was not one provided.</p>"; return(false); } else { Guid RsvpGroupTypeGuid = "1A082EFF-30DA-44B2-8E48-02385C20828E".AsGuid(); var groupTypeGuids = new GroupTypeService(_rockContext).Queryable() .AsNoTracking() .Where(g => g.Guid == RsvpGroupTypeGuid || g.InheritedGroupType.Guid == RsvpGroupTypeGuid) .Select(g => g.Guid) .ToList(); if (groupIsFromQryString && groupTypeGuids.Any() && !groupTypeGuids.Contains(_group.GroupType.Guid)) { _group = null; nbNotice.Heading = "Invalid Group"; nbNotice.Text = "<p>The selected group is a restricted group type therefore this block cannot be used to add people to these groups (unless configured to allow).</p>"; return(false); } else { _defaultGroupRole = _group.GroupType.DefaultGroupRole; } } _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return(false); } _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return(false); } _married = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); _familyType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _adultRole = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return(false); } return(true); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="pledgeId">The pledge identifier.</param> public void ShowDetail(int pledgeId) { pnlDetails.Visible = true; var frequencyTypeGuid = new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY); ddlFrequencyType.BindToDefinedType(DefinedTypeCache.Read(frequencyTypeGuid), true); using (var rockContext = new RockContext()) { FinancialPledge pledge = null; if (pledgeId > 0) { pledge = new FinancialPledgeService(rockContext).Get(pledgeId); lActionTitle.Text = ActionTitle.Edit(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle(); pdAuditDetails.SetEntity(pledge, ResolveRockUrl("~")); } if (pledge == null) { pledge = new FinancialPledge(); lActionTitle.Text = ActionTitle.Add(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle(); // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } var isReadOnly = !IsUserAuthorized(Authorization.EDIT); var isNewPledge = pledge.Id == 0; hfPledgeId.Value = pledge.Id.ToString(); if (pledge.PersonAlias != null) { ppPerson.SetValue(pledge.PersonAlias.Person); } else { ppPerson.SetValue(null); } ppPerson.Enabled = !isReadOnly; GroupType groupType = null; Guid? groupTypeGuid = GetAttributeValue("SelectGroupType").AsGuidOrNull(); if (groupTypeGuid.HasValue) { groupType = new GroupTypeService(rockContext).Get(groupTypeGuid.Value); } if (groupType != null) { ddlGroup.Label = groupType.Name; ddlGroup.Visible = true; LoadGroups(pledge.GroupId); ddlGroup.Enabled = !isReadOnly; } else { ddlGroup.Visible = false; } apAccount.SetValue(pledge.Account); apAccount.Enabled = !isReadOnly; tbAmount.Text = !isNewPledge?pledge.TotalAmount.ToString() : string.Empty; tbAmount.ReadOnly = isReadOnly; dpDateRange.LowerValue = pledge.StartDate; dpDateRange.UpperValue = pledge.EndDate; dpDateRange.ReadOnly = isReadOnly; ddlFrequencyType.SelectedValue = !isNewPledge?pledge.PledgeFrequencyValueId.ToString() : string.Empty; ddlFrequencyType.Enabled = !isReadOnly; if (isReadOnly) { nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialPledge.FriendlyTypeName); lActionTitle.Text = ActionTitle.View(BlockType.FriendlyTypeName); btnCancel.Text = "Close"; } btnSave.Visible = !isReadOnly; } }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var groupService = new GroupService(rockContext); var groupPaths = new List <GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable().Where(gl => gl.Group.IsActive && !gl.Group.IsArchived); int groupTypeId; // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter if (_groupTypeId.HasValue) { groupTypeId = _groupTypeId.Value; } else { groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id; } if (groupTypeId != Rock.Constants.All.Id) { var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents(groupTypeId).Select(a => a.Id); // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor) groupLocationQry = groupLocationQry.Where(a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains(a.Group.GroupTypeId)); groupPaths = groupTypeService.GetAllAssociatedDescendentsPath(groupTypeId).ToList(); } else { List <int> descendantGroupTypeIds = new List <int>(); foreach (GroupType groupType in GetTopGroupTypes(rockContext)) { descendantGroupTypeIds.Add(groupType.Id); groupPaths.AddRange(groupTypeService.GetAllAssociatedDescendentsPath(groupType.Id).ToList()); foreach (var childGroupType in groupTypeService.GetChildGroupTypes(groupType.Id)) { descendantGroupTypeIds.Add(childGroupType.Id); descendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(childGroupType.Id).Select(a => a.Id).ToList()); } } groupLocationQry = groupLocationQry.Where(a => descendantGroupTypeIds.Contains(a.Group.GroupTypeId)); } if (gGroupLocationSchedule.SortProperty != null) { groupLocationQry = groupLocationQry.Sort(gGroupLocationSchedule.SortProperty); } else { groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name); } var qryList = groupLocationQry .Where(a => a.Location != null) .Select(a => new { GroupLocationId = a.Id, a.Location, GroupId = a.GroupId, GroupName = a.Group.Name, ScheduleIdList = a.Schedules.Select(s => s.Id), GroupTypeId = a.Group.GroupTypeId }).ToList(); var locationService = new LocationService(rockContext); int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id; if (parentLocationId != Rock.Constants.All.Id) { var currentAndDescendantLocationIds = new List <int>(); currentAndDescendantLocationIds.Add(parentLocationId); currentAndDescendantLocationIds.AddRange(locationService.GetAllDescendents(parentLocationId).Select(a => a.Id)); qryList = qryList.Where(a => currentAndDescendantLocationIds.Contains(a.Location.Id)).ToList(); } // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add("GroupLocationId"); dataTable.Columns.Add("GroupId"); dataTable.Columns.Add("GroupName"); dataTable.Columns.Add("GroupPath"); dataTable.Columns.Add("LocationName"); dataTable.Columns.Add("LocationPath"); foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { dataTable.Columns.Add(field.DataField, typeof(bool)); } var locationPaths = new Dictionary <int, string>(); foreach (var row in qryList) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = groupService.GroupAncestorPathName(row.GroupId); dataRow["GroupPath"] = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault(); dataRow["LocationName"] = row.Location.Name; if (row.Location.ParentLocationId.HasValue) { int locationId = row.Location.ParentLocationId.Value; if (!locationPaths.ContainsKey(locationId)) { var locationNames = new List <string>(); var parentLocation = locationService.Get(locationId); while (parentLocation != null) { locationNames.Add(parentLocation.Name); parentLocation = parentLocation.ParentLocation; } if (locationNames.Any()) { locationNames.Reverse(); locationPaths.Add(locationId, locationNames.AsDelimited(" > ")); } else { locationPaths.Add(locationId, string.Empty); } } dataRow["LocationPath"] = locationPaths[locationId]; } foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty)); dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId); } dataTable.Rows.Add(dataRow); } gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Get <GroupLocation>().Id; gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); Rock.Data.RockTransactionScope.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var business = new Person(); if (int.Parse(hfBusinessId.Value) != 0) { business = personService.Get(int.Parse(hfBusinessId.Value)); } // int? orphanedPhotoId = null; // if ( business.PhotoId != imgPhoto.BinaryFileId ) // { // orphanedPhotoId = business.PhotoId; // business.PhotoId = imgPhoto.BinaryFileId; // if ( orphanedPhotoId.HasValue ) // { // if ( business.PhotoId.HasValue ) // { // changes.Add( "Modified the photo." ); // } // else // { // changes.Add( "Deleted the photo." ); // } // } // else if ( business.PhotoId.HasValue ) // { // changes.Add( "Added a photo." ); // } // } // Business Name History.EvaluateChange(changes, "First Name", business.FirstName, tbBusinessName.Text); business.FirstName = tbBusinessName.Text; // Phone Number var phoneNumberTypeIds = new List <int>(); var homePhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME)).Id; if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == homePhoneTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = homePhoneTypeId }; business.PhoneNumbers.Add(phoneNumber); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add(homePhoneTypeId); History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(homePhoneTypeId)), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode); } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(rockContext); foreach (var phoneNumber in business.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value)) .ToList()) { History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)), phoneNumber.NumberFormatted, string.Empty); business.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // Record Status int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); business.RecordStatusValueId = newRecordStatusId; // Record Status Reason int?newRecordStatusReasonId = null; if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text); business.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference); business.EmailPreference = newEmailPreference; if (business.IsValid) { if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), business.Id, changes); } // if ( orphanedPhotoId.HasValue ) // { // BinaryFileService binaryFileService = new BinaryFileService( personService.RockContext ); // var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); // if ( binaryFile != null ) // { // // marked the old images as IsTemporary so they will get cleaned up later // binaryFile.IsTemporary = true; // binaryFileService.Save( binaryFile, CurrentPersonAlias ); // } // } // Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } } // Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); var groupService = new GroupService(rockContext); var businessGroup = new Group(); if (business.GivingGroupId != null) { businessGroup = groupService.Get((int)business.GivingGroupId); } businessGroup.GroupTypeId = familyGroupType.Id; businessGroup.Name = tbBusinessName.Text + " Business"; businessGroup.CampusId = ddlCampus.SelectedValueAsInt(); var knownRelationshipGroup = new Group(); var impliedRelationshipGroup = new Group(); if (business.GivingGroupId == null) { groupService.Add(businessGroup); // If there isn't a Giving Group then there aren't any other groups. // We also need to add the Known Relationship and Implied Relationship groups for this business. var knownRelationshipGroupTypeId = new GroupTypeService(rockContext).Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS)).Id; knownRelationshipGroup.GroupTypeId = knownRelationshipGroupTypeId; knownRelationshipGroup.Name = "Known Relationship"; groupService.Add(knownRelationshipGroup); var impliedRelationshipGroupTypeId = new GroupTypeService(rockContext).Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS)).Id; impliedRelationshipGroup.GroupTypeId = impliedRelationshipGroupTypeId; impliedRelationshipGroup.Name = "Implied Relationship"; groupService.Add(impliedRelationshipGroup); } rockContext.SaveChanges(); // Giving Group int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if (business.GivingGroupId != newGivingGroupId) { string oldGivingGroupName = business.GivingGroup != null ? business.GivingGroup.Name : string.Empty; string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty; History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName); } business.GivingGroup = businessGroup; // GroupMember var groupMemberService = new GroupMemberService(rockContext); int?adultRoleId = new GroupTypeRoleService(rockContext).Queryable() .Where(r => r.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT))) .Select(r => r.Id) .FirstOrDefault(); var groupMember = businessGroup.Members.Where(role => role.GroupRoleId == adultRoleId).FirstOrDefault(); if (groupMember == null) { groupMember = new GroupMember(); businessGroup.Members.Add(groupMember); // If we're in here, then this is a new business. // Add the known relationship and implied relationship GroupMember entries. var knownRelationshipGroupMember = new GroupMember(); knownRelationshipGroupMember.Person = business; knownRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()).Id; knownRelationshipGroupMember.GroupId = knownRelationshipGroup.Id; knownRelationshipGroup.Members.Add(knownRelationshipGroupMember); var impliedRelationshipGroupMember = new GroupMember(); impliedRelationshipGroupMember.Person = business; impliedRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()).Id; impliedRelationshipGroupMember.GroupId = impliedRelationshipGroup.Id; impliedRelationshipGroup.Members.Add(impliedRelationshipGroupMember); } groupMember.Person = business; groupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; // GroupLocation & Location var groupLocationService = new GroupLocationService(rockContext); var groupLocation = businessGroup.GroupLocations.FirstOrDefault(); if (groupLocation == null) { groupLocation = new GroupLocation(); businessGroup.GroupLocations.Add(groupLocation); } groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id; var locationService = new LocationService(rockContext); var location = groupLocation.Location; if (location == null) { location = new Location(); groupLocation.Location = location; } location.Street1 = tbStreet1.Text.Trim(); location.Street2 = tbStreet2.Text.Trim(); location.City = tbCity.Text.Trim(); location.State = ddlState.SelectedValue; location.Zip = tbZipCode.Text.Trim(); rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); // Set the Known Relationships between the Owner and the Business. if (ppOwner.PersonId != null) { SetOwner(business); } }); NavigateToParentPage(); }
/// <summary> /// Gets the attendees. /// </summary> private IList <RosterAttendee> GetAttendees(RockContext rockContext) { var startDateTime = RockDateTime.Today; CampusCache campusCache = GetCampusFromContext(); DateTime currentDateTime; if (campusCache != null) { currentDateTime = campusCache.CurrentDateTime; } else { currentDateTime = RockDateTime.Now; } // Get all Attendance records for the current day and location var attendanceQuery = new AttendanceService(rockContext).Queryable().Where(a => a.StartDateTime >= startDateTime && a.DidAttend == true && a.StartDateTime <= currentDateTime && a.PersonAliasId.HasValue && a.Occurrence.GroupId.HasValue && a.Occurrence.ScheduleId.HasValue && a.Occurrence.LocationId.HasValue && a.Occurrence.ScheduleId.HasValue); if (campusCache != null) { // limit locations (rooms) to locations within the selected campus var campusLocationIds = new LocationService(rockContext).GetAllDescendentIds(campusCache.LocationId.Value).ToList(); attendanceQuery = attendanceQuery.Where(a => campusLocationIds.Contains(a.Occurrence.LocationId.Value)); } var selectedScheduleIds = lbSchedules.SelectedValues.AsIntegerList().Where(a => a > 0).ToList(); var selectedGroupIds = GetSelectedGroupIds(); if (selectedScheduleIds.Any()) { attendanceQuery = attendanceQuery.Where(a => selectedScheduleIds.Contains(a.Occurrence.ScheduleId.Value)); } if (selectedGroupIds.Any()) { if (cbIncludeChildGroups.Checked) { var groupService = new GroupService(rockContext); foreach (var groupId in selectedGroupIds.ToList()) { var childGroupIds = groupService.GetAllDescendentGroupIds(groupId, false); selectedGroupIds.AddRange(childGroupIds); } } attendanceQuery = attendanceQuery.Where(a => selectedGroupIds.Contains(a.Occurrence.GroupId.Value)); } else { var checkinAreaFilter = CheckinManagerHelper.GetCheckinAreaFilter(this); if (checkinAreaFilter != null) { // if there is a checkin area filter, limit to groups within the selected check-in area var checkinAreaGroupTypeIds = new GroupTypeService(rockContext).GetCheckinAreaDescendants(checkinAreaFilter.Id).Select(a => a.Id).ToList(); selectedGroupIds = new GroupService(rockContext).Queryable().Where(a => checkinAreaGroupTypeIds.Contains(a.GroupTypeId)).Select(a => a.Id).ToList(); attendanceQuery = attendanceQuery.Where(a => selectedGroupIds.Contains(a.Occurrence.GroupId.Value)); } } RosterStatusFilter rosterStatusFilter = this.GetAttributeValue(AttributeKey.FilterBy).ConvertToEnumOrNull <RosterStatusFilter>() ?? RosterStatusFilter.CheckedIn; attendanceQuery = CheckinManagerHelper.FilterByRosterStatusFilter(attendanceQuery, rosterStatusFilter); var attendanceList = RosterAttendeeAttendance.Select(attendanceQuery).ToList(); attendanceList = CheckinManagerHelper.FilterByActiveCheckins(currentDateTime, attendanceList); attendanceList = attendanceList.Where(a => a.Person != null).ToList(); if (tbSearch.Text.IsNotNullOrWhiteSpace()) { // search by name var searchValue = tbSearch.Text; // ignore the result of reversed (LastName, FirstName vs FirstName LastName bool reversed; var personIds = new PersonService(rockContext) .GetByFullName(searchValue, false, false, false, out reversed) .AsNoTracking() .Select(a => a.Id) .ToList(); attendanceList = attendanceList.Where(a => personIds.Contains(a.PersonId)).ToList(); } var attendees = RosterAttendee.GetFromAttendanceList(attendanceList); return(attendees); }
/// <summary> /// Loads the groups. /// </summary> private void LoadDropDowns() { var groupEntityType = EntityTypeCache.Read(typeof(Group)); var currentGroup = RockPage.GetCurrentContext(groupEntityType) as Group; var groupIdString = Request.QueryString["groupId"]; if (groupIdString != null) { var groupId = groupIdString.AsInteger(); if (currentGroup == null || currentGroup.Id != groupId) { currentGroup = SetGroupContext(groupId, false); } } var parts = (GetAttributeValue("GroupFilter") ?? string.Empty).Split('|'); Guid?groupTypeGuid = null; Guid?rootGroupGuid = null; if (parts.Length >= 1) { groupTypeGuid = parts[0].AsGuidOrNull(); if (parts.Length >= 2) { rootGroupGuid = parts[1].AsGuidOrNull(); } } var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); IQueryable <Group> qryGroups = null; // if rootGroup is set, use that as the filter. Otherwise, use GroupType as the filter if (rootGroupGuid.HasValue) { var rootGroup = groupService.Get(rootGroupGuid.Value); if (rootGroup != null) { qryGroups = groupService.GetAllDescendents(rootGroup.Id).AsQueryable(); } } else if (groupTypeGuid.HasValue) { SetGroupTypeContext(groupTypeGuid); if (GetAttributeValue("IncludeGroupTypeChildren").AsBoolean()) { var childGroupTypeGuids = groupTypeService.Queryable().Where(t => t.ParentGroupTypes.Select(p => p.Guid).Contains(groupTypeGuid.Value)) .Select(t => t.Guid).ToList(); qryGroups = groupService.Queryable().Where(a => childGroupTypeGuids.Contains(a.GroupType.Guid)); } else { qryGroups = groupService.Queryable().Where(a => a.GroupType.Guid == groupTypeGuid.Value); } } if (GetAttributeValue("RespectCampusContext").AsBoolean()) { var campusContext = RockPage.GetCurrentContext(EntityTypeCache.Read(typeof(Campus))); if (campusContext != null) { qryGroups = qryGroups.Where(g => g.CampusId == campusContext.Id); } } // no results if (qryGroups == null) { nbSelectGroupTypeWarning.Visible = true; lCurrentSelection.Text = string.Empty; rptGroups.Visible = false; } else { nbSelectGroupTypeWarning.Visible = false; rptGroups.Visible = true; lCurrentSelection.Text = currentGroup != null?currentGroup.ToString() : GetAttributeValue("NoGroupText"); var groupList = qryGroups.OrderBy(a => a.Name).ToList() .Select(a => new GroupItem() { Name = a.Name, Id = a.Id }) .ToList(); // check if the group can be unselected if (!string.IsNullOrEmpty(GetAttributeValue("ClearSelectionText"))) { var blankGroup = new GroupItem { Name = GetAttributeValue("ClearSelectionText"), Id = Rock.Constants.All.Id }; groupList.Insert(0, blankGroup); } rptGroups.DataSource = groupList; rptGroups.DataBind(); } }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var groupService = new GroupService(rockContext); var groupLocationQry = groupLocationService.Queryable(); var templateGroupPaths = new Dictionary <int, List <GroupTypePath> >(); var currentAndDescendantGroupTypeIds = new List <int>(); foreach (var groupType in groupTypeService.Queryable().Where(a => this.CurrentGroupTypeIds.Contains(a.Id))) { foreach (var parentGroupType in groupType.ParentGroupTypes) { if (!templateGroupPaths.ContainsKey(parentGroupType.Id)) { templateGroupPaths.Add(parentGroupType.Id, groupTypeService.GetAllAssociatedDescendentsPath(parentGroupType.Id).ToList()); } } currentAndDescendantGroupTypeIds.Add(groupType.Id); currentAndDescendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(groupType.Id).Select(a => a.Id).ToList()); } var groupPaths = new List <GroupTypePath>(); foreach (var path in templateGroupPaths) { groupPaths.AddRange(path.Value); } groupLocationQry = groupLocationQry.Where(a => currentAndDescendantGroupTypeIds.Contains(a.Group.GroupTypeId)); groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name); List <int> currentDeviceLocationIdList = this.GetGroupTypesLocations(rockContext).Select(a => a.Id).Distinct().ToList(); var qryList = groupLocationQry .Where(a => currentDeviceLocationIdList.Contains(a.LocationId)) .Select(a => new { GroupLocationId = a.Id, a.Location, GroupId = a.GroupId, GroupName = a.Group.Name, ScheduleIdList = a.Schedules.Select(s => s.Id), GroupTypeId = a.Group.GroupTypeId }).ToList(); var locationService = new LocationService(rockContext); // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add("GroupLocationId"); dataTable.Columns.Add("GroupId"); dataTable.Columns.Add("GroupName"); dataTable.Columns.Add("GroupPath"); dataTable.Columns.Add("LocationName"); dataTable.Columns.Add("LocationPath"); foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { dataTable.Columns.Add(field.DataField, typeof(bool)); } var locationPaths = new Dictionary <int, string>(); foreach (var row in qryList) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = groupService.GroupAncestorPathName(row.GroupId); dataRow["GroupPath"] = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault(); dataRow["LocationName"] = row.Location.Name; if (row.Location.ParentLocationId.HasValue) { int locationId = row.Location.ParentLocationId.Value; if (!locationPaths.ContainsKey(locationId)) { var locationNames = new List <string>(); var parentLocation = locationService.Get(locationId); while (parentLocation != null) { locationNames.Add(parentLocation.Name); parentLocation = parentLocation.ParentLocation; } if (locationNames.Any()) { locationNames.Reverse(); locationPaths.Add(locationId, locationNames.AsDelimited(" > ")); } else { locationPaths.Add(locationId, string.Empty); } } dataRow["LocationPath"] = locationPaths[locationId]; } foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>()) { int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty)); dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId); } dataTable.Rows.Add(dataRow); } gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Get <GroupLocation>().Id; gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Gets the entity type qualifier value by searching the foreign key. /// </summary> /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param> /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public static string GetEntityTypeQualifierValue(string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null) { rockContext = rockContext ?? new RockContext(); var id = entityTypeQualifierValue; switch (entityTypeQualifierColumn) { case "ConnectionTypeId": var connectionType = new ConnectionTypeService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (connectionType != null) { id = connectionType.Id.ToString(); } break; case "ContentChannelId": var contentChannel = new ContentChannelService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (contentChannel != null) { id = contentChannel.Id.ToString(); } break; case "ContentChannelTypeId": var contentChannelType = new ContentChannelTypeService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (contentChannelType != null) { id = contentChannelType.Id.ToString(); } break; case "DefinedTypeId": var definedType = new DefinedTypeService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (definedType != null) { id = definedType.Id.ToString(); } break; case "GroupId": var group = new GroupService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (group != null) { id = group.Id.ToString(); } break; case "GroupTypeId": var groupType = new GroupTypeService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase)); if (groupType != null) { id = groupType.Id.ToString(); } break; } return(id); }