Example #1
0
        /// <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;
            }
        }
Example #2
0
        /// <summary>Gets the person courses.</summary>
        /// <param name="person">The person.</param>
        /// <param name="categories">The categories.</param>
        /// <returns></returns>
        public static List <CourseResult> GetPersonCourses(Person person, List <CategoryCache> categories, bool enrolledOnly = true)
        {
            if (person == null)
            {
                return(null);
            }

            RockContext           rockContext           = new RockContext();
            CourseService         courseService         = new CourseService(rockContext);
            GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
            AttributeValueService attributeValueService = new AttributeValueService(rockContext);

            var courseEntityTypeId = EntityTypeCache.Get(typeof(Course)).Id;

            var attributeValueQry = attributeValueService.Queryable().AsNoTracking()
                                    .Where(av => av.Attribute.EntityTypeId == courseEntityTypeId);

            var qry = courseService.Queryable().AsNoTracking();

            if (categories != null && categories.Any())
            {
                var categoryIds = categories.Select(ca => ca.Id).ToList();
                qry = qry.Where(c => c.Categories.Any(ca => categoryIds.Contains(ca.Id)));
            }

            if (enrolledOnly)
            {
                var riseGroupTypeId = Constants.GetRiseGroupTypeId();
                var riseGroups      = groupMemberService.Queryable().AsNoTracking()
                                      .Where(gm => gm.PersonId == person.Id && gm.Group.GroupTypeId == riseGroupTypeId)
                                      .Select(gm => gm.GroupId);

                qry = qry.Where(c => c.AvailableToAll == true || c.EnrolledGroups.Any(g => riseGroups.Contains(g.Id)));
            }

            var mixedResults = qry.GroupJoin(
                attributeValueQry,
                c => c.Id,
                av => av.EntityId,
                (c, av) => new { Course = c, AttributeValues = av })
                               .OrderBy(m => m.Course.Name)
                               .ToList();

            // Get the Experiences
            int[]    personAliasIds = person.Aliases.Select(a => a.Id).ToArray();
            string[] courseIds      = mixedResults.Select(m => m.Course.Id.ToString()).ToArray();

            ExperienceService experienceService = new ExperienceService(rockContext);
            var experiences = experienceService.Queryable("xObject").Where(e => personAliasIds.Contains(e.PersonAliasId) && courseIds.Contains(e.xObject.ObjectId)).ToList();

            var courses = new List <CourseResult>();

            foreach (var result in mixedResults)
            {
                var courseResult = new CourseResult();
                courseResult.Course = result.Course;
                courseResult.Course.AttributeValues = result.AttributeValues.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                courseResult.Course.Attributes      = result.AttributeValues.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                courseResult.Experiences            = experiences.Where(e => e.xObject != null && e.xObject.ObjectId == result.Course.Id.ToString()).ToList();
                courses.Add(courseResult);
            }

            return(courses);
        }
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using (var rockContext = new RockContext())
            {
                var searchSelections = new Dictionary <string, string>();

                var connectionTypeId             = GetAttributeValue("ConnectionTypeId").AsInteger();
                var connectionType               = new ConnectionTypeService(rockContext).Get(connectionTypeId);
                var connectionOpportunityService = new ConnectionOpportunityService(rockContext);

                var qrySearch = connectionOpportunityService.Queryable().Where(a => a.ConnectionTypeId == connectionTypeId && a.IsActive == true).ToList();

                if (GetAttributeValue("DisplayNameFilter").AsBoolean())
                {
                    if (!string.IsNullOrWhiteSpace(tbSearchName.Text))
                    {
                        searchSelections.Add("tbSearchName", tbSearchName.Text);
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues(true);
                        qrySearch = qrySearch.Where(o => searchTerms.Any(t => t.Contains(o.Name.ToLower()) || o.Name.ToLower().Contains(t))).ToList();
                    }
                }

                if (GetAttributeValue("DisplayCampusFilter").AsBoolean())
                {
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if (searchCampuses.Count > 0)
                    {
                        searchSelections.Add("cblCampus", searchCampuses.AsDelimited("|"));
                        qrySearch = qrySearch.Where(o => o.ConnectionOpportunityCampuses.Any(c => searchCampuses.Contains(c.CampusId))).ToList();
                    }
                }

                if (GetAttributeValue("DisplayAttributeFilters").AsBoolean())
                {
                    // 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)
                        {
                            string filterControlId = "filter_" + attribute.Id.ToString();
                            var    filterControl   = phAttributeFilters.FindControl(filterControlId);
                            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)
                                {
                                    searchSelections.Add(filterControlId, filterValues.ToJson());
                                    var attributeValues = attributeValueService
                                                          .Queryable()
                                                          .Where(v => v.Attribute.Id == attribute.Id);

                                    attributeValues = attributeValues.Where(parameterExpression, expression, null);

                                    qrySearch = qrySearch.Where(o => attributeValues.Select(v => v.EntityId).Contains(o.Id)).ToList();
                                }
                            }
                        }
                    }
                }

                string sessionKey = string.Format("ConnectionSearch_{0}", this.BlockId);
                Session[sessionKey] = searchSelections;

                var opportunities = qrySearch.OrderBy(s => s.PublicName).ToList();

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("CurrentPerson", CurrentPerson);
                mergeFields.Add("Campuses", CampusCache.All());
                mergeFields.Add("CampusContext", RockPage.GetCurrentContext(EntityTypeCache.Read("Rock.Model.Campus")) as Campus);
                var pageReference = new PageReference(GetAttributeValue("DetailPage"), null);
                mergeFields.Add("DetailPage", BuildDetailPageUrl(pageReference.BuildUrl()));

                // iterate through the opportunities and lava merge the summaries and descriptions
                foreach (var opportunity in opportunities)
                {
                    opportunity.Summary     = opportunity.Summary.ResolveMergeFields(mergeFields);
                    opportunity.Description = opportunity.Description.ResolveMergeFields(mergeFields);
                }

                mergeFields.Add("Opportunities", opportunities);

                lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("SetPageTitle").AsBoolean())
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
        }
