コード例 #1
0
        /// <summary>
        /// Saves the attribute value.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        private void SaveAttributeValue(RockContext context, string key, string value)
        {
            var attributeSvc      = new AttributeService(context);
            var attribute         = attributeSvc.GetGlobalAttribute(key);
            var attributeValueSvc = new AttributeValueService(context);
            var attributeValue    = attributeValueSvc.GetByAttributeIdAndEntityId(attribute.Id, null);

            if (attributeValue == null && !String.IsNullOrWhiteSpace(value))
            {
                attributeValue             = new AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.EntityId    = null;
                attributeValueSvc.Add(attributeValue);
            }

            if (attributeValue == null || value.Equals(attributeValue.Value))
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(value))
            {
                attributeValueSvc.Delete(attributeValue);
            }
            else
            {
                attributeValue.Value = value;
            }

            context.SaveChanges();
        }
コード例 #2
0
        void lvAttributeValues_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            PlaceHolder phInsertValue = lvAttributeValues.InsertItem.FindControl("phInsertValue") as PlaceHolder;

            if (phInsertValue != null && phInsertValue.Controls.Count == 1)
            {
                string value = _attribute.FieldType.Field.GetEditValue(phInsertValue.Controls[0], _attribute.QualifierValues);

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

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

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

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

            lvAttributeValues.EditIndex = -1;
            BindData();
        }
コード例 #3
0
        void lvAttributeValues_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            PlaceHolder phEditValue = lvAttributeValues.EditItem.FindControl("phEditValue") as PlaceHolder;

            if (phEditValue != null && phEditValue.Controls.Count == 1)
            {
                string value = _attribute.FieldType.Field.GetEditValue(phEditValue.Controls[0], _attribute.QualifierValues);

                var attributeValueService = new AttributeValueService();
                var attributeValue        = attributeValueService.Get(( int )e.Keys["Id"]);
                if (attributeValue == null)
                {
                    attributeValue = new AttributeValue();
                    attributeValueService.Add(attributeValue, _currentPersonId);

                    attributeValue.AttributeId = _attribute.Id;
                    attributeValue.EntityId    = _model.Id;
                }

                attributeValue.Value = value;
                attributeValueService.Save(attributeValue, _currentPersonId);

                _model.LoadAttributes();
            }

            lvAttributeValues.EditIndex = -1;
            BindData();
        }
コード例 #4
0
ファイル: JobPulse.cs プロジェクト: ChuckWare/Rock-ChMS
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            using ( new Rock.Data.UnitOfWorkScope() )
            {
                AttributeService attribService = new AttributeService();
                AttributeValueService attributeValueService = new AttributeValueService();

                Rock.Core.Attribute jobPulseAttrib = attribService.GetGlobalAttribute( "JobPulse" );
                Rock.Core.AttributeValue jobPulseAttribValue = jobPulseAttrib.AttributeValues.FirstOrDefault();

                // create attribute value if one does not exist
                if ( jobPulseAttribValue == null )
                {
                    jobPulseAttribValue = new AttributeValue();
                    jobPulseAttribValue.AttributeId = jobPulseAttrib.Id;
                    attributeValueService.Add( jobPulseAttribValue, null );
                }

                // store todays date and time
                jobPulseAttribValue.Value = DateTime.Now.ToString();

                // save attribute
                attributeValueService.Save( jobPulseAttribValue, null );
            }
        }
コード例 #5
0
        /// <summary>
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void  Execute(IJobExecutionContext context)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                AttributeService      attribService         = new AttributeService();
                AttributeValueService attributeValueService = new AttributeValueService();

                Rock.Core.Attribute      jobPulseAttrib      = attribService.GetGlobalAttribute("JobPulse");
                Rock.Core.AttributeValue jobPulseAttribValue = jobPulseAttrib.AttributeValues.FirstOrDefault();

                // create attribute value if one does not exist
                if (jobPulseAttribValue == null)
                {
                    jobPulseAttribValue             = new AttributeValue();
                    jobPulseAttribValue.AttributeId = jobPulseAttrib.Id;
                    attributeValueService.Add(jobPulseAttribValue, null);
                }

                // store todays date and time
                jobPulseAttribValue.Value = DateTime.Now.ToString();

                // save attribute
                attributeValueService.Save(jobPulseAttribValue, null);
            }
        }
