예제 #1
0
        /// <summary>
        /// Saves any attribute edits made using an Attribute Editor control
        /// </summary>
        /// <param name="edtAttribute">The edt attribute.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static Rock.Model.Attribute SaveAttributeEdits(AttributeEditor edtAttribute, int?entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null)
        {
            // Create and update a new attribute object with new values
            var newAttribute = new Rock.Model.Attribute();

            edtAttribute.GetAttributeProperties(newAttribute);

            rockContext = rockContext ?? new RockContext();
            var internalAttributeService = new AttributeService(rockContext);

            Rock.Model.Attribute attribute = null;

            if (newAttribute.Id > 0)
            {
                attribute = internalAttributeService.Get(newAttribute.Id);
            }

            if (attribute == null)
            {
                newAttribute.Order = internalAttributeService.Queryable().Max(a => a.Order) + 1;
            }
            else
            {
                newAttribute.Order = attribute.Order;
            }

            return(SaveAttributeEdits(newAttribute, entityTypeId, entityTypeQualifierColumn, entityTypeQualifierValue, rockContext));
        }
예제 #2
0
        /// <summary>
        /// Checks Attribute model for legacy lava and outputs SQL to correct it.
        /// Fields evaluated: DefaultValue
        /// </summary>
        public void CheckAttribute()
        {
            RockContext      rockContext      = new RockContext();
            AttributeService attributeService = new AttributeService(rockContext);

            foreach (Model.Attribute attribute in attributeService.Queryable().ToList())
            {
                // don't change if modified
                if (attribute.ModifiedDateTime != null)
                {
                    continue;
                }

                bool isUpdated = false;

                attribute.DefaultValue = ReplaceUnformatted(attribute.DefaultValue, ref isUpdated);
                attribute.DefaultValue = ReplaceUrl(attribute.DefaultValue, ref isUpdated);
                attribute.DefaultValue = ReplaceGlobal(attribute.DefaultValue, ref isUpdated);
                attribute.DefaultValue = ReplaceDotNotation(attribute.DefaultValue, ref isUpdated);

                if (isUpdated)
                {
                    string sql = $"UPDATE [Attribute] SET [DefaultValue] = '{attribute.DefaultValue.Replace( "'", "''" )}' WHERE [Guid] = '{attribute.Guid}';";
                    _sqlUpdateScripts.Add(sql);
                }
            }
        }
예제 #3
0
        public static List <string> GetCustomDimensions()
        {
            var knownDimensions = new List <string>();

            knownDimensions.Add("rocks.kfs.Intacct.ACCOUNTNO");
            knownDimensions.Add("rocks.kfs.Intacct.DEBITACCOUNTNO");
            knownDimensions.Add("rocks.kfs.Intacct.FEEACCOUNTNO");
            knownDimensions.Add("rocks.kfs.Intacct.DEFAULTFEEACCOUNTNO");
            knownDimensions.Add("rocks.kfs.Intacct.FEEPROCESSING");
            knownDimensions.Add("rocks.kfs.Intacct.CLASSID");
            knownDimensions.Add("rocks.kfs.Intacct.DEPARTMENT");
            knownDimensions.Add("rocks.kfs.Intacct.LOCATION");
            knownDimensions.Add("rocks.kfs.Intacct.PROJECTID");

            var rockContext       = new RockContext();
            var accountCategoryId = new CategoryService(rockContext).Queryable().FirstOrDefault(c => c.Guid.Equals(new System.Guid(KFSConst.Attribute.FINANCIAL_ACCOUNT_ATTRIBUTE_CATEGORY))).Id;
            var gatewayCategoryId = new CategoryService(rockContext).Queryable().FirstOrDefault(c => c.Guid.Equals(new System.Guid(KFSConst.Attribute.FINANCIAL_GATEWAY_ATTRIBUTE_CATEGORY))).Id;
            var attributeService  = new AttributeService(rockContext);
            var accountAttributes = attributeService.Queryable().Where(a => a.Categories.Select(c => c.Id).Contains(accountCategoryId)).ToList();

            var customDimensions = new List <string>();

            foreach (var attribute in accountAttributes)
            {
                if (!knownDimensions.Contains(attribute.Key))
                {
                    customDimensions.Add(attribute.Key);
                }
            }

            return(customDimensions);
        }
예제 #4
0
        private void BindAttributeGrids(bool setValues = true)
        {
            if (setValues)
            {
                RockContext      rockContext      = new RockContext();
                AttributeService attributeService = new AttributeService(rockContext);

                var widgityTypeId = PageParameter(PageParameterKey.WidgityTypeId);

                var widgityEntityTypeId = EntityTypeCache.Get(typeof(Widgity)).Id;
                WidgityAttributes = attributeService.Queryable()
                                    .Where(a => a.EntityTypeId == widgityEntityTypeId && a.EntityTypeQualifierValue == widgityTypeId)
                                    .OrderBy(a => a.Order)
                                    .ToList();

                var widgityItemEntityTypeId = EntityTypeCache.Get(typeof(WidgityItem)).Id;
                WidgityItemAttributes = attributeService.Queryable()
                                        .Where(a => a.EntityTypeId == widgityItemEntityTypeId && a.EntityTypeQualifierValue == widgityTypeId)
                                        .OrderBy(a => a.Order)
                                        .ToList();

                SaveState();
            }

            gWidgityAttributes.DataSource = WidgityAttributes.Select(a => new
            {
                a.Guid,
                a.Name,
                a.Key,
                a.IsRequired,
                FieldType = FieldTypeCache.Get(a.FieldTypeId).Name
            }).ToList();
            gWidgityAttributes.DataBind();

            gWidgityItemAttributes.DataSource = WidgityItemAttributes.Select(a => new
            {
                a.Guid,
                a.Name,
                a.Key,
                a.IsRequired,
                FieldType = FieldTypeCache.Get(a.FieldTypeId).Name
            }).ToList();
            gWidgityItemAttributes.DataBind();
        }