Example #4
0
        /// <summary>
        /// Builds an expression for an attribute field
        /// </summary>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="entityField">The entity field.</param>
        /// <param name="values">The filter parameter values.</param>
        /// <returns></returns>
        public static Expression GetAttributeExpression(IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List <string> values)
        {
            if (!values.Any())
            {
                // if no filter parameter values where specified, don't filter
                return(Expression.Constant(true));
            }

            var service = new AttributeValueService(( RockContext )serviceInstance.Context);

            var attributeValues = service.Queryable().Where(v =>
                                                            v.EntityId.HasValue);

            AttributeCache attributeCache = null;

            if (entityField.AttributeGuid.HasValue)
            {
                attributeCache = AttributeCache.Get(entityField.AttributeGuid.Value);
                var attributeId = attributeCache != null ? attributeCache.Id : 0;

                attributeValues = attributeValues.Where(v => v.AttributeId == attributeId);
            }
            else
            {
                attributeValues = attributeValues.Where(v => v.Attribute.Key == entityField.Name && v.Attribute.FieldTypeId == entityField.FieldType.Id);
            }

            ParameterExpression attributeValueParameterExpression = Expression.Parameter(typeof(AttributeValue), "v");

            // Determine the appropriate comparison type to use for this Expression.
            // Attribute Value records only exist for Entities that have a value specified for the Attribute.
            // Therefore, if the specified comparison works by excluding certain values we must invert our filter logic:
            // first we find the Attribute Values that match those values and then we exclude the associated Entities from the result set.
            ComparisonType?comparisonType          = ComparisonType.EqualTo;
            ComparisonType?evaluatedComparisonType = comparisonType;
            string         compareToValue          = null;

            if (values.Count >= 2)
            {
                comparisonType = values[0].ConvertToEnumOrNull <ComparisonType>();
                compareToValue = values[1];

                switch (comparisonType)
                {
                case ComparisonType.DoesNotContain:
                    evaluatedComparisonType = ComparisonType.Contains;
                    break;

                case ComparisonType.IsBlank:
                    evaluatedComparisonType = ComparisonType.IsNotBlank;
                    break;

                case ComparisonType.LessThan:
                    evaluatedComparisonType = ComparisonType.GreaterThanOrEqualTo;
                    break;

                case ComparisonType.LessThanOrEqualTo:
                    evaluatedComparisonType = ComparisonType.GreaterThan;
                    break;

                case ComparisonType.NotEqualTo:
                    evaluatedComparisonType = ComparisonType.EqualTo;
                    break;

                default:
                    evaluatedComparisonType = comparisonType;
                    break;
                }

                values[0] = evaluatedComparisonType.ToString();
            }

            var filterExpression = entityField.FieldType.Field.AttributeFilterExpression(entityField.FieldConfig, values, attributeValueParameterExpression);

            if (filterExpression != null)
            {
                if (filterExpression is NoAttributeFilterExpression)
                {
                    // Special Case: If AttributeFilterExpression returns NoAttributeFilterExpression, just return the NoAttributeFilterExpression.
                    // For example, If this is a CampusFieldType and they didn't pick any campus, we don't want to do any filtering for this datafilter.
                    return(filterExpression);
                }
                else
                {
                    attributeValues = attributeValues.Where(attributeValueParameterExpression, filterExpression, null);
                }
            }
            else
            {
                // AttributeFilterExpression returned NULL (the FieldType didn't specify any additional filter on AttributeValue),
                // so just filter based on if the AttributeValue exists with a non-empty value
                if (entityField.FieldType.Field.FilterComparisonType.HasFlag(ComparisonType.IsBlank) && string.IsNullOrEmpty(compareToValue))
                {
                    // in the case of EqualTo/NotEqualTo with a NULL compareToValue, filter this using an IsBlank/IsNotBlank filter ( if the fieldtype supports it )
                    if (comparisonType == ComparisonType.EqualTo)
                    {
                        // treat as IsBlank, but invert so that it ends being "NOT (people that *have* a value)"
                        // this will make is so that the filter will return people that have a blank value or no AttributeValue record
                        comparisonType          = ComparisonType.IsBlank;
                        evaluatedComparisonType = ComparisonType.IsNotBlank;
                    }
                    else if (comparisonType == ComparisonType.NotEqualTo)
                    {
                        // treat as IsNotBlank
                        comparisonType          = ComparisonType.IsNotBlank;
                        evaluatedComparisonType = ComparisonType.IsNotBlank;
                    }
                }

                attributeValues = attributeValues.Where(a => !string.IsNullOrEmpty(a.Value));
            }

            IQueryable <int> ids = attributeValues.Select(v => v.EntityId.Value);

            MemberExpression   propertyExpression = Expression.Property(parameterExpression, "Id");
            ConstantExpression idsExpression      = Expression.Constant(ids.AsQueryable(), typeof(IQueryable <int>));
            Expression         expression         = Expression.Call(typeof(Queryable), "Contains", new Type[] { typeof(int) }, idsExpression, propertyExpression);

            if (attributeCache != null)
            {
                var comparedToDefault = entityField.FieldType.Field.IsComparedToValue(values, attributeCache.DefaultValue);
                if (comparedToDefault)
                {
                    var allAttributeValueIds = service.Queryable().Where(v => v.Attribute.Id == attributeCache.Id && v.EntityId.HasValue && !string.IsNullOrEmpty(v.Value)).Select(a => a.EntityId.Value);

                    ConstantExpression allIdsExpression      = Expression.Constant(allAttributeValueIds.AsQueryable(), typeof(IQueryable <int>));
                    Expression         notContainsExpression = Expression.Not(Expression.Call(typeof(Queryable), "Contains", new Type[] { typeof(int) }, allIdsExpression, propertyExpression));

                    expression = Expression.Or(expression, notContainsExpression);
                }
            }

            // If we have used an inverted comparison type for the evaluation, invert the Expression so that it excludes the matching Entities.
            if (comparisonType != evaluatedComparisonType)
            {
                return(Expression.Not(expression));
            }
            else
            {
                return(expression);
            }
        }