コード例 #6
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <param name="saveValue">if set to <c>true</c> [save value].</param>
        public void SetValue(string key, string value, int?currentPersonId, bool saveValue)
        {
            if (saveValue)
            {
                using (new Rock.Data.UnitOfWorkScope())
                {
                    // Save new value
                    var attributeValueService = new AttributeValueService();
                    var attributeValue        = attributeValueService.GetGlobalAttributeValue(key);

                    if (attributeValue == null)
                    {
                        var attributeService = new AttributeService();
                        var attribute        = attributeService.GetGlobalAttribute(key);
                        if (attribute == null)
                        {
                            attribute             = new Rock.Model.Attribute();
                            attribute.FieldTypeId = FieldTypeCache.Read(new Guid(SystemGuid.FieldType.TEXT)).Id;
                            attribute.EntityTypeQualifierColumn = string.Empty;
                            attribute.EntityTypeQualifierValue  = string.Empty;
                            attribute.Key  = key;
                            attribute.Name = key.SplitCase();
                            attributeService.Add(attribute, currentPersonId);
                            attributeService.Save(attribute, currentPersonId);

                            Attributes.Add(AttributeCache.Read(attribute.Id));
                        }

                        attributeValue = new AttributeValue();
                        attributeValueService.Add(attributeValue, currentPersonId);
                        attributeValue.IsSystem    = false;
                        attributeValue.AttributeId = attribute.Id;

                        if (!AttributeValues.Keys.Contains(key))
                        {
                            AttributeValues.Add(key, new KeyValuePair <string, string>(attribute.Name, value));
                        }
                    }

                    attributeValue.Value = value;
                    attributeValueService.Save(attributeValue, currentPersonId);
                }
            }

            var attributeCache = Attributes.FirstOrDefault(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase));

            if (attributeCache != null)   // (Should never be null)
            {
                if (AttributeValues.Keys.Contains(key))
                {
                    AttributeValues[key] = new KeyValuePair <string, string>(attributeCache.Name, value);
                }
                else
                {
                    AttributeValues.Add(key, new KeyValuePair <string, string>(attributeCache.Name, value));
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="saveValue">if set to <c>true</c> [save value].</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetValue(string key, string value, bool saveValue, RockContext rockContext)
        {
            if (saveValue)
            {
                // Save new value
                rockContext = rockContext ?? new RockContext();
                var attributeValueService = new AttributeValueService(rockContext);
                var attributeValue        = attributeValueService.GetGlobalAttributeValue(key);

                if (attributeValue == null)
                {
                    var attributeService = new AttributeService(rockContext);
                    var attribute        = attributeService.GetGlobalAttribute(key);
                    if (attribute == null)
                    {
                        attribute = new Model.Attribute
                        {
                            FieldTypeId = FieldTypeCache.Get(new Guid(SystemGuid.FieldType.TEXT)).Id,
                            EntityTypeQualifierColumn = string.Empty,
                            EntityTypeQualifierValue  = string.Empty,
                            Key  = key,
                            Name = key.SplitCase()
                        };
                        attributeService.Add(attribute);
                        rockContext.SaveChanges();
                    }

                    attributeValue = new AttributeValue
                    {
                        IsSystem    = false,
                        AttributeId = attribute.Id
                    };
                    attributeValueService.Add(attributeValue);
                }

                attributeValue.Value = value;
                rockContext.SaveChanges();
            }

            lock ( _obj )
            {
                _attributeIds = null;
            }

            AttributeValues.AddOrUpdate(key, value, (k, v) => value);

            var attributeCache = Attributes.FirstOrDefault(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase));

            if (attributeCache != null)
            {
                value = attributeCache.FieldType.Field.FormatValue(null, value, attributeCache.QualifierValues, false);
            }
            AttributeValuesFormatted.AddOrUpdate(key, value, (k, v) => value);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext           rockContext           = new RockContext();
            AttributeValueService attributeValueService = new AttributeValueService(rockContext);

            var homePageAttributeCache = GlobalAttributesCache.Read(rockContext).Attributes.Where(a => a.Key == "AvalancheHomePage").FirstOrDefault();
            var homePageAttribute      = attributeValueService.GetByAttributeIdAndEntityId(homePageAttributeCache.Id, null);

            if (homePageAttribute == null)
            {
                homePageAttribute = new AttributeValue()
                {
                    AttributeId = homePageAttributeCache.Id
                };
                attributeValueService.Add(homePageAttribute);
            }

            homePageAttribute.Value = ppHome.SelectedValue;


            var menuPageAttributeCache = GlobalAttributesCache.Read(rockContext).Attributes.Where(a => a.Key == "AvalancheMenuPage").FirstOrDefault();
            var menuPageAttribute      = attributeValueService.GetByAttributeIdAndEntityId(menuPageAttributeCache.Id, null);

            if (menuPageAttribute == null)
            {
                menuPageAttribute = new AttributeValue()
                {
                    AttributeId = menuPageAttributeCache.Id
                };
                attributeValueService.Add(menuPageAttribute);
            }
            menuPageAttribute.Value = ppMenu.SelectedValue;

            rockContext.SaveChanges();
            NavigateToParentPage();
        }
コード例 #9
0
        /// <summary>
        /// Handles the SaveClick event of the mdAttributeValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void mdAttributeValue_SaveClick(object sender, EventArgs e)
        {
            if (_displayValueEdit)
            {
                // If page is not valid, exit and allow validators to display error messages.
                Page.Validate();

                if (!Page.IsValid)
                {
                    return;
                }

                int attributeId = 0;
                if (hfIdValues.Value != string.Empty && !int.TryParse(hfIdValues.Value, out attributeId))
                {
                    attributeId = 0;
                }

                if (attributeId != 0 && phEditControls.Controls.Count > 0)
                {
                    var attribute = Rock.Web.Cache.AttributeCache.Get(attributeId);

                    var rockContext           = new RockContext();
                    var attributeValueService = new AttributeValueService(rockContext);
                    var attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attributeId, _entityId);
                    if (attributeValue == null)
                    {
                        attributeValue = new AttributeValue
                        {
                            AttributeId = attributeId,
                            EntityId    = _entityId
                        };
                        attributeValueService.Add(attributeValue);
                    }

                    var fieldType = FieldTypeCache.Get(attribute.FieldType.Id);
                    attributeValue.Value = fieldType.Field.GetEditValue(attribute.GetControl(phEditControls.Controls[0]), attribute.QualifierValues);

                    rockContext.SaveChanges();
                }

                hfIdValues.Value = string.Empty;

                HideDialog();
            }

            BindGrid();
        }
