示例#1
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            EntityTypeService entityTypeService = new EntityTypeService(new RockContext());
            SortProperty      sortProperty      = gEntityTypes.SortProperty;

            var qry = entityTypeService.Queryable().Where(e => e.IsSecured || e.IsEntity);

            string search = gfSettings.GetUserPreference("Search");

            if (!string.IsNullOrWhiteSpace(search))
            {
                qry = qry.Where(h => h.Name.Contains(search) || h.FriendlyName.Contains(search));
            }

            if (sortProperty != null)
            {
                qry = qry.Sort(sortProperty);
            }
            else
            {
                qry = qry.OrderBy(p => p.Name);
            }

            gEntityTypes.DataSource = qry.ToList();
            gEntityTypes.DataBind();
        }
示例#2
0
        /// <summary>
        /// Gets the query.
        /// </summary>
        /// <returns></returns>
        private IQueryable <EntityType> GetQuery()
        {
            var entityTypeService = new EntityTypeService(new RockContext());

            var entityTypes = entityTypeService.Queryable().AsNoTracking();

            // Filter by Name
            string nameFilter = gfSettings.GetUserPreference("Name");

            if (!string.IsNullOrEmpty(nameFilter.Trim()))
            {
                entityTypes = entityTypes.Where(a => a.Name.Contains(nameFilter.Trim()));
            }

            // Filter by Is Entity
            bool?isEntityFilter = gfSettings.GetUserPreference("IsEntity").AsBooleanOrNull();

            if (isEntityFilter.HasValue)
            {
                entityTypes = entityTypes.Where(a => a.IsEntity == isEntityFilter.Value);
            }

            // Filter by Is Entity
            bool?isSecuredFilter = gfSettings.GetUserPreference("IsEntity").AsBooleanOrNull();

            if (isSecuredFilter.HasValue)
            {
                entityTypes = entityTypes.Where(a => a.IsEntity == isSecuredFilter.Value);
            }

            return(entityTypes);
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            RockContext       rockContext       = new RockContext();
            EntityTypeService entityTypeService = new EntityTypeService(rockContext);
            var assembly     = typeof(org.secc.Trak1.BackgroundCheck.Trak1).AssemblyQualifiedName;
            var entity       = entityTypeService.Queryable().Where(et => et.AssemblyName == assembly).FirstOrDefault();
            var providerGuid = entity.Guid;
            var provider     = BackgroundCheckContainer.GetComponent(providerGuid.ToString());

            var trak1    = (org.secc.Trak1.BackgroundCheck.Trak1)provider;
            var packages = trak1.GetPackageList();

            foreach (var package in packages)
            {
                PanelWidget panelWidget = new PanelWidget()
                {
                    Title    = package.PackageName,
                    Expanded = true
                };
                phPackages.Controls.Add(panelWidget);
                var sb = new StringBuilder();
                sb.Append("<ul>");
                sb.AppendFormat("<li>Price: {0}</li>", package.PackagePrice);
                sb.AppendFormat("<li>Description: {0}</li>", package.PackageDescription);
                sb.Append("<li><b>Components:</b></li>");
                sb.Append("<ul>");
                foreach (var component in package.Components)
                {
                    sb.AppendFormat("<li><b>{0}</b></li>", component.ComponentName);
                    sb.AppendFormat("<li>Description: {0}</li>", component.ComponentDescription);
                    if (component.RequiredFields.Any())
                    {
                        sb.Append("<li><b>Required Fields:</b></li>");
                        sb.Append("<ul>");
                        foreach (var requiredField in component.RequiredFields)
                        {
                            sb.AppendFormat("<li>Name: {0}</li>", requiredField.Name);
                            sb.Append("<ul>");
                            sb.AppendFormat("<li>Type: {0}</li>", requiredField.Type);
                            sb.AppendFormat("<li>Length: {0}</li>", requiredField.Length);
                            sb.AppendFormat("<li>Description: {0}</li>", requiredField.Description);
                            sb.Append("</ul>");
                        }
                        sb.Append("</ul>");
                    }
                }
                sb.Append("</ul>");
                sb.Append("</ul>");
                LiteralControl ltInfo = new LiteralControl
                {
                    Text = sb.ToString()
                };
                panelWidget.Controls.Add(ltInfo);
            }
        }