Example #5
0
        /// <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;
            }
        }
        private void DisplayDetails()
        {
            int         eventItemId = 0;
            RockContext rockContext = new RockContext();

            EventItemService eventItemService = new EventItemService(rockContext);
            var qry = eventItemService
                      .Queryable();


            // get the eventItem id
            if (!string.IsNullOrWhiteSpace(PageParameter("EventItemId")))
            {
                eventItemId = Convert.ToInt32(PageParameter("EventItemId"));
            }
            if (eventItemId > 0)
            {
                /*var qry = eventItemService
                 *  .Queryable()
                 *  ;*/
                qry = qry.Where(i => i.Id == eventItemId);
            }
            else
            {
                // Get the Slug Attribute
                var slugAttribute = AttributeCache.Read(GetAttributeValue("URLSlugAttribute").AsGuid());

                // get the slug
                if (!string.IsNullOrWhiteSpace(PageParameter("URLSlug")) && slugAttribute != null)
                {
                    int slugAttributeId = slugAttribute.Id;
                    EventCalendarItemService eventCalendarItemService = new EventCalendarItemService(rockContext);
                    AttributeValueService    attributeValueService    = new AttributeValueService(rockContext);

                    var tmQry = qry.Join(eventCalendarItemService.Queryable(),
                                         ei => ei.Id,
                                         aci => aci.EventItemId,
                                         (ei, aci) => new { EventItem = ei, EventCalendarItem = aci }
                                         )
                                .Join(attributeValueService.Queryable(),
                                      ei => new { Id = ei.EventCalendarItem.Id, AttributeId = slugAttributeId },
                                      av => new { Id = av.EntityId ?? 0, AttributeId = av.AttributeId },
                                      (ei, av) => new { EventItem = ei.EventItem, EventCalendarItem = ei.EventCalendarItem, Slug = av });

                    string urlSlug = PageParameter("URLSlug");

                    tmQry = tmQry.Where(obj => obj.Slug.Value.Contains(urlSlug));

                    // The page parameter could contain something like 'camp' while the slug value list contains 'camp-freedom' so we need to double-check
                    // to make sure we have an exact match
                    qry = tmQry.ToList().AsQueryable().Where(obj => obj.Slug.Value.ToLower().Split('|').Contains(urlSlug.ToLower())).Select(obj => obj.EventItem);
                }
                else
                {
                    // If we don't have an eventItemId or slug we shouldn't get the first item in the database.  That would be . . . not good
                    qry = null;
                }
            }

            if (qry != null)
            {
                var eventItem = qry.FirstOrDefault();

                if (eventItem != null)
                {
                    // removing any occurrences that don't have a start time in the next twelve months
                    var occurrenceList = eventItem.EventItemOccurrences.ToList();
                    occurrenceList.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddYears(1)).Count() == 0);

                    //Check for Campus Id Parameter
                    var campusId = PageParameter("CampusId").AsIntegerOrNull();
                    if (campusId.HasValue)
                    {
                        //check if there's a campus with this id.
                        var campus = CampusCache.Read(campusId.Value);
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                    }

                    //Check for Campus
                    var campusStr = PageParameter("Campus");
                    if (!string.IsNullOrEmpty(campusStr))
                    {
                        //check if there's a campus with this name.
                        var campus = CampusCache.All().Where(c => c.Name.ToLower() == campusStr.ToLower()).FirstOrDefault();
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                    }

                    eventItem.EventItemOccurrences = occurrenceList;

                    var mergeFields = new Dictionary <string, object>();
                    mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));

                    var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        mergeFields.Add("CampusContext", contextCampus);
                    }

                    // determine registration status (Register, Full, or Join Wait List) for each unique registration instance
                    Dictionary <int, string> registrationStatusLabels = new Dictionary <int, string>();
                    foreach (var occurance in eventItem.EventItemOccurrences)
                    {
                        foreach (var registrationInstance in occurance.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList())
                        {
                            if (registrationStatusLabels.ContainsKey(registrationInstance.Id))
                            {
                                continue;
                            }
                            var maxRegistrantCount       = 0;
                            var currentRegistrationCount = 0;

                            if (registrationInstance != null)
                            {
                                if (registrationInstance.MaxAttendees != 0)
                                {
                                    maxRegistrantCount = registrationInstance.MaxAttendees;
                                }
                            }


                            int?registrationSpotsAvailable = null;
                            if (maxRegistrantCount != 0)
                            {
                                currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking()
                                                           .Where(r =>
                                                                  r.Registration.RegistrationInstanceId == registrationInstance.Id &&
                                                                  r.OnWaitList == false)
                                                           .Count();
                                registrationSpotsAvailable = maxRegistrantCount - currentRegistrationCount;
                            }

                            string registrationStatusLabel = "Register";

                            if (registrationSpotsAvailable.HasValue && registrationSpotsAvailable.Value < 1)
                            {
                                if (registrationInstance.RegistrationTemplate.WaitListEnabled)
                                {
                                    registrationStatusLabel = "Join Wait List";
                                }
                                else
                                {
                                    registrationStatusLabel = "Full";
                                }
                            }

                            registrationStatusLabels.Add(registrationInstance.Id, registrationStatusLabel);
                        }
                    }

                    // Status of each registration instance
                    mergeFields.Add("RegistrationStatusLabels", registrationStatusLabels);

                    mergeFields.Add("Event", eventItem);
                    mergeFields.Add("CurrentPerson", CurrentPerson);

                    lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                    if (GetAttributeValue("SetPageTitle").AsBoolean())
                    {
                        string pageTitle = eventItem != null ? eventItem.Name : "Event";
                        RockPage.PageTitle    = pageTitle;
                        RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                        RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    }
                }
                else
                {
                    lOutput.Text = "<div class='alert alert-warning'>We could not find that event.</div>";
                }
            }
            else
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
            {
                //Load the person based on the FormId
                var personInUrl = PageParameter("FormId");
                SelectedPerson   = GetPersonFromForm(personInUrl);
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
            {
                //Load the person based on the PersonId
                SelectedPerson = GetPersonFromId(PageParameter("PersonId"));
            }

            else
            {
                //Show Error Message
                nbNoPerson.Visible = true;
                return;
            }


            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService   definedValueService   = new DefinedValueService(rockContext);

            string spiritualGift1  = "";
            string spiritualGift2  = "";
            string spiritualGift3  = "";
            string spiritualGift4  = "";
            string heartCategories = "";
            string heartCauses     = "";
            string heartPassion    = "";
            string ability1        = "";
            string ability2        = "";
            string people          = "";
            string places          = "";
            string events          = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            var spiritualGift2AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

            var spiritualGift3AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

            var spiritualGift4AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

            var ability1AttributeValue =
                attributeValueService
                .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

            var ability2AttributeValue =
                attributeValueService
                .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

            var peopleAttributeValue = attributeValueService
                                       .Queryable()
                                       .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

            var placesAttributeValue = attributeValueService
                                       .Queryable()
                                       .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

            var eventsAttributeValue = attributeValueService
                                       .Queryable()
                                       .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

            var heartCategoriesAttributeValue = attributeValueService
                                                .Queryable()
                                                .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

            var heartCausesAttributeValue = attributeValueService
                                            .Queryable()
                                            .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

            var heartPassionAttributeValue = attributeValueService
                                             .Queryable()
                                             .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);


            if (spiritualGift1AttributeValue.Value != null)
            {
                spiritualGift1 = spiritualGift1AttributeValue.Value;
            }
            if (spiritualGift2AttributeValue.Value != null)
            {
                spiritualGift2 = spiritualGift2AttributeValue.Value;
            }
            if (spiritualGift3AttributeValue.Value != null)
            {
                spiritualGift3 = spiritualGift3AttributeValue.Value;
            }
            if (spiritualGift4AttributeValue.Value != null)
            {
                spiritualGift4 = spiritualGift4AttributeValue.Value;
            }
            if (heartCategoriesAttributeValue.Value != null)
            {
                heartCategories = heartCategoriesAttributeValue.Value;
            }
            if (heartCausesAttributeValue.Value != null)
            {
                heartCauses = heartCausesAttributeValue.Value;
            }
            if (heartPassionAttributeValue.Value != null)
            {
                heartPassion = heartPassionAttributeValue.Value;
            }
            if (ability1AttributeValue.Value != null)
            {
                ability1 = ability1AttributeValue.Value;
            }
            if (ability2AttributeValue.Value != null)
            {
                ability2 = ability2AttributeValue.Value;
            }
            if (peopleAttributeValue.Value != null)
            {
                people = peopleAttributeValue.Value;
            }
            if (placesAttributeValue.Value != null)
            {
                places = placesAttributeValue.Value;
            }
            if (eventsAttributeValue.Value != null)
            {
                events = eventsAttributeValue.Value;
            }


            string spiritualGift1Guid;
            string spiritualGift2Guid;
            string spiritualGift3Guid;
            string spiritualGift4Guid;
            string ability1Guid;
            string ability2Guid;


            // Check to see if there are already values saved as an ID.  If so, convert them to GUID
            if (spiritualGift1.ToString().Length < 5)
            {
                if (spiritualGift1 != null)
                {
                    SpiritualGift1 = Int32.Parse(spiritualGift1);
                }
                if (spiritualGift2 != null)
                {
                    SpiritualGift2 = Int32.Parse(spiritualGift2);
                }
                if (spiritualGift3 != null)
                {
                    SpiritualGift3 = Int32.Parse(spiritualGift3);
                }
                if (spiritualGift4 != null)
                {
                    SpiritualGift4 = Int32.Parse(spiritualGift4);
                }
                if (ability1 != null)
                {
                    Ability1 = Int32.Parse(ability1);
                }
                if (ability2 != null)
                {
                    Ability2 = Int32.Parse(ability2);
                }

                var intsOfGifts =
                    definedValueService.GetByIds(new List <int>
                {
                    SpiritualGift1,
                    SpiritualGift2,
                    SpiritualGift3,
                    SpiritualGift4,
                    Ability1,
                    Ability2
                });

                spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                ability1Guid       = intsOfGifts.ToList()[Ability1].Guid.ToString();
                ability2Guid       = intsOfGifts.ToList()[Ability2].Guid.ToString();
            }
            else
            {
                spiritualGift1Guid = spiritualGift1;
                spiritualGift2Guid = spiritualGift2;
                spiritualGift3Guid = spiritualGift3;
                spiritualGift4Guid = spiritualGift4;
                ability1Guid       = ability1;
                ability2Guid       = ability2;
            }



            // Get all of the data about the assiciated gifts and ability categories
            var shapeGift1Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(spiritualGift1Guid)
            }).FirstOrDefault();
            var shapeGift2Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(spiritualGift2Guid)
            }).FirstOrDefault();
            var shapeGift3Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(spiritualGift3Guid)
            }).FirstOrDefault();
            var shapeGift4Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(spiritualGift4Guid)
            }).FirstOrDefault();
            var ability1Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(ability1Guid)
            }).FirstOrDefault();
            var ability2Object = definedValueService.GetListByGuids(new List <Guid> {
                new Guid(ability2Guid)
            }).FirstOrDefault();

            shapeGift1Object.LoadAttributes();
            shapeGift2Object.LoadAttributes();
            shapeGift3Object.LoadAttributes();
            shapeGift4Object.LoadAttributes();
            ability1Object.LoadAttributes();
            ability2Object.LoadAttributes();


            // Get heart choices Values from Guids
            string heartCategoriesString = "";

            if (!heartCategories.IsNullOrWhiteSpace())
            {
                string[] heartCategoryArray = heartCategories.Split(',');
                foreach (string category in heartCategoryArray)
                {
                    var definedValueObject =
                        definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                    if (category.Equals(heartCategoryArray.Last()))
                    {
                        heartCategoriesString += definedValueObject.Value;
                    }
                    else
                    {
                        heartCategoriesString += definedValueObject.Value + ", ";
                    }
                }
            }



            // Get Volunteer Opportunities

            string gift1AssociatedVolunteerOpportunities =
                shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
            string gift2AssociatedVolunteerOpportunities =
                shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
            string gift3AssociatedVolunteerOpportunities =
                shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
            string gift4AssociatedVolunteerOpportunities =
                shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

            string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                         gift2AssociatedVolunteerOpportunities + "," +
                                                         gift3AssociatedVolunteerOpportunities + "," +
                                                         gift4AssociatedVolunteerOpportunities;

            if (allAssociatedVolunteerOpportunities != ",,,")
            {
                List <int> associatedVolunteerOpportunitiesList =
                    allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                Dictionary <int, int> VolunteerOpportunities = new Dictionary <int, int>();


                var i = 0;
                var q = from x in associatedVolunteerOpportunitiesList
                        group x by x
                        into g
                        let count = g.Count()
                                    orderby count descending
                                    select new { Value = g.Key, Count = count };
                foreach (var x in q)
                {
                    VolunteerOpportunities.Add(i, x.Value);
                    i++;
                }

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                List <ConnectionOpportunity> connectionOpportunityList    = new List <ConnectionOpportunity>();

                foreach (KeyValuePair <int, int> entry in VolunteerOpportunities.Take(4))
                {
                    var connection = connectionOpportunityService.GetByIds(new List <int> {
                        entry.Value
                    }).FirstOrDefault();

                    // Only display connection if it is marked Active
                    if (connection.IsActive == true)
                    {
                        connectionOpportunityList.Add(connection);
                    }
                }

                rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                rpVolunteerOpportunities.DataBind();
            }


            //Get DISC Info

            DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);

            if (!savedScores.Equals(null))
            {
                ShowResults(savedScores);
                DISCResults.Visible   = true;
                NoDISCResults.Visible = false;
            }



            // Build the UI

            lbPersonName.Text = SelectedPerson.FullName;

            lbGift1Title.Text    = shapeGift1Object.Value;
            lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

            lbGift2Title.Text    = shapeGift2Object.Value;
            lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

            lbGift3Title.Text    = shapeGift3Object.Value;
            lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

            lbGift4Title.Text    = shapeGift4Object.Value;
            lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

            lbAbility1Title.Text    = ability1Object.Value;
            lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

            lbAbility2Title.Text    = ability2Object.Value;
            lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

            lbPeople.Text = people;
            lbPlaces.Text = places;
            lbEvents.Text = events;

            lbHeartCategories.Text = heartCategoriesString;
            lbHeartCauses.Text     = heartCauses;
            lbHeartPassion.Text    = heartPassion;

            if (spiritualGift1AttributeValue.ModifiedDateTime != null)
            {
                lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
            }
            else
            {
                lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
            }
        }