コード例 #10
0
        /// <summary>
        /// Adds/Updates any attributes that were defined in web.config 's rockConfig section
        /// This is usually used for Plugin Components that need to get any changed values from web.config before startup
        /// </summary>
        private static void UpdateAttributesFromRockConfig(RockContext rockContext)
        {
            var rockConfig = RockConfig.Config;

            if (rockConfig.AttributeValues.Count > 0)
            {
                foreach (AttributeValueConfig attributeValueConfig in rockConfig.AttributeValues)
                {
                    AttributeService      attributeService      = new AttributeService(rockContext);
                    AttributeValueService attributeValueService = new AttributeValueService(rockContext);
                    var attribute = attributeService.Get(
                        attributeValueConfig.EntityTypeId.AsInteger(),
                        attributeValueConfig.EntityTypeQualifierColumm,
                        attributeValueConfig.EntityTypeQualifierValue,
                        attributeValueConfig.AttributeKey);

                    if (attribute == null)
                    {
                        attribute              = new Rock.Model.Attribute();
                        attribute.FieldTypeId  = FieldTypeCache.Get(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
                        attribute.EntityTypeId = attributeValueConfig.EntityTypeId.AsInteger();
                        attribute.EntityTypeQualifierColumn = attributeValueConfig.EntityTypeQualifierColumm;
                        attribute.EntityTypeQualifierValue  = attributeValueConfig.EntityTypeQualifierValue;
                        attribute.Key  = attributeValueConfig.AttributeKey;
                        attribute.Name = attributeValueConfig.AttributeKey.SplitCase();
                        attributeService.Add(attribute);
                        rockContext.SaveChanges();
                    }

                    var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, attributeValueConfig.EntityId.AsInteger());
                    if (attributeValue == null && !string.IsNullOrWhiteSpace(attributeValueConfig.Value))
                    {
                        attributeValue             = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        attributeValue.EntityId    = attributeValueConfig.EntityId.AsInteger();
                        attributeValueService.Add(attributeValue);
                    }

                    if (attributeValue.Value != attributeValueConfig.Value)
                    {
                        attributeValue.Value = attributeValueConfig.Value;
                        rockContext.SaveChanges();
                    }
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Handles the SaveClick event of the mdAttributeValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void mdAttributeValue_SaveClick(object sender, EventArgs e)
        {
            if (_displayValueEdit)
            {
                int attributeId = 0;
                if (hfIdValues.Value != string.Empty && !int.TryParse(hfIdValues.Value, out attributeId))
                {
                    attributeId = 0;
                }

                if (attributeId != 0 && phEditControls.Controls.Count > 0)
                {
                    var attribute = Rock.Web.Cache.AttributeCache.Read(attributeId);

                    var rockContext = new RockContext();
                    AttributeValueService attributeValueService = new AttributeValueService(rockContext);
                    var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId, _entityId);
                    if (attributeValue == null)
                    {
                        attributeValue             = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attributeId;
                        attributeValue.EntityId    = _entityId;
                        attributeValueService.Add(attributeValue);
                    }

                    var fieldType = Rock.Web.Cache.FieldTypeCache.Read(attribute.FieldType.Id);
                    attributeValue.Value = fieldType.Field.GetEditValue(attribute.GetControl(phEditControls.Controls[0]), attribute.QualifierValues);

                    rockContext.SaveChanges();

                    Rock.Web.Cache.AttributeCache.Flush(attributeId);
                    if (!_entityTypeId.HasValue && _entityQualifierColumn == string.Empty && _entityQualifierValue == string.Empty && (!_entityId.HasValue || _entityId.Value == 0))
                    {
                        Rock.Web.Cache.GlobalAttributesCache.Flush();
                    }
                }

                hfIdValues.Value = string.Empty;

                HideDialog();
            }

            BindGrid();
        }
コード例 #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
        /// <summary>
        /// Handles the SaveClick event of the modalDetails control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void modalDetails_SaveClick(object sender, EventArgs e)
        {
            if (_displayValueEdit)
            {
                int attributeId = 0;
                if (hfIdValues.Value != string.Empty && !int.TryParse(hfIdValues.Value, out attributeId))
                {
                    attributeId = 0;
                }

                if (attributeId != 0 && fsEditControl.Controls.Count > 0)
                {
                    var attribute = Rock.Web.Cache.AttributeCache.Read(attributeId);

                    AttributeValueService attributeValueService = new AttributeValueService();
                    var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId, _entityId).FirstOrDefault();
                    if (attributeValue == null)
                    {
                        attributeValue             = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attributeId;
                        attributeValue.EntityId    = _entityId;
                        attributeValueService.Add(attributeValue, CurrentPersonId);
                    }

                    var fieldType = Rock.Web.Cache.FieldTypeCache.Read(attribute.FieldType.Id);
                    attributeValue.Value = fieldType.Field.GetEditValue(attribute.GetControl(fsEditControl.Controls[0]), attribute.QualifierValues);

                    attributeValueService.Save(attributeValue, CurrentPersonId);

                    Rock.Web.Cache.AttributeCache.Flush(attributeId);
                    if (!_entityTypeId.HasValue && _entityQualifierColumn == string.Empty && _entityQualifierValue == string.Empty && !_entityId.HasValue)
                    {
                        Rock.Web.Cache.GlobalAttributesCache.Flush();
                    }
                }

                hfIdValues.Value = string.Empty;

                modalDetails.Hide();
            }

            BindGrid();
        }
コード例 #14
0
        /// <summary>
        /// Sets the value of an existing <see cref="AttributeValue"/> and saves it to the database or creates a new database record if one doesn't already exist.
        /// </summary>
        /// <param name="attributeGuid">The parent <see cref="Rock.Model.Attribute"/> unique identifier.</param>
        /// <param name="entityId">The ID of the entity - if any - to which this <see cref="AttributeValue"/> belongs.</param>
        /// <param name="value">The value to be set.</param>
        /// <param name="previousValue">If a <see cref="AttributeValue"/> already exists in the database, it's current value will be returned, so you can set it back after the current tests complete.</param>
        /// <param name="newAttributeValueGuid">If a <see cref="AttributeValue"/> doesn't already exist in the database, the <see cref="Guid"/> of the newly-created record will be returned, so you can delete it after the current tests complete.</param>
        public static void SetAttributeValue(Guid attributeGuid, int?entityId, string value, out string previousValue, out Guid newAttributeValueGuid)
        {
            using (var rockContext = new RockContext())
            {
                previousValue         = null;
                newAttributeValueGuid = Guid.Empty;

                var attributeId = AttributeCache.GetId(attributeGuid);
                if (!attributeId.HasValue)
                {
                    return;
                }

                var attributeValueService = new AttributeValueService(rockContext);

                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId.Value, entityId);

                if (attributeValue == null)
                {
                    attributeValue = new AttributeValue
                    {
                        AttributeId = attributeId.Value,
                        EntityId    = entityId,
                        Value       = value
                    };

                    attributeValueService.Add(attributeValue);

                    // Remember this so we can delete this AttributeValue upon cleanup.
                    newAttributeValueGuid = attributeValue.Guid;
                }
                else
                {
                    // Remeber this so we can set it back upon cleanup.
                    previousValue        = attributeValue.Value;
                    attributeValue.Value = value;
                }

                rockContext.SaveChanges();
            }
        }