示例#4
0
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var entityTypeService = new EntityTypeService(rockContext);

            return(entityTypeService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
示例#5
0
    /// <summary>
    /// Binds the grid.
    /// </summary>
    private void BindGrid()
    {
        EntityTypeService entityTypeService = new EntityTypeService();
        SortProperty      sortProperty      = gEntityTypes.SortProperty;

        if (sortProperty != null)
        {
            gEntityTypes.DataSource = entityTypeService
                                      .Queryable()
                                      .Where(e => e.IsSecured || e.IsEntity)
                                      .Sort(sortProperty).ToList();
        }
        else
        {
            gEntityTypes.DataSource = entityTypeService
                                      .Queryable()
                                      .Where(e => e.IsSecured || e.IsEntity)
                                      .OrderBy(p => p.Name).ToList();
        }

        gEntityTypes.DataBind();
    }
示例#6
0
        /// <summary>
        /// Finds the attributes that are of type Entity..
        /// </summary>
        /// <returns></returns>
        public static IQueryable <EntityAttribute> GetEntitiyAttributes()
        {
            var rockContext = new RockContext();

            EntityTypeService entityTypeService = new EntityTypeService(rockContext);
            var entityTypes = entityTypeService.Queryable().Where(e => e.IsEntity == true);

            AttributeService attributeService = new AttributeService(rockContext);
            var attributes = attributeService.Queryable();

            return(entityTypes
                   .Where(t => t.FriendlyName != null && t.FriendlyName.Trim() != string.Empty)
                   .Join(
                       attributes,
                       t => t.Id,
                       a => a.EntityTypeId,
                       (type, attribute) => new EntityAttribute
            {
                EntityTypeLegacyLava = type,
                AttributeLegacyLava = attribute
            }));
        }
示例#7
0
        /// <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();
            }
        }
示例#8
0
        private IQueryable <HospitalRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);


            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid();

            var workflowType           = new WorkflowTypeService(rockContext).Get(hospitalWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();


            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new HospitalRow
            {
                Id              = w.Workflow.Id,
                Workflow        = w.Workflow,
                Name            = w.Workflow.Name,
                Hospital        = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(),
                HospitalAddress = new Func <string>(() =>
                {
                    DefinedValueCache dv = DefinedValueCache.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid());
                    return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                           dv.AttributeValues["Qualifier4"].ValueFormatted);
                })(),
                PersonToVisit = new Func <Person>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person);
                    }
                    return(new Person());
                })(),
                Age = new Func <int?>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person.Age);
                    }
                    return(null);
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() => {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName);

            return(newQry);
        }