Example #8
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if (_workflowType != null)
            {
                pnlWorkflowList.Visible = true;

                if (_workflowType != null)
                {
                    var rockContext     = new RockContext();
                    var workflowService = new WorkflowService(rockContext);

                    var qry = workflowService
                              .Queryable("Activities.ActivityType,InitiatorPersonAlias.Person").AsNoTracking()
                              .Where(w => w.WorkflowTypeId.Equals(_workflowType.Id));

                    // Activated Date Range Filter
                    if (drpActivated.LowerValue.HasValue)
                    {
                        qry = qry.Where(w => w.ActivatedDateTime >= drpActivated.LowerValue.Value);
                    }
                    if (drpActivated.UpperValue.HasValue)
                    {
                        DateTime upperDate = drpActivated.UpperValue.Value.Date.AddDays(1);
                        qry = qry.Where(w => w.ActivatedDateTime.Value < upperDate);
                    }

                    // State Filter
                    List <string> states = cblState.SelectedValues;
                    if (states.Count == 1)      // Don't filter if none or both options are selected
                    {
                        if (states[0] == "Active")
                        {
                            qry = qry.Where(w => !w.CompletedDateTime.HasValue);
                        }
                        else
                        {
                            qry = qry.Where(w => w.CompletedDateTime.HasValue);
                        }
                    }

                    // Completed Date Range Filter
                    if (drpCompleted.LowerValue.HasValue)
                    {
                        qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value >= drpCompleted.LowerValue.Value);
                    }
                    if (drpCompleted.UpperValue.HasValue)
                    {
                        DateTime upperDate = drpCompleted.UpperValue.Value.Date.AddDays(1);
                        qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value < upperDate);
                    }

                    string name = tbName.Text;
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        qry = qry.Where(w => w.Name.StartsWith(name));
                    }

                    int?personId = ppInitiator.SelectedValue;
                    if (personId.HasValue)
                    {
                        qry = qry.Where(w => w.InitiatorPersonAlias.PersonId == personId.Value);
                    }

                    string status = tbStatus.Text;
                    if (!string.IsNullOrWhiteSpace(status))
                    {
                        qry = qry.Where(w => w.Status.StartsWith(status));
                    }

                    // 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));
                                }
                            }
                        }
                    }

                    IQueryable <Workflow> workflows = null;

                    var sortProperty = gWorkflows.SortProperty;
                    if (sortProperty != null)
                    {
                        if (sortProperty.Property == "Initiator")
                        {
                            if (sortProperty.Direction == SortDirection.Ascending)
                            {
                                workflows = qry
                                            .OrderBy(w => w.InitiatorPersonAlias.Person.LastName)
                                            .ThenBy(w => w.InitiatorPersonAlias.Person.NickName);
                            }
                            else
                            {
                                workflows = qry
                                            .OrderByDescending(w => w.InitiatorPersonAlias.Person.LastName)
                                            .ThenByDescending(w => w.InitiatorPersonAlias.Person.NickName);
                            }
                        }
                        else
                        {
                            workflows = qry.Sort(sortProperty);
                        }
                    }
                    else
                    {
                        workflows = qry.OrderByDescending(s => s.CreatedDateTime);
                    }

                    // Since we're not binding to actual workflow list, but are using AttributeField columns,
                    // we need to save the workflows into the grid's object list
                    var workflowObjectQry = workflows;
                    if (gWorkflows.AllowPaging)
                    {
                        workflowObjectQry = workflowObjectQry.Skip(gWorkflows.PageIndex * gWorkflows.PageSize).Take(gWorkflows.PageSize);
                    }

                    gWorkflows.ObjectList = workflowObjectQry.ToList().ToDictionary(k => k.Id.ToString(), v => v as object);

                    gWorkflows.EntityTypeId = EntityTypeCache.Read <Workflow>().Id;
                    var qryGrid = workflows.Select(w => new
                    {
                        w.Id,
                        w.Name,
                        Initiator  = w.InitiatorPersonAlias.Person,
                        Activities = w.Activities.Where(a => a.ActivatedDateTime.HasValue && !a.CompletedDateTime.HasValue).OrderBy(a => a.ActivityType.Order).Select(a => a.ActivityType.Name),
                        w.CreatedDateTime,
                        Status      = w.Status,
                        IsCompleted = w.CompletedDateTime.HasValue
                    });

                    gWorkflows.SetLinqDataSource(qryGrid);
                    gWorkflows.DataBind();
                }
                else
                {
                    pnlWorkflowList.Visible = false;
                }
            }
        }