コード例 #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
        public BlockActionResult SaveEditAttributeValue(Guid attributeGuid, string value)
        {
            if (GetAttributeValue(AttributeKey.AllowSettingofValues).AsBooleanOrNull() != true)
            {
                return(ActionBadRequest("Setting values is not enabled."));
            }

            var attribute = AttributeCache.Get(attributeGuid);

            if (attribute == null)
            {
                return(ActionBadRequest());
            }

            using (var rockContext = new RockContext())
            {
                var entityId = GetEntityId();
                var attributeValueService = new AttributeValueService(rockContext);
                var attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, entityId);

                if (attributeValue == null)
                {
                    attributeValue = new AttributeValue
                    {
                        AttributeId = attribute.Id,
                        EntityId    = entityId
                    };
                    attributeValueService.Add(attributeValue);
                }

                attributeValue.Value = PublicAttributeHelper.GetPrivateValue(attribute, value);

                rockContext.SaveChanges();

                return(ActionOk(GetAttributeRow(attribute, rockContext)));
            }
        }
コード例 #17
0
        void modalDetails_SaveClick(object sender, EventArgs e)
        {
            int attributeId = 0;

            if (hfId.Value != string.Empty && !Int32.TryParse(hfId.Value, out attributeId))
            {
                attributeId = 0;
            }

            if (attributeId != 0 && phEditControl.Controls.Count > 0)
            {
                AttributeService attributeService = new AttributeService();
                var attribute = attributeService.Get(attributeId);

                AttributeValueService attributeValueService = new AttributeValueService();
                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId, _entityId).FirstOrDefault();
                if (attributeValue == null)
                {
                    attributeValue             = new Rock.Core.AttributeValue();
                    attributeValue.AttributeId = attributeId;
                    attributeValue.EntityId    = _entityId;
                    attributeValueService.Add(attributeValue, CurrentPersonId);
                }

                var fieldType = Rock.Web.Cache.FieldType.Read(attribute.FieldTypeId);
                attributeValue.Value = fieldType.Field.ReadValue(phEditControl.Controls[0]);

                attributeValueService.Save(attributeValue, CurrentPersonId);

                Rock.Web.Cache.Attribute.Flush(attributeId);
            }

            modalDetails.Hide();

            BindGrid();
        }
