/// <summary> /// Filters a Query to rows that have matching attribute value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="rockContext">The rock context.</param> /// <param name="attributeKey">The attribute key.</param> /// <param name="attributeValue">The attribute value.</param> /// <returns></returns> /// <example> /// var test = new PersonService( rockContext ).Queryable().Where( a => a.FirstName == "Bob" ).WhereAttributeValue( rockContext, "BaptizedHere", "True" ).ToList(); /// </example> public static IQueryable <T> WhereAttributeValue <T>(this IQueryable <T> source, RockContext rockContext, string attributeKey, string attributeValue) where T : Entity <T>, new() { int entityTypeId = EntityTypeCache.GetId(typeof(T)) ?? 0; var avs = new AttributeValueService(rockContext).Queryable() .Where(a => a.Attribute.Key == attributeKey) .Where(a => a.Attribute.EntityTypeId == entityTypeId) .Where(a => a.Value == attributeValue) .Select(a => a.EntityId); var result = source.Where(a => avs.Contains((a as T).Id)); return(result); }
public IQueryable <ContentChannelItem> ContentChannelItemsByAttributeValue(int campusId) { RockContext rockContext = new RockContext(); string campusGuid = new CampusService(rockContext).Get(campusId).Guid.ToString(); // Get the Id of the Rock.Model.ContentChannelItem Entity. int contentChannelItemEntityTypeId = EntityTypeCache.Get("Rock.Model.ContentChannelItem").Id; // Get the Field Type (Attribute Type) Id of the Data View Field Type. int fieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.CAMPUSES.AsGuid()).Id; // Get the list of attributes that are of the Rock.Model.ContentChannelItem entity type // and that are of the Campus field type. List <int> campusAttributeIdList = new AttributeService(rockContext) .GetByEntityTypeId(contentChannelItemEntityTypeId) .Where(item => item.FieldTypeId == fieldTypeId) .Select(a => a.Id) .ToList(); List <string> campusAttributeIdKeyList = new AttributeService(rockContext) .GetByEntityTypeId(contentChannelItemEntityTypeId) .Where(item => item.FieldTypeId == fieldTypeId) .Select(a => a.Key) .ToList(); var avsWithCampus = new AttributeValueService(rockContext).Queryable() .Where(a => campusAttributeIdList.Contains(a.AttributeId)) .Where(a => a.Attribute.EntityTypeId == contentChannelItemEntityTypeId) .Where(a => a.Value.Contains(campusGuid)) .Select(a => a.EntityId); // I want a list of content channel items whose ids match up to attribute values that represent entity ids IQueryable <ContentChannelItem> contentChannelItemList = new ContentChannelItemService(rockContext) .Queryable() .AsNoTracking() .Where(c => avsWithCampus.Contains(c.Id) || c.Attributes.Keys.Contains(campusAttributeIdKeyList.FirstOrDefault())); // Return this list return(contentChannelItemList); }
/// <summary> /// Filters a Query to rows that have matching attribute values that meet the condition /// NOTE: Make sure your predicate references 'Attribute.Key' and not 'AttributeKey' /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="rockContext">The rock context.</param> /// <param name="predicate">The predicate.</param> /// <returns></returns> public static IQueryable <T> WhereAttributeValue <T>(this IQueryable <T> source, RockContext rockContext, Expression <Func <AttributeValue, bool> > predicate) where T : Entity <T>, new() { /* * Example: * var qryPerson = new PersonService( rockContext ).Queryable().Where( a => a.FirstName == "Bob" ) * .WhereAttributeValue( rockContext, a => a.Attribute.Key == "IsAwesome" && a.ValueAsBoolean == true ); */ int entityTypeId = EntityTypeCache.GetId(typeof(T)) ?? 0; var avs = new AttributeValueService(rockContext).Queryable() .Where(a => a.Attribute.EntityTypeId == entityTypeId) .Where(predicate) .Select(a => a.EntityId); var result = source.Where(a => avs.Contains((a as T).Id)); return(result); }
/// <summary> /// Handles the Click event of the btnFindByEnvelopeNumber control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnFindByEnvelopeNumber_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); var envelopeNumber = tbEnvelopeNumber.Text; if (!string.IsNullOrEmpty(envelopeNumber)) { var personIdsWithEnvelopeNumber = new AttributeValueService(rockContext).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.Value == envelopeNumber) .Select(a => a.EntityId.Value); var count = personIdsWithEnvelopeNumber.Count(); var personService = new PersonService(rockContext); if (count == 0) { lEnvelopeSearchResults.Text = string.Format("No individual found with envelope number of {0}.", envelopeNumber); cblEnvelopeSearchPersons.Visible = false; mdEnvelopeSearchResults.SaveButtonText = string.Empty; mdEnvelopeSearchResults.Show(); } else if (count == 1) { var personId = personIdsWithEnvelopeNumber.First(); ppSelectNew.SetValue(personService.Get(personId)); LoadPersonPreview(personId); } else { lEnvelopeSearchResults.Text = string.Format("More than one person is assigned envelope number {0}. Please select the individual you wish to use.", envelopeNumber); cblEnvelopeSearchPersons.Visible = true; cblEnvelopeSearchPersons.Items.Clear(); var personList = personService.Queryable().Where(a => personIdsWithEnvelopeNumber.Contains(a.Id)).AsNoTracking().ToList(); foreach (var person in personList) { cblEnvelopeSearchPersons.Items.Add(new ListItem(person.FullName, person.Id.ToString())); } mdEnvelopeSearchResults.SaveButtonText = "Select"; mdEnvelopeSearchResults.Show(); } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var workflowActivityGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "Activity").AsGuid()).AsGuid(); if (workflowActivityGuid.IsEmpty()) { action.AddLogEntry("Invalid Activity Property", true); return(false); } var attributeKey = GetAttributeValue(action, "WorkflowAttributeKey", true); var attributeValue = GetAttributeValue(action, "WorkflowAttributeValue", true); if (string.IsNullOrWhiteSpace(attributeKey) || string.IsNullOrWhiteSpace(attributeValue)) { action.AddLogEntry("Invalid Workflow Property", true); return(false); } var activityType = WorkflowActivityTypeCache.Read(workflowActivityGuid); if (activityType == null) { action.AddLogEntry("Invalid Activity Property", true); return(false); } var entityType = EntityTypeCache.Read(typeof(Rock.Model.Workflow)); var workflowIds = new AttributeValueService(rockContext) .Queryable() .AsNoTracking() .Where(a => a.Attribute.Key == attributeKey && a.Value == attributeValue && a.Attribute.EntityTypeId == entityType.Id) .Select(a => a.EntityId); var workflows = new WorkflowService(rockContext) .Queryable() //.AsNoTracking() .Where(w => w.WorkflowType.ActivityTypes.Any(a => a.Guid == activityType.Guid) && workflowIds.Contains(w.Id)) .ToList(); foreach (var workflow in workflows) { WorkflowActivity.Activate(activityType, workflow); action.AddLogEntry(string.Format("Activated new '{0}' activity in {1} {2}", activityType.ToString(), workflow.TypeName, workflow.WorkflowId)); } return(true); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { using (var rockContext = new RockContext()) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); Guid homeBoundPersonWorkflow = GetAttributeValue("HomeboundPersonWorkflow").AsGuid(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(homeBoundPersonWorkflow); if (workflowType == null) { nbError.Visible = true; return; } var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == homeBoundPersonWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "HomeboundPerson" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = 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) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { WorkflowObjects = wf, VisitationActivities = wa }) .Select(obj => new { Workflow = obj.WorkflowObjects.Workflow, AttributeValues = obj.WorkflowObjects.AttributeValues, VisitationActivities = obj.VisitationActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new { Id = w.Workflow.Id, Workflow = w.Workflow, Name = w.Workflow.Name, Address = new Func <string>(() => { PersonAlias p = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()); Location homeLocation = p.Person.GetHomeLocation(); if (homeLocation == null) { return(""); } return(homeLocation.Street1 + homeLocation.City + " " + homeLocation.State + ", " + homeLocation.PostalCode); })(), HomeboundPerson = new Func <Person>(() => { return(personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person); })(), Age = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.Age, StartDate = w.AttributeValues.Where(av => av.AttributeKey == "StartDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), EndDate = w.AttributeValues.Where(av => av.AttributeKey == "EndDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).OrderBy(w => w.Name).ToList().AsQueryable(); SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Name)); } gReport.DataBind(); } }
private IQueryable <HospitalRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid(); var workflowType = new WorkflowTypeService(rockContext).Get(hospitalWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = 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) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new HospitalRow { Id = w.Workflow.Id, Workflow = w.Workflow, Name = w.Workflow.Name, Hospital = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(), HospitalAddress = new Func <string>(() => { DefinedValueCache dv = DefinedValueCache.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid()); return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); })(), PersonToVisit = new Func <Person>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person); } return(new Person()); })(), Age = new Func <int?>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person.Age); } return(null); })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName); return(newQry); }
/// <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, }); // 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(); }
public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid(); Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid(); Guid volunteerGroup = GetAttributeValue("VolunteerGroup").AsGuid(); Group groupId = new Group(); List <DefinedValueCache> facilities = DefinedTypeCache.Get(nursingHomeList).DefinedValues; Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>(); groupId = groupService.GetByGuid(volunteerGroup); var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id; var groupMemberAttributeQry = attributeService.Queryable() .Where(a => a.EntityTypeId == groupMemberEntityTypeId) .Select(a => a.Id); var groupMemberAttributeValueQry = attributeValueService.Queryable() .Where(av => groupMemberAttributeQry.Contains(av.AttributeId)); if (groupId.IsNotNull()) { var groupMemberList = groupMemberService.Queryable() .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active) .GroupJoin(groupMemberAttributeValueQry, gm => gm.Id, av => av.EntityId, (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av }) .ToList(); var groupMembers = new List <GroupMember>(); foreach (var set in groupMemberList) { var groupMember = set.GroupMember; groupMember.Attributes = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId)); groupMember.AttributeValues = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av)); groupMembers.Add(groupMember); } foreach (var nursingHome in facilities) { foreach (var groupMember in groupMembers) { if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace()) { if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower())) { if (volunteerList.ContainsKey(nursingHome.Guid)) { volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue; } else { volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue); } } } } } } int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = 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) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new NursingHomeRow { Id = w.Workflow.Id, Workflow = w.Workflow, NursingHome = new Func <string>(() => { if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any()) { return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault()); } return("N/A"); })(), Person = new Func <Person>(() => { AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); return(pa != null ? pa.Person : new Person()); } return(new Person()); })(), Address = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null) { return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); } return(""); })(), PastoralMinister = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6"))) { return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted); } return(""); })(), Volunteers = new Func <string>(() => { String vList = ""; if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList)) { return(vList); } else { return(""); } })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName); return(newQry); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (IsUserAuthorized(Rock.Security.Authorization.EDIT)) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var person = personService.Get(Person.Id); int?orphanedPhotoId = null; if (person.PhotoId != imgPhoto.BinaryFileId) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if (orphanedPhotoId.HasValue) { if (person.PhotoId.HasValue) { changes.Add("Modified the photo."); } else { changes.Add("Deleted the photo."); } } else if (person.PhotoId.HasValue) { changes.Add("Added a photo."); } } int?newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId)); person.TitleValueId = newTitleId; History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, nickName); person.NickName = tbNickName.Text; History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text); person.MiddleName = tbMiddleName.Text; History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text); person.LastName = tbLastName.Text; int?newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId)); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if (birthday.HasValue) { person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if (birthday.Value.Year != DateTime.MinValue.Year) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate(null); } History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth); History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay); History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear); int?graduationYear = null; if (ypGraduation.SelectedYear.HasValue) { graduationYear = ypGraduation.SelectedYear.Value; } History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear); person.GraduationYear = graduationYear; History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>(); History.EvaluateChange(changes, "Gender", person.Gender, newGender); person.Gender = newGender; int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId)); person.MaritalStatusValueId = newMaritalStatusId; int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId)); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List <int>(); bool smsSelected = false; foreach (RepeaterItem item in rContactInfo.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null) { if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); // Only allow one number to have SMS selected if (smsSelected) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add(phoneNumberTypeId); History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(rockContext); foreach (var phoneNumber in person.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value)) .ToList()) { History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)), phoneNumber.ToString(), string.Empty); person.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text); person.Email = tbEmail.Text.Trim(); History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference); person.EmailPreference = newEmailPreference; var newCommunicationPreference = rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>(); History.EvaluateChange(changes, "Communication Preference", person.CommunicationPreference, newCommunicationPreference); person.CommunicationPreference = newCommunicationPreference; int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if (person.GivingGroupId != newGivingGroupId) { string oldGivingGroupName = string.Empty; if (Person.GivingGroup != null) { oldGivingGroupName = GetFamilyNameWithFirstNames(Person.GivingGroup.Name, Person.GivingGroup.Members); } string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty; History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName); } // Save the Envelope Number attribute if it exists and has changed var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); if (GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null) { if (person.Attributes == null) { person.LoadAttributes(rockContext); } var newEnvelopeNumber = tbGivingEnvelopeNumber.Text; var oldEnvelopeNumber = person.GetAttributeValue(personGivingEnvelopeAttribute.Key); if (newEnvelopeNumber != oldEnvelopeNumber) { // If they haven't already comfirmed about duplicate, see if the envelope number if assigned to somebody else if (!string.IsNullOrWhiteSpace(newEnvelopeNumber) && hfGivingEnvelopeNumberConfirmed.Value != newEnvelopeNumber) { var otherPersonIdsWithEnvelopeNumber = new AttributeValueService(rockContext).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.Value == newEnvelopeNumber && a.EntityId != person.Id) .Select(a => a.EntityId); if (otherPersonIdsWithEnvelopeNumber.Any()) { var personList = new PersonService(rockContext).Queryable().Where(a => otherPersonIdsWithEnvelopeNumber.Contains(a.Id)).AsNoTracking().ToList(); string personListMessage = personList.Select(a => a.FullName).ToList().AsDelimited(", ", " and "); int maxCount = 5; if (personList.Count > maxCount) { var otherCount = personList.Count() - maxCount; personListMessage = personList.Select(a => a.FullName).Take(10).ToList().AsDelimited(", ") + " and " + otherCount.ToString() + " other " + "person".PluralizeIf(otherCount > 1); } string givingEnvelopeWarningText = string.Format( "The envelope #{0} is already assigned to {1}. Do you want to also assign this number to {2}?", newEnvelopeNumber, personListMessage, person.FullName); string givingEnvelopeWarningScriptFormat = @" Rock.dialogs.confirm('{0}', function (result) {{ if ( result ) {{ $('#{1}').val('{2}'); }} }})"; string givingEnvelopeWarningScript = string.Format( givingEnvelopeWarningScriptFormat, givingEnvelopeWarningText, hfGivingEnvelopeNumberConfirmed.ClientID, newEnvelopeNumber); ScriptManager.RegisterStartupScript(hfGivingEnvelopeNumberConfirmed, hfGivingEnvelopeNumberConfirmed.GetType(), "confirm-envelope-number", givingEnvelopeWarningScript, true); return; } } History.EvaluateChange(changes, "Giving Envelope Number", oldEnvelopeNumber, newEnvelopeNumber); person.SetAttributeValue(personGivingEnvelopeAttribute.Key, newEnvelopeNumber); } } person.GivingGroupId = newGivingGroupId; bool recordStatusChangedToOrFromInactive = false; var recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id; int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); // Is the person's record status changing? if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId != newRecordStatusId) { // If it was inactive OR if the new status is inactive, flag this for use later below. if (person.RecordStatusValueId == recordStatusInactiveId || newRecordStatusId == recordStatusInactiveId) { recordStatusChangedToOrFromInactive = true; } } History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); person.RecordStatusValueId = newRecordStatusId; int?newRecordStatusReasonId = null; if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == recordStatusInactiveId) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); person.RecordStatusReasonValueId = newRecordStatusReasonId; History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text); person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim(); // Save any Removed/Added Previous Names var personPreviousNameService = new PersonPreviousNameService(rockContext); var databasePreviousNames = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList(); foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid))) { personPreviousNameService.Delete(deletedPreviousName); History.EvaluateChange( changes, "Previous Name", deletedPreviousName.ToString(), string.Empty); } foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid))) { addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value; personPreviousNameService.Add(addedPreviousName); History.EvaluateChange( changes, "Previous Name", string.Empty, addedPreviousName.ToString()); } if (person.IsValid) { var saveChangeResult = rockContext.SaveChanges(); // if AttributeValues where loaded and set (for example Giving Envelope Number), Save Attribute Values if (person.AttributeValues != null) { person.SaveAttributeValues(rockContext); } if (saveChangeResult > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } if (orphanedPhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(orphanedPhotoId.Value); if (binaryFile != null) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if (imgPhoto.CropBinaryFileId.HasValue) { if (imgPhoto.CropBinaryFileId != person.PhotoId) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } } // If the person's record status was changed to or from inactive, // we need to check if any of their families need to be activated or inactivated. if (recordStatusChangedToOrFromInactive) { foreach (var family in personService.GetFamilies(person.Id)) { // Are there any more members of the family who are NOT inactive? // If not, mark the whole family inactive. if (!family.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveId).Any()) { family.IsActive = false; } else { family.IsActive = true; } } rockContext.SaveChanges(); } } Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } }); } }
/// <summary> /// Cleanups the orphaned attributes. /// </summary> /// <param name="dataMap">The data map.</param> /// <returns></returns> private int CleanupOrphanedAttributes(JobDataMap dataMap) { int recordsDeleted = 0; // Cleanup AttributeMatrix records that are no longer associated with an attribute value using (RockContext rockContext = new RockContext()) { AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext); AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext); var matrixFieldTypeId = FieldTypeCache.Read <MatrixFieldType>().Id; // get a list of attribute Matrix Guids that are actually in use var usedAttributeMatrices = new AttributeValueService(rockContext).Queryable().Where(a => a.Attribute.FieldTypeId == matrixFieldTypeId).Select(a => a.Value).ToList().AsGuidList(); // clean up any orphaned attribute matrices var dayAgo = RockDateTime.Now.AddDays(-1); var orphanedAttributeMatrices = attributeMatrixService.Queryable().Where(a => (a.CreatedDateTime < dayAgo) && !usedAttributeMatrices.Contains(a.Guid)).ToList(); if (orphanedAttributeMatrices.Any()) { recordsDeleted += orphanedAttributeMatrices.Count; attributeMatrixItemService.DeleteRange(orphanedAttributeMatrices.SelectMany(a => a.AttributeMatrixItems)); attributeMatrixService.DeleteRange(orphanedAttributeMatrices); rockContext.SaveChanges(); } } // clean up other orphaned entity attributes Type rockContextType = typeof(Rock.Data.RockContext); foreach (var cachedType in EntityTypeCache.All().Where(e => e.IsEntity)) { Type entityType = cachedType.GetEntityType(); if (entityType != null && typeof(IEntity).IsAssignableFrom(entityType) && typeof(IHasAttributes).IsAssignableFrom(entityType) && !entityType.Namespace.Equals("Rock.Rest.Controllers")) { try { bool ignore = false; if (entityType.Assembly != rockContextType.Assembly) { // If the model is from a custom project, verify that it is using RockContext, if not, ignore it since an // exception will occur due to the AttributeValue query using RockContext. var entityContextType = Reflection.SearchAssembly(entityType.Assembly, typeof(System.Data.Entity.DbContext)); ignore = (entityContextType.Any() && !entityContextType.First().Value.Equals(rockContextType)); } if (!ignore) { var classMethod = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .First(m => m.Name == "CleanupOrphanedAttributeValuesForEntityType"); var genericMethod = classMethod.MakeGenericMethod(entityType); var result = genericMethod.Invoke(this, null) as int?; if (result.HasValue) { recordsDeleted += (int)result; } } } catch { } } } return(recordsDeleted); }