예제 #5
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //Get the old groupTypeId before we change it
            var stringGroupTypeId = group.GroupTypeId.ToString();

            //Map group roles
            group.GroupTypeId = ddlGroupTypes.SelectedValue.AsInteger();
            var groupMembers = group.Members;

            foreach (var role in group.GroupType.Roles)
            {
                var ddlRole     = ( RockDropDownList )phRoles.FindControl(role.Id.ToString() + "_ddlRole");
                var roleMembers = groupMembers.Where(gm => gm.GroupRoleId == role.Id);
                foreach (var member in roleMembers)
                {
                    member.GroupRoleId = ddlRole.SelectedValue.AsInteger();
                }
            }

            //Map attributes
            var attributeService      = new AttributeService(rockContext);
            var attributeValueService = new AttributeValueService(rockContext);

            var groupMemberEntityId = new EntityTypeService(rockContext).Get(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id;

            var attributes = attributeService.Queryable()
                             .Where(a =>
                                    a.EntityTypeQualifierColumn == "GroupTypeId" &&
                                    a.EntityTypeQualifierValue == stringGroupTypeId &&
                                    a.EntityTypeId == groupMemberEntityId
                                    ).ToList();

            foreach (var attribute in attributes)
            {
                var ddlAttribute = ( RockDropDownList )phAttributes.FindControl(attribute.Id.ToString() + "_ddlAttribute");
                if (ddlAttribute != null)
                {
                    var newAttributeId = ddlAttribute.SelectedValue.AsInteger();
                    if (newAttributeId != 0)
                    {
                        foreach (var member in groupMembers)
                        {
                            var attributeEntity = attributeValueService.Queryable()
                                                  .Where(av => av.EntityId == member.Id && av.AttributeId == attribute.Id)
                                                  .FirstOrDefault();
                            if (attributeEntity != null)
                            {
                                attributeEntity.AttributeId = newAttributeId;
                            }
                        }
                    }
                }
            }
            rockContext.SaveChanges();
            nbSuccess.Visible = true;
        }
예제 #6
0
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var attributeService = new AttributeService(rockContext);

            return(attributeService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
예제 #7
0
        private void DisplaySettings()
        {
            RockContext      rockContext      = new RockContext();
            EntitySetService entitySetService = new EntitySetService(rockContext);
            var entitySet        = entitySetService.Get(PageParameter("EntitySetId").AsInteger());
            var workflowEntityId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow));

            if (entitySet == null || entitySet.EntityTypeId != workflowEntityId)
            {
                return;
            }

            WorkflowService workflowService = new WorkflowService(rockContext);

            var workflowQueryable = workflowService.Queryable();

            var workflows = entitySet.Items
                            .Join(workflowQueryable,
                                  i => i.EntityId,
                                  w => w.Id,
                                  (i, w) => w);

            var firstWorkflow = workflows.FirstOrDefault();

            if (firstWorkflow == null)
            {
                return;
            }

            var workflowTypeId = firstWorkflow.WorkflowTypeId;

            AttributeService attributeService = new AttributeService(rockContext);

            var attributes = attributeService.Queryable()
                             .Where(a => a.EntityTypeId == workflowEntityId &&
                                    a.EntityTypeQualifierColumn == "WorkflowTypeId" &&
                                    a.EntityTypeQualifierValue == workflowTypeId.ToString())
                             .OrderBy(a => a.Order)
                             .ToList();

            rAttributes.DataSource = attributes;
            rAttributes.DataBind();

            var workflowActivityTypes = firstWorkflow.WorkflowType.ActivityTypes;

            ddlActivities.DataSource = workflowActivityTypes;
            ddlActivities.DataBind();
            ddlActivities.Items.Insert(0, new ListItem());

            hfCount.Value            = workflows.Count().ToString();
            hfWorkflowTypeName.Value = firstWorkflow.WorkflowType.Name;
            nbNotification.Text      = string.Format("Updating {0} {1} workflows.", workflows.Count(), firstWorkflow.WorkflowType.Name);
        }
        protected void BindGrid()
        {
            RockContext                   rockContext                   = new RockContext();
            PersonAliasService            personAliasService            = new PersonAliasService(rockContext);
            WorkflowService               workflowTypeService           = new WorkflowService(rockContext);
            WorkflowService               workflowService               = new WorkflowService(rockContext);
            AttributeService              attributeService              = new AttributeService(rockContext);
            AttributeValueService         attributeValueService         = new AttributeValueService(rockContext);
            RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService(rockContext);

            List <string> workflowTypes   = GetAttributeValues("WorkflowTypes");
            List <string> workflowTypeIds = new List <string>();

            foreach (string workflowTypeGuid in workflowTypes)
            {
                workflowTypeIds.Add(WorkflowTypeCache.Get(workflowTypeGuid.AsGuid()).Id.ToString());
            }

            var attributes   = attributeService.Queryable().Where(a => workflowTypeIds.Contains(a.EntityTypeQualifierValue) && a.EntityTypeQualifierColumn == "WorkflowTypeId");
            var attributeIds = attributes.Select(a => a.Id);

            // Get all the family members
            var familyMembers = personAliasService.Get(PageParameter("PersonAliasId").AsInteger()).Person.GetFamilyMembers(true);

            var familyAliasIds = familyMembers.SelectMany(fm => fm.Person.Aliases.Select(pa => pa.Id)).ToList();

            var discountCodes = registrationRegistrantService.Queryable().Where(rr => rr.PersonAliasId.HasValue && familyAliasIds.Contains(rr.PersonAliasId.Value))
                                .Where(rr => rr.Registration.DiscountCode != null && rr.Registration.DiscountCode != "")
                                .ToDictionary(x => x.Registration.DiscountCode.ToUpper(), x => x.Registration.DiscountAmount);

            var qry = workflowService.Queryable().Where(w => workflowTypeIds.Contains(w.WorkflowTypeId.ToString()))
                      .GroupJoin(attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                                 w => w.Id,
                                 av => av.EntityId,
                                 (w, av) => new { Workflow = w, AttributeValues = av })
                      .Where(obj => obj.AttributeValues.Any(av => av.Attribute.Key == "DiscountCode" && discountCodes.Keys.Contains(av.Value)))
                      .ToList()
                      .Select(obj => new {
                Id              = obj.Workflow.Id,
                FirstName       = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentFirstName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentFirstName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                LastName        = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentLastName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentLastName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Campus          = obj.AttributeValues.Where(av => av.Attribute.Key == "Campus").Select(av => CampusCache.Get(av.Value.AsGuid())).FirstOrDefault(),
                ApplicationYear = obj.AttributeValues.Where(av => av.Attribute.Key == "ApplicationYear").Select(av => av.Value).DefaultIfEmpty(attributes.Where(a => a.Key == "ApplicationYear").Select(a => a.DefaultValue).FirstOrDefault()).FirstOrDefault(),
                DiscountCode    = obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value).FirstOrDefault(),
                DiscountAmount  = discountCodes.ContainsKey(obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()) ?discountCodes[obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()]:0,
                Event           = obj.AttributeValues.Where(av => av.Attribute.Key == "EventStudentisAttending").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "EventLeaderisAttending").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Status          = obj.Workflow.Status
            });

            gFamilyProfile.DataSource = qry.ToList();
            gFamilyProfile.DataBind();
        }