コード例 #18
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");
            var  groupTypeList     = dataMap.GetString("GroupTypes");

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            resultContext.Database.CommandTimeout = 3600;

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int eraAttributeId            = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()).Id;
            int personAnalyticsCategoryId = CategoryCache.Read(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            foreach (var result in results)
            {
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext         = new RockContext();
                var         attributeValueService = new AttributeValueService(updateContext);
                var         historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption             = "eRA";
                                    historyRecord.Summary             = "Exited eRA Status";
                                    historyRecord.Verb                = "EXITED";
                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person))
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Summary             = "Entered eRA Status";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
            }

            // load giving attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process history for group types
            if (!string.IsNullOrWhiteSpace(groupTypeList))
            {
                string[] groupTypeGuids = groupTypeList.Split(',');

                var inactiveRecordValue = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);

                var groupTypeEntityTypeId = EntityTypeCache.Read("Rock.Model.GroupType").Id;

                foreach (var groupTypeGuid in groupTypeGuids)
                {
                    var groupType = GroupTypeCache.Read(groupTypeGuid.AsGuid());

                    if (groupType != null)
                    {
                        // if the person is in a group of that type and the last history record for that group type isn't START write a start
                        RockContext rockContext = new RockContext();

                        // get history for this group type
                        var historyRecords = new HistoryService(rockContext).Queryable()
                                             .Where(h =>
                                                    h.EntityTypeId == personEntityTypeId &&
                                                    h.RelatedEntityTypeId == groupTypeEntityTypeId &&
                                                    h.RelatedEntityId == groupType.Id
                                                    )
                                             .GroupBy(h => h.EntityId)
                                             .Select(g => g.OrderByDescending(h => h.CreatedDateTime).Select(h => new { h.EntityId, h.Verb }).FirstOrDefault())
                                             .ToList();

                        // get group member information
                        var groupMemberInfo = new GroupMemberService(rockContext).Queryable()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == groupType.Id &&
                                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                     m.Group.IsActive
                                                     //&& m.Person.RecordStatusValueId != inactiveRecordValue.Id
                                                     )
                                              .GroupBy(m => m.PersonId)
                                              .Select(g => g.OrderBy(m => m.CreatedDateTime).Select(m => new { m.PersonId, m.CreatedDateTime, PersonAliasId = m.Person.Aliases.Select(p => p.Id).FirstOrDefault() }).FirstOrDefault())
                                              .ToList();

                        var needsStartDate = groupMemberInfo.Where(m => !historyRecords.Any(h => h.EntityId == m.PersonId && h.Verb == "STARTED"));

                        foreach (var startItem in needsStartDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var     historyService = new HistoryService(updateContext);
                                History history        = new History();
                                historyService.Add(history);
                                history.EntityTypeId        = personEntityTypeId;
                                history.EntityId            = startItem.PersonId;
                                history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                history.RelatedEntityId     = groupType.Id;
                                history.Caption             = groupType.Name;
                                history.Summary             = "Started Membership in Group Of Type";
                                history.Verb                   = "STARTED";
                                history.CreatedDateTime        = startItem.CreatedDateTime;
                                history.CreatedByPersonAliasId = startItem.PersonAliasId;
                                history.CategoryId             = personAnalyticsCategoryId;

                                updateContext.SaveChanges();
                            }
                        }

                        var needsStoppedDate = historyRecords.Where(h => h.Verb == "STARTED" && !groupMemberInfo.Any(m => m.PersonId == h.EntityId));

                        foreach (var stopItem in needsStoppedDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var person = new PersonService(updateContext).Get(stopItem.EntityId);

                                if (person != null)
                                {
                                    var     historyService = new HistoryService(updateContext);
                                    History history        = new History();
                                    historyService.Add(history);
                                    history.EntityTypeId        = personEntityTypeId;
                                    history.EntityId            = person.Id;
                                    history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                    history.RelatedEntityId     = groupType.Id;
                                    history.Caption             = groupType.Name;
                                    history.Summary             = "Stopped Membership in Group Of Type";
                                    history.Verb                   = "STOPPED";
                                    history.CreatedDateTime        = RockDateTime.Now;
                                    history.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    history.CategoryId             = personAnalyticsCategoryId;

                                    updateContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            // process visit dates
            if (updateVisitDates)
            {
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }
        }
コード例 #19
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");

            int commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600;

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            if (eraAttribute == null || eraStartAttribute == null || eraEndAttribute == null)
            {
                throw new Exception("Family analytic attributes could not be found");
            }

            resultContext.Database.CommandTimeout = commandTimeout;

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Get("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Get("Rock.Model.Attribute").Id;
            int eraAttributeId            = eraAttribute.Id;
            int personAnalyticsCategoryId = CategoryCache.Get(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            foreach (var result in results)
            {
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext = new RockContext();
                updateContext.SourceOfChange          = SOURCE_OF_CHANGE;
                updateContext.Database.CommandTimeout = commandTimeout;
                var attributeValueService = new AttributeValueService(updateContext);
                var historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption = "eRA";

                                    historyRecord.Verb       = "EXITED";
                                    historyRecord.ChangeType = History.HistoryChangeType.Attribute.ConvertToString();
                                    historyRecord.ValueName  = "eRA";
                                    historyRecord.NewValue   = "Exited";

                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                    historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person))
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.ChangeType          = History.HistoryChangeType.Attribute.ConvertToString();
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                                historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
            }

            // load giving attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process visit dates
            if (updateVisitDates)
            {
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }
        }
