/// <summary> /// Показать окно предпросмотра отчета /// </summary> /// <param name="reportController">Контроллер</param> /// <param name="reportContainerHandle">Дескриптор</param> /// <param name="parametersObject">Объект параметров</param> /// <param name="criteria">Критерий</param> /// <param name="canApplyCriteria">Можно ли применить критерий</param> /// <param name="sortProperty">Сортировка</param> /// <param name="canApplySortProperty">Можно ли применить сортировку</param> /// <param name="showViewParameters">Объект DevExpress.ExpressApp.ShowViewParameters</param> public static void ShowPreview(this ReportServiceController reportController, string reportContainerHandle, ReportParametersObjectBase parametersObject, CriteriaOperator criteria, bool canApplyCriteria, SortProperty[] sortProperty, bool canApplySortProperty, ShowViewParameters showViewParameters) { var objectSpace = ReportDataProvider.ReportObjectSpaceProvider.CreateObjectSpace(typeof(ReportDataV2)); Audit.ReportTrail.LogOperation(objectSpace, reportContainerHandle, parametersObject); var type = reportController.GetType().BaseType; var method = type.GetMethod("ShowReportPreview", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(string), typeof(ReportParametersObjectBase), typeof(CriteriaOperator), typeof(bool), typeof(SortProperty[]), typeof(bool), typeof(ShowViewParameters) }, null); if (method != null) { method.Invoke(reportController, new object[] { reportContainerHandle, parametersObject, criteria, canApplyCriteria, sortProperty, canApplySortProperty, showViewParameters }); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { using (var rockContext = new RockContext()) { var qry = new BackgroundCheckService(rockContext) .Queryable("PersonAlias.Person").AsNoTracking() .Where(g => g.PersonAlias != null && g.PersonAlias.Person != null) .Where(g => g.ForeignId == 1); // FirstName string firstName = fRequest.GetUserPreference("First Name"); if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(t => t.PersonAlias.Person.FirstName.StartsWith(firstName) || t.PersonAlias.Person.NickName.StartsWith(firstName)); } // LastName string lastName = fRequest.GetUserPreference("Last Name"); if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(t => t.PersonAlias.Person.LastName.StartsWith(lastName)); } // Request Date Range var drpRequestDates = new DateRangePicker(); drpRequestDates.DelimitedValues = fRequest.GetUserPreference("Request Date Range"); if (drpRequestDates.LowerValue.HasValue) { qry = qry.Where(t => t.RequestDate >= drpRequestDates.LowerValue.Value); } if (drpRequestDates.UpperValue.HasValue) { DateTime upperDate = drpRequestDates.UpperValue.Value.Date.AddDays(1); qry = qry.Where(t => t.RequestDate < upperDate); } // Response Date Range var drpResponseDates = new DateRangePicker(); drpResponseDates.DelimitedValues = fRequest.GetUserPreference("Response Date Range"); if (drpResponseDates.LowerValue.HasValue) { qry = qry.Where(t => t.ResponseDate >= drpResponseDates.LowerValue.Value); } if (drpResponseDates.UpperValue.HasValue) { DateTime upperDate = drpResponseDates.UpperValue.Value.Date.AddDays(1); qry = qry.Where(t => t.ResponseDate < upperDate); } // Record Found string recordFound = fRequest.GetUserPreference("Record Found"); if (!string.IsNullOrWhiteSpace(recordFound)) { if (recordFound == "Yes") { qry = qry.Where(t => t.RecordFound.HasValue && t.RecordFound.Value); } else if (recordFound == "No") { qry = qry.Where(t => t.RecordFound.HasValue && !t.RecordFound.Value); } } List <Rock.Model.BackgroundCheck> items = null; SortProperty sortProperty = gRequest.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Name") { if (sortProperty.Direction == SortDirection.Descending) { items = qry.OrderByDescending(q => q.PersonAlias.Person.LastName).ThenBy(q => q.PersonAlias.Person.FirstName).ToList(); } else { items = qry.OrderBy(q => q.PersonAlias.Person.LastName).ThenBy(q => q.PersonAlias.Person.FirstName).ToList(); } } else { items = qry.Sort(sortProperty).ToList(); } } else { items = qry.OrderByDescending(d => d.RequestDate).ToList(); } gRequest.DataSource = items.Select(b => new BackgroundCheckRow { Name = b.PersonAlias.Person.LastName + ", " + b.PersonAlias.Person.NickName, Id = b.Id, PersonId = b.PersonAlias.PersonId, HasWorkflow = b.WorkflowId.HasValue, RequestDate = b.RequestDate, ResponseDate = b.ResponseDate, RecordFound = b.RecordFound, RecordFoundLabel = b.RecordFound.HasValue ? ( b.RecordFound.Value ? "<span class='label label-warning'>Yes</span>" : "<span class='label label-success'>No</span>") : string.Empty, HasResponseData = !string.IsNullOrWhiteSpace(b.ResponseData), ResponseDocumentText = b.ResponseDocumentId.HasValue ? "<i class='fa fa-file-pdf-o fa-lg'></i>" : "", ResponseDocumentId = b.ResponseDocumentId ?? 0 }).ToList(); gRequest.DataBind(); } }
private void BindPOGrid() { ConfigurePOGrid(); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("PurchaseOrderID", typeof(int)), new DataColumn("VendorName", typeof(string)), new DataColumn("POType", typeof(string)), new DataColumn("Status", typeof(string)), new DataColumn("ItemDetails", typeof(int)), new DataColumn("TotalPayments", typeof(string)), new DataColumn("NoteCount", typeof(int)), new DataColumn("AttachmentCount", typeof(int)) }); SortProperty sortProperty = dgPurchaseOrders.SortProperty; if (GetUserPreferences(PersonSettingKeyPrefix).Count() > 0) { var POListItems = PurchaseOrder.GetPurchaseOrderList(BuildFilter()); // Check User Preferences to see if we have a pre-existing sort property if (sortProperty == null) { sortProperty = new SortProperty(); sortProperty.Direction = GetUserPreference(string.Format("{0}_Sort_Direction", PersonSettingKeyPrefix)) == "ASC" ? SortDirection.Ascending : SortDirection.Descending; sortProperty.Property = GetUserPreference(string.Format("{0}_Sort_Column", PersonSettingKeyPrefix)); if (string.IsNullOrEmpty(sortProperty.Property)) { sortProperty.Property = "PurchaseOrderID"; } } if (sortProperty != null) { try { if (sortProperty.Direction == SortDirection.Ascending) { POListItems = POListItems.OrderBy(r => r.GetType().GetProperty(sortProperty.Property).GetValue(r)).ToList(); } else { POListItems = POListItems.OrderByDescending(r => r.GetType().GetProperty(sortProperty.Property).GetValue(r)).ToList(); } SetUserPreference(string.Format("{0}_Sort_Direction", PersonSettingKeyPrefix), sortProperty.DirectionString); SetUserPreference(string.Format("{0}_Sort_Column", PersonSettingKeyPrefix), sortProperty.Property); } catch (NullReferenceException) { // Just eat this exception } } else { POListItems = POListItems.OrderByDescending(p => p.PurchaseOrderID).ToList(); } foreach (var po in POListItems) { DataRow dr = dt.NewRow(); dr["PurchaseOrderID"] = po.PurchaseOrderID; dr["VendorName"] = po.VendorName; dr["POType"] = po.POType; dr["Status"] = po.Status; dr["ItemDetails"] = po.ItemDetailCount; dr["TotalPayments"] = string.Format("{0:c}", po.TotalPayments); dr["NoteCount"] = po.NoteCount; dr["AttachmentCount"] = po.AttachmentCount; dt.Rows.Add(dr); } } dgPurchaseOrders.DataSource = dt; dgPurchaseOrders.DataBind(); if (sortProperty != null) { foreach (var column in dgPurchaseOrders.Columns) { var dcf = column as DataControlField; if (dcf != null && dcf.SortExpression == sortProperty.Property) { dgPurchaseOrders.HeaderRow.Cells[dgPurchaseOrders.Columns.IndexOf(dcf)].AddCssClass(sortProperty.Direction.ToString().ToLower()); break; } } if (dgPurchaseOrders.SortProperty == null) { dgPurchaseOrders.Sort(sortProperty.Property, sortProperty.Direction); } } }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGroupMembersGrid(bool selectAll = false) { if (_group != null) { pnlGroupMembers.Visible = true; lHeading.Text = string.Format("{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize()); if (_group.GroupType.Roles.Any()) { nbRoleWarning.Visible = false; rFilter.Visible = true; gGroupMembers.Visible = true; var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService(rockContext); var qry = groupMemberService.Queryable("Person,GroupRole", true).AsNoTracking() .Where(m => m.GroupId == _group.Id); // Filter by First Name string firstName = tbFirstName.Text; if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(m => m.Person.FirstName.StartsWith(firstName)); } // Filter by Last Name string lastName = tbLastName.Text; if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(m => m.Person.LastName.StartsWith(lastName)); } // Filter by role var validGroupTypeRoles = _group.GroupType.Roles.Select(r => r.Id).ToList(); var roles = new List <int>(); foreach (string role in cblRole.SelectedValues) { if (!string.IsNullOrWhiteSpace(role)) { int roleId = int.MinValue; if (int.TryParse(role, out roleId) && validGroupTypeRoles.Contains(roleId)) { roles.Add(roleId); } } } if (roles.Any()) { qry = qry.Where(m => roles.Contains(m.GroupRoleId)); } // Filter by Status var statuses = new List <GroupMemberStatus>(); foreach (string status in cblStatus.SelectedValues) { if (!string.IsNullOrWhiteSpace(status)) { statuses.Add(status.ConvertToEnum <GroupMemberStatus>()); } } if (statuses.Any()) { qry = qry.Where(m => statuses.Contains(m.GroupMemberStatus)); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); SortProperty sortProperty = gGroupMembers.SortProperty; bool hasGroupRequirements = new GroupRequirementService(rockContext).Queryable().Where(a => a.GroupId == _group.Id).Any(); // If there are group requirements that that member doesn't meet, show an icon in the grid bool includeWarnings = false; var groupMemberIdsThatLackGroupRequirements = new GroupService(rockContext).GroupMembersNotMeetingRequirements(_group.Id, includeWarnings).Select(a => a.Key.Id); List <GroupMember> groupMembersList = null; if (sortProperty != null) { groupMembersList = qry.Sort(sortProperty).ToList(); } else { groupMembersList = qry.OrderBy(a => a.GroupRole.Order).ThenBy(a => a.Person.LastName).ThenBy(a => a.Person.FirstName).ToList(); } // Since we're not binding to actual group member list, but are using AttributeField columns, // we need to save the workflows into the grid's object list gGroupMembers.ObjectList = new Dictionary <string, object>(); groupMembersList.ForEach(m => gGroupMembers.ObjectList.Add(m.Id.ToString(), m)); gGroupMembers.EntityTypeId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id; var homePhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); var cellPhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE); // If exporting to Excel, the selectAll option will be true, and home location should be calculated var homeLocations = new Dictionary <int, Location>(); if (selectAll) { foreach (var m in groupMembersList) { homeLocations.Add(m.Id, m.Person.GetHomeLocation(rockContext)); } } gGroupMembers.DataSource = groupMembersList .ToList().Select(m => new { m.Id, m.Guid, m.PersonId, Name = m.Person.NickName + " " + m.Person.LastName + (hasGroupRequirements && groupMemberIdsThatLackGroupRequirements.Contains(m.Id) ? " <i class='fa fa-exclamation-triangle text-warning'></i>" : string.Empty) + (!string.IsNullOrEmpty(m.Note) ? " <i class='fa fa-file-text-o text-info'></i>" : string.Empty), Email = m.Person.Email, HomePhone = homePhoneType != null ? m.Person.PhoneNumbers .Where(p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == homePhoneType.Id) .Select(p => p.NumberFormatted) .FirstOrDefault() : string.Empty, CellPhone = cellPhoneType != null ? m.Person.PhoneNumbers .Where(p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == cellPhoneType.Id) .Select(p => p.NumberFormatted) .FirstOrDefault() : string.Empty, HomeAddress = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].FormattedAddress : string.Empty, Latitude = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].Latitude : (double?)null, Longitude = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].Longitude : (double?)null, GroupRole = m.GroupRole.Name, m.GroupMemberStatus, RecordStatusValueId = m.Person.RecordStatusValueId, IsDeceased = m.Person.IsDeceased }).ToList(); gGroupMembers.DataBind(); } else { nbRoleWarning.Text = string.Format( "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.", _group.GroupType.GroupMemberTerm.Pluralize(), _group.GroupType.GroupTerm, _group.GroupType.Name); nbRoleWarning.Visible = true; rFilter.Visible = false; gGroupMembers.Visible = false; } } else { pnlGroupMembers.Visible = false; } }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindInstancesGrid() { if (_template != null) { pnlInstances.Visible = true; lHeading.Text = string.Format("{0} Instances", _template.Name); var rockContext = new RockContext(); RegistrationInstanceService instanceService = new RegistrationInstanceService(rockContext); var qry = instanceService.Queryable().AsNoTracking() .Where(i => i.RegistrationTemplateId == _template.Id); // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = rFilter.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(i => i.StartDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(i => i.StartDateTime < upperDate); } string statusFilter = rFilter.GetUserPreference("Active Status"); if (!string.IsNullOrWhiteSpace(statusFilter)) { if (statusFilter == "inactive") { qry = qry.Where(i => i.IsActive == false); } else { qry = qry.Where(i => i.IsActive == true); } } SortProperty sortProperty = gInstances.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(a => a.StartDateTime); } var instanceQry = qry.Select(i => new { i.Id, i.Guid, i.Name, i.StartDateTime, i.EndDateTime, i.IsActive, Details = string.Empty, Registrants = i.Registrations.SelectMany(r => r.Registrants).Count() }); gInstances.SetLinqDataSource(instanceQry); gInstances.DataBind(); } else { pnlInstances.Visible = false; } }
/// <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); } int[] registrationInstanceIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("RegistrationInstances"))) { registrationInstanceIds = Array.ConvertAll(GetAttributeValue("RegistrationInstances").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); var group = new GroupService(rockContext).Get(bbGroup); 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(personAliasService.Queryable(), obj => obj.PersonId, pa => pa.PersonId, (obj, pa) => new { GroupMember = obj, PersonAlias = pa } ) .Join(registrationRegistrantService.Queryable(), obj => obj.PersonAlias.Id, rr => rr.PersonAliasId, (obj, rr) => new { GroupMember = obj.GroupMember, Person = obj.GroupMember.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 */ }) .Where(obj => registrationInstanceIds.Contains(obj.RegistrationRegistrant.Registration.RegistrationInstanceId)); 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)) { CampusCache campus = CampusCache.Read(cmpCampus.SelectedCampusId.Value); qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampus" && ra.Value.Contains(campus.Name.Replace(" ", ""))).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> /// Gets the data to display. /// </summary> private void GetData() { var rockContext = new RockContext(); var itemService = new ContentChannelItemService(rockContext); // Get all of the content channels var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType").AsNoTracking(); List <Guid> contentChannelGuidsFilter = GetAttributeValue(AttributeKey.ContentChannelsFilter).SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue(AttributeKey.ContentChannelTypesInclude).SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue(AttributeKey.ContentChannelTypesExclude).SplitDelimitedValues().AsGuidList(); if (contentChannelGuidsFilter.Any()) { // if contentChannelGuidsFilter is specified, only get those content channels. // NOTE: This take precedence over all the other Include/Exclude settings. contentChannelsQry = contentChannelsQry.Where(a => contentChannelGuidsFilter.Contains(a.Guid)); } else if (contentChannelTypeGuidsInclude.Any()) { // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precedence and the excluded ones would already not be included contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid) || a.ContentChannelType.ShowInChannelList); } else if (contentChannelTypeGuidsExclude.Any()) { contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid) && a.ContentChannelType.ShowInChannelList); } else { contentChannelsQry = contentChannelsQry.Where(a => a.ContentChannelType.ShowInChannelList); } if (GetAttributeValue(AttributeKey.ShowCategoryFilter).AsBoolean()) { var categoryId = ddlCategory.SelectedValueAsId(); var parentCategoryGuid = GetAttributeValue(AttributeKey.ParentCategory).AsGuidOrNull(); if (ddlCategory.Visible && categoryId.HasValue) { contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.Id == categoryId)); } else if (parentCategoryGuid.HasValue) { var parentCategoryId = CategoryCache.GetId(parentCategoryGuid.Value); contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.ParentCategoryId == parentCategoryId)); } } var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList(); // Create variable for storing authorized channels and the count of active items var channelCounts = new Dictionary <int, int>(); foreach (var channel in contentChannelsList) { if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson)) { channelCounts.Add(channel.Id, 0); } } // Get the pending approval item counts for each channel (if the channel requires approval) itemService.Queryable() .Where(i => channelCounts.Keys.Contains(i.ContentChannelId) && i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval) .GroupBy(i => i.ContentChannelId) .Select(i => new { Id = i.Key, Count = i.Count() }) .ToList() .ForEach(i => channelCounts[i.Id] = i.Count); // Create a query to return channel, the count of items, and the selected class var qry = contentChannelsList .Where(c => channelCounts.Keys.Contains(c.Id)) .Select(c => new { Channel = c, Count = channelCounts[c.Id], Class = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : "" }); // If displaying active only, update query to exclude those content channels without any items if (tglStatus.Checked) { qry = qry.Where(c => c.Count > 0); } var contentChannels = qry.ToList(); rptChannels.DataSource = contentChannels; rptChannels.DataBind(); ContentChannel selectedChannel = null; if (SelectedChannelId.HasValue) { selectedChannel = contentChannelsList .Where(w => w.Id == SelectedChannelId.Value && channelCounts.Keys.Contains(SelectedChannelId.Value)) .FirstOrDefault(); } if (selectedChannel != null && contentChannels.Count > 0) { // show the content item panel divItemPanel.Visible = true; BindAttributes(selectedChannel); AddDynamicControls(selectedChannel); bool isFiltered = false; var items = GetItems(rockContext, selectedChannel, out isFiltered); var reorderFieldColumn = gContentChannelItems.ColumnsOfType <ReorderField>().FirstOrDefault(); if (selectedChannel.ItemsManuallyOrdered && !isFiltered) { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = true; } gContentChannelItems.AllowSorting = false; } else { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = false; } gContentChannelItems.AllowSorting = true; SortProperty sortProperty = gContentChannelItems.SortProperty; if (sortProperty != null) { items = items.AsQueryable().Sort(sortProperty).ToList(); } else { items = items.OrderByDescending(p => p.StartDateTime).ToList(); } } // Find any possible tags for the items var itemTags = new Dictionary <Guid, string>(); if (selectedChannel.IsTaggingEnabled) { itemTags = items.ToDictionary(i => i.Guid, v => ""); var entityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.CONTENT_CHANNEL_ITEM.AsGuid()).Id; var testedTags = new Dictionary <int, string>(); foreach (var taggedItem in new TaggedItemService(rockContext) .Queryable().AsNoTracking() .Where(i => i.EntityTypeId == entityTypeId && itemTags.Keys.Contains(i.EntityGuid)) .OrderBy(i => i.Tag.Name)) { if (!testedTags.ContainsKey(taggedItem.TagId)) { testedTags.Add(taggedItem.TagId, taggedItem.Tag.IsAuthorized(Authorization.VIEW, CurrentPerson) ? taggedItem.Tag.Name : string.Empty); } if (testedTags[taggedItem.TagId].IsNotNullOrWhiteSpace()) { itemTags[taggedItem.EntityGuid] += string.Format("<span class='tag'>{0}</span>", testedTags[taggedItem.TagId]); } } } gContentChannelItems.ObjectList = new Dictionary <string, object>(); items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i)); var gridList = items.Select(i => new { i.Id, i.Guid, i.Title, i.StartDateTime, i.ExpireDateTime, i.Priority, Status = DisplayStatus(i.Status), Tags = itemTags.GetValueOrNull(i.Guid), Occurrences = i.EventItemOccurrences.Any(), CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty }).ToList(); // only show the Event Occurrences item if any of the displayed content channel items have any occurrences (and the block setting is enabled) var eventOccurrencesColumn = gContentChannelItems.ColumnsWithDataField("Occurrences").FirstOrDefault(); eventOccurrencesColumn.Visible = gridList.Any(a => a.Occurrences == true); gContentChannelItems.DataSource = gridList; gContentChannelItems.DataBind(); lContentChannelItems.Text = selectedChannel.Name + " Items"; } else { divItemPanel.Visible = false; } }
public XPCursor GetCursor(int pagesize) { SortingCollection sortingCollection = Sorting; var sortProperties = new SortProperty[Sorting.Count]; for (int i = 0; i < sortProperties.Length; i++) sortProperties[i] = sortingCollection[i]; var xpCursor = new XPCursor(Session, ObjectType, Criteria, sortProperties) {PageSize = pagesize}; return xpCursor; }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGrid() { if (_group != null) { lHeading.Text = _group.Name; DateTime? fromDateTime = drpDates.LowerValue; DateTime? toDateTime = drpDates.UpperValue; List <int> locationIds = new List <int>(); List <int> scheduleIds = new List <int>(); // Location Filter if (ddlLocation.Visible) { string locValue = ddlLocation.SelectedValue; if (locValue.StartsWith("P")) { int?parentLocationId = locValue.Substring(1).AsIntegerOrNull(); if (parentLocationId.HasValue) { locationIds = new LocationService(_rockContext) .GetAllDescendents(parentLocationId.Value) .Select(l => l.Id) .ToList(); } } else { int?locationId = locValue.AsIntegerOrNull(); if (locationId.HasValue) { locationIds.Add(locationId.Value); } } } // Schedule Filter if (ddlSchedule.Visible && ddlSchedule.SelectedValue != "0") { scheduleIds.Add(ddlSchedule.SelectedValueAsInt() ?? 0); } var qry = new ScheduleService(_rockContext) .GetGroupOccurrences(_group, fromDateTime, toDateTime, locationIds, scheduleIds, true, bddlCampus.SelectedValueAsInt()) .AsQueryable(); SortProperty sortProperty = gOccurrences.SortProperty; List <ScheduleOccurrence> occurrences = null; if (sortProperty != null) { occurrences = qry.Sort(sortProperty).ToList(); } else { occurrences = qry.OrderByDescending(a => a.Date).ThenByDescending(a => a.StartTime).ToList(); } gOccurrences.DataSource = occurrences; gOccurrences.DataBind(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var personAliasEntityType = EntityTypeCache.Read("Rock.Model.PersonAlias"); if (personAliasEntityType != null && CurrentPersonAlias != null) { var rockContext = new RockContext(); // PersonAlias query for joining the followed entity id to var personAliasQry = new PersonAliasService(rockContext).Queryable(); // Get all the people that the current person currently follows var followedPersonIds = new FollowingService(rockContext).Queryable() .Where(f => f.EntityTypeId == personAliasEntityType.Id && f.PersonAliasId == CurrentPersonAlias.Id) .Join(personAliasQry, s => s.EntityId, p => p.Id, (s, p) => p.PersonId) .Distinct(); // Get all the person suggestions for the current person that they are not already following var qry = new FollowingSuggestedService(rockContext) .Queryable("SuggestionType") .Where(s => s.SuggestionType != null && s.EntityTypeId == personAliasEntityType.Id && s.PersonAliasId == CurrentPersonAlias.Id) .Join(personAliasQry, s => s.EntityId, p => p.Id, (s, p) => new { s, p }) .Where(j => !followedPersonIds.Contains(j.p.PersonId)) .Select(j => new { j.s.Id, j.s.LastPromotedDateTime, j.s.StatusChangedDateTime, j.s.SuggestionType.ReasonNote, j.s.Status, Person = j.p.Person, LastName = j.p.Person.LastName, NickName = j.p.Person.NickName }); // Sort the result SortProperty sortProperty = gSuggestions.SortProperty; if (sortProperty == null) { sortProperty = new SortProperty(new GridViewSortEventArgs("LastName,NickName", SortDirection.Ascending)); } // Bind grid to the query gSuggestions.DataSource = qry.Sort(sortProperty) .Select(s => new { s.Id, s.LastPromotedDateTime, s.StatusChangedDateTime, s.ReasonNote, s.Status, StatusLabel = s.Status == FollowingSuggestedStatus.Ignored ? "<span class='label label-warning'>Ignored</span>" : "<span class='label label-success'>Suggested</span>", s.Person, s.LastName, s.NickName }) .ToList(); gSuggestions.DataBind(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var queryable = new FinancialTransactionService().Queryable(); // Set up the selection filter if (_batch != null) { // If transactions are for a batch, the filter is hidden so only check the batch id queryable = queryable.Where(t => t.BatchId.HasValue && t.BatchId.Value == _batch.Id); } else { // otherwise set the selection based on filter settings if (_person != null) { queryable = queryable.Where(t => t.AuthorizedPersonId == _person.Id); } // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = rFilter.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { queryable = queryable.Where(t => t.TransactionDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); queryable = queryable.Where(t => t.TransactionDateTime < upperDate); } // Amount Range var nre = new NumberRangeEditor(); nre.DelimitedValues = rFilter.GetUserPreference("Amount Range"); if (nre.LowerValue.HasValue) { queryable = queryable.Where(t => t.Amount >= nre.LowerValue.Value); } if (nre.UpperValue.HasValue) { queryable = queryable.Where(t => t.Amount <= nre.UpperValue.Value); } // Transaction Code string transactionCode = rFilter.GetUserPreference("Transaction Code"); if (!string.IsNullOrWhiteSpace(transactionCode)) { queryable = queryable.Where(t => t.TransactionCode == transactionCode.Trim()); } // Account Id int accountId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Account"), out accountId)) { queryable = queryable.Where(t => t.TransactionDetails.Any(d => d.AccountId == accountId)); } // Transaction Type int transactionTypeId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Transaction Type"), out transactionTypeId)) { queryable = queryable.Where(t => t.TransactionTypeValueId == transactionTypeId); } // Currency Type int currencyTypeId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Currency Type"), out currencyTypeId)) { queryable = queryable.Where(t => t.CurrencyTypeValueId == currencyTypeId); } // Credit Card Type int creditCardTypeId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Credit Card Type"), out creditCardTypeId)) { queryable = queryable.Where(t => t.CreditCardTypeValueId == creditCardTypeId); } // Source Type int sourceTypeId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Source Type"), out sourceTypeId)) { queryable = queryable.Where(t => t.SourceTypeValueId == sourceTypeId); } } SortProperty sortProperty = rGridTransactions.SortProperty; if (sortProperty != null) { queryable = queryable.Sort(sortProperty); } else { queryable = queryable.OrderBy(t => t.TransactionDateTime); } rGridTransactions.DataSource = queryable.AsNoTracking().ToList(); rGridTransactions.DataBind(); }
/// <summary> /// Вызов приватного метода ReportServiceController.ShowReportPreview() /// Public Morozov /// </summary> /// <param name="reportContainerHandle"></param> /// <param name="parametersObject"></param> /// <param name="criteria"></param> /// <param name="canApplyCriteria"></param> /// <param name="sortProperty"></param> /// <param name="canApplySortProperty"></param> /// <param name="showViewParameters"></param> private void ShowReportPreview(string reportContainerHandle, ReportParametersObjectBase parametersObject, CriteriaOperator criteria, bool canApplyCriteria, SortProperty[] sortProperty, bool canApplySortProperty, ShowViewParameters showViewParameters) { var reportController = Frame.GetController<ReportServiceController>(); Guard.ArgumentNotNull(reportController, "reportController"); reportController.ShowPreview(reportContainerHandle, parametersObject, criteria, canApplyCriteria, sortProperty, canApplySortProperty, showViewParameters); }
/// <summary> /// Übernimmt die Sortiereinstellungen und sortiert die Daten. /// </summary> /// <param name="sortProp"></param> /// <param name="sortDirectionAsc"></param> public void Sort(SortProperty sortProp, bool sortDirectionAsc) { this.sortProperty = sortProp; this.sortDirectionAsc = sortDirectionAsc; // Das Sortieren der Verzeichnisse ist noch nicht implementiert. SortFiles(); // Sortierkriterien an die Unterverzeichnisse weitergeben. if (this.subDirectories != null) { foreach (DirectoryWrapper dir in this.subDirectories) dir.Sort(sortProp, sortDirectionAsc); } }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGroupMembersGrid() { if (_group != null) { pnlGroupMembers.Visible = true; lHeading.Text = string.Format("{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize()); if (_group.GroupType.Roles.Any()) { nbRoleWarning.Visible = false; rFilter.Visible = true; gGroupMembers.Visible = true; var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService(rockContext); var qry = groupMemberService.Queryable("Person,GroupRole", true) .Where(m => m.GroupId == _group.Id); // Filter by First Name string firstName = tbFirstName.Text; if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(m => m.Person.FirstName.StartsWith(firstName)); } // Filter by Last Name string lastName = tbLastName.Text; if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(m => m.Person.LastName.StartsWith(lastName)); } // Filter by role var validGroupTypeRoles = _group.GroupType.Roles.Select(r => r.Id).ToList(); var roles = new List <int>(); foreach (string role in cblRole.SelectedValues) { if (!string.IsNullOrWhiteSpace(role)) { int roleId = int.MinValue; if (int.TryParse(role, out roleId) && validGroupTypeRoles.Contains(roleId)) { roles.Add(roleId); } } } if (roles.Any()) { qry = qry.Where(m => roles.Contains(m.GroupRoleId)); } // Filter by Status var statuses = new List <GroupMemberStatus>(); foreach (string status in cblStatus.SelectedValues) { if (!string.IsNullOrWhiteSpace(status)) { statuses.Add(status.ConvertToEnum <GroupMemberStatus>()); } } if (statuses.Any()) { qry = qry.Where(m => statuses.Contains(m.GroupMemberStatus)); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); SortProperty sortProperty = gGroupMembers.SortProperty; List <GroupMember> groupMembers = null; if (sortProperty != null) { groupMembers = qry.Sort(sortProperty).ToList(); } else { groupMembers = qry.OrderBy(a => a.GroupRole.Order).ThenBy(a => a.Person.LastName).ThenBy(a => a.Person.FirstName).ToList(); } // Since we're not binding to actual group member list, but are using AttributeField columns, // we need to save the workflows into the grid's object list gGroupMembers.ObjectList = new Dictionary <string, object>(); groupMembers.ForEach(m => gGroupMembers.ObjectList.Add(m.Id.ToString(), m)); gGroupMembers.DataSource = groupMembers.Select(m => new { m.Id, m.Guid, m.PersonId, Name = m.Person.NickName + " " + m.Person.LastName, GroupRole = m.GroupRole.Name, m.GroupMemberStatus }).ToList(); gGroupMembers.DataBind(); } else { nbRoleWarning.Text = string.Format( "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.", _group.GroupType.GroupMemberTerm.Pluralize(), _group.GroupType.GroupTerm, _group.GroupType.Name); nbRoleWarning.Visible = true; rFilter.Visible = false; gGroupMembers.Visible = false; } } else { pnlGroupMembers.Visible = false; } }
private IQueryable <CommunionData> getQuery <T>() { using (var rockContext = new RockContext()) { var workflowService = new WorkflowService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var personService = new PersonService(rockContext); var definedValueService = new DefinedValueService(rockContext); Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid(); Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid(); Guid homeBoundPersonWorkflow = GetAttributeValue("HomeboundPersonWorkflow").AsGuid(); Guid hospitalList = GetAttributeValue("HospitalList").AsGuid(); Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid(); var workflowTypesIdAsStrings = new WorkflowTypeService(rockContext).Queryable() .Where(wt => wt.Guid == hospitalWorkflow || wt.Guid == nursingHomeAdmissionWorkflow || wt.Guid == homeBoundPersonWorkflow ) .ToList() .Select(wf => wf.Id.ToString()) .ToList(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && workflowTypesIdAsStrings.Contains(a.EntityTypeQualifierValue)) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => ( w.WorkflowType.Guid == hospitalWorkflow || w.WorkflowType.Guid == nursingHomeAdmissionWorkflow || w.WorkflowType.Guid == homeBoundPersonWorkflow ) && (w.Status == "Active")); var tqry = wfTmpqry.Join(attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); var qry = tqry.ToList(); List <DefinedValue> facilities = definedValueService.Queryable().Where(dv => dv.DefinedType.Guid == hospitalList || dv.DefinedType.Guid == nursingHomeList).ToList(); facilities.ForEach(h => { h.LoadAttributes(); }); var newQry = qry.Select(w => new CommunionData { Campus = new Func <Campus>(() => { Campus campus = null; AttributeValue personAliasAV = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "PersonToVisit" || av.AttributeKey == "HomeboundPerson").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); if (pa != null) { campus = pa.Person.GetCampus(); } } if (campus == null) { campus = new Campus() { Name = "Unknown" }; } return(campus); })(), Person = GetPerson(personAliasService, w.AttributeValues), Age = GetPerson(personAliasService, w.AttributeValues).Age, Description = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "VisitationRequestDescription" || av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Location = new Func <string>(() => { return(w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "NursingHome" || av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).DefaultIfEmpty("Home").FirstOrDefault()); })(), Address = GetLocation(personService, w.AttributeValues, facilities).Street1 + " " + GetLocation(personService, w.AttributeValues, facilities).Street2, City = GetLocation(personService, w.AttributeValues, facilities).City, State = GetLocation(personService, w.AttributeValues, facilities).State, PostalCode = GetLocation(personService, w.AttributeValues, facilities).PostalCode, FacilityNumber = GetFacilityNumber(personService, w.AttributeValues, facilities), Room = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "AdmitDate" || av.AttributeKey == "StartDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Communion").FirstOrDefault().ValueFormatted }) .Where(o => o.Communion.AsBoolean() && !o.Person.IsDeceased) .OrderBy(a => a.PostalCode) .ThenBy(a => a.Address) .ToList() .AsQueryable(); List <COMMUNION_STATES> states = cblState.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => ( COMMUNION_STATES )int.Parse(i.Value)).ToList(); if (states.Count > 0) { newQry = newQry.Where(o => (states.Contains(COMMUNION_STATES.KY) && o.State == "KY") || (states.Contains(COMMUNION_STATES.IN) && o.State == "IN") || ((states.Contains(COMMUNION_STATES.Other) && o.State != "IN" && o.State != "KY"))); } List <int> campuses = cpCampus.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => int.Parse(i.Value)).ToList(); if (campuses.Count > 0) { newQry = newQry.Where(o => campuses.Contains(o.Campus.Id)); } //AddGridColumns( newQry.FirstOrDefault() ); SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { newQry = newQry.Sort(sortProperty); } return(newQry); } }
private void BindRequisitionGrid() { ConfigureRequisitionGrid(); List <RequisitionListItem> Requisitions = GetRequisitions(); SortProperty sortProperty = dgRequisitions.SortProperty; // Check User Preferences to see if we have a pre-existing sort property if (sortProperty == null) { sortProperty = new SortProperty(); sortProperty.Direction = GetUserPreference(string.Format("{0}_Sort_Direction", PersonSettingsKeyPrefix)) == "ASC"? SortDirection.Ascending: SortDirection.Descending; sortProperty.Property = GetUserPreference(string.Format("{0}_Sort_Column", PersonSettingsKeyPrefix)); if (string.IsNullOrEmpty(sortProperty.Property)) { sortProperty.Property = "DateSubmitted"; } } if (sortProperty != null) { if (sortProperty.Property == "DateSubmitted") { if (sortProperty.Direction == SortDirection.Ascending) { Requisitions = Requisitions.OrderBy(r => r.DateSubmitted).ThenBy(r => r.DateCreated).ToList(); } else { Requisitions = Requisitions.OrderByDescending(r => r.DateSubmitted).ThenByDescending(r => r.DateCreated).ToList(); } } else { if (sortProperty.Direction == SortDirection.Ascending) { Requisitions = Requisitions.OrderBy(r => r.GetType().GetProperty(sortProperty.Property).GetValue(r)).ToList(); } else { Requisitions = Requisitions.OrderByDescending(r => r.GetType().GetProperty(sortProperty.Property).GetValue(r)).ToList(); } } SetUserPreference(string.Format("{0}_Sort_Direction", PersonSettingsKeyPrefix), sortProperty.DirectionString); SetUserPreference(string.Format("{0}_Sort_Column", PersonSettingsKeyPrefix), sortProperty.Property); } else { Requisitions = Requisitions.OrderByDescending(r => r.DateSubmitted).ThenByDescending(r => r.DateCreated).ToList(); } DataTable dt = new DataTable("Requisitions"); dt.Columns.AddRange( new DataColumn[] { new DataColumn("RequisitionID", typeof(int)), new DataColumn("Title", typeof(string)), new DataColumn("RequesterID", typeof(int)), new DataColumn("Requester_Last_First", typeof(string)), new DataColumn("Status", typeof(string)), new DataColumn("RequisitionType", typeof(string)), new DataColumn("ItemCount", typeof(int)), new DataColumn("NoteCount", typeof(int)), new DataColumn("AttachmentCount", typeof(int)), new DataColumn("DateSubmitted", typeof(DateTime)), new DataColumn("IsExpedited", typeof(bool)), new DataColumn("IsApproved", typeof(bool)), new DataColumn("IsAccepted", typeof(bool)) }); var statuses = Requisition.GetStatuses(true); int submittedOrder = statuses.Where(s => s.Value == "Submitted to Purchasing").Select(s => s.Order).FirstOrDefault(); foreach (RequisitionListItem item in Requisitions) { DataRow dr = dt.NewRow(); dr["RequisitionID"] = item.RequisitionID; dr["Title"] = item.Title; dr["RequesterID"] = item.RequesterID; dr["Requester_Last_First"] = item.RequesterLastFirst; dr["Status"] = item.Status; dr["RequisitionType"] = item.RequisitionType; dr["ItemCount"] = item.ItemCount; dr["NoteCount"] = item.NoteCount; dr["AttachmentCount"] = item.AttachmentCount; if (item.DateSubmitted != null && statuses.Where(s => s.Value == item.Status).Select(s => s.Order).FirstOrDefault() >= submittedOrder) { dr["DateSubmitted"] = item.DateSubmitted; } else { dr["DateSubmitted"] = item.DateCreated; } dr["IsExpedited"] = item.IsExpedited; dr["IsApproved"] = item.IsApproved; dr["IsAccepted"] = item.IsAccepted; dt.Rows.Add(dr); } dgRequisitions.DataSource = dt; dgRequisitions.DataBind(); if (sortProperty != null) { foreach (var column in dgRequisitions.Columns) { var dcf = column as DataControlField; if (dcf != null && dcf.SortExpression == sortProperty.Property) { dgRequisitions.HeaderRow.Cells[dgRequisitions.Columns.IndexOf(dcf)].AddCssClass(sortProperty.Direction.ToString().ToLower()); break; } } if (dgRequisitions.SortProperty == null) { dgRequisitions.Sort(sortProperty.Property, sortProperty.Direction); } } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (CurrentPersonAlias != null) { var rockContext = new RockContext(); int personAliasEntityTypeId = EntityTypeCache.Read("Rock.Model.PersonAlias").Id; var personAliasIds = new FollowingService(rockContext).Queryable() .Where(f => f.EntityTypeId == personAliasEntityTypeId && f.PersonAliasId == CurrentPersonAlias.Id) .Select(f => f.EntityId) .Distinct() .ToList(); var qry = new PersonAliasService(rockContext).Queryable() .Where(p => personAliasIds.Contains(p.Id)) .Select(p => p.Person) .Distinct(); // Sort SortProperty sortProperty = gFollowings.SortProperty; if (sortProperty == null) { sortProperty = new SortProperty(new GridViewSortEventArgs("LastName,NickName", SortDirection.Ascending)); } Guid homePhoneGuid = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(); Guid cellPhoneGuid = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(); Guid adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid(); Guid marriedGuid = Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid(); gFollowings.DataSource = qry.Sort(sortProperty) .Select(p => new { Person = p, p.Id, p.LastName, p.NickName, p.BirthDate, p.Email, HomePhone = p.PhoneNumbers .Where(n => n.NumberTypeValue.Guid.Equals(homePhoneGuid)) .Select(n => n.NumberFormatted) .FirstOrDefault(), CellPhone = p.PhoneNumbers .Where(n => n.NumberTypeValue.Guid.Equals(cellPhoneGuid)) .Select(n => n.NumberFormatted) .FirstOrDefault(), Spouse = p.Members .Where(m => p.MaritalStatusValue.Guid.Equals(marriedGuid) && m.GroupRole.Guid.Equals(adultGuid)) .SelectMany(m => m.Group.Members) .Where(m => m.PersonId != p.Id && m.GroupRole.Guid.Equals(adultGuid) && m.Person.MaritalStatusValue.Guid.Equals(marriedGuid)) .Select(s => s.Person) .FirstOrDefault() }).ToList(); gFollowings.DataBind(); } }
void IBindingList.ApplySort(PropertyDescriptor memberDescriptor, ListSortDirection direction) { sorting.Clear(); SortProperty sortProperty = new SortProperty(memberDescriptor.Name, (direction == ListSortDirection.Ascending) ? SortingDirection.Ascending : SortingDirection.Descending); sorting.Add(sortProperty); ClearObjects(); RaiseListChangedEvent(new ListChangedEventArgs(ListChangedType.Reset, 0)); }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { var attendanceService = new AttendanceService(new RockContext()); var attendanceQuery = attendanceService.Queryable(); if (_person != null) { attendanceQuery = attendanceQuery.Where(a => a.PersonId == _person.Id); } else if (_group != null) { attendanceQuery = attendanceQuery.Where(a => a.GroupId == _group.Id); } var attendanceList = attendanceQuery.ToList(); var qry = attendanceList.AsQueryable() .Select(a => new { Location = a.Location, Schedule = a.Schedule, FullName = a.Person.FullName, Group = a.Group, StartDateTime = a.StartDateTime, EndDateTime = a.EndDateTime }); // Filter by Date Range var drp = new DateRangePicker(); drp.DelimitedValues = rFilter.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(t => t.StartDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(t => t.EndDateTime < upperDate); } // Filter by Person if (ddlPeople.SelectedIndex > 0) { if (ddlPeople.SelectedValue.ToLower() != "all") { qry = qry.Where(h => h.FullName == ddlPeople.SelectedValue); } } // Filter by Group if (ddlGroups.SelectedIndex > 0) { if (ddlGroups.SelectedValue.ToLower() != "all") { qry = qry.Where(h => h.Group.Name == ddlGroups.SelectedValue); } } // Filter by Schedule if (ddlSchedules.SelectedIndex > 0) { if (ddlSchedules.SelectedValue.ToLower() != "all") { qry = qry.Where(h => h.Schedule.Name == ddlSchedules.SelectedValue); } } SortProperty sortProperty = gHistory.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(p => p.StartDateTime); } gHistory.DataSource = qry.ToList(); gHistory.DataBind(); }
private List <MedicalItem> GetMedicalItems(bool overrideHideDistributed = false) { RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext); AttributeValueService attributeValueService = new AttributeValueService(rockContext); AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext); NoteService noteService = new NoteService(rockContext); var groupIdStrings = GetAttributeValue("GroupIds").SplitDelimitedValues(); var groupIds = new List <int>(); foreach (var id in groupIdStrings) { groupIds.Add(id.AsInteger()); } var groups = groupService.GetByIds(groupIds); if (cpCampus.SelectedCampusId != null && cpCampus.SelectedCampusId != 0) { groups = groups.Where(g => g.CampusId == cpCampus.SelectedCampusId); } var groupTypeIds = groups.ToList().Select(g => g.GroupTypeId.ToString()).Distinct(); var personEntityid = EntityTypeCache.GetId <Rock.Model.Person>().Value; var groupMemberEntityid = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value; var key = GetAttributeValue("MedicationMatrixKey"); var days = GetAttributeValue(AttributeKey.Days).AsIntegerOrNull() ?? 14; var cutoffDate = Rock.RockDateTime.Today.AddDays(-days); var lastMedicationCheckinAttribute = AttributeCache.Get(Constants.PERSON_ATTRIBUTE_LASTMEDICATIONCHECKIN.AsGuid()); var allowedPersonIds = attributeValueService.GetByAttributeId(lastMedicationCheckinAttribute.Id) .Where(av => av.ValueAsDateTime != null && av.ValueAsDateTime >= cutoffDate) .Select(av => av.EntityId); var groupMembers = groups .SelectMany(g => g.Members) .Where(gm => allowedPersonIds.Contains(gm.PersonId)); AttributeService attributeService = new AttributeService(rockContext); List <int> attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeId == personEntityid && a.Key == key) .Select(a => a.Id).ToList(); if (attributeIds == null) { nbAlert.Visible = true; nbAlert.Text = "Medication attribute not found"; return(null); } List <int> filterAttributeIds = null; var filterAttributeKey = GetAttributeValue("GroupMemberAttributeFilter"); if (!string.IsNullOrWhiteSpace(filterAttributeKey)) { filterAttributeIds = attributeService.Queryable() .Where(a => (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) && a.Key == filterAttributeKey && a.EntityTypeId == groupMemberEntityid) .Select(a => a.Id).ToList(); } var attributeMatrixItemEntityId = EntityTypeCache.GetId <AttributeMatrixItem>(); var qry = groupMembers .Join( attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)), m => m.PersonId, av => av.EntityId.Value, (m, av) => new { Person = m.Person, Member = m, AttributeValue = av.Value } ) .Join( attributeMatrixService.Queryable(), m => m.AttributeValue, am => am.Guid.ToString(), (m, am) => new { Person = m.Person, Member = m.Member, AttributeMatrix = am } ) .Join( attributeMatrixItemService.Queryable(), m => m.AttributeMatrix.Id, ami => ami.AttributeMatrixId, (m, ami) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = ami, TemplateId = ami.AttributeMatrix.AttributeMatrixTemplateId } ) .Join( attributeService.Queryable(), m => new { TemplateIdString = m.TemplateId.ToString(), EntityTypeId = attributeMatrixItemEntityId }, a => new { TemplateIdString = a.EntityTypeQualifierValue, EntityTypeId = a.EntityTypeId }, (m, a) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = m.AttributeMatrixItem, Attribute = a } ) .Join( attributeValueService.Queryable(), m => new { EntityId = m.AttributeMatrixItem.Id, AttributeId = m.Attribute.Id }, av => new { EntityId = av.EntityId ?? 0, AttributeId = av.AttributeId }, (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = av, MatrixItemId = m.AttributeMatrixItem.Id, FilterValue = "" } ); if (filterAttributeIds != null && pnlAttribute.Visible && !string.IsNullOrWhiteSpace(ddlAttribute.SelectedValue)) { var filterValue = ddlAttribute.SelectedValue; qry = qry .Join( attributeValueService.Queryable().Where(av => filterAttributeIds.Contains(av.AttributeId)), m => new { Id = m.Member.Id, Value = filterValue }, av => new { Id = av.EntityId ?? 0, Value = av.Value }, (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = m.AttributeValue, MatrixItemId = m.MatrixItemId, FilterValue = av.Value }); } var members = qry.ToList().GroupBy(a => a.Person).ToList(); var firstDay = (dpDate.SelectedDate ?? Rock.RockDateTime.Today).Date; var nextday = firstDay.AddDays(1); var personIds = members.Select(m => m.Key.Id); var attributeMatrixEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value; var noteType = NoteTypeCache.Get(GetAttributeValue("NoteType").AsGuid()); if (noteType == null) { return(new List <MedicalItem>()); } var noteItems = noteService.Queryable() .Where(n => n.NoteTypeId == noteType.Id) .Where(n => personIds.Contains(n.EntityId ?? 0)) .Where(h => h.CreatedDateTime >= firstDay && h.CreatedDateTime < nextday) .Where(h => h.ForeignId != null) .ToList(); foreach (var member in members) { if (!string.IsNullOrWhiteSpace(tbName.Text) && !member.Key.FullName.ToLower().Contains(tbName.Text.ToLower()) && !member.Key.FullNameReversed.ToLower().Contains(tbName.Text.ToLower())) { continue; } var medicines = member.GroupBy(m => m.MatrixItemId); foreach (var medicine in medicines) { var scheduleAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Schedule"); if (scheduleAtt == null || scheduleAtt.AttributeValue.Value == null) { continue; } var schedules = scheduleAtt.AttributeValue.Value.SplitDelimitedValues(); foreach (var schedule in schedules) { if (ddlSchedule.SelectedValue != "" && ddlSchedule.SelectedValue.AsGuid() != schedule.AsGuid()) { continue; } var medicalItem = new MedicalItem() { Person = member.Key.FullNameReversed, GroupMemberId = member.Key.Id, GroupMember = member.Key.Members.FirstOrDefault(), PersonId = member.Key.Id, FilterAttribute = member.FirstOrDefault().FilterValue, }; if (!string.IsNullOrWhiteSpace(schedule)) { var dv = DefinedValueCache.Get(schedule.AsGuid()); if (dv != null) { medicalItem.Schedule = dv.Value; medicalItem.ScheduleGuid = dv.Guid; } } var medAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Medication"); if (medAtt != null) { medicalItem.Medication = medAtt.AttributeValue.Value; } var instructionAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Instructions"); if (instructionAtt != null) { medicalItem.Instructions = instructionAtt.AttributeValue.Value; } medicalItem.Key = string.Format("{0}|{1}|{2}", medicalItem.PersonId, medicine.Key, medicalItem.ScheduleGuid); var notes = noteItems .Where(n => n.EntityId == medicalItem.PersonId && n.ForeignId == medicine.Key && n.ForeignGuid == medicalItem.ScheduleGuid); if (notes.Any()) { medicalItem.Distributed = true; medicalItem.History = string.Join("<br>", notes.Select(n => n.Text)); } medicalItems.Add(medicalItem); } } if (overrideHideDistributed == false && cbHideDistributed.Checked == true) { medicalItems = medicalItems.Where(i => i.Distributed == false).ToList(); } } SortProperty sortProperty = gGrid.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Person") { if (sortProperty.Direction == SortDirection.Ascending) { medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList(); } else { medicalItems = medicalItems.OrderByDescending(mi => mi.Person).ToList(); } } } else { medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList(); gGrid.SortProperty = new SortProperty() { Property = "Person" }; } return(medicalItems); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { BlockTypeService blockTypeService = new BlockTypeService(new RockContext()); SortProperty sortProperty = gBlockTypes.SortProperty; var blockTypes = blockTypeService.Queryable(); // Exclude system blocks if checked. if (!string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Exclude System"))) { blockTypes = blockTypes.Where(b => b.IsSystem == false); } // Filter by Name string nameFilter = gfSettings.GetUserPreference("Name"); if (!string.IsNullOrEmpty(nameFilter.Trim())) { blockTypes = blockTypes.Where(b => b.Name.Contains(nameFilter.Trim())); } // Filter by Path string path = gfSettings.GetUserPreference("Path"); if (!string.IsNullOrEmpty(path.Trim())) { blockTypes = blockTypes.Where(b => b.Path.Contains(path.Trim())); } string category = gfSettings.GetUserPreference("Category"); if (!string.IsNullOrWhiteSpace(category)) { blockTypes = blockTypes.Where(b => b.Category == category); } var selectQry = blockTypes.Select(a => new { a.Id, a.Name, a.Category, a.Description, a.Path, BlocksCount = a.Blocks.Count(), a.IsSystem }); if (sortProperty != null) { if (sortProperty.Property == "Status") { // special case: See if the file exists and sort by that if (sortProperty.Direction == System.Web.UI.WebControls.SortDirection.Ascending) { gBlockTypes.DataSource = selectQry.ToList().OrderBy(a => System.IO.File.Exists(Request.MapPath(a.Path))).ToList(); } else { gBlockTypes.DataSource = selectQry.ToList().OrderBy(a => !System.IO.File.Exists(Request.MapPath(a.Path))).ToList(); } } else { gBlockTypes.DataSource = selectQry.Sort(sortProperty).ToList(); } } else { gBlockTypes.DataSource = selectQry.OrderBy(b => b.Name).ToList(); } gBlockTypes.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (_entity != null) { var entityTypeCache = EntityTypeCache.Get(_entity.GetType(), false); if (entityTypeCache != null) { var rockContext = new RockContext(); var historyService = new HistoryService(rockContext); IQueryable <History> qry; if (entityTypeCache.Id == EntityTypeCache.GetId <Rock.Model.Person>()) { // If this is History for a Person, also include any History for any of their Families int? groupEntityTypeId = EntityTypeCache.GetId <Rock.Model.Group>(); List <int> familyIds = (_entity as Person).GetFamilies().Select(a => a.Id).ToList(); qry = historyService.Queryable().Include(a => a.CreatedByPersonAlias.Person) .Where(h => (h.EntityTypeId == entityTypeCache.Id && h.EntityId == _entity.Id) || (h.EntityTypeId == groupEntityTypeId && familyIds.Contains(h.EntityId))); // as per issue #1594, if relatedEntityType is an Attribute then check View Authorization var attributeEntity = EntityTypeCache.Get(Rock.SystemGuid.EntityType.ATTRIBUTE.AsGuid()); var personAttributes = new AttributeService(rockContext).GetByEntityTypeId(entityTypeCache.Id).ToList().Select(a => AttributeCache.Get(a)); var allowedAttributeIds = personAttributes.Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)).Select(a => a.Id).ToList(); qry = qry.Where(a => (a.RelatedEntityTypeId == attributeEntity.Id) ? allowedAttributeIds.Contains(a.RelatedEntityId.Value) : true); } else { qry = historyService.Queryable().Include(a => a.CreatedByPersonAlias.Person) .Where(h => (h.EntityTypeId == entityTypeCache.Id && h.EntityId == _entity.Id)); } var historyCategories = new CategoryService(rockContext).GetByEntityTypeId(EntityTypeCache.GetId <Rock.Model.History>()).ToList().Select(a => CategoryCache.Get(a)); var allowedCategoryIds = historyCategories.Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)).Select(a => a.Id).ToList(); qry = qry.Where(a => allowedCategoryIds.Contains(a.CategoryId)); int?categoryId = gfSettings.GetUserPreference("Category").AsIntegerOrNull(); if (categoryId.HasValue) { qry = qry.Where(a => a.CategoryId == categoryId.Value); } int?personId = gfSettings.GetUserPreference("Who").AsIntegerOrNull(); if (personId.HasValue) { qry = qry.Where(h => h.CreatedByPersonAlias.PersonId == personId.Value); } var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(h => h.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(h => h.CreatedDateTime < upperDate); } // Combine history records that were saved at the same time var historySummaryList = historyService.GetHistorySummary(qry); string summary = gfSettings.GetUserPreference("Summary Contains"); if (!string.IsNullOrWhiteSpace(summary)) { historySummaryList = historySummaryList.Where(h => h.HistoryList.Any(x => x.SummaryHtml.IndexOf(summary, StringComparison.OrdinalIgnoreCase) >= 0)).ToList(); } SortProperty sortProperty = gHistory.SortProperty; if (sortProperty != null) { historySummaryList = historySummaryList.AsQueryable().Sort(sortProperty).ToList(); } else { historySummaryList = historySummaryList.OrderByDescending(t => t.CreatedDateTime).ToList(); } gHistory.DataSource = historySummaryList; gHistory.EntityTypeId = EntityTypeCache.Get <History>().Id; gHistory.DataBind(); } } }
/// <summary> /// Binds the event calendar items grid. /// </summary> protected void BindEventCalendarItemsGrid() { if (_eventCalendar != null) { pnlEventCalendarItems.Visible = true; var rockContext = new RockContext(); EventCalendarItemService eventCalendarItemService = new EventCalendarItemService(rockContext); var qry = eventCalendarItemService .Queryable("EventCalendar,EventItem.EventItemAudiences,EventItem.EventItemOccurrences.Schedule") .Where(m => m.EventItem != null && m.EventCalendarId == _eventCalendar.Id); // Filter by Status string statusFilter = ddlStatus.SelectedValue; if (statusFilter == "Active") { qry = qry .Where(m => m.EventItem.IsActive); } else if (statusFilter == "Inactive") { qry = qry .Where(m => !m.EventItem.IsActive); } // Filter by Approval Status string approvalStatusFilter = ddlApprovalStatus.SelectedValue; if (approvalStatusFilter == "Approved") { qry = qry .Where(m => m.EventItem.IsApproved); } else if (approvalStatusFilter == "Not Approved") { qry = qry .Where(m => !m.EventItem.IsApproved); } // Filter by Campus List <int> campusIds = cblCampus.SelectedValuesAsInt; if (campusIds.Any()) { qry = qry .Where(i => i.EventItem.EventItemOccurrences .Any(c => !c.CampusId.HasValue || campusIds.Contains(c.CampusId.Value))); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } // Filter by Audience List <int> audiences = cblAudience.SelectedValuesAsInt; if (audiences.Any()) { qry = qry.Where(i => i.EventItem.EventItemAudiences .Any(c => audiences.Contains(c.DefinedValueId))); } SortProperty sortProperty = gEventCalendarItems.SortProperty; // Sort and query db List <EventCalendarItem> eventCalendarItems = null; if (sortProperty != null) { // If sorting on date, wait until after checking to see if date range was specified if (sortProperty.Property == "Date") { eventCalendarItems = qry.ToList(); } else { eventCalendarItems = qry.Sort(sortProperty).ToList(); } } else { eventCalendarItems = qry.OrderBy(a => a.EventItem.Name).ToList(); } // Now that items have been loaded and ordered from db, calculate the next start date for each item var calendarItemsWithDates = eventCalendarItems .Select(i => new EventCalendarItemWithDates { EventCalendarItem = i, NextStartDateTime = i.EventItem.NextStartDateTime, }) .ToList(); var dateCol = gEventCalendarItems.Columns.OfType <BoundField>().Where(c => c.DataField == "Date").FirstOrDefault(); // if a date range was specified, need to get all dates for items and filter based on any that have an occurrence withing the date range DateTime?lowerDateRange = drpDate.LowerValue; DateTime?upperDateRange = drpDate.UpperValue; if (lowerDateRange.HasValue || upperDateRange.HasValue) { // If only one value was included, default the other to be a years difference lowerDateRange = lowerDateRange ?? upperDateRange.Value.AddYears(-1).AddDays(1); upperDateRange = upperDateRange ?? lowerDateRange.Value.AddYears(1).AddDays(-1); // Get the start datetimes within the selected date range calendarItemsWithDates.ForEach(i => i.StartDateTimes = i.EventCalendarItem.EventItem.GetStartTimes(lowerDateRange.Value, upperDateRange.Value.AddDays(1))); // Filter out calendar items with no dates within range calendarItemsWithDates = calendarItemsWithDates.Where(i => i.StartDateTimes.Any()).ToList(); // Update the Next Start Date to be the next date in range instead dateCol.HeaderText = "Next Date In Range"; calendarItemsWithDates.ForEach(i => i.NextStartDateTime = i.StartDateTimes.Min()); } else { dateCol.HeaderText = "Next Start Date"; } // Now sort on date if that is what was selected if (sortProperty != null && sortProperty.Property == "Date") { if (sortProperty.Direction == SortDirection.Ascending) { calendarItemsWithDates = calendarItemsWithDates.OrderBy(a => a.NextStartDateTime).ToList(); } else { calendarItemsWithDates = calendarItemsWithDates.OrderByDescending(a => a.NextStartDateTime).ToList(); } } // Save the calendar items to the grid's objectlist gEventCalendarItems.ObjectList = new Dictionary <string, object>(); calendarItemsWithDates.ForEach(i => gEventCalendarItems.ObjectList.Add(i.EventCalendarItem.EventItem.Id.ToString(), i.EventCalendarItem)); gEventCalendarItems.EntityTypeId = EntityTypeCache.Read("Rock.Model.EventCalendarItem").Id; gEventCalendarItems.DataSource = calendarItemsWithDates.Select(i => new { Id = i.EventCalendarItem.EventItem.Id, Guid = i.EventCalendarItem.EventItem.Guid, Date = i.NextStartDateTime.HasValue ? i.NextStartDateTime.Value.ToShortDateString() : "N/A", Name = i.EventCalendarItem.EventItem.Name, Occurrences = campusIds.Any() ? i.EventCalendarItem.EventItem.EventItemOccurrences.Where(c => !c.CampusId.HasValue || campusIds.Contains(c.CampusId.Value)).Count() : i.EventCalendarItem.EventItem.EventItemOccurrences.Count(), Calendar = i.EventCalendarItem.EventItem.EventCalendarItems.ToList().Select(c => c.EventCalendar.Name).ToList().AsDelimited("<br>"), Audience = i.EventCalendarItem.EventItem.EventItemAudiences.ToList().Select(a => a.DefinedValue.Value).ToList().AsDelimited("<br>"), Status = i.EventCalendarItem.EventItem.IsActive ? "<span class='label label-success'>Active</span>" : "<span class='label label-default'>Inactive</span>", ApprovalStatus = i.EventCalendarItem.EventItem.IsApproved ? "<span class='label label-info'>Approved</span>" : "<span class='label label-warning'>Not Approved</span>" }).ToList(); gEventCalendarItems.DataBind(); } else { pnlEventCalendarItems.Visible = false; } }
/// <summary> /// Binds the registrations grid. /// </summary> private void BindRegistrationsGrid() { int?instanceId = this.RegistrationInstanceId; if (instanceId.HasValue && instanceId > 0) { using (var rockContext = new RockContext()) { var registrationEntityType = EntityTypeCache.Get(typeof(Rock.Model.Registration)); var instance = new RegistrationInstanceService(rockContext).Get(instanceId.Value); if (instance != null) { decimal cost = instance.RegistrationTemplate.Cost; if (instance.RegistrationTemplate.SetCostOnInstance ?? false) { cost = instance.Cost ?? 0.0m; } _instanceHasCost = cost > 0.0m; } var qry = new RegistrationService(rockContext) .Queryable("PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee") .AsNoTracking() .Where(r => r.RegistrationInstanceId == instanceId.Value && !r.IsTemporary); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(sdrpRegistrationDateRange.DelimitedValues); if (dateRange.Start.HasValue) { qry = qry.Where(r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= dateRange.Start.Value); } if (dateRange.End.HasValue) { qry = qry.Where(r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value < dateRange.End.Value); } if (!string.IsNullOrWhiteSpace(tbRegistrationRegisteredByFirstName.Text)) { string pfname = tbRegistrationRegisteredByFirstName.Text; qry = qry.Where(r => r.FirstName.StartsWith(pfname) || r.PersonAlias.Person.NickName.StartsWith(pfname) || r.PersonAlias.Person.FirstName.StartsWith(pfname)); } if (!string.IsNullOrWhiteSpace(tbRegistrationRegisteredByLastName.Text)) { string plname = tbRegistrationRegisteredByLastName.Text; qry = qry.Where(r => r.LastName.StartsWith(plname) || r.PersonAlias.Person.LastName.StartsWith(plname)); } if (!string.IsNullOrWhiteSpace(tbRegistrationRegistrantFirstName.Text)) { string rfname = tbRegistrationRegistrantFirstName.Text; qry = qry.Where(r => r.Registrants.Any(p => p.PersonAlias.Person.NickName.StartsWith(rfname) || p.PersonAlias.Person.FirstName.StartsWith(rfname))); } if (!string.IsNullOrWhiteSpace(tbRegistrationRegistrantLastName.Text)) { string rlname = tbRegistrationRegistrantLastName.Text; qry = qry.Where(r => r.Registrants.Any(p => p.PersonAlias.Person.LastName.StartsWith(rlname))); } // If filtering on payment status, need to do some sub-querying... if (ddlRegistrationPaymentStatus.SelectedValue != string.Empty && registrationEntityType != null) { // Get all the registrant costs var rCosts = new Dictionary <int, decimal>(); qry.ToList() .Select(r => new { RegistrationId = r.Id, DiscountCosts = r.Registrants.Sum(p => ( decimal? )p.DiscountedCost(r.DiscountPercentage, r.DiscountAmount)) ?? 0.0m, }).ToList() .ForEach(c => rCosts.AddOrReplace(c.RegistrationId, c.DiscountCosts)); var rPayments = new Dictionary <int, decimal>(); new FinancialTransactionDetailService(rockContext) .Queryable().AsNoTracking() .Where(d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && rCosts.Keys.Contains(d.EntityId.Value)) .Select(d => new { RegistrationId = d.EntityId.Value, Payment = d.Amount }) .ToList() .GroupBy(d => d.RegistrationId) .Select(d => new { RegistrationId = d.Key, Payments = d.Sum(p => p.Payment) }) .ToList() .ForEach(p => rPayments.AddOrReplace(p.RegistrationId, p.Payments)); var rPmtSummary = rCosts .Join( rPayments, c => c.Key, p => p.Key, (c, p) => new { RegistrationId = c.Key, Costs = c.Value, Payments = p.Value }) .ToList(); var ids = new List <int>(); if (ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full") { ids = rPmtSummary .Where(r => r.Costs <= r.Payments) .Select(r => r.RegistrationId) .ToList(); } else { ids = rPmtSummary .Where(r => r.Costs > r.Payments) .Select(r => r.RegistrationId) .ToList(); } qry = qry.Where(r => ids.Contains(r.Id)); } SortProperty sortProperty = gRegistrations.SortProperty; if (sortProperty != null) { // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering, // and then ordering needs to be done in memory since TotalCost and BalanceDue are not database fields. if (sortProperty.Property == "TotalCost") { if (sortProperty.Direction == SortDirection.Ascending) { gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(r => r.TotalCost).AsQueryable()); } else { gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(r => r.TotalCost).AsQueryable()); } } else if (sortProperty.Property == "BalanceDue") { if (sortProperty.Direction == SortDirection.Ascending) { gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(r => r.BalanceDue).AsQueryable()); } else { gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(r => r.BalanceDue).AsQueryable()); } } else if (sortProperty.Property == "RegisteredBy") { // Sort by the Person name if we have it, otherwise the provided first and last name. Func <Registration, string> sortBy = (r) => { return(r.PersonAlias != null && r.PersonAlias.Person != null ? r.PersonAlias.Person.FullNameReversed : string.Format("{0}, {1}", r.LastName, r.FirstName)); }; if (sortProperty.Direction == SortDirection.Ascending) { gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(sortBy).AsQueryable()); } else { gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(sortBy).AsQueryable()); } } else { gRegistrations.SetLinqDataSource(qry.Sort(sortProperty)); } } else { gRegistrations.SetLinqDataSource(qry.OrderByDescending(r => r.CreatedDateTime)); } // Get all the payments for any registrations being displayed on the current page. // This is used in the RowDataBound event but queried now so that each row does // not have to query for the data. var currentPageRegistrations = gRegistrations.DataSource as List <Registration>; if (currentPageRegistrations != null && registrationEntityType != null) { var registrationIds = currentPageRegistrations .Select(r => r.Id) .ToList(); _registrationPayments = new FinancialTransactionDetailService(rockContext) .Queryable().AsNoTracking() .Where(d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && registrationIds.Contains(d.EntityId.Value)) .ToList(); } var discountCodeHeader = gRegistrations.GetColumnByHeaderText("Discount Code"); if (discountCodeHeader != null) { discountCodeHeader.Visible = GetAttributeValue(AttributeKey.DisplayDiscountCodes).AsBoolean(); } gRegistrations.DataBind(); } } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); int entityTypeIdBlock = EntityTypeCache.Read(typeof(Rock.Model.Block), true, rockContext).Id; string entityTypeQualifier = BlockTypeCache.Read(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid(), rockContext).Id.ToString(); var htmlContentService = new HtmlContentService(rockContext); var attributeValueQry = new AttributeValueService(rockContext).Queryable() .Where(a => a.Attribute.Key == "RequireApproval" && a.Attribute.EntityTypeId == entityTypeIdBlock) .Where(a => a.Attribute.EntityTypeQualifierColumn == "BlockTypeId" && a.Attribute.EntityTypeQualifierValue == entityTypeQualifier) .Where(a => a.Value == "True") .Select(a => a.EntityId); var qry = htmlContentService.Queryable().Where(a => attributeValueQry.Contains(a.BlockId)); // Filter by approved/unapproved if (ddlApprovedFilter.SelectedIndex > -1) { if (ddlApprovedFilter.SelectedValue.ToLower() == "unapproved") { qry = qry.Where(a => a.IsApproved == false); } else if (ddlApprovedFilter.SelectedValue.ToLower() == "approved") { qry = qry.Where(a => a.IsApproved == true); } } // Filter by the person that approved the content if (_canApprove) { int?personId = gContentListFilter.GetUserPreference("Approved By").AsIntegerOrNull(); if (personId.HasValue) { qry = qry.Where(a => a.ApprovedByPersonAliasId.HasValue && a.ApprovedByPersonAlias.PersonId == personId); } } SortProperty sortProperty = gContentList.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(a => a.ModifiedDateTime); } var selectQry = qry.Select(a => new { a.Id, SiteName = a.Block.PageId.HasValue ? a.Block.Page.Layout.Site.Name : a.Block.Layout.Site.Name, PageName = a.Block.Page.InternalName, a.ModifiedDateTime, a.IsApproved, ApprovedDateTime = a.IsApproved ? a.ApprovedDateTime : null, ApprovedByPerson = a.IsApproved ? a.ApprovedByPersonAlias.Person : null, BlockPageId = a.Block.PageId, BlockLayoutId = a.Block.LayoutId, }); gContentList.EntityTypeId = EntityTypeCache.Read <HtmlContent>().Id; // Filter by Site if (ddlSiteFilter.SelectedIndex > 0) { if (ddlSiteFilter.SelectedValue.ToLower() != "all") { selectQry = selectQry.Where(h => h.SiteName == ddlSiteFilter.SelectedValue); } } gContentList.DataSource = selectQry.ToList(); gContentList.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var recordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; var queryable = new PersonService(rockContext).Queryable() .Where(q => q.RecordTypeValueId == recordTypeValueId); // Business Name Filter var businessName = gfBusinessFilter.GetUserPreference("Business Name"); if (!string.IsNullOrWhiteSpace(businessName)) { queryable = queryable.Where(a => a.LastName.Contains(businessName)); } var activeRecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; string activeFilterValue = gfBusinessFilter.GetUserPreference("Active Status"); if (activeFilterValue == "inactive") { queryable = queryable.Where(b => b.RecordStatusValueId != activeRecordStatusValueId); } else if (activeFilterValue == "active") { queryable = queryable.Where(b => b.RecordStatusValueId == activeRecordStatusValueId); } SortProperty sortProperty = gBusinessList.SortProperty; if (sortProperty != null) { queryable = queryable.Sort(sortProperty); } else { queryable = queryable.OrderBy(q => q.LastName); } var groupMemberQuery = new GroupMemberService(rockContext).Queryable(); var businessList = queryable.Select(b => new { Id = b.Id, b.LastName, BusinessName = b.LastName, PhoneNumber = b.PhoneNumbers.FirstOrDefault().NumberFormatted, Email = b.Email, Address = b.Members .Where(m => m.Group.GroupType.Guid.ToString() == Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY) .SelectMany(m => m.Group.GroupLocations) .FirstOrDefault() .Location, Contacts = b.Members .Where(m => m.Group.GroupType.Guid.ToString() == Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS) .SelectMany(m => m.Group.Members) .Where(p => p.GroupRole.Guid.ToString() == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER && p.PersonId != b.Id) .Select(p => p.Person.LastName + ", " + p.Person.NickName) }); gBusinessList.EntityTypeId = EntityTypeCache.Read <Person>().Id; gBusinessList.DataSource = businessList.ToList(); gBusinessList.DataBind(); }
private List <ContentChannelItem> GetContent(List <string> errorMessages) { List <ContentChannelItem> items = null; // only load from the cache if a cacheDuration was specified if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0) { items = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>; } if (items == null) { Guid?channelGuid = GetAttributeValue("Channel").AsGuidOrNull(); if (channelGuid.HasValue) { var rockContext = new RockContext(); var service = new ContentChannelItemService(rockContext); var itemType = typeof(Rock.Model.ContentChannelItem); ParameterExpression paramExpression = service.ParameterExpression; var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value); if (contentChannel != null) { var entityFields = HackEntityFields(contentChannel, rockContext); items = new List <ContentChannelItem>(); var qry = service .Queryable("ContentChannel,ContentChannelType") .Where(i => i.ContentChannelId == contentChannel.Id); if (contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus) { // Check for the configured status and limit query to those var statuses = new List <ContentChannelItemStatus>(); foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>(); if (status != null) { statuses.Add(status.Value); } } if (statuses.Any()) { qry = qry.Where(i => statuses.Contains(i.Status)); } } int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull(); if (dataFilterId.HasValue) { var dataFilterService = new DataViewFilterService(rockContext); var dataFilter = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value); Expression whereExpression = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null; qry = qry.Where(paramExpression, whereExpression, null); } // All filtering has been added, now run query, check security and load attributes foreach (var item in qry.ToList()) { if (item.IsAuthorized(Authorization.VIEW, CurrentPerson)) { item.LoadAttributes(rockContext); items.Add(item); } } // Order the items SortProperty sortProperty = null; string orderBy = GetAttributeValue("Order"); if (!string.IsNullOrWhiteSpace(orderBy)) { var fieldDirection = new List <string>(); foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^'))) { if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0])) { var sortDirection = SortDirection.Ascending; if (!string.IsNullOrWhiteSpace(itemPair[1])) { sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending); } fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : "")); } } sortProperty = new SortProperty(); sortProperty.Direction = SortDirection.Ascending; sortProperty.Property = fieldDirection.AsDelimited(","); string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var itemQry = items.AsQueryable(); IOrderedQueryable <ContentChannelItem> orderedQry = null; for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { string column = columns[columnIndex].Trim(); var direction = sortProperty.Direction; if (column.ToLower().EndsWith(" desc")) { column = column.Left(column.Length - 5); direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } try { if (column.StartsWith("Attribute:")) { string attributeKey = column.Substring(10); if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } } else { if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column); } } } catch { } } try { if (orderedQry != null) { items = orderedQry.ToList(); } } catch { } } if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0) { var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ItemCacheDuration.Value) }; AddCacheItem(CONTENT_CACHE_KEY, items, cacheItemPolicy); } } } } return(items); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid(bool isExporting = false) { int?personId = null; int?givingGroupId = null; bool validRequest = false; if (TargetPerson != null) { personId = TargetPerson.Id; givingGroupId = TargetPerson.GivingGroupId; validRequest = true; } else { int personEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id; if (!ContextTypesRequired.Any(e => e.Id == personEntityTypeId)) { validRequest = true; } } if (validRequest) { var rockContext = new RockContext(); var qry = new FinancialScheduledTransactionService(rockContext) .Queryable("ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue") .AsNoTracking(); // Valid Accounts var accountGuids = GetAttributeValue("Accounts").SplitDelimitedValues().AsGuidList(); if (accountGuids.Any()) { qry = qry.Where(t => t.ScheduledTransactionDetails.Any(d => accountGuids.Contains(d.Account.Guid))); } // Amount Range var nre = new NumberRangeEditor(); nre.DelimitedValues = gfSettings.GetUserPreference("Amount"); if (nre.LowerValue.HasValue) { qry = qry.Where(t => t.ScheduledTransactionDetails.Sum(d => d.Amount) >= nre.LowerValue.Value); } if (nre.UpperValue.HasValue) { qry = qry.Where(t => t.ScheduledTransactionDetails.Sum(d => d.Amount) <= nre.UpperValue.Value); } // Frequency int?frequencyTypeId = gfSettings.GetUserPreference("Frequency").AsIntegerOrNull(); if (frequencyTypeId.HasValue) { qry = qry.Where(t => t.TransactionFrequencyValueId == frequencyTypeId.Value); } // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Created"); if (drp.LowerValue.HasValue) { qry = qry.Where(t => t.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(t => t.CreatedDateTime < upperDate); } // Account Id int accountId = int.MinValue; if (int.TryParse(gfSettings.GetUserPreference("Account"), out accountId) && ddlAccount.Visible) { qry = qry.Where(t => t.ScheduledTransactionDetails.Any(d => d.AccountId == accountId)); } // Active only (no filter) if (string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Include Inactive"))) { qry = qry.Where(t => t.IsActive); } if (givingGroupId.HasValue) { // Person contributes with family qry = qry.Where(t => t.AuthorizedPersonAlias.Person.GivingGroupId == givingGroupId); } else if (personId.HasValue) { // Person contributes individually qry = qry.Where(t => t.AuthorizedPersonAlias.PersonId == personId); } SortProperty sortProperty = gList.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Amount") { if (sortProperty.Direction == SortDirection.Ascending) { qry = qry.OrderBy(t => t.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.00M); } else { qry = qry.OrderByDescending(t => t.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M); } } else { qry = qry.Sort(sortProperty); } } else { qry = qry .OrderBy(t => t.AuthorizedPersonAlias.Person.LastName) .ThenBy(t => t.AuthorizedPersonAlias.Person.NickName) .ThenByDescending(t => t.IsActive) .ThenByDescending(t => t.StartDate); } _isExporting = isExporting; gList.SetLinqDataSource <FinancialScheduledTransaction>(qry); gList.DataBind(); _isExporting = false; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { int?metricId = hfMetricId.Value.AsIntegerOrNull(); if (!metricId.HasValue) { return; } var rockContext = new RockContext(); SortProperty sortProperty = gMetricValues.SortProperty; MetricValueService metricValueService = new MetricValueService(rockContext); var qry = metricValueService.Queryable().Include(a => a.MetricValuePartitions); qry = qry.Where(a => a.MetricId == metricId); var metricValuePartitionsColumn = gMetricValues.Columns.OfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lMetricValuePartitions"); var metric = new MetricService(rockContext).Get(metricId ?? 0); metricValuePartitionsColumn.Visible = metric != null && metric.MetricPartitions.Any(a => a.EntityTypeId.HasValue); var drp = new DateRangePicker(); drp.DelimitedValues = gfMetricValues.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(a => a.MetricValueDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(a => a.MetricValueDateTime < upperDate); } var metricValueType = gfMetricValues.GetUserPreference("Goal/Measure").ConvertToEnumOrNull <MetricValueType>(); if (metricValueType.HasValue) { qry = qry.Where(a => a.MetricValueType == metricValueType.Value); } var entityTypeEntityUserPreference = gfMetricValues.GetUserPreference(this.EntityTypeEntityPreferenceKey) ?? string.Empty; var entityTypeEntityList = entityTypeEntityUserPreference.Split(',').Select(a => a.Split('|')).Where(a => a.Length == 2).Select(a => new { EntityTypeId = a[0].AsIntegerOrNull(), EntityId = a[1].AsIntegerOrNull() }); foreach (var entityTypeEntity in entityTypeEntityList) { if (entityTypeEntity.EntityTypeId.HasValue && entityTypeEntity.EntityId.HasValue) { qry = qry.Where(a => a.MetricValuePartitions.Any(x => x.MetricPartition.EntityTypeId == entityTypeEntity.EntityTypeId && x.EntityId == entityTypeEntity.EntityId)); } } if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(s => s.MetricValueDateTime).ThenBy(s => s.YValue).ThenBy(s => s.XValue).ThenByDescending(s => s.ModifiedDateTime); } gMetricValues.SetLinqDataSource(qry); gMetricValues.DataBind(); }
/// <summary> /// Binds the grid to a list of Prayer Requests. /// </summary> private void BindGrid() { PrayerRequestService prayerRequestService = new PrayerRequestService(new RockContext()); SortProperty sortProperty = gPrayerRequests.SortProperty; var prayerRequests = prayerRequestService.Queryable().Select(a => new { a.Id, FullName = a.FirstName + " " + a.LastName, CategoryName = a.Category.Name, EnteredDate = a.EnteredDateTime, a.ExpirationDate, a.Text, a.FlagCount, a.IsApproved, a.CategoryId, CategoryParentCategoryId = a.Category.ParentCategoryId, a.IsUrgent, a.IsPublic, a.IsActive, a.AllowComments }); // Filter by prayer category if one is selected... int selectedPrayerCategoryID = catpPrayerCategoryFilter.SelectedValue.AsInteger(false) ?? All.Id; if (selectedPrayerCategoryID != All.Id && selectedPrayerCategoryID != None.Id) { prayerRequests = prayerRequests.Where(c => c.CategoryId == selectedPrayerCategoryID || c.CategoryParentCategoryId == selectedPrayerCategoryID); } // Filter by approved/unapproved if (ddlApprovedFilter.SelectedIndex > -1) { if (ddlApprovedFilter.SelectedValue == "unapproved") { prayerRequests = prayerRequests.Where(a => a.IsApproved == false || !a.IsApproved.HasValue); } else if (ddlApprovedFilter.SelectedValue == "approved") { prayerRequests = prayerRequests.Where(a => a.IsApproved == true); } } // Filter by urgent/non-urgent if (ddlUrgentFilter.SelectedIndex > -1) { if (ddlUrgentFilter.SelectedValue == "non-urgent") { prayerRequests = prayerRequests.Where(a => a.IsUrgent == false || !a.IsUrgent.HasValue); } else if (ddlUrgentFilter.SelectedValue == "urgent") { prayerRequests = prayerRequests.Where(a => a.IsUrgent == true); } } // Filter by public/non-public if (ddlPublicFilter.SelectedIndex > -1) { if (ddlPublicFilter.SelectedValue == "non-public") { prayerRequests = prayerRequests.Where(a => a.IsPublic == false || !a.IsPublic.HasValue); } else if (ddlPublicFilter.SelectedValue == "public") { prayerRequests = prayerRequests.Where(a => a.IsPublic == true); } } // Filter by active/inactive if (ddlActiveFilter.SelectedIndex > -1) { if (ddlActiveFilter.SelectedValue == "inactive") { prayerRequests = prayerRequests.Where(a => a.IsActive == false || !a.IsActive.HasValue); } else if (ddlActiveFilter.SelectedValue == "active") { prayerRequests = prayerRequests.Where(a => a.IsActive == true); } } // Filter by active/inactive if (ddlAllowCommentsFilter.SelectedIndex > -1) { if (ddlAllowCommentsFilter.SelectedValue == "unallow") { prayerRequests = prayerRequests.Where(a => a.AllowComments == false || !a.AllowComments.HasValue); } else if (ddlAllowCommentsFilter.SelectedValue == "allow") { prayerRequests = prayerRequests.Where(a => a.AllowComments == true); } } // Filter by Date Range if (drpDateRange.LowerValue.HasValue) { DateTime startDate = drpDateRange.LowerValue.Value.Date; prayerRequests = prayerRequests.Where(a => a.EnteredDate >= startDate); } if (drpDateRange.UpperValue.HasValue) { // Add one day in order to include everything up to the end of the selected datetime. var endDate = drpDateRange.UpperValue.Value.AddDays(1); prayerRequests = prayerRequests.Where(a => a.EnteredDate < endDate); } // Don't show expired prayer requests. // TODO save users filter setting? if (!cbShowExpired.Checked) { prayerRequests = prayerRequests.Where(a => RockDateTime.Today <= a.ExpirationDate); } // Sort by the given property otherwise sort by the EnteredDate (and Id) // (this is a hack because the Date field alone doesn't sort in the descending direction well) if (sortProperty != null) { gPrayerRequests.DataSource = prayerRequests.Sort(sortProperty).ToList(); } else { // TODO Figure out how to tell Grid what Direction and Property it's sorting on //sortProperty.Direction = SortDirection.Ascending; //sortProperty.Property = "EnteredDate"; gPrayerRequests.DataSource = prayerRequests.OrderByDescending(p => p.EnteredDate).ThenByDescending(p => p.Id).ToList(); } gPrayerRequests.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (Person != null) { var familyIds = families.Select(f => f.Key).ToList(); var qry = new HistoryService(new RockContext()).Queryable("CreatedByPersonAlias.Person") .Where(h => (h.EntityTypeId == personEntityTypeId && h.EntityId == Person.Id) || (h.EntityTypeId == groupEntityTypeId && familyIds.Contains(h.EntityId))); int?categoryId = gfSettings.GetUserPreference("Category").AsIntegerOrNull(); if (categoryId.HasValue) { qry = qry.Where(a => a.CategoryId == categoryId.Value); } string summary = gfSettings.GetUserPreference("Summary Contains"); if (!string.IsNullOrWhiteSpace(summary)) { qry = qry.Where(h => h.Summary.Contains(summary)); } int personId = int.MinValue; if (int.TryParse(gfSettings.GetUserPreference("Who"), out personId)) { qry = qry.Where(h => h.CreatedByPersonAlias.PersonId == personId); } var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(h => h.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(h => h.CreatedDateTime < upperDate); } SortProperty sortProperty = gHistory.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(t => t.CreatedDateTime); } // Combine history records that were saved at the same time var histories = new List <History>(); foreach (var history in qry) { var existingHistory = histories .Where(h => h.CreatedByPersonAliasId == history.CreatedByPersonAliasId && h.CreatedDateTime == history.CreatedDateTime && h.EntityTypeId == history.EntityTypeId && h.EntityId == history.EntityId && h.CategoryId == history.CategoryId && h.RelatedEntityTypeId == history.RelatedEntityTypeId && h.RelatedEntityId == history.RelatedEntityId).FirstOrDefault(); if (existingHistory != null) { existingHistory.Summary += "<br/>" + history.Summary; } else { histories.Add(history); } } gHistory.DataSource = histories.Select(h => new { Id = h.Id, CategoryId = h.CategoryId, Category = h.Category != null ? h.Category.Name : "", EntityTypeId = h.EntityTypeId, EntityId = h.EntityId, Caption = h.Caption ?? string.Empty, Summary = h.Summary, RelatedEntityTypeId = h.RelatedEntityTypeId ?? 0, RelatedEntityId = h.RelatedEntityId ?? 0, CreatedByPersonId = h.CreatedByPersonAlias != null ? h.CreatedByPersonAlias.PersonId : 0, PersonName = h.CreatedByPersonAlias != null && h.CreatedByPersonAlias.Person != null ? h.CreatedByPersonAlias.Person.NickName + " " + h.CreatedByPersonAlias.Person.LastName : "", CreatedDateTime = h.CreatedDateTime }).ToList(); gHistory.EntityTypeId = EntityTypeCache.Read <History>().Id; gHistory.DataBind(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { phSummary.Controls.Clear(); rFilter.Visible = true; gList.Visible = true; RockContext rockContext = new RockContext(); BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService(rockContext); var qry = benevolenceRequestService.Queryable("BenevolenceResults,RequestedByPersonAlias,RequestedByPersonAlias.Person,CaseWorkerPersonAlias,CaseWorkerPersonAlias.Person"); // Filter by Start Date DateTime?startDate = drpDate.LowerValue; if (startDate != null) { qry = qry.Where(b => b.RequestDateTime >= startDate); } // Filter by End Date DateTime?endDate = drpDate.UpperValue; if (endDate != null) { qry = qry.Where(b => b.RequestDateTime <= endDate); } // Filter by Campus if (cpCampus.SelectedCampusId.HasValue) { qry = qry.Where(b => b.CampusId == cpCampus.SelectedCampusId); } if (TargetPerson != null) { // show benevolence request for the target person and also for their family members var qryFamilyMembers = TargetPerson.GetFamilyMembers(true, rockContext); qry = qry.Where(a => a.RequestedByPersonAliasId.HasValue && qryFamilyMembers.Any(b => b.PersonId == a.RequestedByPersonAlias.PersonId)); } else { // Filter by First Name string firstName = tbFirstName.Text; if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(b => b.FirstName.StartsWith(firstName)); } // Filter by Last Name string lastName = tbLastName.Text; if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(b => b.LastName.StartsWith(lastName)); } } // Filter by Government Id string governmentId = tbGovernmentId.Text; if (!string.IsNullOrWhiteSpace(governmentId)) { qry = qry.Where(b => b.GovernmentId.StartsWith(governmentId)); } // Filter by Case Worker int?caseWorkerPersonAliasId = ddlCaseWorker.SelectedItem.Value.AsIntegerOrNull(); if (caseWorkerPersonAliasId != null) { qry = qry.Where(b => b.CaseWorkerPersonAliasId == caseWorkerPersonAliasId); } // Filter by Result int?resultTypeValueId = ddlResult.SelectedItem.Value.AsIntegerOrNull(); if (resultTypeValueId != null) { qry = qry.Where(b => b.BenevolenceResults.Where(r => r.ResultTypeValueId == resultTypeValueId).Count() > 0); } // Filter by Request Status int?requestStatusValueId = ddlStatus.SelectedItem.Value.AsIntegerOrNull(); if (requestStatusValueId != null) { qry = qry.Where(b => b.RequestStatusValueId == requestStatusValueId); } SortProperty sortProperty = gList.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "TotalAmount") { if (sortProperty.Direction == SortDirection.Descending) { qry = qry.OrderByDescending(a => a.BenevolenceResults.Sum(b => b.Amount)); } else { qry = qry.OrderBy(a => a.BenevolenceResults.Sum(b => b.Amount)); } } else { qry = qry.Sort(sortProperty); } } else { qry = qry.OrderByDescending(a => a.RequestDateTime).ThenByDescending(a => a.Id); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } gList.DataSource = qry.ToList(); gList.DataBind(); // Builds the Totals section var definedTypeCache = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_RESULT_TYPE)); Dictionary <string, decimal> resultTotals = new Dictionary <string, decimal>(); decimal grandTotal = 0; foreach (BenevolenceRequest request in qry.ToList()) { foreach (BenevolenceResult result in request.BenevolenceResults) { if (result.Amount != null) { if (resultTotals.ContainsKey(result.ResultTypeValue.Value)) { resultTotals[result.ResultTypeValue.Value] += result.Amount.Value; } else { resultTotals.Add(result.ResultTypeValue.Value, result.Amount.Value); } grandTotal += result.Amount.Value; } } } foreach (KeyValuePair <string, decimal> keyValuePair in resultTotals) { phSummary.Controls.Add(new LiteralControl(string.Format("<div class='row'><div class='col-xs-8'>{0}: </div><div class='col-xs-4 text-right'>{1}{2:#,##0.00}</div></div>", keyValuePair.Key, GlobalAttributesCache.Value("CurrencySymbol"), keyValuePair.Value))); } phSummary.Controls.Add(new LiteralControl(string.Format("<div class='row'><div class='col-xs-8'><b>Total: </div><div class='col-xs-4 text-right'>{0}{1:#,##0.00}</b></div></div>", GlobalAttributesCache.Value("CurrencySymbol"), grandTotal))); }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { var showProfilesViewed = GetAttributeValue("SeeProfilesViewed").AsBoolean(); var rockContext = new RockContext(); var personViewedService = new PersonViewedService(rockContext); var personService = new PersonService(rockContext); if (showProfilesViewed) { // This grid should show the profiles viewed by this person. pnlViewed.Visible = true; pnlViewedBy.Visible = false; if (personId.HasValue) { var viewedList = personViewedService.Queryable() .Where(p => p.ViewerPersonAlias != null && p.ViewerPersonAlias.PersonId == personId) .GroupBy(p => p.TargetPersonAlias.PersonId) .Select(p => new { TargetPersonId = p.Key, FirstViewed = p.Min(g => g.ViewDateTime), LastViewed = p.Max(g => g.ViewDateTime), ViewedCount = p.Count() }); var pQry = personService.Queryable(); var qry = viewedList .Join(pQry, v => v.TargetPersonId, p => p.Id, (v, p) => new { p.Id, FullName = p.NickName + " " + p.LastName, p.BirthDate, p.Gender, FirstViewedDate = v.FirstViewed, LastViewedDate = v.LastViewed, ViewedCount = v.ViewedCount }); SortProperty sortProperty = gViewed.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(q => q.LastViewedDate); } gViewed.EntityTypeId = EntityTypeCache.Read <PersonViewed>().Id; gViewed.DataSource = qry.ToList(); gViewed.DataBind(); } } else { // This grid should show the profiles that have viewed this person. pnlViewed.Visible = false; pnlViewedBy.Visible = true; if (personId.HasValue) { var viewedList = personViewedService.Queryable() .Where(p => p.TargetPersonAlias != null && p.TargetPersonAlias.PersonId == personId) .GroupBy(p => p.ViewerPersonAlias.PersonId) .Select(p => new { ViewerPersonId = p.Key, FirstViewed = p.Min(g => g.ViewDateTime), LastViewed = p.Max(g => g.ViewDateTime), ViewedCount = p.Count() }); var pQry = personService.Queryable(); var qry = viewedList .Join(pQry, v => v.ViewerPersonId, p => p.Id, (v, p) => new { p.Id, FullName = p.NickName + " " + p.LastName, p.BirthDate, p.Gender, FirstViewedDate = v.FirstViewed, LastViewedDate = v.LastViewed, ViewedCount = v.ViewedCount }); SortProperty sortProperty = gViewedBy.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(q => q.LastViewedDate); } gViewedBy.EntityTypeId = EntityTypeCache.Read <Person>().Id; gViewedBy.DataSource = qry.ToList(); gViewedBy.DataBind(); } } }
private void RefreshDataSource(int pageIndex, string searchText) { int totalPages = 0; ResourceListView.PageIndex = 0; ResourceListView.TotalRecords = 0; ResourceListView.DataSource.Clear(); if (!string.IsNullOrEmpty(searchText)) { int totalRecords = 0; ResourceListView.PageSize = _pageSize; int totalParsedRecords = totalParsedRecords = _pageSize * pageIndex; List <Resource> foundRestResource = null; Dictionary <Guid, IEnumerable <string> > userPermissions = null; SortProperty sortProp = null; if (ResourceListView.SortDirection == System.Web.UI.WebControls.SortDirection.Ascending) { sortProp = new SortProperty(ResourceListView.SortExpression, Zentity.Platform.SortDirection.Ascending); } else { sortProp = new SortProperty(ResourceListView.SortExpression, Zentity.Platform.SortDirection.Descending); } //search resources and user permissions on the searched resources. using (ResourceDataAccess dataAccess = new ResourceDataAccess()) { AuthenticatedToken token = this.Session[Constants.AuthenticationTokenKey] as AuthenticatedToken; if (token != null) { foundRestResource = dataAccess.SearchResources(token, searchText, _pageSize, sortProp, totalParsedRecords, false, out totalRecords).ToList(); userPermissions = GetPermissions(token, foundRestResource); } } //Calculate total pages if (totalRecords > 0) { totalPages = Convert.ToInt32(Math.Ceiling((double)totalRecords / _pageSize)); } // Update empty resource's title with default value. if (foundRestResource != null && foundRestResource.Count() > 0) { Utility.UpdateResourcesEmptyTitle(foundRestResource); } //Bind data to GridView ResourceListView.TotalRecords = totalRecords; ResourceListView.PageIndex = pageIndex; foreach (Resource resource in foundRestResource) { ResourceListView.DataSource.Add(resource); } ResourceListView.UserPermissions = userPermissions; //Enable feed for this page. string searchString = GetSearchString(); if (!string.IsNullOrEmpty(searchString)) { ResourceListView.EnableFeed(searchString); } ResourceListView.DataBind(); } }
/// <summary> /// Binds the event calendar items grid. /// </summary> protected void BindConnectionOpportunitiesGrid() { if (_connectionType != null) { pnlConnectionOpportunities.Visible = true; rFilter.Visible = true; gConnectionOpportunities.Visible = true; var rockContext = new RockContext(); ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext); var qry = connectionOpportunityService.Queryable() .Where(o => o.ConnectionTypeId == _connectionType.Id); // Filter by Active Only if (cbActive.Checked) { qry = qry.Where(o => o.IsActive); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } SortProperty sortProperty = gConnectionOpportunities.SortProperty; List <ConnectionOpportunity> connectionOpportunities = null; if (sortProperty != null) { connectionOpportunities = qry.Sort(sortProperty).ToList(); } else { connectionOpportunities = qry.ToList().OrderBy(a => a.Name).ToList(); } gConnectionOpportunities.DataSource = connectionOpportunities; gConnectionOpportunities.DataBind(); } else { pnlConnectionOpportunities.Visible = false; } }
public DBCollection(XPCollection collection) : this(collection.Session, collection.ObjectType, collection.Criteria) { var sortProperties = new SortProperty[collection.Sorting.Count]; for (int i = 0; i < collection.Sorting.Count; i++) { SortProperty sortProperty = collection.Sorting[i]; sortProperties[i] = new SortProperty(sortProperty.PropertyName, sortProperty.Direction); } Sorting = new SortingCollection(this, sortProperties); }
private void ImportLessons(Session uow, XElement xElement, Dictionary <string,Lesson> lessonDic, Dictionary<string,Subject> subjectDic, Dictionary<string,TkbClass> classDic, Dictionary<string, TkbGroup> groupDic, Dictionary<string,TkbTeacher> teacherDic, StreamWriter fileStreamlog) { SortProperty sort = new SortProperty("LessonCode", SortingDirection.Descending); int nextcode = 0; using (XPCollection collection = new XPCollection(uow, typeof(Lesson), new BinaryOperator( "Semester.SemesterName", Semester.SemesterName), sort) { TopReturnedObjects = 1 }) { if (collection.Count > 0) { Lesson firstLesson = collection[0] as Lesson; nextcode = firstLesson.LessonCode; } } int newcode=Convert.ToInt32(Semester.SemesterName+"0000"); //first lesson of semester if (newcode > nextcode) nextcode = newcode; foreach (XElement row in xElement.Elements()) { string sid = "", classids = "", subjectid = "", teacherids = "", classroomids = "", groupids = ""; string weeks = "", studentcoustudentidsnt = "", periodsperweek = ""; int periodspercard = 0; foreach (XAttribute column in row.Attributes()) { switch (column.Name.LocalName) { case "id": sid = column.Value; break; case "classids": classids = column.Value; break; case "subjectid": subjectid = column.Value; break; case "periodspercard": periodspercard = int.Parse(column.Value); break; case "periodsperweek": periodsperweek = column.Value; break; case "teacherids": teacherids = column.Value; break; case "classroomids": classroomids = column.Value; break; case "groupids": groupids = column.Value; break; case "studentcoustudentidsnt": studentcoustudentidsnt = column.Value; break; case "weeks": weeks = column.Value; break; default: break; } } TkbLesson tkblesson = uow.FindObject<TkbLesson>(new BinaryOperator("ID", sid)); if (tkblesson == null) { tkblesson = new TkbLesson(uow) { Semester = uow.FindObject<Semester>(new BinaryOperator("Oid", this.Semester.Oid)), ID = sid, PeriodsPerCard = periodspercard, PeriodsPerWeek = periodsperweek, ClassroomIDs = classroomids, GroupIDs = groupids, StudentIDs = studentcoustudentidsnt, Week = weeks, Note = this.Note, SubjectID = (subjectDic.ContainsKey(subjectid)?subjectDic[subjectid].SubjectCode:null) }; tkblesson.NumExpectation = 0; tkblesson.GroupIDs = ""; if (groupids != "") { foreach (string groupid in groupids.Split(',')) { string groupname =""; if (groupDic.ContainsKey(groupid)) { if (groupDic[groupid].EntireClass) { groupname = classDic.ContainsKey(groupDic[groupid].Classid) ? classDic[groupDic[groupid].Classid].Name : groupDic[groupid].Name; } else { groupname = groupDic[groupid].Name; } } else { groupname = groupid; } tkblesson.GroupIDs += (groupname!="" ? groupname + "," : ""); tkblesson.NumExpectation += (groupDic.ContainsKey(groupid) ? groupDic[groupid].StudentCount : 0); } tkblesson.GroupIDs = tkblesson.GroupIDs.TrimEnd(','); } tkblesson.ClassIDs = ""; if (classids != "") { foreach (string classid in classids.Split(',')) { tkblesson.ClassIDs += (classDic.ContainsKey(classid) ? classDic[classid].Short + "," :""); } tkblesson.ClassIDs= tkblesson.ClassIDs.TrimEnd(','); } tkblesson.TeacherIDs = ""; if (teacherids != "") { foreach (string teacherid in teacherids.Split(',')) { tkblesson.TeacherIDs += (teacherDic.ContainsKey(teacherid)? teacherDic[teacherid].Short + "," : ""); } tkblesson.TeacherIDs = tkblesson.TeacherIDs.TrimEnd(','); } tkblesson.Save(); //fileStreamlog.WriteLine(String.Format("Create tkblesson: \"{0}\" successful on {1: dd-mm-yyyy HH:MM:ss}", tkblesson.ID + "-" + tkblesson.SubjectID, DateTime.Now)); } else { tkblesson.Semester = uow.FindObject<Semester>(new BinaryOperator("Oid", this.Semester.Oid)); tkblesson.ID = sid; tkblesson.PeriodsPerCard = periodspercard; tkblesson.PeriodsPerWeek = periodsperweek; tkblesson.ClassroomIDs = classroomids; tkblesson.StudentIDs = studentcoustudentidsnt; tkblesson.Week = weeks; tkblesson.Note = this.Note; tkblesson.SubjectID = (subjectDic.ContainsKey(subjectid) ? subjectDic[subjectid].SubjectCode : ""); tkblesson.NumExpectation = 0; tkblesson.GroupIDs = ""; if (groupids != "") { foreach (string groupid in groupids.Split(',')) { string groupname = ""; if (groupDic.ContainsKey(groupid)) { if (groupDic[groupid].EntireClass) { groupname = classDic.ContainsKey(groupDic[groupid].Classid) ? classDic[groupDic[groupid].Classid].Name : groupDic[groupid].Name; } else { groupname = groupDic[groupid].Name; } } else { groupname = groupid; } tkblesson.GroupIDs += (groupname != "" ? groupname + "," : ""); tkblesson.NumExpectation += (groupDic.ContainsKey(groupid) ? groupDic[groupid].StudentCount : 0); } tkblesson.GroupIDs = tkblesson.GroupIDs.TrimEnd(','); } tkblesson.ClassIDs = ""; if (classids != "") { foreach (string classid in classids.Split(',')) { tkblesson.ClassIDs += (classDic.ContainsKey(classid) ? classDic[classid].Short + "," : ""); } tkblesson.ClassIDs = tkblesson.ClassIDs.TrimEnd(','); } tkblesson.TeacherIDs = ""; if (teacherids != "") { foreach (string teacherid in teacherids.Split(',')) { tkblesson.TeacherIDs += (teacherDic.ContainsKey(teacherid) ? teacherDic[teacherid].Short + "," : ""); } tkblesson.TeacherIDs = tkblesson.TeacherIDs.TrimEnd(','); } tkblesson.Save(); //fileStreamlog.WriteLine(String.Format("Update tkblesson: \"{0}\" successful on {1: dd-mm-yyyy HH:MM:ss}", tkblesson.ID, DateTime.Now)); } Lesson lesson = new Lesson(uow) { CanRegister = Active, TkbLesson = tkblesson, Semester = uow.FindObject<Semester>(new BinaryOperator("Oid", this.Semester.Oid)), Subject = (subjectDic.ContainsKey(subjectid) ? subjectDic[subjectid] : null), LessonNote = Note, ClassIDs = tkblesson.GroupIDs, NumExpectation = tkblesson.NumExpectation, LessonCode = ++nextcode //tăng dần }; foreach (string teacherCode in tkblesson.TeacherIDs.Split(',')) { Teacher teacher = uow.FindObject<Teacher>(new BinaryOperator("TeacherCode", teacherCode)); if (teacher !=null) lesson.Teachers.Add(teacher); } lesson.Save(); if (lesson.Subject != null) { //fileStreamlog.WriteLine(String.Format("Create Lesson: \"{0}\" successfully on {1: dd-mm-yyyy HH:MM:ss}", lesson.Subject.SubjectCode + lesson.TkbLesson.Name, DateTime.Now)); fileStreamlog.WriteLine(String.Format("<TR><TD>LESSON</TD><TD>CREATE NEW</TD><TD>\"{0}\"</TD><TD> {1:dd-mm-yy HH:MM:ss}</TD><TD>OK</TD></TR>", lesson.LessonCode.ToString() + "-" + lesson.Subject.SubjectCode +"-"+ lesson.ClassIDs, DateTime.Now)); } else { //fileStreamlog.WriteLine(String.Format("WARNING: Create Lesson: \"{0}\" without Lesson \"{1}\" successfully on {2: dd-mm-yyyy HH:MM:ss}", lesson.TkbLesson.Name, tkblesson.SubjectID, DateTime.Now)); fileStreamlog.WriteLine(String.Format("<TR><TD>LESSON</TD><TD>CREATE NEW</TD><TD>\"{0}\"</TD><TD> {1:dd-mm-yy HH:MM:ss}</TD><TD>WARNING</TD></TR>", lesson.LessonCode.ToString() + "-" + lesson.TkbLesson.Name + "-"+lesson.TkbLesson.SubjectID + "-" + lesson.ClassIDs, DateTime.Now)); } lessonDic.Add(sid, lesson); } //fileStreamlog.WriteLine(String.Format("Create {0} lesson successfully on {1: dd-mm-yyyy HH:MM:ss}", lessonDic.Count, DateTime.Now)); }