예제 #9
0
        /// <summary>
        /// Gets the Attributes associated to groups.
        /// </summary>
        /// <returns></returns>
        private List <EntityField> GetGroupAttributes()
        {
            if (_GroupAttributes == null)
            {
                _GroupAttributes = new List <EntityField>();

                var rockContext      = new RockContext();
                var attributeService = new AttributeService(rockContext);
                var groupTypeService = new GroupTypeService(rockContext);

                var groupEntityTypeId = EntityTypeCache.GetId(typeof(Model.Group));

                var groupAttributes = attributeService
                                      .Queryable().AsNoTracking()
                                      .Where(a =>
                                             a.EntityTypeId == groupEntityTypeId &&
                                             a.EntityTypeQualifierColumn == "GroupTypeId")
                                      .Join(groupTypeService.Queryable(),
                                            a => a.EntityTypeQualifierValue, gt => gt.Id.ToString(), (a, gt) =>
                                            new
                {
                    a.Name,
                    a.Guid,
                    GroupTypeName = gt.Name
                })
                                      .OrderBy(a => a.GroupTypeName)
                                      .ThenBy(a => a.Name)
                                      .ToList();

                int index = 0;
                foreach (var attribute in groupAttributes)
                {
                    if (!_GroupAttributes.Any(e => e.AttributeGuid == attribute.Guid))
                    {
                        var attributeCache = AttributeCache.Get(attribute.Guid);
                        var entityField    = EntityHelper.GetEntityFieldForAttribute(attributeCache, false);
                        if (entityField != null)
                        {
                            entityField.Title         = $"{attribute.GroupTypeName}: {attribute.Name}";
                            entityField.AttributeGuid = attribute.Guid;
                            entityField.Index         = index++;
                            _GroupAttributes.Add(entityField);
                        }
                    }
                }
            }

            return(_GroupAttributes);
        }
예제 #10
0
        /// <summary>
        /// Returns a list of matching people
        /// </summary>
        /// <param name="searchterm"></param>
        /// <returns></returns>
        public override IQueryable <string> Search(string searchterm)
        {
            var rockContext        = new RockContext();
            var aService           = new AttributeService(rockContext);
            var avService          = new AttributeValueService(rockContext);
            var personEntityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.PERSON.AsGuid()).Id;
            var attribute          = aService.Queryable().Where(a => a.Key == "GivingEnvelopeNumber" && a.EntityTypeId == personEntityTypeId).FirstOrDefault();

            if (attribute != null)
            {
                return(avService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value.Equals(searchterm)).Select(av => av.Value));
            }

            return(null);
        }
예제 #11
0
        public void AuthenticateWithoutPinAuthenticationActive()
        {
            // Set PIN authentication Active status to false
            var activeAttributeGuid = Guid.Parse("f8926e80-1cd1-4dfd-ac1f-28b5dc75b207");
            var attributeService    = new AttributeService(new RockContext());
            var activeAttribute     = attributeService.Queryable().FirstOrDefault(a => a.Guid == activeAttributeGuid);

            var pinAuthentication = AuthenticationContainer.GetComponent(typeof(Security.Authentication.PINAuthentication).FullName);

            pinAuthentication.AttributeValues["Active"] = new AttributeValueCache {
                AttributeId = activeAttribute.Id, EntityId = pinAuthentication.Id, Value = "False"
            };

            // Add signed in user to trigger PIN authentication check
            var principal      = new GenericPrincipal(new GenericIdentity("tdecker"), null);
            var requestContext = new HttpRequestContext()
            {
                Principal = principal
            };
            var request = new HttpRequestMessage();

            request.SetUserPrincipal(principal);

            // Categories controller because it is authenticated and will activate SecuredAttribute filter and has an endpoint which us called to populate a tree-view
            var descriptor = new HttpControllerDescriptor(new HttpConfiguration(), nameof(CategoriesController), typeof(CategoriesController));
            var controller = new CategoriesController()
            {
                Request = request, RequestContext = requestContext, User = principal
            };
            var actionFilter = new SecuredAttribute();
            var httpContext  = new HttpActionContext()
            {
                ControllerContext = new HttpControllerContext(requestContext, request, descriptor, controller),
                ActionDescriptor  = new ReflectedHttpActionDescriptor()
                {
                    ControllerDescriptor = descriptor, MethodInfo = descriptor.ControllerType.GetMethod("GetChildren")
                },
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            actionFilter.OnActionExecuting(httpContext);

            Assert.That.AreEqual(httpContext.Response.StatusCode, HttpStatusCode.OK);
        }
예제 #12
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string attributeKey = GetAttributeValue("OAuthConfigAttributeKey");
            Dictionary <string, string> settings = GlobalAttributesCache.Value(attributeKey).AsDictionary();

            settings["OAuthAuthorizePath"]        = "/" + ddlAuthorizeRoute.SelectedValue;
            settings["OAuthLoginPath"]            = "/" + ddlLoginRoute.SelectedValue;
            settings["OAuthLogoutPath"]           = "/" + ddlLogoutRoute.SelectedValue;
            settings["OAuthTokenPath"]            = "/" + ddlTokenRoute.SelectedValue;
            settings["OAuthRequireSsl"]           = cbSSLRequired.Checked.ToString();
            settings["OAuthTokenLifespan"]        = tbTokenLifespan.Text;
            settings["OAuthRefreshTokenLifespan"] = tbRefreshTokenLifespan.Text;

            RockContext      context          = new RockContext();
            AttributeService attributeService = new AttributeService(context);

            Rock.Model.Attribute attribute = attributeService.Queryable().Where(a => a.Key == attributeKey).FirstOrDefault();
            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.Name        = "OAuth Settings";
                attribute.Description = "Settings for the OAuth server plugin.";
                attribute.Key         = "OAuthSettings";
                FieldTypeService fieldTypeService = new FieldTypeService(context);
                attribute.FieldType = fieldTypeService.Get(Rock.SystemGuid.FieldType.KEY_VALUE_LIST.AsGuid());
                context.SaveChanges();
            }
            // Update the actual attribute value.
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeValue        attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, null);

            if (attributeValue == null)
            {
                attributeValue             = new AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValueService.Add(attributeValue);
            }
            attributeValue.Value = string.Join("|", settings.Select(a => a.Key + "^" + a.Value).ToList());
            context.SaveChanges();

            // Flush the cache(s)
            AttributeCache.Flush(attribute.Id);
            GlobalAttributesCache.Flush();
        }
예제 #13
0
        private void BindFilter()
        {
            ddlCategoryFilter.Items.Clear();
            ddlCategoryFilter.Items.Add("[All]");

            AttributeService attributeService = new AttributeService();
            var items = attributeService.Queryable().
                        Where(a => a.Entity == _entity &&
                              (a.EntityQualifierColumn ?? string.Empty) == _entityQualifierColumn &&
                              (a.EntityQualifierValue ?? string.Empty) == _entityQualifierValue &&
                              a.Category != "" && a.Category != null).
                        OrderBy(a => a.Category).
                        Select(a => a.Category).
                        Distinct().ToList();

            foreach (var item in items)
            {
                ddlCategoryFilter.Items.Add(item);
            }
        }
예제 #14
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
            }));
        }