示例#9
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();
        }
        public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);
            var groupMemberService      = new GroupMemberService(rockContext);
            var groupService            = new GroupService(rockContext);

            Guid  nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid();
            Guid  nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid();
            Guid  volunteerGroup  = GetAttributeValue("VolunteerGroup").AsGuid();
            Group groupId         = new Group();

            List <DefinedValueCache>  facilities    = DefinedTypeCache.Get(nursingHomeList).DefinedValues;
            Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>();

            groupId = groupService.GetByGuid(volunteerGroup);

            var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id;

            var groupMemberAttributeQry = attributeService.Queryable()
                                          .Where(a => a.EntityTypeId == groupMemberEntityTypeId)
                                          .Select(a => a.Id);

            var groupMemberAttributeValueQry = attributeValueService.Queryable()
                                               .Where(av => groupMemberAttributeQry.Contains(av.AttributeId));

            if (groupId.IsNotNull())
            {
                var groupMemberList = groupMemberService.Queryable()
                                      .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active)
                                      .GroupJoin(groupMemberAttributeValueQry,
                                                 gm => gm.Id,
                                                 av => av.EntityId,
                                                 (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av })
                                      .ToList();

                var groupMembers = new List <GroupMember>();

                foreach (var set in groupMemberList)
                {
                    var groupMember = set.GroupMember;

                    groupMember.Attributes = set.GroupMemberAttributeValues
                                             .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));

                    groupMember.AttributeValues = set.GroupMemberAttributeValues
                                                  .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));

                    groupMembers.Add(groupMember);
                }

                foreach (var nursingHome in facilities)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace())
                        {
                            if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower()))
                            {
                                if (volunteerList.ContainsKey(nursingHome.Guid))
                                {
                                    volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue;
                                }

                                else
                                {
                                    volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue);
                                }
                            }
                        }
                    }
                }
            }
            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            var workflowType           = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();

            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new NursingHomeRow
            {
                Id          = w.Workflow.Id,
                Workflow    = w.Workflow,
                NursingHome = new Func <string>(() =>
                {
                    if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any())
                    {
                        return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault());
                    }
                    return("N/A");
                })(),
                Person = new Func <Person>(() =>
                {
                    AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault();
                    if (personAliasAV != null)
                    {
                        PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid());

                        return(pa != null ? pa.Person : new Person());
                    }
                    return(new Person());
                })(),
                Address = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null)
                    {
                        return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                               dv.AttributeValues["Qualifier4"].ValueFormatted);
                    }
                    return("");
                })(),
                PastoralMinister = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6")))
                    {
                        return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted);
                    }
                    return("");
                })(),
                Volunteers = new Func <string>(() =>
                {
                    String vList = "";
                    if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList))
                    {
                        return(vList);
                    }
                    else
                    {
                        return("");
                    }
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() =>
                {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName);

            return(newQry);
        }
        /// <summary>
        /// Maps the authorizations to an attribute.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapAuthorizations(IQueryable <Row> tableData)
        {
            var lookupContext   = new RockContext();
            var rockContext     = new RockContext();
            var categoryService = new CategoryService(lookupContext);
            var personService   = new PersonService(lookupContext);

            var noteList = new List <Note>();


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

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

            var attributeList            = new AttributeService(lookupContext).Queryable().ToList();
            int authorizationAttributeId = 0;

            if (attributeList.Find(a => a.Key == "PickupAuthorization") != null)
            {
                authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id;
            }

            var authorizationAttributeValueList = new List <AttributeValue>();

            authorizationAttributeValueList = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == authorizationAttributeId).ToList();

            int f1HouseholdIdAttributeId = attributeList.Find(a => a.Key == "F1HouseholdId").Id;

            //places all household attributes in a dictionary where the key is the personId and the houshold is the value.
            var householdDictionary = new AttributeValueService(lookupContext).Queryable()
                                      .Where(av => av.AttributeId == f1HouseholdIdAttributeId)
                                      .Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value })
                                      .ToDictionary(t => t.PersonId, t => t.HouseholdId);


            foreach (var row in tableData)
            {
                //var rockContext = new RockContext();
                var categoryList = new CategoryService(rockContext).Queryable().ToList();


                //check if category exists
                //If it doesn't (though it should), it will create a new category called Authorization
                if (categoryList.Find(c => c.Name == "Childhood Information") == null)
                {
                    var entityType = new EntityTypeService(rockContext);
                    //creates if category doesn't exist
                    var newCategory = new Category();
                    newCategory.IsSystem     = false;
                    newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault();
                    newCategory.EntityTypeQualifierColumn = "EntityTypeId";
                    newCategory.EntityTypeQualifierValue  = Convert.ToString(PersonEntityTypeId);
                    newCategory.Name        = "Authorization";
                    newCategory.Description = "Contains the pickup authorization";

                    //var newCategoryContext = new RockContext();
                    //newCategoryContext.WrapTransaction( () =>
                    //{
                    //    newCategoryContext.Configuration.AutoDetectChangesEnabled = false;
                    //    newCategoryContext.Categories.Add( newCategory );
                    //    newCategoryContext.SaveChanges( DisableAudit );
                    //} );
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Categories.Add(newCategory);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                attributeList = new AttributeService(lookupContext).Queryable().ToList();

                //Check if Attribute exists
                //If it doesn't it creates the attribute
                if (attributeList.Find(a => a.Key == "PickupAuthorization") == null)
                {
                    var fieldType = new FieldTypeService(rockContext);
                    //var newAttributeList = new List<Rock.Model.Attribute>();
                    var fieldTypeId = fieldType.Queryable().Where(e => e.Name == "Memo").FirstOrDefault().Id;
                    var category2   = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Childhood Information").FirstOrDefault();
                    var category3   = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Authorization").FirstOrDefault();

                    //Creates if attribute doesn't exist
                    //The attribute is a memo attribute
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Key                       = "PickupAuthorization";
                    newAttribute.Name                      = "Pickup Authorization";
                    newAttribute.FieldTypeId               = fieldTypeId;
                    newAttribute.EntityTypeId              = PersonEntityTypeId;
                    newAttribute.EntityTypeQualifierValue  = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.Description               = "Lists who is authorized to pickup this child along with their current phone number.";
                    newAttribute.DefaultValue              = string.Empty;
                    newAttribute.IsMultiValue              = false;
                    newAttribute.IsRequired                = false;

                    if (categoryList.Find(c => c.Name == "Childhood Information") != null)
                    {
                        newAttribute.Categories = new List <Category>();
                        newAttribute.Categories.Add(category2);
                    }
                    //If authorization category was create, this is where the attribute is set to that category.
                    else
                    {
                        newAttribute.Categories = new List <Category>();
                        newAttribute.Categories.Add(category3);    //Sets to Authorization Attribute Category.
                    }

                    //saves the attribute
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Attributes.Add(newAttribute);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //Adding to the person's attributes
                int?     householdId       = row["HouseholdID"] as int?;
                string   personName        = row["PersonName"] as string;
                DateTime?authorizationDate = row["AuthorizationDate"] as DateTime?;

                attributeList = new AttributeService(rockContext).Queryable().ToList();

                //Gets the Attribute Id for Pickup Authorization.
                authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id;


                //since F1 authorization applies to the household id and not individual I have to apply it to all members in that household.
                //Value in F1 is a text entry and not a person select. Discuss with staff that we need to break away from this and start using known relationships for authorization
                foreach (var household in householdDictionary.Where(h => h.Value == Convert.ToString(householdId)))
                {
                    //checks if a record already exists in the list

                    if (authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key) == null)
                    {
                        var person = new PersonService(rockContext).Queryable().Where(p => p.Id == household.Key).FirstOrDefault();

                        //trying to keep from adding this attribute to adult records
                        if (person != null && (person.Age <= 18 || person.Age == null))
                        {
                            //creates new attribute record if it does not exist.
                            var newAuthorizationAttribute = new AttributeValue();
                            newAuthorizationAttribute.IsSystem        = false;
                            newAuthorizationAttribute.AttributeId     = authorizationAttributeId;
                            newAuthorizationAttribute.EntityId        = household.Key;     //the key is the person ID
                            newAuthorizationAttribute.Value           = personName + ", "; //text field
                            newAuthorizationAttribute.CreatedDateTime = authorizationDate;

                            //adds the new record to the list
                            authorizationAttributeValueList.Add(newAuthorizationAttribute);
                        }
                    }
                    //if a record already exists
                    else
                    {
                        //adds to the current value.
                        authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key).Value = personName + ", ";
                    }
                }
                completed++;
                if (completed % percentage < 1)
                {
                    int percentComplete = completed / percentage;
                    ReportProgress(percentComplete, string.Format("{0:N0} authorizations imported ({1}% complete).", completed, percentComplete));
                }
                else if (completed % ReportingNumber < 1)
                {
                    //rockContext.WrapTransaction( () =>
                    // {
                    //     rockContext.Configuration.AutoDetectChangesEnabled = false;
                    //     rockContext.AttributeValues.AddRange( authorizationAttributeValueList );
                    //     rockContext.SaveChanges( DisableAudit );  //I get can't insert duplicate entry error
                    // } );

                    ReportPartialProgress();
                }
            }

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

            ReportProgress(100, string.Format("Finished authorization import: {0:N0} notes imported.", completed));
        }