Example #9
0
        private bool UpdateSearchValueRecords(IJobExecutionContext context, int howManyToConvert, int commandTimeout)
        {
            bool anyRemaining = true;

            int howManyLeft = howManyToConvert;

            var attribute       = AttributeCache.Get("8F528431-A438-4488-8DC3-CA42E66C1B37".AsGuid());
            var searchTypeValue = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid());

            if (attribute != null && searchTypeValue != null)
            {
                while (howManyLeft > 0)
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupMemberService     = new GroupMemberService(rockContext);
                        var attributeValueService  = new AttributeValueService(rockContext);
                        var personSearchKeyService = new PersonSearchKeyService(rockContext);

                        int take = howManyLeft < 100 ? howManyLeft : 100;

                        var attributeValueRecords = attributeValueService
                                                    .Queryable()
                                                    .Where(v =>
                                                           v.AttributeId == attribute.Id &&
                                                           v.EntityId.HasValue)
                                                    .OrderBy(v => v.Id)
                                                    .Take(take)
                                                    .ToList();

                        anyRemaining = attributeValueRecords.Count >= take;
                        howManyLeft  = anyRemaining ? howManyLeft - take : 0;

                        foreach (var attributevalueRecord in attributeValueRecords)
                        {
                            var hoh = groupMemberService
                                      .Queryable()
                                      .Where(m => m.GroupId == attributevalueRecord.EntityId.Value)
                                      .HeadOfHousehold();

                            if (hoh != null && hoh.PrimaryAlias != null)
                            {
                                var keys = attributevalueRecord.Value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var key in keys)
                                {
                                    var searchValue = new PersonSearchKey
                                    {
                                        PersonAliasId     = hoh.PrimaryAlias.Id,
                                        SearchTypeValueId = searchTypeValue.Id,
                                        SearchValue       = key
                                    };
                                    personSearchKeyService.Add(searchValue);
                                }
                            }

                            attributeValueService.Delete(attributevalueRecord);

                            rockContext.SaveChanges();
                        }

                        int numberMigrated  = howManyToConvert - howManyLeft;
                        var percentComplete = howManyToConvert > 0 ? (numberMigrated * 100.0) / howManyToConvert : 100.0;
                        var statusMessage   = $@"Progress: {numberMigrated} of {howManyToConvert} ({Math.Round( percentComplete, 1 )}%) Family Check-in Identifiers migrated to person search key values";
                        context.UpdateLastStatusMessage(statusMessage);

                        rockContext.SaveChanges(disablePrePostProcessing: true);
                    }
                }
            }

            return(anyRemaining);
        }
        private void LoadKeywordGroup()
        {
            var keyword = PageParameter("keyword");

            if (keyword.IsNullOrWhiteSpace())
            {
                pnlKeyword.Visible = false;
                return;
            }

            var attributeKey = GetAttributeValue("KeywordKey");

            int         communicationListGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id;
            var         groupEntityTypeId            = EntityTypeCache.Get(typeof(Group)).Id;
            RockContext rockContext = new RockContext();

            AttributeService attributeService = new AttributeService(rockContext);
            var attribute = attributeService.Queryable().AsNoTracking()
                            .Where(a => a.EntityTypeId == groupEntityTypeId &&
                                   a.EntityTypeQualifierValue == communicationListGroupTypeId.ToString() &&
                                   a.Key == attributeKey)
                            .FirstOrDefault();

            if (attribute == null)
            {
                pnlKeyword.Visible = false;
                return;
            }

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            var attributeValue = attributeValueService.Queryable().AsNoTracking()
                                 .Where(av => av.AttributeId == attribute.Id &&
                                        (av.Value == keyword ||
                                         av.Value.Contains("|" + keyword) ||
                                         av.Value.Contains(keyword + "|") ||
                                         av.Value.Contains("|" + keyword + "|"))
                                        ).FirstOrDefault();

            if (attributeValue == null)
            {
                pnlKeyword.Visible = false;
                return;
            }

            GroupService groupService = new GroupService(rockContext);
            var          group        = groupService.Get(attributeValue.EntityId ?? 0);

            if (group == null || !group.IsActive || group.IsArchived)
            {
                pnlKeyword.Visible = false;
                return;
            }
            group.LoadAttributes();

            var name = group.GetAttributeValue("PublicName");

            if (name.IsNullOrWhiteSpace())
            {
                name = group.Name;
            }
            ltGroupName.Text = name;

            var type = group.GetAttributeValue(GetAttributeValue("AttributeKey"));

            if (type.IsNullOrWhiteSpace())
            {
                type = "Text Message,Email";
            }

            type = string.Join(", ", type.SplitDelimitedValues(false));

            ltType.Text        = type;
            ltDescription.Text = group.Description;

            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            GroupMember activeMember = null;

            var groupMembers = groupMemberService.GetByGroupIdAndPersonId(group.Id, Person.Id).ToList();

            foreach (var member in groupMembers)
            {
                if (member.GroupMemberStatus == GroupMemberStatus.Active)
                {
                    activeMember = member;
                }
            }

            bool hasActiveMember = false;

            if (activeMember != null)
            {
                hasActiveMember = true;
            }
            else
            {
                activeMember = new GroupMember
                {
                    GroupId = group.Id
                };
            }

            activeMember.LoadAttributes();
            activeMember.Attributes = activeMember.Attributes.Where(a => a.Value.IsGridColumn).ToDictionary(a => a.Key, a => a.Value);


            if (hasActiveMember)
            {
                if (activeMember.Attributes.Any())
                {
                    nbAlreadySubscribed.Visible = true;
                    nbAlreadySubscribed.Text    = "You are already subscribed to this list, but you can update your subscription settings here.";
                    btnSubscribe.Text           = "Update";
                }
                else
                {
                    nbAlreadySubscribed.Visible = true;
                    nbAlreadySubscribed.Text    = "You are already subscribed to this list, but you can manage the rest of your subscriptions on this page. ";
                    btnSubscribe.Visible        = false;
                }
            }

            if (activeMember.Attributes.Any())
            {
                ltAttributesHeader.Text = "<h3>Subscription Settings</h3>";
                Rock.Attribute.Helper.AddEditControls(activeMember, phGroupAttributes, true);
            }

            ViewState["KeywordGroupId"] = group.Id;
        }