예제 #15
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string attributeKey = GetAttributeValue("RoomscannerConfigAttributeKey");
            Dictionary <string, string> settings = GlobalAttributesCache.Value(attributeKey).AsDictionary();

            settings["AllowedGroupId"]      = tbAllowedGroupId.Text;
            settings["SubroomLocationType"] = tbSubroomLocationTypeId.Text;

            RockContext      context          = new RockContext();
            AttributeService attributeService = new AttributeService(context);

            Rock.Model.Attribute attribute = attributeService.Queryable().Where(a => a.Key == attributeKey).FirstOrDefault();
            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.Name        = "RoomScanner Settings";
                attribute.Description = "Settings for the OAuth server plugin.";
                attribute.Key         = "RoomScannerSettings";
                FieldTypeService fieldTypeService = new FieldTypeService(context);
                attribute.FieldType = fieldTypeService.Get(Rock.SystemGuid.FieldType.KEY_VALUE_LIST.AsGuid());
                context.SaveChanges();
            }
            // Update the actual attribute value.
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeValue        attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, null);

            if (attributeValue == null)
            {
                attributeValue             = new AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValueService.Add(attributeValue);
            }
            attributeValue.Value = string.Join("|", settings.Select(a => a.Key + "^" + a.Value).ToList());
            context.SaveChanges();

            // Flush the cache(s)
            AttributeCache.Remove(attribute.Id);
            GlobalAttributesCache.Clear();
        }
예제 #16
0
        private void BindGrid()
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                AttributeService attributeService = new AttributeService();

                var queryable = attributeService.
                                Queryable().
                                Where(a => a.Entity == _entity &&
                                      (a.EntityQualifierColumn ?? string.Empty) == _entityQualifierColumn &&
                                      (a.EntityQualifierValue ?? string.Empty) == _entityQualifierValue);

                if (ddlCategoryFilter.SelectedValue != "[All]")
                {
                    queryable = queryable.
                                Where(a => a.Category == ddlCategoryFilter.SelectedValue);
                }

                rGrid.DataSource = queryable.
                                   OrderBy(a => a.Category).
                                   ThenBy(a => a.Name).
                                   Select(a => new
                {
                    a.Id,
                    a.Category,
                    a.Name,
                    a.Description,
                    a.DefaultValue
                }).
                                   ToList();

                rGrid.DataBind();
            }

            hfId.Value = string.Empty;
        }
예제 #17
0
        /// <summary>
        /// Evaluate the list of child entities. This is a list of key value pairs that identify
        /// the property that the child came from as well as the child entity itself. Implementations
        /// of this method may add or remove from this list. For example, a WorkflowActionForm has
        /// it's actions encoded in a single string. This must processed to include any other
        /// objects that should exist (such as a DefinedValue for the button type).
        /// </summary>
        /// <param name="entity">The parent entity of the children.</param>
        /// <param name="children">The child entities and what properties of the parent they came from.</param>
        /// <param name="helper">The helper class for this export.</param>
        protected override void EvaluateChildEntities(WidgityType entity, List <KeyValuePair <string, IEntity> > children, EntityCoder helper)
        {
            var attributeService = new AttributeService(helper.RockContext);

            var entityIds = new List <int?> {
                EntityTypeCache.GetId(typeof(Widgity)), EntityTypeCache.GetId(typeof(WidgityItem))
            };

            var items = attributeService
                        .Queryable()
                        .Where(a =>
                               entityIds.Contains(a.EntityTypeId) &&
                               a.EntityTypeQualifierColumn.Equals("WidgityTypeId", StringComparison.OrdinalIgnoreCase) &&
                               a.EntityTypeQualifierValue.Equals(entity.Id.ToString()))
                        .ToList();

            //
            // We have to special process the attributes since we modify them.
            //
            foreach (var item in items)
            {
                children.Add(new KeyValuePair <string, IEntity>("AttributeTypes", item));
            }
        }
예제 #18
0
        /// <summary>
        /// Gets a list of other attributes that can be used in the form.
        /// </summary>
        /// <param name="workflowTypeId">The identifier of the workflow type used to load user attributes.</param>
        /// <param name="rockContext">The database context to execute queries in.</param>
        /// <returns>A list of <see cref="FormOtherAttributeViewModel"/> view models that represent the attributes.</returns>
        private static List <FormOtherAttributeViewModel> GetOtherAttributes(int workflowTypeId, RockContext rockContext)
        {
            var attributeService     = new AttributeService(rockContext);
            var workflowEntityTypeId = EntityTypeCache.GetId <Rock.Model.Workflow>();

            return(attributeService.Queryable()
                   .Where(a => a.EntityTypeId == workflowEntityTypeId &&
                          a.EntityTypeQualifierColumn == nameof(Rock.Model.Workflow.WorkflowTypeId) &&
                          a.EntityTypeQualifierValue == workflowTypeId.ToString() &&
                          (
                              !a.IsSystem ||
                              a.Key == WorkflowFormBuilderKey.Person ||
                              a.Key == WorkflowFormBuilderKey.Spouse ||
                              a.Key == WorkflowFormBuilderKey.Family
                          )
                          )
                   .Select(a => new FormOtherAttributeViewModel
            {
                Guid = a.Guid,
                FieldTypeGuid = a.FieldType.Guid,
                Name = a.Name
            })
                   .ToList());
        }