示例#12
0
        /// <summary>
        /// Maps the Giftedness Program.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapGiftednessProgram(IQueryable <Row> tableData)
        {
            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));

            foreach (var row in tableData)
            {
                var rockContext      = new RockContext();
                var categoryList     = new CategoryService(rockContext).Queryable().ToList();
                var attributeList    = new AttributeService(rockContext).Queryable().ToList();
                var definedTypeList  = new DefinedTypeService(rockContext).Queryable().ToList();
                var definedValueList = new DefinedValueService(rockContext).Queryable().ToList();

                //check if category exists
                string category = row["CategoryName"] as string;
                if (categoryList.Find(c => c.Name == category) == null)
                {
                    var entityType = new EntityTypeService(rockContext);
                    //creates if category doesn't exist
                    var newCategory = new Category();
                    newCategory.IsSystem     = false;
                    newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault();
                    newCategory.EntityTypeQualifierColumn = "EntityTypeId";
                    newCategory.EntityTypeQualifierValue  = Convert.ToString(PersonEntityTypeId);   //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault());
                    newCategory.Name        = category;
                    newCategory.Description = "Contains the spiritual gifts attributes";

                    //var newCategoryContext = new RockContext();
                    //newCategoryContext.WrapTransaction( () =>
                    //{
                    //    newCategoryContext.Configuration.AutoDetectChangesEnabled = false;
                    //    newCategoryContext.Categories.Add( newCategory );
                    //    newCategoryContext.SaveChanges( DisableAudit );
                    //} );
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Categories.Add(newCategory);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //Check if Attribute exists
                if (attributeList.Find(a => a.Key == "Rank1") == null || attributeList.Find(a => a.Key == "Rank2") == null || attributeList.Find(a => a.Key == "Rank3") == null || attributeList.Find(a => a.Key == "Rank4") == null)
                {
                    var fieldType        = new FieldTypeService(rockContext);
                    var newAttributeList = new List <Rock.Model.Attribute>();
                    var fieldTypeId      = fieldType.Queryable().Where(e => e.Name == "Defined Value").FirstOrDefault().Id;
                    var category2        = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Spiritual Gifts").FirstOrDefault();


                    if (attributeList.Find(a => a.Key == "Rank1") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank1";
                        newAttribute.Name                      = "Rank 1";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 1";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank2") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank2";
                        newAttribute.Name                      = "Rank 2";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 2";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank3") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank3";
                        newAttribute.Name                      = "Rank 3";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 3";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank4") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank4";
                        newAttribute.Name                      = "Rank 4";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 4";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);


                        newAttributeList.Add(newAttribute);
                    }

                    if (newAttributeList.Any())
                    {
                        //var newAttributeContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Attributes.AddRange(newAttributeList);
                            rockContext.SaveChanges(DisableAudit);
                            newAttributeList.Clear();
                        });
                    }
                }
                //checks if Defined Type exists
                if (definedTypeList.Find(d => d.Name == "Spiritual Gifts") == null)
                {
                    var fieldTypeService = new FieldTypeService(rockContext);

                    //creates Defined Type
                    var newDefinedType = new DefinedType();
                    newDefinedType.IsSystem    = false;
                    newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where(f => f.Name == "Text").Select(f => f.Id).FirstOrDefault();
                    newDefinedType.Name        = "Spiritual Gifts";
                    newDefinedType.Description = "Defined Type for Spiritual Gifts values";
                    newDefinedType.CategoryId  = categoryList.Find(c => c.Name == "Person").Id;

                    //var newDTContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedTypes.Add(newDefinedType);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //checks if Defined Value exists
                var    spiritualGiftsDefineType = new DefinedTypeService(rockContext).Queryable().Where(d => d.Name == "Spiritual Gifts").FirstOrDefault();
                string attributeName            = row["AttributeName"] as string;
                int?   giftAttributeId          = row["GiftAttributeID"] as int?;
                if (definedValueList.Find(d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName) == null)
                {
                    var definedTypeService = new DefinedTypeService(rockContext);
                    //creates Defined Value
                    var newDefinedValue = new DefinedValue();
                    newDefinedValue.IsSystem      = false;
                    newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where(d => d.Name == "Spiritual Gifts").Select(d => d.Id).FirstOrDefault();
                    newDefinedValue.Value         = attributeName;
                    newDefinedValue.Description   = "Spiritual Gift attribute value: " + attributeName;
                    newDefinedValue.ForeignId     = Convert.ToString(giftAttributeId);

                    //var newDVContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedValues.Add(newDefinedValue);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }

                completed++;

                if (completed % percentage < 1)
                {
                    int percentComplete = completed / percentage;
                    ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete));
                }
                else if (completed % ReportingNumber < 1)
                {
                    ReportPartialProgress();
                }
            }

            ReportProgress(100, string.Format("Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed));
        }
示例#13
0
        /// <summary>
        /// Maps the Connect Groups.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapGroups(IQueryable <Row> tableData)  //Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?)
        {
            var lookupContext           = new RockContext();
            int completedMembers        = 0;
            int completedGroups         = 0;
            int completedLifeStages     = 0;
            int completedTags           = 0;
            int completedIndividualTags = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying group import ({0:N0} found. Total may vary based on Group Type Name).", totalRows));


            foreach (var row in tableData)
            {
                var rockContext               = new RockContext();
                var lifeStageContext          = new RockContext();
                var connectGroupContext       = new RockContext();
                var connectGroupMemberContext = new RockContext();

                string groupTypeName = row["Group_Type_Name"] as string;
                if (groupTypeName.Trim() == "Connect Groups")              //Moves Connect Groups into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var connectGroupsId       = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Connect Group Tree exists

                    //If it doesn't exist
                    if (connectGroupsId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Connect Groups";
                        connectGroupTree.Description = "Crossroads Connect Group Ministry";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Groups.Add(connectGroupTree);
                            rockContext.SaveChanges(DisableAudit);
                        });
                    }

                    //check to see if life stage exists
                    //getting the life stage name
                    string lifeStage = groupName;
                    int    index     = lifeStage.IndexOf("-");
                    if (index > 0)
                    {
                        lifeStage = lifeStage.Substring(0, index).Trim();
                    }

                    //checks to see if it exists
                    int existingLifeStage = new GroupService(lookupContext).Queryable().Where(g => g.Name == lifeStage).Select(a => a.Id).FirstOrDefault();
                    if (existingLifeStage == 0)
                    {
                        //Create one.
                        var connectGroupsLifeStage = new Group();
                        connectGroupsLifeStage.IsSystem      = false;
                        connectGroupsLifeStage.ParentGroupId = connectGroupsId;
                        connectGroupsLifeStage.GroupTypeId   = groupTypeIdSection;
                        connectGroupsLifeStage.CampusId      = 1;
                        connectGroupsLifeStage.Name          = lifeStage;
                        connectGroupsLifeStage.Description   = "";
                        connectGroupsLifeStage.IsActive      = true;
                        //connectGroupsLifeStage.Order = 0;
                        connectGroupsLifeStage.CreatedByPersonAliasId = 1;
                        connectGroupsLifeStage.CreatedDateTime        = DateTime.Now;

                        //save Life Stage

                        lifeStageContext.WrapTransaction(() =>
                        {
                            lifeStageContext.Configuration.AutoDetectChangesEnabled = false;
                            lifeStageContext.Groups.Add(connectGroupsLifeStage);
                            lifeStageContext.SaveChanges(DisableAudit);
                        });
                        completedLifeStages++;
                    }

                    int existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    existingLifeStage = new GroupService(lookupContext).Queryable().Where(g => g.Name == lifeStage).Select(a => a.Id).FirstOrDefault();
                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var connectGroups = new Group();
                        connectGroups.IsSystem      = false;
                        connectGroups.GroupTypeId   = groupTypeIdSmallGroup;
                        connectGroups.ParentGroupId = existingLifeStage;
                        connectGroups.CampusId      = 1;
                        connectGroups.Name          = groupName;
                        connectGroups.Description   = "";
                        connectGroups.IsActive      = true;
                        //connectGroups.Order = 0;
                        connectGroups.CreatedByPersonAliasId = 1;
                        connectGroups.CreatedDateTime        = createdDateTime;
                        connectGroups.ForeignId = groupId.ToString(); //Will use this for GroupsAttendance

                        //Save Group
                        connectGroupContext.WrapTransaction(() =>
                        {
                            connectGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            connectGroupContext.Groups.Add(connectGroups);
                            connectGroupContext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            // ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            connectGroupMemberContext.WrapTransaction(() =>
                            {
                                connectGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                connectGroupMemberContext.GroupMembers.Add(connectGroupMember);
                                connectGroupMemberContext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        //ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }


                if (groupTypeName.Trim() == "Care Ministries")              //Moves Care Ministries into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var careMinistriesId      = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Care Ministries" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if (careMinistriesId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Care Ministries";
                        connectGroupTree.Description = "Crossroads Care Ministries";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        var careMinistryContext = new RockContext();
                        careMinistryContext.WrapTransaction(() =>
                        {
                            careMinistryContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryContext.Groups.Add(connectGroupTree);
                            careMinistryContext.SaveChanges(DisableAudit);
                        });
                    }

                    int existingConnectGroup   = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    int existingCareMinistries = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Care Ministries").Select(a => a.Id).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var careGroup = new Group();
                        careGroup.IsSystem      = false;
                        careGroup.GroupTypeId   = groupTypeIdSmallGroup;
                        careGroup.ParentGroupId = existingCareMinistries;
                        careGroup.CampusId      = 1;
                        careGroup.Name          = groupName;
                        careGroup.Description   = "";
                        careGroup.IsActive      = true;
                        //connectGroups.Order = 0;
                        careGroup.CreatedByPersonAliasId = 1;
                        careGroup.CreatedDateTime        = createdDateTime;
                        careGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var careMinistryGroupContext = new RockContext();
                        careMinistryGroupContext.WrapTransaction(() =>
                        {
                            careMinistryGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryGroupContext.Groups.Add(careGroup);
                            careMinistryGroupContext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var careGroupMemberContext = new RockContext();
                            careGroupMemberContext.WrapTransaction(() =>
                            {
                                careGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                careGroupMemberContext.GroupMembers.Add(connectGroupMember);
                                careGroupMemberContext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }


                if (groupTypeName.Trim() == "Intro Connect Groups")              //Moves Intro Connect Groups into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var introConnectGroupsId  = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Intro Connect Groups" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if (introConnectGroupsId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Intro Connect Groups";
                        connectGroupTree.Description = "Crossroads Intro Connect Groups";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        var introConnectGroupTreeContext = new RockContext();
                        introConnectGroupTreeContext.WrapTransaction(() =>
                        {
                            introConnectGroupTreeContext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupTreeContext.Groups.Add(connectGroupTree);
                            introConnectGroupTreeContext.SaveChanges(DisableAudit);
                        });
                    }

                    int existingConnectGroup      = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    int existingIntroConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Intro Connect Groups").Select(a => a.Id).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var introConnectGroup = new Group();
                        introConnectGroup.IsSystem      = false;
                        introConnectGroup.GroupTypeId   = groupTypeIdSmallGroup;
                        introConnectGroup.ParentGroupId = existingIntroConnectGroup;
                        introConnectGroup.CampusId      = 1;
                        introConnectGroup.Name          = groupName;
                        introConnectGroup.Description   = "";
                        introConnectGroup.IsActive      = true;
                        //connectGroups.Order = 0;
                        introConnectGroup.CreatedByPersonAliasId = 1;
                        introConnectGroup.CreatedDateTime        = createdDateTime;
                        introConnectGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var introConnectGroupConext = new RockContext();
                        introConnectGroupConext.WrapTransaction(() =>
                        {
                            introConnectGroupConext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupConext.Groups.Add(introConnectGroup);
                            introConnectGroupConext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var introConnectGroupMemberConext = new RockContext();
                            introConnectGroupMemberConext.WrapTransaction(() =>
                            {
                                introConnectGroupMemberConext.Configuration.AutoDetectChangesEnabled = false;
                                introConnectGroupMemberConext.GroupMembers.Add(connectGroupMember);
                                introConnectGroupMemberConext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }



                if (groupTypeName.Trim() == "People List")      //Places People Lists in tags
                {
                    var tagService        = new TagService(lookupContext);
                    var entityTypeService = new EntityTypeService(lookupContext);
                    var taggedItemService = new TaggedItemService(lookupContext);
                    var personService     = new PersonService(lookupContext);

                    //var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    //var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    //var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();


                    string   peopleListName  = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;

                    if (personId != null)
                    {
                        //check if tag exists
                        if (tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault() == null)
                        {
                            //create if it doesn't
                            var newTag = new Tag();
                            newTag.IsSystem = false;
                            newTag.Name     = peopleListName;
                            newTag.EntityTypeQualifierColumn = string.Empty;
                            newTag.EntityTypeQualifierValue  = string.Empty;
                            newTag.EntityTypeId = entityTypeService.Queryable().Where(e => e.Name == "Rock.Model.Person").FirstOrDefault().Id;

                            //Save tag
                            var tagContext = new RockContext();
                            tagContext.WrapTransaction(() =>
                            {
                                tagContext.Configuration.AutoDetectChangesEnabled = false;
                                tagContext.Tags.Add(newTag);
                                tagContext.SaveChanges(DisableAudit);
                            });

                            completedTags++;
                        }

                        var personAlias = new PersonAlias();
                        personAlias = null;

                        if (tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault() != null)     //Makes sure tag exists
                        {
                            //selects the ID of the current people list / tag
                            int tagId = tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault().Id;

                            //gets the person instance in order to use person's GUID later.
                            var personTagged = personService.Queryable().Where(p => p.Id == personId).FirstOrDefault();
                            if (personTagged == null)
                            {
                                var personAliasService = new PersonAliasService(lookupContext);
                                personAlias = personAliasService.Queryable().Where(p => p.PersonId == (int)personId).FirstOrDefault();
                                //ReportProgress( 0, string.Format( "Not able to tag person Id: {0} Tag Name: {1} F1 groupId: {2} Tag Id: {3}. ", personId, peopleListName, groupId, tagId ) );
                            }

                            //check if person already has this tag
                            if (personTagged != null && taggedItemService.Queryable().Where(t => t.EntityGuid == personTagged.Guid && t.TagId == tagId).FirstOrDefault() == null)
                            {
                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem        = false;
                                taggedItem.TagId           = tagId;
                                taggedItem.EntityGuid      = personTagged.Guid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction(() =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add(taggedItem);
                                    tagContext.SaveChanges(DisableAudit);
                                });

                                completedIndividualTags++;
                            }
                            if (personAlias != null && taggedItemService.Queryable().Where(t => t.EntityGuid == personAlias.AliasPersonGuid && t.TagId == tagId).FirstOrDefault() == null)
                            {
                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem        = false;
                                taggedItem.TagId           = tagId;
                                taggedItem.EntityGuid      = personAlias.AliasPersonGuid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction(() =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add(taggedItem);
                                    tagContext.SaveChanges(DisableAudit);
                                });

                                completedIndividualTags++;
                            }
                        }
                        //report Progress
                        if (completedIndividualTags != 0)
                        {
                            if (completedIndividualTags % percentage < 1)
                            {
                                int percentComplete = completedIndividualTags / percentage;
                                // ReportProgress( percentComplete, string.Format( "People Lists / Tags Imported: {0:N0}, Tagged Individuals: {1:N0} ({2:N0}% complete). ", completedTags, completedIndividualTags, percentComplete ) );
                            }
                            else if (completedMembers % ReportingNumber < 1)
                            {
                                ReportPartialProgress();
                            }
                        }
                    }
                }
            }
        }