/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValue(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null) { if (model != null && attribute != null) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService(rockContext); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id); if (attributeValue == null) { if (newValue == null) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValueService.Add(attributeValue); } attributeValue.Value = newValue; rockContext.SaveChanges(); if (model.AttributeValues != null && model.AttributeValues.ContainsKey(attribute.Key)) { model.AttributeValues[attribute.Key] = attributeValue.Clone(false) as Rock.Model.AttributeValue; } } }
/// <summary> /// Saves the attribute value. /// </summary> /// <param name="entityId">The entity identifier.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValue(int entityId, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null) { if (attribute != null) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService(rockContext); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, entityId); if (attributeValue == null) { if (newValue == null) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = entityId; attributeValueService.Add(attributeValue); } attributeValue.Value = newValue; rockContext.SaveChanges(); } }
/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="personId">The person id.</param> public static void SaveAttributeValue(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, int?personId) { Model.AttributeValueService attributeValueService = new Model.AttributeValueService(); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id).FirstOrDefault(); if (attributeValue == null) { if (newValue == null) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValue.Order = 0; attributeValueService.Add(attributeValue, personId); } attributeValue.Value = newValue; attributeValueService.Save(attributeValue, personId); model.AttributeValues[attribute.Key] = new List <Rock.Model.AttributeValue>() { attributeValue.Clone() as Rock.Model.AttributeValue }; }
/// <summary> /// Saves the attribute value. /// </summary> /// <param name="workflow">The workflow.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="fieldType">Type of the field.</param> /// <param name="rockContext">The rock context.</param> /// <param name="qualifiers">The qualifiers.</param> /// <returns></returns> private static bool SaveAttributeValue(Rock.Model.Workflow workflow, string key, string value, FieldTypeCache fieldType, RockContext rockContext, Dictionary <string, string> qualifiers = null) { bool createdNewAttribute = false; if (workflow.Attributes.ContainsKey(key)) { workflow.SetAttributeValue(key, value); } else { // Read the attribute var attributeService = new AttributeService(rockContext); var attribute = attributeService .Get(workflow.TypeId, "WorkflowTypeId", workflow.WorkflowTypeId.ToString()) .Where(a => a.Key == key) .FirstOrDefault(); // If workflow attribute doesn't exist, create it // ( should only happen first time a background check is processed for given workflow type) if (attribute == null) { attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = workflow.TypeId; attribute.EntityTypeQualifierColumn = "WorkflowTypeId"; attribute.EntityTypeQualifierValue = workflow.WorkflowTypeId.ToString(); attribute.Name = key.SplitCase(); attribute.Key = key; attribute.FieldTypeId = fieldType.Id; attributeService.Add(attribute); if (qualifiers != null) { foreach (var keyVal in qualifiers) { var qualifier = new Rock.Model.AttributeQualifier(); qualifier.Key = keyVal.Key; qualifier.Value = keyVal.Value; attribute.AttributeQualifiers.Add(qualifier); } } createdNewAttribute = true; } // Set the value for this action's instance to the current time var attributeValue = new Rock.Model.AttributeValue(); attributeValue.Attribute = attribute; attributeValue.EntityId = workflow.Id; attributeValue.Value = value; new AttributeValueService(rockContext).Add(attributeValue); } return(createdNewAttribute); }
/// <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(); } } } }
/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValues">The new values.</param> /// <param name="personId">The person id.</param> public static void SaveAttributeValues(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, List <Rock.Model.AttributeValue> newValues, int?personId) { Model.AttributeValueService attributeValueService = new Model.AttributeValueService(); var attributeValues = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id).ToList(); int i = 0; while (i < attributeValues.Count || i < newValues.Count) { Rock.Model.AttributeValue attributeValue; if (i < attributeValues.Count) { attributeValue = attributeValues[i]; } else { attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValue.Order = i; attributeValueService.Add(attributeValue, personId); } if (i >= newValues.Count) { attributeValueService.Delete(attributeValue, personId); } else { if (attributeValue.Value != newValues[i].Value) { attributeValue.Value = newValues[i].Value; } newValues[i] = attributeValue.Clone() as Rock.Model.AttributeValue; } attributeValueService.Save(attributeValue, personId); i++; } model.AttributeValues[attribute.Key] = newValues; }
/// <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(); }
/// <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(); }
/// <summary> /// Executes the action. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); // Get the number of minutes to delay int?minutes = GetAttributeValue(action, "MinutesToDelay").AsIntegerOrNull(); if (!minutes.HasValue || minutes.Value <= 0) { return(true); } // Use the current action type' guid as the key for a 'Delay Activated' attribute string AttrKey = action.ActionType.Guid.ToString(); // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute. // The first time this action runs on any workflow instance using this action instance, the // attribute will not exist and need to be created if (!action.Activity.Attributes.ContainsKey(AttrKey)) { var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = action.Activity.TypeId; attribute.EntityTypeQualifierColumn = "ActivityTypeId"; attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString(); attribute.Name = "Delay Activated"; attribute.Key = AttrKey; attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id; // Need to save the attribute now (using different context) so that an attribute id is returned. var newRockContext = new RockContext(); new AttributeService(newRockContext).Add(attribute); newRockContext.SaveChanges(); action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute)); var attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.Value = RockDateTime.Now.ToString("o"); action.Activity.AttributeValues.Add(AttrKey, attributeValue); action.AddLogEntry(string.Format("{0:N0} Minute Delay Activated.", minutes.Value), true); } else { // Check to see if this action instance has a value for the 'Delay Activated' attrbute DateTime?activated = action.Activity.GetAttributeValue(AttrKey).AsDateTime(); if (!activated.HasValue) { // If no value exists, set the value to the current time action.Activity.SetAttributeValue(AttrKey, RockDateTime.Now.ToString("o")); action.AddLogEntry(string.Format("{0:N0} Minute Delay Activated.", minutes.Value), true); } else { // If a value does exist, check to see if the number of minutes to delay has passed // since the value was saved if (activated.Value.AddMinutes(minutes.Value).CompareTo(RockDateTime.Now) < 0) { // If delay has elapsed, return True ( so that processing of activity will continue ) action.AddLogEntry(string.Format("{0:N0} Minute Delay Completed.", minutes.Value), true); return(true); } } } // If delay has not elapsed, return false so that processing of activity stops return(false); }
/// <summary> /// Returns true if the field for these FieldVisibilityRules should be visible given the supplied attributeValues /// </summary> /// <param name="attributeValues">The attribute values.</param> /// <param name="personFieldValues">The person field values.</param> /// <returns></returns> public bool Evaluate(Dictionary <int, AttributeValueCache> attributeValues, Dictionary <RegistrationPersonFieldType, string> personFieldValues) { bool visible = true; var fieldVisibilityRules = this; if (!fieldVisibilityRules.RuleList.Any() || (!attributeValues.Any() && !personFieldValues.Any())) { // if no rules or no values, just exit return(visible); } foreach (var fieldVisibilityRule in fieldVisibilityRules.RuleList.Where(a => a.ComparedToRegistrationTemplateFormFieldGuid.HasValue)) { bool conditionResult; var filterValues = new List <string>(); var comparedToField = RegistrationTemplateFormFieldCache.Get(fieldVisibilityRule.ComparedToRegistrationTemplateFormFieldGuid.Value); if (comparedToField?.AttributeId != null) { var comparedToAttribute = AttributeCache.Get(comparedToField.AttributeId.Value); // if this is a TextFieldType, In-Memory LINQ is case-sensitive but LinqToSQL is not, so lets compare values using ToLower() if (comparedToAttribute.FieldType.Field is Rock.Field.Types.TextFieldType) { fieldVisibilityRule.ComparedToValue = fieldVisibilityRule.ComparedToValue?.ToLower(); } filterValues.Add(fieldVisibilityRule.ComparisonType.ConvertToString(false)); filterValues.Add(fieldVisibilityRule.ComparedToValue); Expression entityCondition; ParameterExpression parameterExpression = Expression.Parameter(typeof(Rock.Model.AttributeValue)); entityCondition = comparedToAttribute.FieldType.Field.AttributeFilterExpression(comparedToAttribute.QualifierValues, filterValues, parameterExpression); if (entityCondition is NoAttributeFilterExpression) { continue; } var conditionLambda = Expression.Lambda <Func <Rock.Model.AttributeValue, bool> >(entityCondition, parameterExpression); var conditionFunc = conditionLambda.Compile(); var comparedToAttributeValue = attributeValues.GetValueOrNull(comparedToAttribute.Id)?.Value; // if this is a TextFieldType, In-Memory LINQ is case-sensitive but LinqToSQL is not, so lets compare values using ToLower() if (comparedToAttribute.FieldType.Field is Rock.Field.Types.TextFieldType) { comparedToAttributeValue = comparedToAttributeValue?.ToLower(); } // create an instance of an AttributeValue to run the expressions against var attributeValueToEvaluate = new Rock.Model.AttributeValue { AttributeId = comparedToAttribute.Id, Value = comparedToAttributeValue, ValueAsBoolean = comparedToAttributeValue.AsBooleanOrNull(), ValueAsNumeric = comparedToAttributeValue.AsDecimalOrNull(), ValueAsDateTime = comparedToAttributeValue.AsDateTime() }; conditionResult = conditionFunc.Invoke(attributeValueToEvaluate); } else if (IsFieldSupported(comparedToField.PersonFieldType)) { var comparedToFieldValue = personFieldValues.GetValueOrNull(comparedToField.PersonFieldType); conditionResult = comparedToFieldValue == fieldVisibilityRule.ComparedToValue; } else { // ignore if not an attribute and not a supported field type continue; } switch (fieldVisibilityRules.FilterExpressionType) { case Rock.Model.FilterExpressionType.GroupAll: { visible = visible && conditionResult; break; } case Rock.Model.FilterExpressionType.GroupAllFalse: { visible = visible && !conditionResult; break; } case Rock.Model.FilterExpressionType.GroupAny: { visible = visible || conditionResult; break; } case Rock.Model.FilterExpressionType.GroupAnyFalse: { visible = visible || !conditionResult; break; } default: { // ignore if unexpected FilterExpressionType break; } } } return(visible); }
/// <summary> /// Executes the action. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); // Get the number of minutes to delay int? minutes = GetAttributeValue( action, "MinutesToDelay" ).AsIntegerOrNull(); if ( !minutes.HasValue || minutes.Value <= 0 ) { return true; } // Use the current action type' guid as the key for a 'Delay Activated' attribute string AttrKey = action.ActionType.Guid.ToString(); // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute. // The first time this action runs on any workflow instance using this action instance, the // attribute will not exist and need to be created if ( !action.Activity.Attributes.ContainsKey( AttrKey ) ) { var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = action.Activity.TypeId; attribute.EntityTypeQualifierColumn = "ActivityTypeId"; attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString(); attribute.Name = "Delay Activated"; attribute.Key = AttrKey; attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ).Id; // Need to save the attribute now (using different context) so that an attribute id is returned. var newRockContext = new RockContext(); new AttributeService( newRockContext ).Add( attribute ); newRockContext.SaveChanges(); action.Activity.Attributes.Add( AttrKey, AttributeCache.Read( attribute ) ); var attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.Value = RockDateTime.Now.ToString( "o" ); action.Activity.AttributeValues.Add( AttrKey, attributeValue ); action.AddLogEntry( string.Format( "{0:N0} Minute Delay Activated.", minutes.Value ), true ); } else { // Check to see if this action instance has a value for the 'Delay Activated' attrbute DateTime? activated = action.Activity.GetAttributeValue( AttrKey ).AsDateTime(); if ( !activated.HasValue ) { // If no value exists, set the value to the current time action.Activity.SetAttributeValue( AttrKey, RockDateTime.Now.ToString( "o" ) ); action.AddLogEntry( string.Format( "{0:N0} Minute Delay Activated.", minutes.Value ), true ); } else { // If a value does exist, check to see if the number of minutes to delay has passed // since the value was saved if ( activated.Value.AddMinutes( minutes.Value ).CompareTo( RockDateTime.Now ) < 0 ) { // If delay has elapsed, return True ( so that processing of activity will continue ) action.AddLogEntry( string.Format( "{0:N0} Minute Delay Completed.", minutes.Value ), true ); return true; } } } // If delay has not elapsed, return false so that processing of activity stops return false; }
/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValue( IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null ) { if ( model != null && attribute != null ) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, model.Id ); if ( attributeValue == null ) { if ( newValue == null ) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValueService.Add( attributeValue ); } attributeValue.Value = newValue; rockContext.SaveChanges(); if ( model.AttributeValues != null && model.AttributeValues.ContainsKey( attribute.Key ) ) { model.AttributeValues[attribute.Key] = attributeValue.Clone( false ) as Rock.Model.AttributeValue; } } }
/// <summary> /// Saves the attribute value. /// </summary> /// <param name="entityId">The entity identifier.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValue( int entityId, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null ) { if ( attribute != null ) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, entityId ); if ( attributeValue == null ) { if ( newValue == null ) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = entityId; attributeValueService.Add( attributeValue ); } attributeValue.Value = newValue; rockContext.SaveChanges(); } }
private static void SaveAttributeValue( Rock.Model.Workflow workflow, string key, string value, FieldTypeCache fieldType, RockContext rockContext, Dictionary<string, string> qualifiers = null ) { if (workflow.Attributes.ContainsKey(key)) { workflow.SetAttributeValue( key, value ); } else { // If workflow attribute doesn't exist, create it // ( should only happen first time a background check is processed for given workflow type) var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = workflow.WorkflowType.TypeId; attribute.EntityTypeQualifierColumn = "WorkflowTypeId"; attribute.EntityTypeQualifierValue = workflow.WorkflowTypeId.ToString(); attribute.Name = key.SplitCase(); attribute.Key = key; attribute.FieldTypeId = fieldType.Id; if ( qualifiers != null ) { foreach( var keyVal in qualifiers ) { var qualifier = new Rock.Model.AttributeQualifier(); qualifier.Key = keyVal.Key; qualifier.Value = keyVal.Value; attribute.AttributeQualifiers.Add( qualifier ); } } // Set the value for this action's instance to the current time var attributeValue = new Rock.Model.AttributeValue(); attributeValue.Attribute = attribute; attributeValue.EntityId = workflow.Id; attributeValue.Value = value; new AttributeValueService( rockContext ).Add( attributeValue ); } }
/// <summary> /// Processes the confirmation. /// </summary> /// <param name="errorMessage">The error message.</param> /// <returns></returns> private bool ProcessConfirmation( out string errorMessage ) { var rockContext = new RockContext(); if ( string.IsNullOrWhiteSpace( TransactionCode ) ) { GatewayComponent gateway = null; var financialGateway = hfPaymentTab.Value == "ACH" ? _achGateway : _ccGateway; if ( financialGateway != null ) { gateway = financialGateway.GetGatewayComponent(); } if ( gateway == null ) { errorMessage = "There was a problem creating the payment gateway information"; return false; } Person person = GetPerson( true ); if ( person == null ) { errorMessage = "There was a problem creating the person information"; return false; } if ( !person.PrimaryAliasId.HasValue ) { errorMessage = "There was a problem creating the person's primary alias"; return false; } PaymentInfo paymentInfo = GetPaymentInfo(); if ( paymentInfo == null ) { errorMessage = "There was a problem creating the payment information"; return false; } else { paymentInfo.FirstName = person.FirstName; paymentInfo.LastName = person.LastName; } if ( paymentInfo.CreditCardTypeValue != null ) { CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id; } if ( _showCommmentEntry ) { paymentInfo.Comment1 = !string.IsNullOrWhiteSpace( GetAttributeValue( "PaymentComment" ) ) ? string.Format( "{0}: {1}", GetAttributeValue( "PaymentComment" ), txtCommentEntry.Text ) : txtCommentEntry.Text; } else { paymentInfo.Comment1 = GetAttributeValue( "PaymentComment" ); } PaymentSchedule schedule = GetSchedule(); if ( schedule != null ) { schedule.PersonId = person.Id; var scheduledTransaction = gateway.AddScheduledPayment( financialGateway, schedule, paymentInfo, out errorMessage ); if ( scheduledTransaction != null ) { scheduledTransaction.TransactionFrequencyValueId = schedule.TransactionFrequencyValue.Id; scheduledTransaction.AuthorizedPersonAliasId = person.PrimaryAliasId.Value; scheduledTransaction.FinancialGatewayId = financialGateway.Id; if ( scheduledTransaction.FinancialPaymentDetail == null ) { scheduledTransaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } scheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo( paymentInfo, gateway, rockContext ); var changeSummary = new StringBuilder(); changeSummary.AppendFormat( "{0} starting {1}", schedule.TransactionFrequencyValue.Value, schedule.StartDate.ToShortDateString() ); changeSummary.AppendLine(); changeSummary.Append( paymentInfo.CurrencyTypeValue.Value ); if ( paymentInfo.CreditCardTypeValue != null ) { changeSummary.AppendFormat( " - {0}", paymentInfo.CreditCardTypeValue.Value ); } changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber ); changeSummary.AppendLine(); foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) ) { var transactionDetail = new FinancialScheduledTransactionDetail(); transactionDetail.Amount = account.Amount; transactionDetail.AccountId = account.Id; scheduledTransaction.ScheduledTransactionDetails.Add( transactionDetail ); changeSummary.AppendFormat( "{0}: {1}", account.Name, account.Amount.FormatAsCurrency() ); changeSummary.AppendLine(); } var transactionService = new FinancialScheduledTransactionService( rockContext ); transactionService.Add( scheduledTransaction ); rockContext.SaveChanges(); // Add a note about the change var noteType = NoteTypeCache.Read( Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid() ); if ( noteType != null ) { var noteService = new NoteService( rockContext ); var note = new Note(); note.NoteTypeId = noteType.Id; note.EntityId = scheduledTransaction.Id; note.Caption = "Created Transaction"; note.Text = changeSummary.ToString(); noteService.Add( note ); } rockContext.SaveChanges(); ScheduleId = scheduledTransaction.GatewayScheduleId; TransactionCode = scheduledTransaction.TransactionCode; } else { return false; } } else { var transaction = gateway.Charge( financialGateway, paymentInfo, out errorMessage ); if ( transaction != null ) { var txnChanges = new List<string>(); txnChanges.Add( "Created Transaction" ); History.EvaluateChange( txnChanges, "Transaction Code", string.Empty, transaction.TransactionCode ); transaction.AuthorizedPersonAliasId = person.PrimaryAliasId; History.EvaluateChange( txnChanges, "Person", string.Empty, person.FullName ); transaction.TransactionDateTime = RockDateTime.Now; History.EvaluateChange( txnChanges, "Date/Time", null, transaction.TransactionDateTime ); transaction.FinancialGatewayId = financialGateway.Id; History.EvaluateChange( txnChanges, "Gateway", string.Empty, financialGateway.Name ); var txnType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ); transaction.TransactionTypeValueId = txnType.Id; History.EvaluateChange( txnChanges, "Type", string.Empty, txnType.Value ); if ( transaction.FinancialPaymentDetail == null ) { transaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } transaction.FinancialPaymentDetail.SetFromPaymentInfo( paymentInfo, gateway, rockContext, txnChanges ); Guid sourceGuid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "Source" ), out sourceGuid ) ) { var source = DefinedValueCache.Read( sourceGuid ); if ( source != null ) { transaction.SourceTypeValueId = source.Id; History.EvaluateChange( txnChanges, "Source", string.Empty, source.Value ); } } foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) ) { var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = account.Amount; transactionDetail.AccountId = account.Id; transaction.TransactionDetails.Add( transactionDetail ); History.EvaluateChange( txnChanges, account.Name, 0.0M.FormatAsCurrency(), transactionDetail.Amount.FormatAsCurrency() ); } var batchService = new FinancialBatchService( rockContext ); // Get the batch var batch = batchService.Get( GetAttributeValue( "BatchNamePrefix" ), paymentInfo.CurrencyTypeValue, paymentInfo.CreditCardTypeValue, transaction.TransactionDateTime.Value, financialGateway.GetBatchTimeOffset() ); var batchChanges = new List<string>(); if ( batch.Id == 0 ) { batchChanges.Add( "Generated the batch" ); History.EvaluateChange( batchChanges, "Batch Name", string.Empty, batch.Name ); History.EvaluateChange( batchChanges, "Status", null, batch.Status ); History.EvaluateChange( batchChanges, "Start Date/Time", null, batch.BatchStartDateTime ); History.EvaluateChange( batchChanges, "End Date/Time", null, batch.BatchEndDateTime ); } decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount; History.EvaluateChange( batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency() ); batch.ControlAmount = newControlAmount; transaction.BatchId = batch.Id; batch.Transactions.Add( transaction ); rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), batch.Id, batchChanges ); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), batch.Id, txnChanges, person.FullName, typeof( FinancialTransaction ), transaction.Id ); SendReceipt( transaction.Id ); TransactionCode = transaction.TransactionCode; } else { return false; } } tdTransactionCodeReceipt.Description = TransactionCode; tdTransactionCodeReceipt.Visible = !string.IsNullOrWhiteSpace( TransactionCode ); tdScheduleId.Description = ScheduleId; tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId ); tdNameReceipt.Description = paymentInfo.FullName; tdPhoneReceipt.Description = paymentInfo.Phone; tdEmailReceipt.Description = paymentInfo.Email; tdAddressReceipt.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode ); rptAccountListReceipt.DataSource = SelectedAccounts.Where( a => a.Amount != 0 ); rptAccountListReceipt.DataBind(); tdTotalReceipt.Description = paymentInfo.Amount.ToString( "C" ); tdPaymentMethodReceipt.Description = paymentInfo.CurrencyTypeValue.Description; tdAccountNumberReceipt.Description = paymentInfo.MaskedNumber; tdWhenReceipt.Description = schedule != null ? schedule.ToString() : "Today"; // If there was a transaction code returned and this was not already created from a previous saved account, // show the option to save the account. if ( !( paymentInfo is ReferencePaymentInfo ) && !string.IsNullOrWhiteSpace( TransactionCode ) && gateway.SupportsSavedAccount( paymentInfo.CurrencyTypeValue ) ) { cbSaveAccount.Visible = true; pnlSaveAccount.Visible = true; txtSaveAccount.Visible = true; // If current person does not have a login, have them create a username and password phCreateLogin.Visible = !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any(); } else if ( !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any() ) { pnlSaveAccount.Visible = true; phCreateLogin.Visible = true; cbSaveAccount.Visible = false; txtSaveAccount.Visible = false; } else { pnlSaveAccount.Visible = false; } if ( PageParameter( "argsd" ) == "1" ) { var rc = new RockContext(); var ats = new AttributeService( rc ); var argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault(); if ( argsd == null ) { argsd = new Rock.Model.Attribute(); argsd.FieldTypeId = 85; argsd.EntityTypeId = 15; argsd.Key = "AutomatedRecurringGiftSetupDate"; argsd.Name = "Automated Recurring Gift Setup Date"; argsd.Guid = Guid.NewGuid(); argsd.CreatedDateTime = argsd.ModifiedDateTime = DateTime.Now; ats.Add( argsd ); rc.SaveChanges(); rc = new RockContext(); ats = new AttributeService( rc ); argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault(); } if ( argsd != null ) { var atvs = new AttributeValueService( rc ); var argsdVal = atvs.Queryable().Where( x => x.AttributeId == argsd.Id && x.EntityId == person.Id ).FirstOrDefault(); if ( argsdVal == null ) { argsdVal = new Rock.Model.AttributeValue(); argsdVal.AttributeId = argsd.Id; argsdVal.EntityId = person.Id; argsdVal.Value = DateTime.Now.ToString( "o" ); argsdVal.Guid = Guid.NewGuid(); argsdVal.CreatedDateTime = argsdVal.ModifiedDateTime = DateTime.Now; atvs.Add( argsdVal ); rc.SaveChanges(); } else { argsdVal.Value = DateTime.Now.ToString( "o" ); rc.SaveChanges(); } } } return true; } else { pnlDupWarning.Visible = true; divActions.Visible = false; errorMessage = string.Empty; return false; } }
/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValues">The new values.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValues( IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, List<Rock.Model.AttributeValue> newValues, RockContext rockContext = null ) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService( rockContext ); var attributeValues = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, model.Id ).ToList(); int i = 0; while ( i < attributeValues.Count || i < newValues.Count ) { Rock.Model.AttributeValue attributeValue; if ( i < attributeValues.Count ) { attributeValue = attributeValues[i]; } else { attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValue.Order = i; attributeValueService.Add( attributeValue ); } if ( i >= newValues.Count ) attributeValueService.Delete( attributeValue ); else { if ( attributeValue.Value != newValues[i].Value ) attributeValue.Value = newValues[i].Value; newValues[i] = attributeValue.Clone( false ) as Rock.Model.AttributeValue; } i++; } rockContext.SaveChanges(); model.AttributeValues[attribute.Key] = newValues; }
/// <summary> /// Applies the additional properties and security to view model. /// </summary> /// <param name="model">The model.</param> /// <param name="viewModel">The view model.</param> /// <param name="currentPerson">The current person.</param> /// <param name="loadAttributes">if set to <c>true</c> [load attributes].</param> public override void ApplyAdditionalPropertiesAndSecurityToViewModel(AttributeValue model, AttributeValueViewModel viewModel, Person currentPerson = null, bool loadAttributes = true) { viewModel.Attribute = AttributeCache.Get(model.AttributeId).ToViewModel(); }
/// <summary> /// Saves an attribute value. /// </summary> /// <param name="model">The model.</param> /// <param name="attribute">The attribute.</param> /// <param name="newValue">The new value.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void SaveAttributeValue( IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null ) { rockContext = rockContext ?? new RockContext(); var attributeValueService = new Model.AttributeValueService( rockContext ); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, model.Id ).FirstOrDefault(); if ( attributeValue == null ) { if ( newValue == null ) { return; } attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; attributeValue.EntityId = model.Id; attributeValue.Order = 0; attributeValueService.Add( attributeValue ); } attributeValue.Value = newValue; rockContext.SaveChanges(); model.AttributeValues[attribute.Key] = new List<Rock.Model.AttributeValue>() { attributeValue.Clone( false ) as Rock.Model.AttributeValue }; }
/// <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(); }
/// <summary> /// Instantiates a new DTO object from the entity /// </summary> /// <param name="attributeValue"></param> public AttributeValueDto(AttributeValue attributeValue) { CopyFromModel(attributeValue); }
/// <summary> /// To the dto. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static AttributeValueDto ToDto(this AttributeValue value) { return(new AttributeValueDto(value)); }
/// <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 && phEditControl.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( phEditControl.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(); }
/// <summary> /// Initializes a new instance of the <see cref="AttributeValueCache"/> class. /// </summary> /// <param name="model">The model.</param> public AttributeValueCache(Rock.Model.AttributeValue model) { AttributeId = model.AttributeId; Value = model.Value; EntityId = model.EntityId; }
/// <summary> /// Loads the <see cref="P:IHasAttributes.Attributes" /> and <see cref="P:IHasAttributes.AttributeValues" /> of any <see cref="IHasAttributes" /> object /// </summary> /// <param name="entity">The item.</param> /// <param name="rockContext">The rock context.</param> public static void LoadAttributes( Rock.Attribute.IHasAttributes entity, RockContext rockContext ) { if ( entity != null ) { Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>(); Type entityType = entity.GetType(); if ( entityType.Namespace == "System.Data.Entity.DynamicProxies" ) entityType = entityType.BaseType; rockContext = rockContext ?? new RockContext(); // Check for group type attributes var groupTypeIds = new List<int>(); if ( entity is GroupMember || entity is Group || entity is GroupType ) { // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation var groupTypeService = new GroupTypeService( rockContext ); GroupType groupType = null; if ( entity is GroupMember ) { var group = ( (GroupMember)entity ).Group ?? new GroupService( rockContext ) .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ( (GroupMember)entity ).GroupId ); if ( group != null ) { groupType = group.GroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == group.GroupTypeId ); } } else if ( entity is Group ) { groupType = ( (Group)entity ).GroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( (Group)entity ).GroupTypeId ); } else { groupType = ( (GroupType)entity ); } while ( groupType != null ) { groupTypeIds.Insert( 0, groupType.Id ); // Check for inherited group type id's if ( groupType.InheritedGroupTypeId.HasValue ) { groupType = groupType.InheritedGroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( groupType.InheritedGroupTypeId ?? 0 ) ); } else { groupType = null; } } } foreach ( PropertyInfo propertyInfo in entityType.GetProperties() ) properties.Add( propertyInfo.Name.ToLower(), propertyInfo ); Rock.Model.AttributeService attributeService = new Rock.Model.AttributeService( rockContext ); Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService( rockContext ); var inheritedAttributes = new Dictionary<int, List<Rock.Web.Cache.AttributeCache>>(); if ( groupTypeIds.Any() ) { groupTypeIds.ForEach( g => inheritedAttributes.Add( g, new List<Rock.Web.Cache.AttributeCache>() ) ); } else { inheritedAttributes.Add( 0, new List<Rock.Web.Cache.AttributeCache>() ); } var attributes = new List<Rock.Web.Cache.AttributeCache>(); // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read( entityType); if ( entityTypeCache != null ) { int entityTypeId = entityTypeCache.Id; foreach ( var attribute in attributeService.Queryable() .AsNoTracking() .Where( a => a.EntityTypeId == entityTypeCache.Id ) .Select( a => new { a.Id, a.EntityTypeQualifierColumn, a.EntityTypeQualifierValue } ) ) { // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id if ( groupTypeIds.Any() && ( ( entity is GroupMember && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) || ( entity is Group && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) || ( entity is GroupType && string.Compare( attribute.EntityTypeQualifierColumn, "Id", true ) == 0 ) ) ) { int groupTypeIdValue = int.MinValue; if ( int.TryParse( attribute.EntityTypeQualifierValue, out groupTypeIdValue ) && groupTypeIds.Contains( groupTypeIdValue ) ) { inheritedAttributes[groupTypeIdValue].Add( Rock.Web.Cache.AttributeCache.Read( attribute.Id ) ); } } else if ( string.IsNullOrEmpty( attribute.EntityTypeQualifierColumn ) || ( properties.ContainsKey( attribute.EntityTypeQualifierColumn.ToLower() ) && ( string.IsNullOrEmpty( attribute.EntityTypeQualifierValue ) || ( properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue( entity, null ) ?? "" ).ToString() == attribute.EntityTypeQualifierValue ) ) ) { attributes.Add( Rock.Web.Cache.AttributeCache.Read( attribute.Id ) ); } } } var allAttributes = new List<Rock.Web.Cache.AttributeCache>(); foreach ( var attributeGroup in inheritedAttributes ) { foreach ( var attribute in attributeGroup.Value ) { allAttributes.Add( attribute ); } } foreach ( var attribute in attributes ) { allAttributes.Add( attribute ); } var attributeValues = new Dictionary<string, Rock.Model.AttributeValue>(); if ( allAttributes.Any() ) { foreach ( var attribute in allAttributes ) { // Add a placeholder for this item's value for each attribute attributeValues.Add( attribute.Key, null ); } // If loading attributes for a saved item, read the item's value(s) for each attribute if ( !entityTypeCache.IsEntity || entity.Id != 0 ) { List<int> attributeIds = allAttributes.Select( a => a.Id ).ToList(); foreach ( var attributeValue in attributeValueService.Queryable().AsNoTracking() .Where( v => v.EntityId == entity.Id && attributeIds.Contains( v.AttributeId ) ) ) { var attributeKey = AttributeCache.Read( attributeValue.AttributeId ).Key; attributeValues[attributeKey] = attributeValue.Clone( false ) as Rock.Model.AttributeValue; } } // Look for any attributes that don't have a value and create a default value entry foreach ( var attribute in allAttributes ) { if ( attributeValues[attribute.Key] == null ) { var attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; if ( entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey( attribute.Name ) ) { attributeValue.Value = entity.AttributeValueDefaults[attribute.Name]; } else { attributeValue.Value = attribute.DefaultValue; } attributeValues[attribute.Key] = attributeValue; } else { if ( !String.IsNullOrWhiteSpace( attribute.DefaultValue ) && String.IsNullOrWhiteSpace( attributeValues[attribute.Key].Value ) ) { attributeValues[attribute.Key].Value = attribute.DefaultValue; } } } } entity.Attributes = new Dictionary<string, Web.Cache.AttributeCache>(); allAttributes.ForEach( a => entity.Attributes.Add( a.Key, a ) ); entity.AttributeValues = attributeValues; } }
/// <summary> /// Returns true if the field for these FieldVisibilityRules should be visible given the supplied attributeValues /// </summary> /// <param name="attributeValues">The attribute values.</param> /// <param name="personFieldValues">The person field values.</param> /// <returns></returns> public bool Evaluate(Dictionary <int, AttributeValueCache> attributeValues, Dictionary <RegistrationPersonFieldType, string> personFieldValues) { var fieldVisibilityRules = this; List <bool> conditionResults = new List <bool>(); if (!fieldVisibilityRules.RuleList.Any() || (!attributeValues.Any() && !personFieldValues.Any())) { // if no rules or no values, just exit return(true); } foreach (var fieldVisibilityRule in fieldVisibilityRules.RuleList.Where(a => a.ComparedToFormFieldGuid.HasValue)) { bool conditionResult; var filterValues = new List <string>(); var comparedToField = RegistrationTemplateFormFieldCache.Get(fieldVisibilityRule.ComparedToFormFieldGuid.Value); var comparedToFieldAttributeId = comparedToField?.AttributeId ?? AttributeCache.Get(fieldVisibilityRule.ComparedToFormFieldGuid.Value)?.Id; if (comparedToFieldAttributeId != null) { var comparedToAttribute = AttributeCache.Get(comparedToFieldAttributeId.Value); // if this is a TextFieldType, In-Memory LINQ is case-sensitive but LinqToSQL is not, so lets compare values using ToLower() if (comparedToAttribute.FieldType.Field is Rock.Field.Types.TextFieldType) { fieldVisibilityRule.ComparedToValue = fieldVisibilityRule.ComparedToValue?.ToLower(); } var comparisonTypeValue = fieldVisibilityRule.ComparisonType.ConvertToString(false); if (comparisonTypeValue != null) { // only add the comparisonTypeValue if it is specified, just like the logic at https://github.com/SparkDevNetwork/Rock/blob/22f64416b2461c8a988faf4b6e556bc3dcb209d3/Rock/Field/FieldType.cs#L558 filterValues.Add(comparisonTypeValue); } filterValues.Add(fieldVisibilityRule.ComparedToValue); Expression entityCondition; ParameterExpression parameterExpression = Expression.Parameter(typeof(Rock.Model.AttributeValue)); entityCondition = comparedToAttribute.FieldType.Field.AttributeFilterExpression(comparedToAttribute.QualifierValues, filterValues, parameterExpression); if (entityCondition is NoAttributeFilterExpression) { continue; } var conditionLambda = Expression.Lambda <Func <Rock.Model.AttributeValue, bool> >(entityCondition, parameterExpression); var conditionFunc = conditionLambda.Compile(); var comparedToAttributeValue = attributeValues.GetValueOrNull(comparedToAttribute.Id)?.Value; // if this is a TextFieldType, In-Memory LINQ is case-sensitive but LinqToSQL is not, so lets compare values using ToLower() if (comparedToAttribute.FieldType.Field is Rock.Field.Types.TextFieldType) { comparedToAttributeValue = comparedToAttributeValue?.ToLower(); } // create an instance of an AttributeValue to run the expressions against var attributeValueToEvaluate = new Rock.Model.AttributeValue { AttributeId = comparedToAttribute.Id, Value = comparedToAttributeValue, ValueAsBoolean = comparedToAttributeValue.AsBooleanOrNull(), ValueAsNumeric = comparedToAttributeValue.AsDecimalOrNull(), ValueAsDateTime = comparedToAttributeValue.AsDateTime() }; conditionResult = conditionFunc.Invoke(attributeValueToEvaluate); } else if (comparedToField != null && IsFieldSupported(comparedToField.PersonFieldType)) { var comparedToFieldValue = personFieldValues.GetValueOrNull(comparedToField.PersonFieldType); conditionResult = comparedToFieldValue == fieldVisibilityRule.ComparedToValue; } else { // ignore if not an attribute and not a supported field type continue; } conditionResults.Add(conditionResult); } if (!conditionResults.Any()) { // ended up not having any conditions, so return true return(true); } bool visible; switch (fieldVisibilityRules.FilterExpressionType) { case Rock.Model.FilterExpressionType.GroupAll: { // Show if all of the conditions are met (A && B && C && D) visible = conditionResults.All(a => a == true); break; } case Rock.Model.FilterExpressionType.GroupAllFalse: { // Hide if all of the conditions are met (A && B && C && D) visible = !conditionResults.All(a => a == true); break; } case Rock.Model.FilterExpressionType.GroupAny: { // Show if any of the conditions are met (A || B || C || D) visible = conditionResults.Any(a => a == true); break; } case Rock.Model.FilterExpressionType.GroupAnyFalse: { // Hide if any of the conditions are met (A || B || C || D) visible = !conditionResults.Any(a => a == true); break; } default: { // show if unexpected FilterExpressionType visible = true; break; } } return(visible); }
/// <summary> /// Loads the <see cref="P:IHasAttributes.Attributes" /> and <see cref="P:IHasAttributes.AttributeValues" /> of any <see cref="IHasAttributes" /> object /// </summary> /// <param name="entity">The item.</param> /// <param name="rockContext">The rock context.</param> public static void LoadAttributes(Rock.Attribute.IHasAttributes entity, RockContext rockContext) { if (entity != null) { Dictionary <string, PropertyInfo> properties = new Dictionary <string, PropertyInfo>(); Type entityType = entity.GetType(); if (entityType.Namespace == "System.Data.Entity.DynamicProxies") { entityType = entityType.BaseType; } rockContext = rockContext ?? new RockContext(); // Check for group type attributes var groupTypeIds = new List <int>(); if (entity is GroupMember || entity is Group || entity is GroupType) { // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation var groupTypeService = new GroupTypeService(rockContext); GroupType groupType = null; if (entity is GroupMember) { var group = ((GroupMember)entity).Group ?? new GroupService(rockContext) .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ((GroupMember)entity).GroupId); if (group != null) { groupType = group.GroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == group.GroupTypeId); } } else if (entity is Group) { groupType = ((Group)entity).GroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == ((Group)entity).GroupTypeId); } else { groupType = ((GroupType)entity); } while (groupType != null) { groupTypeIds.Insert(0, groupType.Id); // Check for inherited group type id's if (groupType.InheritedGroupTypeId.HasValue) { groupType = groupType.InheritedGroupType ?? groupTypeService .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == (groupType.InheritedGroupTypeId ?? 0)); } else { groupType = null; } } } foreach (PropertyInfo propertyInfo in entityType.GetProperties()) { properties.Add(propertyInfo.Name.ToLower(), propertyInfo); } Rock.Model.AttributeService attributeService = new Rock.Model.AttributeService(rockContext); Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService(rockContext); var inheritedAttributes = new Dictionary <int, List <Rock.Web.Cache.AttributeCache> >(); if (groupTypeIds.Any()) { groupTypeIds.ForEach(g => inheritedAttributes.Add(g, new List <Rock.Web.Cache.AttributeCache>())); } else { inheritedAttributes.Add(0, new List <Rock.Web.Cache.AttributeCache>()); } var attributes = new List <Rock.Web.Cache.AttributeCache>(); // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read(entityType); if (entityTypeCache != null) { int entityTypeId = entityTypeCache.Id; foreach (var attribute in attributeService.Queryable() .AsNoTracking() .Where(a => a.EntityTypeId == entityTypeCache.Id) .Select(a => new { a.Id, a.EntityTypeQualifierColumn, a.EntityTypeQualifierValue } )) { // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id if (groupTypeIds.Any() && ( (entity is GroupMember && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) || (entity is Group && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) || (entity is GroupType && string.Compare(attribute.EntityTypeQualifierColumn, "Id", true) == 0))) { int groupTypeIdValue = int.MinValue; if (int.TryParse(attribute.EntityTypeQualifierValue, out groupTypeIdValue) && groupTypeIds.Contains(groupTypeIdValue)) { inheritedAttributes[groupTypeIdValue].Add(Rock.Web.Cache.AttributeCache.Read(attribute.Id)); } } else if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) || (properties.ContainsKey(attribute.EntityTypeQualifierColumn.ToLower()) && (string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) || (properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue(entity, null) ?? "").ToString() == attribute.EntityTypeQualifierValue))) { attributes.Add(Rock.Web.Cache.AttributeCache.Read(attribute.Id)); } } } var allAttributes = new List <Rock.Web.Cache.AttributeCache>(); foreach (var attributeGroup in inheritedAttributes) { foreach (var attribute in attributeGroup.Value) { allAttributes.Add(attribute); } } foreach (var attribute in attributes) { allAttributes.Add(attribute); } var attributeValues = new Dictionary <string, Rock.Model.AttributeValue>(); if (allAttributes.Any()) { foreach (var attribute in allAttributes) { // Add a placeholder for this item's value for each attribute attributeValues.Add(attribute.Key, null); } // If loading attributes for a saved item, read the item's value(s) for each attribute if (!entityTypeCache.IsEntity || entity.Id != 0) { List <int> attributeIds = allAttributes.Select(a => a.Id).ToList(); foreach (var attributeValue in attributeValueService.Queryable().AsNoTracking() .Where(v => v.EntityId == entity.Id && attributeIds.Contains(v.AttributeId))) { var attributeKey = AttributeCache.Read(attributeValue.AttributeId).Key; attributeValues[attributeKey] = attributeValue.Clone(false) as Rock.Model.AttributeValue; } } // Look for any attributes that don't have a value and create a default value entry foreach (var attribute in allAttributes) { if (attributeValues[attribute.Key] == null) { var attributeValue = new Rock.Model.AttributeValue(); attributeValue.AttributeId = attribute.Id; if (entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey(attribute.Name)) { attributeValue.Value = entity.AttributeValueDefaults[attribute.Name]; } else { attributeValue.Value = attribute.DefaultValue; } attributeValues[attribute.Key] = attributeValue; } else { if (!String.IsNullOrWhiteSpace(attribute.DefaultValue) && String.IsNullOrWhiteSpace(attributeValues[attribute.Key].Value)) { attributeValues[attribute.Key].Value = attribute.DefaultValue; } } } } entity.Attributes = new Dictionary <string, Web.Cache.AttributeCache>(); allAttributes.ForEach(a => entity.Attributes.Add(a.Key, a)); entity.AttributeValues = attributeValues; } }