예제 #19
0
        private void DisplayAttributes()
        {
            phAttributes.Controls.Clear();

            var newGroupTypeId = ddlGroupTypes.SelectedValue.AsInteger();

            if (newGroupTypeId == 0)
            {
                pnlAttributes.Visible = false;
                return;
            }

            var attributeService = new AttributeService(rockContext);

            var groupMemberEntityId = new EntityTypeService(rockContext).Get(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id;
            var stringGroupTypeId   = group.GroupTypeId.ToString();

            var attributes = attributeService.Queryable()
                             .Where(a =>
                                    a.EntityTypeQualifierColumn == "GroupTypeId" &&
                                    a.EntityTypeQualifierValue == stringGroupTypeId &&
                                    a.EntityTypeId == groupMemberEntityId
                                    ).ToList();

            if (attributes.Any())
            {
                var newGroupTypeIdString = newGroupTypeId.ToString();
                var selectableAttributes = attributeService.Queryable()
                                           .Where(a =>
                                                  a.EntityTypeQualifierColumn == "GroupTypeId" &&
                                                  a.EntityTypeQualifierValue == newGroupTypeIdString &&
                                                  a.EntityTypeId == groupMemberEntityId
                                                  )
                                           .ToList()
                                           .Select(a => new
                {
                    Id   = a.Id.ToString(),
                    Name = a.Name + " [" + a.Key + "]"
                })
                                           .ToList();

                var groupIdString   = group.Id.ToString();
                var groupAttributes = attributeService.Queryable()
                                      .Where(a =>
                                             a.EntityTypeQualifierColumn == "GroupId" &&
                                             a.EntityTypeQualifierValue == groupIdString &&
                                             a.EntityTypeId == groupMemberEntityId
                                             )
                                      .ToList()
                                      .Select(a => new
                {
                    Id   = a.Id.ToString(),
                    Name = a.Name + " [" + a.Key + "]"
                })
                                      .ToList();

                selectableAttributes.AddRange(groupAttributes);


                pnlAttributes.Visible = true;
                foreach (var attribute in attributes)
                {
                    RockDropDownList ddlAttribute = new RockDropDownList()
                    {
                        ID             = attribute.Id.ToString() + "_ddlAttribute",
                        Label          = attribute.Name,
                        DataValueField = "Id",
                        DataTextField  = "Name"
                    };
                    ddlAttribute.DataSource = selectableAttributes;
                    ddlAttribute.DataBind();
                    phAttributes.Controls.Add(ddlAttribute);
                }
            }
            else
            {
                pnlAttributes.Visible = false;
            }
        }
예제 #20
0
        /// <summary>
        /// Filters the results.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="service">The service.</param>
        /// <param name="itemQry">The item qry.</param>
        /// <returns></returns>
        private IQueryable <ContentChannelItem> FilterResults(RockContext rockContext, ContentChannelItemService service, IQueryable <ContentChannelItem> itemQry)
        {
            var contentChannelId = GetAttributeValue(AttributeKeys.ContentChannel).AsInteger();
            var itemType         = typeof(Rock.Model.ContentChannelItem);
            var paramExpression  = service.ParameterExpression;

            //
            // Apply Data Filter.
            //
            int?dataFilterId = GetAttributeValue(AttributeKeys.FilterId).AsIntegerOrNull();

            if (dataFilterId.HasValue)
            {
                var        dataFilterService = new DataViewFilterService(rockContext);
                var        dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                var        errorMessages     = new List <string>();
                Expression whereExpression   = dataFilter?.GetExpression(itemType, service, paramExpression, errorMessages);

                itemQry = itemQry.Where(paramExpression, whereExpression, null);
            }

            //
            // Apply page parameter filtering.
            //
            var pageParameters = RequestContext.GetPageParameters();

            if (GetAttributeValue(AttributeKeys.QueryParameterFiltering).AsBoolean() && pageParameters.Count > 0)
            {
                var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter();

                foreach (var kvp in pageParameters)
                {
                    var selection = new List <string>();

                    // Since there could be many matches by the key name for an attribute we have to construct the unique name used by EntityHelper.FindFromFilterSelection and use that
                    var attributeService = new AttributeService(rockContext);
                    var attributeGuid    = attributeService
                                           .Queryable()
                                           .Where(a => a.EntityTypeQualifierColumn == "ContentChannelId")
                                           .Where(a => a.EntityTypeQualifierValue == contentChannelId.ToString())
                                           .Where(a => a.Key == kvp.Key)
                                           .Select(a => a.Guid)
                                           .FirstOrDefault();

                    string uniqueName = kvp.Key;
                    if (attributeGuid != null)
                    {
                        uniqueName = string.Format("Attribute_{0}_{1}", kvp.Key, attributeGuid.ToString().Replace("-", string.Empty));
                    }

                    // Keep using uniquename for attributes since common keys (e.g. "category")will return mutliple values
                    selection.Add(uniqueName);

                    var entityField = Rock.Reporting.EntityHelper.FindFromFilterSelection(itemType, uniqueName, false, false);
                    if (entityField != null)
                    {
                        string value = kvp.Value;
                        switch (entityField.FieldType.Guid.ToString().ToUpper())
                        {
                        case Rock.SystemGuid.FieldType.DAY_OF_WEEK:
                        case Rock.SystemGuid.FieldType.SINGLE_SELECT:
                        {
                            selection.Add(value);
                        }
                        break;

                        case Rock.SystemGuid.FieldType.MULTI_SELECT:
                        {
                            selection.Add(ComparisonType.Contains.ConvertToInt().ToString());
                            selection.Add(value);
                        }
                        break;

                        default:
                        {
                            selection.Add(ComparisonType.EqualTo.ConvertToInt().ToString());
                            selection.Add(value);
                        }
                        break;
                        }

                        itemQry = itemQry.Where(paramExpression, propertyFilter.GetExpression(itemType, service, paramExpression, selection.ToJson()));
                    }
                }
            }

            return(itemQry);
        }
예제 #21
0
        private List <MedicalItem> GetMedicalItems(bool overrideHideDistributed = false)
        {
            RockContext                rockContext                = new RockContext();
            GroupService               groupService               = new GroupService(rockContext);
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeValueService      attributeValueService      = new AttributeValueService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            NoteService                noteService                = new NoteService(rockContext);

            var groupIdStrings = GetAttributeValue("GroupIds").SplitDelimitedValues();
            var groupIds       = new List <int>();

            foreach (var id in groupIdStrings)
            {
                groupIds.Add(id.AsInteger());
            }

            var groups = groupService.GetByIds(groupIds);

            if (cpCampus.SelectedCampusId != null && cpCampus.SelectedCampusId != 0)
            {
                groups = groups.Where(g => g.CampusId == cpCampus.SelectedCampusId);
            }

            var groupTypeIds = groups.ToList().Select(g => g.GroupTypeId.ToString()).Distinct();

            var personEntityid      = EntityTypeCache.GetId <Rock.Model.Person>().Value;
            var groupMemberEntityid = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
            var key = GetAttributeValue("MedicationMatrixKey");

            var days       = GetAttributeValue(AttributeKey.Days).AsIntegerOrNull() ?? 14;
            var cutoffDate = Rock.RockDateTime.Today.AddDays(-days);

            var lastMedicationCheckinAttribute = AttributeCache.Get(Constants.PERSON_ATTRIBUTE_LASTMEDICATIONCHECKIN.AsGuid());


            var allowedPersonIds = attributeValueService.GetByAttributeId(lastMedicationCheckinAttribute.Id)
                                   .Where(av => av.ValueAsDateTime != null && av.ValueAsDateTime >= cutoffDate)
                                   .Select(av => av.EntityId);

            var groupMembers = groups
                               .SelectMany(g => g.Members)
                               .Where(gm => allowedPersonIds.Contains(gm.PersonId));

            AttributeService attributeService = new AttributeService(rockContext);

            List <int> attributeIds = attributeService.Queryable()
                                      .Where(a =>
                                             a.EntityTypeId == personEntityid &&
                                             a.Key == key)
                                      .Select(a => a.Id).ToList();

            if (attributeIds == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Medication attribute not found";
                return(null);
            }

            List <int> filterAttributeIds = null;
            var        filterAttributeKey = GetAttributeValue("GroupMemberAttributeFilter");

            if (!string.IsNullOrWhiteSpace(filterAttributeKey))
            {
                filterAttributeIds = attributeService.Queryable()
                                     .Where(a =>
                                            (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) &&
                                            a.Key == filterAttributeKey &&
                                            a.EntityTypeId == groupMemberEntityid)
                                     .Select(a => a.Id).ToList();
            }

            var attributeMatrixItemEntityId = EntityTypeCache.GetId <AttributeMatrixItem>();

            var qry = groupMembers
                      .Join(
                attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                m => m.PersonId,
                av => av.EntityId.Value,
                (m, av) => new { Person = m.Person, Member = m, AttributeValue = av.Value }
                )
                      .Join(
                attributeMatrixService.Queryable(),
                m => m.AttributeValue,
                am => am.Guid.ToString(),
                (m, am) => new { Person = m.Person, Member = m.Member, AttributeMatrix = am }
                )
                      .Join(
                attributeMatrixItemService.Queryable(),
                m => m.AttributeMatrix.Id,
                ami => ami.AttributeMatrixId,
                (m, ami) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = ami, TemplateId = ami.AttributeMatrix.AttributeMatrixTemplateId }
                )
                      .Join(
                attributeService.Queryable(),
                m => new { TemplateIdString = m.TemplateId.ToString(), EntityTypeId = attributeMatrixItemEntityId },
                a => new { TemplateIdString = a.EntityTypeQualifierValue, EntityTypeId = a.EntityTypeId },
                (m, a) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = m.AttributeMatrixItem, Attribute = a }
                )
                      .Join(
                attributeValueService.Queryable(),
                m => new { EntityId = m.AttributeMatrixItem.Id, AttributeId = m.Attribute.Id },
                av => new { EntityId = av.EntityId ?? 0, AttributeId = av.AttributeId },
                (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = av, MatrixItemId = m.AttributeMatrixItem.Id, FilterValue = "" }
                );

            if (filterAttributeIds != null && pnlAttribute.Visible && !string.IsNullOrWhiteSpace(ddlAttribute.SelectedValue))
            {
                var filterValue = ddlAttribute.SelectedValue;
                qry = qry
                      .Join(
                    attributeValueService.Queryable().Where(av => filterAttributeIds.Contains(av.AttributeId)),
                    m => new { Id = m.Member.Id, Value = filterValue },
                    av => new { Id = av.EntityId ?? 0, Value = av.Value },
                    (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = m.AttributeValue, MatrixItemId = m.MatrixItemId, FilterValue = av.Value });
            }
            var members = qry.ToList().GroupBy(a => a.Person).ToList();

            var firstDay = (dpDate.SelectedDate ?? Rock.RockDateTime.Today).Date;
            var nextday  = firstDay.AddDays(1);

            var personIds = members.Select(m => m.Key.Id);
            var attributeMatrixEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value;

            var noteType = NoteTypeCache.Get(GetAttributeValue("NoteType").AsGuid());

            if (noteType == null)
            {
                return(new List <MedicalItem>());
            }

            var noteItems = noteService.Queryable()
                            .Where(n => n.NoteTypeId == noteType.Id)
                            .Where(n => personIds.Contains(n.EntityId ?? 0))
                            .Where(h => h.CreatedDateTime >= firstDay && h.CreatedDateTime < nextday)
                            .Where(h => h.ForeignId != null)
                            .ToList();

            foreach (var member in members)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text) &&
                    !member.Key.FullName.ToLower().Contains(tbName.Text.ToLower()) &&
                    !member.Key.FullNameReversed.ToLower().Contains(tbName.Text.ToLower()))
                {
                    continue;
                }

                var medicines = member.GroupBy(m => m.MatrixItemId);
                foreach (var medicine in medicines)
                {
                    var scheduleAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Schedule");
                    if (scheduleAtt == null || scheduleAtt.AttributeValue.Value == null)
                    {
                        continue;
                    }
                    var schedules = scheduleAtt.AttributeValue.Value.SplitDelimitedValues();
                    foreach (var schedule in schedules)
                    {
                        if (ddlSchedule.SelectedValue != "" && ddlSchedule.SelectedValue.AsGuid() != schedule.AsGuid())
                        {
                            continue;
                        }

                        var medicalItem = new MedicalItem()
                        {
                            Person          = member.Key.FullNameReversed,
                            GroupMemberId   = member.Key.Id,
                            GroupMember     = member.Key.Members.FirstOrDefault(),
                            PersonId        = member.Key.Id,
                            FilterAttribute = member.FirstOrDefault().FilterValue,
                        };

                        if (!string.IsNullOrWhiteSpace(schedule))
                        {
                            var dv = DefinedValueCache.Get(schedule.AsGuid());
                            if (dv != null)
                            {
                                medicalItem.Schedule     = dv.Value;
                                medicalItem.ScheduleGuid = dv.Guid;
                            }
                        }

                        var medAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Medication");
                        if (medAtt != null)
                        {
                            medicalItem.Medication = medAtt.AttributeValue.Value;
                        }

                        var instructionAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Instructions");
                        if (instructionAtt != null)
                        {
                            medicalItem.Instructions = instructionAtt.AttributeValue.Value;
                        }
                        medicalItem.Key = string.Format("{0}|{1}|{2}", medicalItem.PersonId, medicine.Key, medicalItem.ScheduleGuid);

                        var notes = noteItems
                                    .Where(n => n.EntityId == medicalItem.PersonId && n.ForeignId == medicine.Key && n.ForeignGuid == medicalItem.ScheduleGuid);

                        if (notes.Any())
                        {
                            medicalItem.Distributed = true;
                            medicalItem.History     = string.Join("<br>", notes.Select(n => n.Text));
                        }

                        medicalItems.Add(medicalItem);
                    }
                }
                if (overrideHideDistributed == false && cbHideDistributed.Checked == true)
                {
                    medicalItems = medicalItems.Where(i => i.Distributed == false).ToList();
                }
            }

            SortProperty sortProperty = gGrid.SortProperty;

            if (sortProperty != null)
            {
                if (sortProperty.Property == "Person")
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList();
                    }
                    else
                    {
                        medicalItems = medicalItems.OrderByDescending(mi => mi.Person).ToList();
                    }
                }
            }
            else
            {
                medicalItems       = medicalItems.OrderBy(mi => mi.Person).ToList();
                gGrid.SortProperty = new SortProperty()
                {
                    Property = "Person"
                };
            }

            return(medicalItems);
        }
        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);
        }