コード例 #20
0
        void lvAttributeValues_ItemInserting( object sender, ListViewInsertEventArgs e )
        {
            PlaceHolder phInsertValue = lvAttributeValues.InsertItem.FindControl( "phInsertValue" ) as PlaceHolder;
            if ( phInsertValue != null && phInsertValue.Controls.Count == 1 )
            {
                string value = _attribute.FieldType.Field.ReadValue( phInsertValue.Controls[0] );

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

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

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

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

            lvAttributeValues.EditIndex = -1;
            BindData();
        }
コード例 #21
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");

            int commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600;

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            if (eraAttribute == null || eraStartAttribute == null || eraEndAttribute == null)
            {
                throw new Exception("Family analytic attributes could not be found");
            }

            resultContext.Database.CommandTimeout = commandTimeout;

            context.UpdateLastStatusMessage("Getting Family Analytics Era Dataset...");

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Get("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Get("Rock.Model.Attribute").Id;
            int eraAttributeId            = eraAttribute.Id;
            int personAnalyticsCategoryId = CategoryCache.Get(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            int progressPosition = 0;
            int progressTotal    = results.Count;

            foreach (var result in results)
            {
                progressPosition++;
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext = new RockContext();
                updateContext.SourceOfChange          = SOURCE_OF_CHANGE;
                updateContext.Database.CommandTimeout = commandTimeout;
                var attributeValueService = new AttributeValueService(updateContext);
                var historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    // This process will not remove eRA status from a single inactive family member if the family is considered eRA, even if the person record status is inactive.
                    // It removes eRA status from all family members if the family no longer meets the eRA requirements.
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption = "eRA";

                                    historyRecord.Verb       = "EXITED";
                                    historyRecord.ChangeType = History.HistoryChangeType.Attribute.ConvertToString();
                                    historyRecord.ValueName  = "eRA";
                                    historyRecord.NewValue   = "Exited";

                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                    historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        // The stored procedure does not filter out inactive users because we want to exit the family from eRA if they are not active.
                        // So check the status for each person here and do not add the person if they are inactive. If the system defined value for
                        // an inactive person is not available then use "-1" as every record should pass != -1.
                        int inactiveStatusId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()) ?? -1;

                        var familyMembers = family.Members
                                            .Where(m => !m.Person.IsDeceased)
                                            .Where(m => m.Person.RecordStatusValueId != inactiveStatusId)
                                            .Select(m => m.Person);

                        foreach (var person in familyMembers)
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.ChangeType          = History.HistoryChangeType.Attribute.ConvertToString();
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                                historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
                context.UpdateLastStatusMessage($"Updating eRA {progressPosition} of {progressTotal}");
            }

            // load giving attributes
            context.UpdateLastStatusMessage("Updating Giving...");
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            context.UpdateLastStatusMessage("Updating Attendance...");
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process visit dates
            if (updateVisitDates)
            {
                context.UpdateLastStatusMessage("Updating Visit Dates...");
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }

            context.UpdateLastStatusMessage("");
        }
コード例 #22
0
        void lvAttributeValues_ItemUpdating( object sender, ListViewUpdateEventArgs e )
        {
            PlaceHolder phEditValue = lvAttributeValues.EditItem.FindControl( "phEditValue" ) as PlaceHolder;
            if ( phEditValue != null && phEditValue.Controls.Count == 1 )
            {
                string value = _attribute.FieldType.Field.ReadValue( phEditValue.Controls[0] );

                var attributeValueService = new AttributeValueService();
                var attributeValue = attributeValueService.Get( ( int )e.Keys["Id"] );
                if ( attributeValue == null )
                {
                    attributeValue = new AttributeValue();
                    attributeValueService.Add( attributeValue, _currentPersonId );

                    attributeValue.AttributeId = _attribute.Id;
                    attributeValue.EntityId = _model.Id;
                }

                attributeValue.Value = value;
                attributeValueService.Save( attributeValue, _currentPersonId );

                Rock.Attribute.Helper.LoadAttributes( _model );
            }

            lvAttributeValues.EditIndex = -1;
            BindData();
        }
コード例 #23
0
        /// <summary>
        /// Maps the authorizations to an attribute.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapAuthorizations(IQueryable <Row> tableData)
        {
            var lookupContext   = new RockContext();
            var rockContext     = new RockContext();
            var categoryService = new CategoryService(lookupContext);
            var personService   = new PersonService(lookupContext);

            var noteList = new List <Note>();


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

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

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

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

            var authorizationAttributeValueList = new List <AttributeValue>();

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

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

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


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


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

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

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

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

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

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

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

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


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

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

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

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

                    ReportPartialProgress();
                }
            }

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

            ReportProgress(100, string.Format("Finished authorization import: {0:N0} notes imported.", completed));
        }
コード例 #24
0
        void modalDetails_SaveClick( object sender, EventArgs e )
        {
            int attributeId = 0;
            if ( hfId.Value != string.Empty && !Int32.TryParse( hfId.Value, out attributeId ) )
                attributeId = 0;

            if ( attributeId != 0 && phEditControl.Controls.Count > 0 )
            {
                AttributeService attributeService = new AttributeService();
                var attribute = attributeService.Get( attributeId );

                AttributeValueService attributeValueService = new AttributeValueService();
                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attributeId, _entityId ).FirstOrDefault();
                if ( attributeValue == null )
                {
                    attributeValue = new Rock.Core.AttributeValue();
                    attributeValue.AttributeId = attributeId;
                    attributeValue.EntityId = _entityId;
                    attributeValueService.Add( attributeValue, CurrentPersonId );
                }

                var fieldType = Rock.Web.Cache.FieldType.Read( attribute.FieldTypeId );
                attributeValue.Value = fieldType.Field.ReadValue( phEditControl.Controls[0] );

                attributeValueService.Save(attributeValue, CurrentPersonId);

                Rock.Web.Cache.Attribute.Flush( attributeId );

            }

            modalDetails.Hide();

            BindGrid();
        }