Example #11
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var groupMemberService            = new GroupMemberService(rockContext);
            var groupService                  = new GroupService(rockContext);
            var groupTypeService              = new GroupTypeService(rockContext);
            var attributeService              = new AttributeService(rockContext);
            var attributeValueService         = new AttributeValueService(rockContext);
            var personService                 = new PersonService(rockContext);
            var personAliasService            = new PersonAliasService(rockContext);
            var entityTypeService             = new EntityTypeService(rockContext);
            var registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var eiogmService                  = new EventItemOccurrenceGroupMapService(rockContext);
            var groupLocationService          = new GroupLocationService(rockContext);
            var locationService               = new LocationService(rockContext);
            var signatureDocumentServce       = new SignatureDocumentService(rockContext);
            var phoneNumberService            = new PhoneNumberService(rockContext);

            int[] signatureDocumentIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates")))
            {
                signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse);
            }
            Guid bbGroup = GetAttributeValue("Group").AsGuid();
            var  group   = new GroupService(rockContext).Get(bbGroup);

            if (group.Name.Contains("Week 2"))
            {
                cmpCampus.Visible = true;
            }

            Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid();
            int? hsmGroupTypeId   = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault();

            int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id;

            var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList();

            hlGroup.NavigateUrl = "/group/" + group.Id;

            var attributeIds = attributeService.Queryable()
                               .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue)))
                               .Select(a => a.Id).ToList();

            var gmTmpqry = groupMemberService.Queryable()
                           .Where(gm => (gm.GroupId == group.Id));

            var qry = gmTmpqry
                      .GroupJoin(registrationRegistrantService.Queryable(),
                                 obj => obj.Id,
                                 rr => rr.GroupMemberId,
                                 (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 },
                                 av => new { PersonId = av.EntityId, av.AttributeId },
                                 (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.GroupMember.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.RegistrationRegistrant.FirstOrDefault().Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ });

            var qry2 = gmTmpqry
                       .GroupJoin(
                groupMemberService.Queryable()
                .Join(groupService.Queryable(),
                      gm => new { Id = gm.GroupId, GroupTypeId = 10 },
                      g => new { g.Id, g.GroupTypeId },
                      (gm, g) => new { GroupMember = gm, Group = g })
                .Join(groupLocationService.Queryable(),
                      obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 },
                      gl => new { gl.GroupId, gl.GroupLocationTypeValueId },
                      (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl })
                .Join(locationService.Queryable(),
                      obj => obj.GroupLocation.LocationId,
                      l => l.Id,
                      (obj, l) => new { GroupMember = obj.GroupMember, Location = l }),
                gm => gm.PersonId,
                glgm => glgm.GroupMember.PersonId,
                (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() }
                )
                       .GroupJoin(signatureDocumentServce.Queryable()
                                  .Join(personAliasService.Queryable(),
                                        sd => sd.AppliesToPersonAliasId,
                                        pa => pa.Id,
                                        (sd, pa) => new { SignatureDocument = sd, Alias = pa }),
                                  obj => obj.GroupMember.PersonId,
                                  sd => sd.Alias.PersonId,
                                  (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds })
                       .GroupJoin(phoneNumberService.Queryable(),
                                  obj => obj.GroupMember.PersonId,
                                  p => p.PersonId,
                                  (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn });


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix))))
            {
                string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower();
                qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable();
            }
            decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull();
            decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull();

            if (lowerVal != null && upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal && q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable();
            }
            else if (lowerVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal).AsQueryable();
            }
            else if (upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable();
            }
            else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue))
            {
                if (group.Name.Contains("Week 2"))
                {
                    qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).AsQueryable();
                }
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var tmp  = qry.ToList();
            var tmp2 = qry2.ToList();

            lStats.Text = "Query Runtime: " + stopwatch.Elapsed;
            stopwatch.Reset();

            stopwatch.Start();

            var newQry = tmp.Select(g => new
            {
                Id                    = g.GroupMember.Id,
                RegisteredBy          = new ModelValue <Person>(g.RegistrationRegistrant.Select(rr => rr.Registration.PersonAlias.Person).FirstOrDefault()),
                Registrant            = new ModelValue <Person>(g.Person),
                Age                   = g.Person.Age,
                GraduationYear        = g.Person.GraduationYear,
                RegistrationId        = g.RegistrationRegistrant.Select(rr => rr.RegistrationId).FirstOrDefault(),
                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.FirstOrDefault(), 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();
        }
Example #12
0
        /// <summary>
        /// Binds the grid to a list of Prayer Requests.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
            SortProperty         sortProperty         = gPrayerRequests.SortProperty;

            var prayerRequests = prayerRequestService.Queryable().AsNoTracking();

            // Filter by prayer category if one is selected...
            int selectedPrayerCategoryID = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull() ?? All.Id;

            if (selectedPrayerCategoryID != All.Id && selectedPrayerCategoryID != None.Id)
            {
                prayerRequests = prayerRequests.Where(c => c.CategoryId == selectedPrayerCategoryID ||
                                                      (c.CategoryId.HasValue && c.Category.ParentCategoryId == selectedPrayerCategoryID));
            }

            // Filter by Campus if one is selected...
            int?selectedPrayerCampusID = cpPrayerCampusFilter.SelectedCampusId;

            if (selectedPrayerCampusID.HasValue && selectedPrayerCampusID.Value > 0)
            {
                prayerRequests = prayerRequests.Where(c => c.CampusId == selectedPrayerCampusID);
            }

            // 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.Visible)
            {
                prayerRequests = prayerRequests.Where(a => a.IsPublic == true);
            }
            else
            {
                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.EnteredDateTime >= 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.EnteredDateTime < endDate);
            }

            // Don't show expired prayer requests.
            if (!cbShowExpired.Checked)
            {
                prayerRequests = prayerRequests.Where(a => a.ExpirationDate == null || RockDateTime.Today <= a.ExpirationDate);
            }

            // 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)
                    {
                        continue;
                    }

                    var filterValues    = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter);
                    var filterIsDefault = attribute.FieldType.Field.IsEqualToValue(filterValues, attribute.DefaultValue);
                    var expression      = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression);
                    if (expression == null)
                    {
                        continue;
                    }

                    var attributeValues = attributeValueService
                                          .Queryable()
                                          .Where(v => v.Attribute.Id == attribute.Id);

                    var filteredAttributeValues = attributeValues.Where(parameterExpression, expression, null);

                    if (filterIsDefault)
                    {
                        prayerRequests = prayerRequests.Where(w =>
                                                              !attributeValues.Any(v => v.EntityId == w.Id) ||
                                                              filteredAttributeValues.Select(v => v.EntityId).Contains(w.Id));
                    }
                    else
                    {
                        prayerRequests = prayerRequests.Where(w =>
                                                              filteredAttributeValues.Select(v => v.EntityId).Contains(w.Id));
                    }
                }
            }

            var personContext = this.ContextEntity <Person>();

            if (personContext != null)
            {
                prayerRequests = prayerRequests.Where(a => a.RequestedByPersonAlias.PersonId == personContext.Id);
            }

            if (sortProperty != null)
            {
                gPrayerRequests.DataSource = prayerRequests.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerRequests.DataSource = prayerRequests.OrderByDescending(p => p.EnteredDateTime).ThenByDescending(p => p.Id).ToList();
            }

            gPrayerRequests.EntityTypeId = EntityTypeCache.Read <PrayerRequest>().Id;
            gPrayerRequests.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);
        }