예제 #23
0
        /// <summary>
        /// Gets the Attributes for a Group Member of a specific Group Type.
        /// </summary>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <returns></returns>
        private List <EntityField> GetGroupMemberAttributes()
        {
            var entityAttributeFields = new Dictionary <string, EntityField>();
            var context = new RockContext();

            var attributeService = new AttributeService(context);
            var groupTypeService = new GroupTypeService(context);

            var groupMemberEntityTypeId = EntityTypeCache.GetId(typeof(Model.GroupMember));

            var groupMemberAttributes = attributeService.Queryable()
                                        .AsNoTracking()
                                        .Where(a => a.EntityTypeId == groupMemberEntityTypeId)
                                        .Join(groupTypeService.Queryable(), a => a.EntityTypeQualifierValue, gt => gt.Id.ToString(),
                                              (a, gt) =>
                                              new
            {
                Attribute     = a,
                AttributeKey  = a.Key,
                FieldTypeName = a.FieldType.Name,
                a.FieldTypeId,
                AttributeName = a.Name,
                GroupTypeName = gt.Name
            })
                                        .GroupBy(x => x.AttributeName)
                                        .ToList();

            foreach (var attributesByName in groupMemberAttributes)
            {
                var attributeNameAndTypeGroups = attributesByName.GroupBy(x => x.FieldTypeId).ToList();

                bool requiresTypeQualifier = (attributeNameAndTypeGroups.Count > 1);

                foreach (var attributeNameAndTypeGroup in attributeNameAndTypeGroups)
                {
                    foreach (var attribute in attributeNameAndTypeGroup)
                    {
                        string fieldKey;
                        string fieldName;

                        if (requiresTypeQualifier)
                        {
                            fieldKey = attribute.AttributeName + "_" + attribute.FieldTypeId;

                            fieldName = string.Format("{0} [{1}]", attribute.AttributeName, attribute.FieldTypeName);
                        }
                        else
                        {
                            fieldName = attribute.AttributeName;
                            fieldKey  = attribute.AttributeName;
                        }

                        if (entityAttributeFields.ContainsKey(fieldKey))
                        {
                            continue;
                        }

                        var attributeCache = AttributeCache.Read(attribute.Attribute);

                        var entityField = EntityHelper.GetEntityFieldForAttribute(attributeCache);

                        entityField.Title         = fieldName;
                        entityField.AttributeGuid = null;

                        entityAttributeFields.Add(fieldKey, entityField);
                    }
                }
            }

            int index        = 0;
            var sortedFields = new List <EntityField>();

            foreach (var entityProperty in entityAttributeFields.Values.OrderBy(p => p.Title).ThenBy(p => p.Name))
            {
                entityProperty.Index = index;
                index++;
                sortedFields.Add(entityProperty);
            }

            return(sortedFields);
        }
예제 #24
0
        private void BindGrid()
        {
            string type = PageParameter("SearchType");
            string term = PageParameter("SearchTerm");

            if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term))
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService          = new PersonService(rockContext);
                IQueryable <Person> people = null;

                switch (type.ToLower())
                {
                case ("name"):
                {
                    bool allowFirstNameOnly = false;
                    if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly))
                    {
                        allowFirstNameOnly = false;
                    }
                    people = personService.GetByFullName(term, allowFirstNameOnly, true);
                    break;
                }

                case ("phone"):
                {
                    var phoneService = new PhoneNumberService(rockContext);
                    var personIds    = phoneService.GetPersonIdsByNumber(term);
                    people = personService.Queryable().Where(p => personIds.Contains(p.Id));
                    break;
                }

                case ("address"):
                {
                    var personIds2 = GetPersonIdsByHomePrevAddress(rockContext, term);
                    people = personService.Queryable().Where(p => personIds2.Contains(p.Id));
                    break;
                }

                case ("email"):
                {
                    people = personService.Queryable().Where(p => p.Email.Contains(term));
                    break;
                }

                case ("envelope"):
                {
                    var aService           = new AttributeService(rockContext);
                    var avService          = new AttributeValueService(rockContext);
                    var personEntityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.PERSON.AsGuid()).Id;
                    var attribute          = aService.Queryable().Where(a => a.Key == "GivingEnvelopeNumber" && a.EntityTypeId == personEntityTypeId).FirstOrDefault();
                    if (attribute != null)
                    {
                        var personIds = avService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value.Equals(term)).Select(av => av.EntityId);
                        people = personService.Queryable().Where(p => personIds.Contains(p.Id));
                    }
                    break;
                }

                case ("dob"):
                {
                    term = term.ToLower();
                    List <DateTime?> birthDateList = new List <DateTime?>();
                    var birthDates      = personService.Queryable().Where(p => p.BirthDate.HasValue).Select(p => p.BirthDate).Distinct().AsEnumerable();
                    var shortDateSearch = birthDates.Where(p => p.Value.ToString("d").ToLower().Contains(term) || p.Value.ToString("MM/dd/yyyy").ToLower().Contains(term));
                    var longDateSearch  = birthDates.Where(p => p.Value.ToString("MMMM d, yyyy").ToLower().Contains(term));
                    if (shortDateSearch.Union(longDateSearch).Any())
                    {
                        birthDateList = shortDateSearch.Union(longDateSearch).Distinct().ToList();
                    }
                    else
                    {
                        // Just get crazy with things (Yep, you can find out who was born on a Tuesday)
                        var longestDateSearch = birthDates.Where(p => p.Value.ToString("D").ToLower().Contains(term));
                        birthDateList = longestDateSearch.Distinct().ToList();
                    }
                    gPeople.Columns[3].Visible = true;
                    people = personService.Queryable().Where(p => birthDateList.Contains(p.BirthDate));
                    break;
                }
                }

                SortProperty sortProperty = gPeople.SortProperty;
                if (sortProperty != null)
                {
                    people = people.Sort(sortProperty);
                }
                else
                {
                    people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                }

                Guid familyGuid          = new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);
                Guid homeAddressTypeGuid = new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                var personList = people.Select(p => new PersonSearchResult
                {
                    Id         = p.Id,
                    FirstName  = p.FirstName,
                    NickName   = p.NickName,
                    LastName   = p.LastName,
                    BirthDate  = p.BirthDate,
                    BirthYear  = p.BirthYear,
                    BirthMonth = p.BirthMonth,
                    BirthDay   = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId     = p.RecordStatusValueId,
                    RecordTypeValueId       = p.RecordTypeValueId,
                    SuffixValueId           = p.SuffixValueId,
                    IsDeceased = p.IsDeceased,
                    Email      = p.Email,
                    Gender     = p.Gender,
                    PhotoId    = p.PhotoId,
                    CampusIds  = new List <int> {
                        p.PrimaryFamily.CampusId ?? 0
                    },
                    HomeAddresses = p.PrimaryFamily.GroupLocations.Select(gl => gl.Location)
                }).ToList();

                if (personList.Count == 1)
                {
                    Response.Redirect(string.Format("~/Person/{0}", personList[0].Id), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    if (type.ToLower() == "name")
                    {
                        var similarNames = personService.GetSimilarNames(term,
                                                                         personList.Select(p => p.Id).ToList(), true);
                        if (similarNames.Any())
                        {
                            var hyperlinks = new List <string>();
                            foreach (string name in similarNames.Distinct())
                            {
                                var pageRef = CurrentPageReference;
                                pageRef.Parameters["SearchTerm"] = name;
                                hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name));
                            }
                            string altNames = string.Join(", ", hyperlinks);
                            nbNotice.Text    = string.Format("Other Possible Matches: {0}", altNames);
                            nbNotice.Visible = true;
                        }
                    }

                    _inactiveStatus      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                    gPeople.EntityTypeId = EntityTypeCache.GetId <Person>();

                    gPeople.DataSource = personList;
                    gPeople.DataBind();
                }
            }
        }