Example #14
0
        private static List <BreakoutGroupItem> GetBreakoutGroupItems(Person person)
        {
            List <BreakoutGroupItem> allBreakoutGroupItems = RockCache.Get(cacheKey) as List <BreakoutGroupItem>;

            if (allBreakoutGroupItems == null || !allBreakoutGroupItems.Any())
            {
                allBreakoutGroupItems = new List <BreakoutGroupItem>();
                RockContext rockContext = new RockContext();

                var attributeService      = new AttributeService(rockContext);
                var attributeValueService = new AttributeValueService(rockContext);

                var groupEntityTypeId        = EntityTypeCache.GetId(typeof(Rock.Model.Group));
                var breakoutGroupGroupTypeId = GroupTypeCache.GetId(Constants.GROUP_TYPE_BREAKOUT_GROUPS.AsGuid());

                if (groupEntityTypeId == null || breakoutGroupGroupTypeId == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout groups due to missing breakoutgroup type"));
                    return(new List <BreakoutGroupItem>());
                }

                var letterAttribute = attributeService.GetByEntityTypeQualifier(groupEntityTypeId, "GroupTypeId", breakoutGroupGroupTypeId.Value.ToString(), false)
                                      .Where(a => a.Key == Constants.GROUP_ATTRIBUTE_KEY_LETTER)
                                      .FirstOrDefault();

                if (letterAttribute == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout group letter attribute."));
                    return(new List <BreakoutGroupItem>());
                }

                var attributeQueryable = attributeValueService.Queryable().AsNoTracking()
                                         .Where(av => letterAttribute.Id == av.AttributeId);

                //Get all the data in one go
                var breakoutData = new GroupService(rockContext)
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(g => g.GroupTypeId == breakoutGroupGroupTypeId && g.IsActive && !g.IsArchived)
                                   .Join(attributeQueryable,
                                         g => g.Id,
                                         av => av.EntityId,
                                         (g, av) => new
                {
                    ScheduleId = g.ScheduleId ?? 0,
                    PersonIds  = g.Members.Where(gm => gm.IsArchived == false && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.PersonId),
                    Letter     = av.Value
                })
                                   .ToList();

                foreach (var item in breakoutData)
                {
                    foreach (var personId in item.PersonIds)
                    {
                        allBreakoutGroupItems.Add(new BreakoutGroupItem
                        {
                            Letter     = item.Letter,
                            PersonId   = personId,
                            ScheduleId = item.ScheduleId
                        });
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroupItems, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }

            return(allBreakoutGroupItems.Where(i => i.PersonId == person.Id).ToList());
        }
Example #15
0
        /// <summary>
        /// Builds an expression for an attribute field
        /// </summary>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="entityField">The property.</param>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        public static Expression CreateAttributeExpression(IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List <string> values)
        {
            var service = new AttributeValueService((RockContext)serviceInstance.Context);

            var attributeValues = service.Queryable().Where(v =>
                                                            v.EntityId.HasValue &&
                                                            v.Value != string.Empty);

            if (entityField.AttributeGuid.HasValue)
            {
                attributeValues = attributeValues.Where(v => v.Attribute.Guid == entityField.AttributeGuid);
            }
            else
            {
                attributeValues = attributeValues.Where(v => v.Attribute.Key == entityField.Name && v.Attribute.FieldTypeId == entityField.FieldType.Id);
            }

            ParameterExpression attributeValueParameterExpression = Expression.Parameter(typeof(AttributeValue), "v");

            // Determine the appropriate comparison type to use for this Expression.
            // Attribute Value records only exist for Entities that have a value specified for the Attribute.
            // Therefore, if the specified comparison works by excluding certain values we must invert our filter logic:
            // first we find the Attribute Values that match those values and then we exclude the associated Entities from the result set.
            var            comparisonType          = ComparisonType.EqualTo;
            ComparisonType evaluatedComparisonType = comparisonType;

            if (values.Count >= 2)
            {
                string comparisonValue = values[0];

                // If no comparison is specified, we do not have sufficient information to create a valid filter.
                if (comparisonValue == "0")
                {
                    return(null);
                }

                comparisonType = comparisonValue.ConvertToEnum <ComparisonType>(ComparisonType.EqualTo);

                switch (comparisonType)
                {
                case ComparisonType.DoesNotContain:
                    evaluatedComparisonType = ComparisonType.Contains;
                    break;

                case ComparisonType.IsBlank:
                    evaluatedComparisonType = ComparisonType.IsNotBlank;
                    break;

                case ComparisonType.NotEqualTo:
                    evaluatedComparisonType = ComparisonType.EqualTo;
                    break;

                default:
                    evaluatedComparisonType = comparisonType;
                    break;
                }

                values[0] = evaluatedComparisonType.ToString();
            }

            var filterExpression = entityField.FieldType.Field.AttributeFilterExpression(entityField.FieldConfig, values, attributeValueParameterExpression);

            // The filter values could not be used to create a valid expression, so exit.
            if (filterExpression == null)
            {
                return(null);
            }

            attributeValues = attributeValues.Where(attributeValueParameterExpression, filterExpression, null);


            IQueryable <int> ids = attributeValues.Select(v => v.EntityId.Value);

            MemberExpression   propertyExpression = Expression.Property(parameterExpression, "Id");
            ConstantExpression idsExpression      = Expression.Constant(ids.AsQueryable(), typeof(IQueryable <int>));
            Expression         expression         = Expression.Call(typeof(Queryable), "Contains", new Type[] { typeof(int) }, idsExpression, propertyExpression);

            // If we have used an inverted comparison type for the evaluation, invert the Expression so that it excludes the matching Entities.
            if (comparisonType != evaluatedComparisonType)
            {
                return(Expression.Not(expression));
            }
            else
            {
                return(expression);
            }
        }
        /// <summary>
        /// Maps the Individual Giftedness.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapIndividualGiftedness(IQueryable <Row> tableData)
        {
            var lookupContext    = new RockContext();
            var attributeService = new AttributeService(lookupContext);

            int rank1Id = attributeService.Queryable().Where(a => a.Key == "Rank1").FirstOrDefault().Id;
            int rank2Id = attributeService.Queryable().Where(a => a.Key == "Rank2").FirstOrDefault().Id;
            int rank3Id = attributeService.Queryable().Where(a => a.Key == "Rank3").FirstOrDefault().Id;
            int rank4Id = attributeService.Queryable().Where(a => a.Key == "Rank4").FirstOrDefault().Id;



            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Giftedness Program import ({0:N0} found).", totalRows));

            var newAttributeValueList = new List <AttributeValue>();

            foreach (var row in tableData)
            {
                int?individualId      = row["Individual_ID"] as int?;
                int personId          = (int)GetPersonAliasId(individualId);
                var newAttributeValue = new AttributeValue();
                int?rank   = row["Rank"] as int?;
                int rankId = 0;

                //not everyone has all 4 ranks, some are missing the fourth and that was causing it to run in the below if condition and try to create a duplicate record.
                if (rank == 1)
                {
                    rankId = rank1Id;
                }
                if (rank == 2)
                {
                    rankId = rank2Id;
                }
                if (rank == 3)
                {
                    rankId = rank3Id;
                }
                if (rank == 4)
                {
                    rankId = rank4Id;
                }


                if (personId != 0 && rankId != 0)
                {
                    var attributeValueService = new AttributeValueService(lookupContext);

                    //checks if they are in the database already or if there is a record currently in the newAttributeValueList
                    if (attributeValueService.Queryable().Where(a => a.AttributeId == rankId && a.EntityId == personId).FirstOrDefault() == null && newAttributeValueList.Find(a => a.AttributeId == rankId && a.EntityId == personId) == null)
                    {
                        DateTime?assessmentDate        = row["AssessmentDate"] as DateTime?;
                        int?     giftAttributeId       = row["GiftAttributeID"] as int?;
                        string   giftAttributeIdString = Convert.ToString(giftAttributeId);



                        var definedValueService = new DefinedValueService(lookupContext);


                        newAttributeValue.IsSystem = false;
                        newAttributeValue.EntityId = personId;

                        if (rank == 1)
                        {
                            newAttributeValue.AttributeId = rank1Id;
                        }
                        if (rank == 2)
                        {
                            newAttributeValue.AttributeId = rank2Id;
                        }
                        if (rank == 3)
                        {
                            newAttributeValue.AttributeId = rank3Id;
                        }
                        if (rank == 4)
                        {
                            newAttributeValue.AttributeId = rank4Id;
                        }

                        newAttributeValue.Value           = Convert.ToString(definedValueService.Queryable().Where(a => a.ForeignId == giftAttributeIdString).FirstOrDefault().Guid);
                        newAttributeValue.CreatedDateTime = assessmentDate;

                        newAttributeValueList.Add(newAttributeValue);
                        completed++;
                    }
                }
                if (newAttributeValueList.Any())
                {
                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        var rockContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.AttributeValues.AddRange(newAttributeValueList);
                            rockContext.SaveChanges(DisableAudit);
                            newAttributeValueList.Clear();
                        });
                        ReportPartialProgress();
                    }
                }
            }

            if (newAttributeValueList.Any())
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    rockContext.AttributeValues.AddRange(newAttributeValueList);
                    rockContext.SaveChanges(DisableAudit);
                });
            }

            ReportProgress(100, string.Format("Finished individual gifts import: {0:N0} spiritual gifts imported.", completed));
        }
        protected void BindData()
        {
            List <int> campusIds  = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            // Initialize services
            var rockContext           = new RockContext();
            var publishGroupService   = new PublishGroupService(rockContext);
            var attributeService      = new AttributeService(rockContext);
            var attributeValueService = new AttributeValueService(rockContext);

            //Get the entity types
            var publishGroupEntityTypeId = EntityTypeCache.Get(typeof(PublishGroup)).Id;
            var groupEntityTypeId        = EntityTypeCache.Get(typeof(Group)).Id;

            //Attribute Queryables
            var publishGroupAttributeQry = attributeService.Queryable()
                                           .Where(a => a.EntityTypeId == publishGroupEntityTypeId)
                                           .Select(a => a.Id);

            var groupAttributeQry = attributeService.Queryable()
                                    .Where(a => a.EntityTypeId == groupEntityTypeId)
                                    .Select(a => a.Id);

            //Attribute Value Queryables
            var publishGroupAttributeValueQry = attributeValueService.Queryable()
                                                .Where(av => publishGroupAttributeQry.Contains(av.AttributeId));

            var groupAttributeValueQry = attributeValueService.Queryable()
                                         .Where(av => groupAttributeQry.Contains(av.AttributeId));


            var qry = publishGroupService
                      .Queryable("Group")
                      .Where(pg => !pg.IsHidden)                                                                             //Is not hidden from list
                      .Where(pg => pg.PublishGroupStatus == PublishGroupStatus.Approved)                                     //Approved
                      .Where(pg => pg.StartDateTime <= Rock.RockDateTime.Today && pg.EndDateTime >= Rock.RockDateTime.Today) //Active
                      .Where(pg => pg.Group.GroupType.GroupCapacityRule == GroupCapacityRule.None ||
                             pg.Group.GroupCapacity == null || pg.Group.GroupCapacity == 0 ||
                             pg.Group.Members.Count() < pg.Group.GroupCapacity);      // Not full


            // Filter by campus
            if (campusIds.Any())
            {
                qry = qry
                      .Where(pg =>
                             !pg.Group.CampusId.HasValue || // All
                             campusIds.Contains(pg.Group.CampusId.Value));
            }

            // Filter by Category
            if (categories.Any())
            {
                qry = qry
                      .Where(pg => pg.AudienceValues
                             .Any(dv => categories.Contains(dv.Id)));
            }

            //Group join in attributes
            var mixedQry = qry
                           .GroupJoin(publishGroupAttributeValueQry,
                                      pg => pg.Id,
                                      av => av.EntityId,
                                      (pg, av) => new { pg, av })
                           .GroupJoin(groupAttributeValueQry,
                                      pg => pg.pg.GroupId,
                                      av => av.EntityId,
                                      (pg, av) => new { PublishGroup = pg.pg, PublishGroupAttributes = pg.av, GroupAttributes = av });

            //Add in the attributes in the proper format
            var publishGroups = new List <PublishGroup>();

            foreach (var item in mixedQry.ToList())
            {
                var publishGroup = item.PublishGroup;
                publishGroup.AttributeValues = item.PublishGroupAttributes.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                publishGroup.Attributes      = item.PublishGroupAttributes.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                if (publishGroup.Group == null)
                {
                    continue;
                }
                publishGroup.Group.AttributeValues = item.GroupAttributes.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                publishGroup.Group.Attributes      = item.GroupAttributes.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                publishGroups.Add(publishGroup);
            }

            // Output mergefields.
            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("PublishGroups", publishGroups);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
        void lvAttributeValues_ItemInserting( object sender, ListViewInsertEventArgs e )
        {
            PlaceHolder phInsertValue = lvAttributeValues.InsertItem.FindControl( "phInsertValue" ) as PlaceHolder;
            if ( phInsertValue != null && phInsertValue.Controls.Count == 1 )
            {
                string value = _attribute.FieldType.Field.ReadValue( phInsertValue.Controls[0] );

                var attributeValueService = new AttributeValueService();
                var attributeValue = new AttributeValue();
                attributeValue.AttributeId = _attribute.Id;
                attributeValue.EntityId = _model.Id;
                attributeValue.Value = value;

                int? maxOrder = attributeValueService.Queryable().
                    Where( a => a.AttributeId == attributeValue.AttributeId &&
                        a.EntityId == attributeValue.EntityId).
                    Select( a => ( int? )a.Order ).Max();

                attributeValue.Order = maxOrder.HasValue ? maxOrder.Value + 1 : 0;

                attributeValueService.Add( attributeValue, _currentPersonId);
                attributeValueService.Save( attributeValue, _currentPersonId );
                Rock.Attribute.Helper.LoadAttributes( _model );
            }

            lvAttributeValues.EditIndex = -1;
            BindData();
        }
        /// <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();
            }
        }