예제 #25
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);
        }
예제 #26
0
        private List <BinaryFileWrapper> GetBinaryFiles()
        {
            Guid        binaryFileTypeGuid    = binaryFileType != null ? binaryFileType.Guid : Guid.NewGuid();
            RockContext context               = new RockContext();
            var         binaryFileService     = new BinaryFileService(context);
            var         attributeService      = new AttributeService(context);
            var         attributeValueService = new AttributeValueService(context);
            var         personAliasService    = new PersonAliasService(context);

            string binaryFileId = binaryFileType != null?binaryFileType.Id.ToString() : "0";

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

            var queryable = binaryFileService.Queryable().Where(f => f.BinaryFileType.Guid == binaryFileTypeGuid)
                            .GroupJoin(attributeValueService.Queryable(),
                                       obj => obj.Id,
                                       av => av.EntityId.Value,
                                       (obj, avs) => new BinaryFileWrapper()
            {
                BinaryFile = obj, AttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId))
            });

            var    sortProperty = gBinaryFile.SortProperty;
            string name         = fBinaryFile.GetUserPreference("File Name");

            if (!string.IsNullOrWhiteSpace(name))
            {
                queryable = queryable.Where(f => f.BinaryFile.FileName.Contains(name));
            }

            if (sortProperty != null && sortProperty.Property != "PersonNames" && sortProperty.Property != "PersonNames")
            {
                queryable = queryable.Sort(sortProperty);
            }
            else
            {
                queryable = queryable.OrderBy(d => d.BinaryFile.FileName);
            }
            var list = queryable.ToList();

            // Set all the PersonIds;
            foreach (var document in list)
            {
                document.PersonIds.AddRange(
                    document.AttributeValues.Where(a => a.Attribute.Key == "PersonIds").Where(v => !string.IsNullOrWhiteSpace(v.Value)).Select(v => v.Value).FirstOrDefault().SplitDelimitedValues().AsIntegerList()
                    );
            }

            if (sortProperty != null && sortProperty.Property == "PersonNames")
            {
                if (sortProperty.Direction == SortDirection.Ascending)
                {
                    list = list.OrderBy(l => l.Persons.FirstOrDefault().LastName).ToList();
                }
                else
                {
                    list = list.OrderByDescending(l => l.Persons.FirstOrDefault().LastName).ToList();
                }
            }

            List <Guid?> dataviews = GetAttributeValue("PrintAndMail").SplitDelimitedValues().AsGuidOrNullList();

            if (list.Count() > 0)
            {
                if (dataviews != null && dataviews.Count > 0)
                {
                    var dataViewService = new DataViewService(context);
                    foreach (var dataviewguid in dataviews)
                    {
                        List <string> errorMessages = new List <string>();
                        list.FirstOrDefault().MailPersonIds.AddRange(dataViewService.Get(dataviewguid.Value).GetQuery(null, null, out errorMessages).OfType <Rock.Model.Person>().Select(p => p.Id).ToList());
                    }
                }
            }

            if (sortProperty != null && sortProperty.Property == "PersonNames")
            {
                if (sortProperty.Direction == SortDirection.Ascending)
                {
                    list = list.OrderBy(l => l.Persons.FirstOrDefault().LastName).ToList();
                }
                else
                {
                    list = list.OrderByDescending(l => l.Persons.FirstOrDefault().LastName).ToList();
                }
            }

            if (fBinaryFile.GetUserPreference("Statement Delivery Preference") == "Electronic")
            {
                list = list.Where(l => !l.MailPersonIds.Contains(l.Persons.Select(p => p.Id).FirstOrDefault())).ToList();
            }
            else if (fBinaryFile.GetUserPreference("Statement Delivery Preference") == "Print & Mail")
            {
                list = list.Where(l => l.MailPersonIds.Contains(l.Persons.Select(p => p.Id).FirstOrDefault())).ToList();
            }

            return(list);
        }
예제 #27
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();
            }
        }
예제 #28
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();
        }
예제 #29
0
        protected void BindData()
        {
            List <int> campusIds  = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

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

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

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

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

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

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


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


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

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

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

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

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

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

            mergeFields.Add("PublishGroups", publishGroups);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
예제 #30
0
        private List <Rock.Model.Workflow> GetWorkflows(RockContext rockContext)
        {
            EntitySetService entitySetService = new EntitySetService(rockContext);
            var entitySet        = entitySetService.Get(PageParameter("EntitySetId").AsInteger());
            var workflowEntityId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow));

            if (entitySet == null || entitySet.EntityTypeId != workflowEntityId)
            {
                return(null);
            }

            WorkflowService workflowService = new WorkflowService(rockContext);

            var workflowQueryable = workflowService.Queryable();

            var qry = entitySet.Items
                      .Join(workflowQueryable,
                            i => i.EntityId,
                            w => w.Id,
                            (i, w) => w);

            var firstWorkflow = qry.FirstOrDefault();

            if (firstWorkflow == null)
            {
                return(null);
            }

            var workflowTypeId = firstWorkflow.WorkflowTypeId;

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

            var attributeQueryable = attributeService.Queryable()
                                     .Where(a => a.EntityTypeId == workflowEntityId &&
                                            a.EntityTypeQualifierColumn == "WorkflowTypeId" &&
                                            a.EntityTypeQualifierValue == workflowTypeId.ToString())
                                     .Select(a => a.Id);

            var attributeValueQueryable = attributeValueService.Queryable()
                                          .Where(av => attributeQueryable.Contains(av.AttributeId));

            var mixedItems = qry.GroupJoin(attributeValueQueryable,
                                           w => w.Id,
                                           av => av.EntityId,
                                           (w, av) => new { Workflow = w, AttributeValues = av })
                             .ToList();

            Dictionary <string, AttributeCache> attributes = new Dictionary <string, AttributeCache>();

            foreach (var id in attributeQueryable.ToList())
            {
                var attributeCache = AttributeCache.Get(id);
                if (attributeCache != null)
                {
                    attributes[attributeCache.Key] = attributeCache;
                }
            }

            var workflows = new List <Rock.Model.Workflow>();

            foreach (var item in mixedItems)
            {
                var workflow = item.Workflow;
                workflow.Attributes      = attributes;
                workflow.AttributeValues = new Dictionary <string, AttributeValueCache>();
                foreach (var attribute in attributes)
                {
                    var attributeValue = item.AttributeValues.Where(av => av.AttributeKey == attribute.Key).FirstOrDefault();
                    workflow.AttributeValues[attribute.Key] = attributeValue != null ? new AttributeValueCache(attributeValue) : new AttributeValueCache();
                }
                workflows.Add(workflow);
            }
            return(workflows);
        }