private async Task <object> GetAttributeDistances(int attributeId, string address) { RockContext rockContext = new RockContext(); AttributeValueService attributeValueService = new AttributeValueService(rockContext); LocationService locationService = new LocationService(rockContext); var attributeValues = attributeValueService.Queryable() .Where(av => av.AttributeId == attributeId && !string.IsNullOrEmpty(av.Value)) .ToList(); var locationGuids = attributeValues .Select(a => a.Value.AsGuidOrNull()) .Where(g => g != null) .ToList(); var locations = locationService.Queryable() .Where(l => locationGuids.Contains(l.Guid)) .ToList(); var destinations = attributeValues .Select(av => new Destination { EntityId = av.EntityId, LocationId = locations.Where(l => l.Guid == av.Value.AsGuid()).Select(l => l.Id).FirstOrDefault() }) .Where(d => d.LocationId.HasValue && d.EntityId.HasValue) .ToList(); var output = await BingDistanceMatrix.OrderDestinations(address, destinations); return(output.ToDictionary(d => d.EntityId.ToString(), d => d.TravelDistance.ToString())); }
/// <summary> /// Checks if this person or business has been imported and returns the Rock.Person Id /// </summary> /// <param name="individualId">The individual identifier.</param> /// <param name="householdId">The household identifier.</param> /// <returns></returns> private int?GetPersonAliasId(int?individualId = null, int?householdId = null) { var existingPerson = ImportedPeople.FirstOrDefault(p => p.IndividualId == individualId && p.HouseholdId == householdId); if (existingPerson != null) { return(existingPerson.PersonAliasId); } else { var rockContext = new RockContext(); int lookupAttributeId = individualId.HasValue ? IndividualAttributeId : HouseholdAttributeId; string lookupValueId = individualId.HasValue ? individualId.ToString() : householdId.ToString(); var lookup = new AttributeValueService(rockContext).Queryable() .Where(av => av.AttributeId == lookupAttributeId && av.Value == lookupValueId); var lookupPerson = lookup.FirstOrDefault(); if (lookupPerson != null) { ImportedPeople.Add(new ImportedPerson() { PersonAliasId = lookupPerson.EntityId, HouseholdId = householdId, IndividualId = individualId }); return(lookupPerson.EntityId); } } return(null); }
/// <summary> /// Assigns the next sequential unused number for the configured AttributeName. /// </summary> /// <returns>the number assigned or null</returns> private int?AssignNewNumber() { string attributeKey = GetAttributeValue("AttributeName").Replace(" ", ""); var thePersonAttribute = _person.Attributes.Values.Where(a => a.Key == attributeKey).FirstOrDefault(); if (thePersonAttribute != null) { // Get the highest value stored in this attribute. int maxValue = 0; RockContext rockContext = new RockContext(); var maxValueString = new AttributeValueService(rockContext).Queryable().Where(a => a.AttributeId == thePersonAttribute.Id).OrderByDescending(av => av.Value).FirstOrDefault(); if (maxValueString != null && !string.IsNullOrEmpty(maxValueString.Value)) { maxValue = maxValueString.Value.AsInteger() ?? 0; } // Now load the person's attributes, increment the number, then save it to their record. _person.LoadAttributes(); int nextNumber = maxValue + 1; _person.SetAttributeValue(attributeKey, nextNumber.ToStringSafe()); _person.SaveAttributeValues(); return(nextNumber); } else { return(null); } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override System.Linq.Expressions.Expression GetExpression(Rock.Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection) { var attributeValueService = new AttributeValueService(context); var roomReservationGroupAttGuid = ZoomGuid.Attribute.ROOM_RESERVATION_GROUP_ATTRIBUTE.AsGuid(); var reservationLocationEntityTypeId = new EntityTypeService(context).GetNoTracking(com.bemaservices.RoomManagement.SystemGuid.EntityType.RESERVATION_LOCATION.AsGuid()).Id; var resGroupAttValues = attributeValueService.Queryable() .Where(x => x.Attribute.Guid == roomReservationGroupAttGuid) .Select(x => new { EntityId = x.EntityId, Value = x.Value }); var groupQuery = new GroupService(context).Queryable() .Select(g => new { GuidString = g.Guid.ToString(), GroupName = g.Name + " (" + g.Id.ToString() + ")" }); var reservationQuery = new ReservationService(context).Queryable() .Select(r => new { r.Id }); var reservationlocationQuery = new ReservationLocationService(context).Queryable() .Select(rl => new { rl.Id, rl.ReservationId }); var occurrenceService = new RoomOccurrenceService(context); var resultQuery = occurrenceService.Queryable("ReservationLocation") .Select(ro => groupQuery.FirstOrDefault(g => resGroupAttValues.FirstOrDefault(v => reservationQuery.FirstOrDefault(r => reservationlocationQuery.FirstOrDefault(rl => ro.EntityTypeId == reservationLocationEntityTypeId && rl.Id == ro.EntityId).ReservationId == r.Id).Id == v.EntityId).Value.Contains(g.GuidString)).GroupName); return(SelectExpressionExtractor.Extract(resultQuery, entityIdProperty, "ro")); }
public System.Net.Http.HttpResponseMessage GroupImport([FromBody] List <Rock.Slingshot.Model.GroupImport> groupImports, string foreignSystemKey) { var responseText = InitiateBulkImporter().BulkGroupImport(groupImports, foreignSystemKey); AttributeValueService.UpdateAllValueAsDateTimeFromTextValue(); return(ControllerContext.Request.CreateResponse <string>(HttpStatusCode.Created, responseText)); }
// helper functional methods (like BindGrid(), etc.) private void Import() { string attributeKey = GetAttributeValue("SponsorKey"); int personEntityTypeId = EntityTypeCache.Read(typeof(Person)).Id; var rockContext = new RockContext(); var followUpSponsorAttribute = new AttributeService(rockContext) .Queryable() .AsNoTracking() .FirstOrDefault(a => a.Key == attributeKey && a.EntityTypeId == personEntityTypeId); if (followUpSponsorAttribute == null) { nbInfo.NotificationBoxType = NotificationBoxType.Danger; nbInfo.Title = "Failure"; nbInfo.Text = "Cannot fetch the Sponsor Person Attribute"; return; } var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var peopleWithFollowUpSponsors = attributeValueService.GetByAttributeId(followUpSponsorAttribute.Id).Where(av => av.EntityId != null).Select(av => new { PersonId = av.EntityId, SponsorAliasGuid = av.Guid }); foreach (var pair in peopleWithFollowUpSponsors) { var followUp = personService.Get(pair.PersonId.Value); var sponsor = personAliasService.GetPerson(pair.SponsorAliasGuid); if (!followUp.HasConsolidator()) { followUp.SetConsolidator(sponsor); } } lbImport.Enabled = false; lbImport.Text = "Done"; }
/// <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 ); } }
private int GetJobAttributeValue(string key, int defaultValue, RockContext rockContext) { var jobEntityType = EntityTypeCache.Get(typeof(Rock.Model.ServiceJob)); int intValue = 3; var jobExpirationAttribute = new AttributeService(rockContext) .Queryable().AsNoTracking() .Where(a => a.EntityTypeId == jobEntityType.Id && a.EntityTypeQualifierColumn == "Class" && a.EntityTypeQualifierValue == "Rock.Jobs.SendCommunications" && a.Key == key) .FirstOrDefault(); if (jobExpirationAttribute != null) { intValue = jobExpirationAttribute.DefaultValue.AsIntegerOrNull() ?? 3; var attributeValue = new AttributeValueService(rockContext) .Queryable().AsNoTracking() .Where(v => v.AttributeId == jobExpirationAttribute.Id) .FirstOrDefault(); if (attributeValue != null) { intValue = attributeValue.Value.AsIntegerOrNull() ?? intValue; } } return(intValue); }
/// <summary> /// Checks AttributeValue model for legacy lava and outputs SQL to correct it. /// Fields evaluated: Value /// </summary> public void CheckAttributeValue() { RockContext rockContext = new RockContext(); AttributeValueService attributeValueService = new AttributeValueService(rockContext); foreach (AttributeValue attributeValue in attributeValueService.Queryable().ToList()) { // don't change if modified if (attributeValue.ModifiedDateTime != null) { continue; } bool isUpdated = false; attributeValue.Value = ReplaceUnformatted(attributeValue.Value, ref isUpdated); attributeValue.Value = ReplaceUrl(attributeValue.Value, ref isUpdated); attributeValue.Value = ReplaceGlobal(attributeValue.Value, ref isUpdated); attributeValue.Value = ReplaceDotNotation(attributeValue.Value, ref isUpdated); if (isUpdated) { string sql = $"UPDATE [AttributeValue] SET [Value] = '{attributeValue.Value.Replace( "'", "''" )}' WHERE [Guid] = '{attributeValue.Guid}';"; _sqlUpdateScripts.Add(sql); } } }
/// <summary> /// Gets a filter expression for an attribute value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <returns></returns> public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression) { Expression comparison = null; if (filterValues.Count > 1) { ComparisonType comparisonType = filterValues[0].ConvertToEnum <ComparisonType>(ComparisonType.Contains); List <string> selectedValues = filterValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (var selectedValue in selectedValues) { var searchValue = "," + selectedValue + ","; var qryToExtract = new AttributeValueService(new Data.RockContext()).Queryable().Where(a => ("," + a.Value + ",").Contains(searchValue)); var valueExpression = FilterExpressionExtractor.Extract <AttributeValue>(qryToExtract, parameterExpression, "a"); if (comparisonType != ComparisonType.Contains) { valueExpression = Expression.Not(valueExpression); } if (comparison == null) { comparison = valueExpression; } else { comparison = Expression.Or(comparison, valueExpression); } } } return(comparison); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection) { var kciSmallGroupGuid = SystemGuid.GroupType.CELL_GROUP.AsGuid(); // TODO Change var attributeId = 1; var leaderAttributes = new AttributeValueService(context) .Queryable() .Where(av => av.AttributeId == attributeId); var personService = new PersonService(context).Queryable(); var lineLeaderQuery = new PersonService(context) .Queryable() .Select(p => leaderAttributes .Where(a => a.EntityId == p.Id) .Select(a => personService .AsQueryable() .FirstOrDefault(q => q.Id == a.ValueAsPersonId) .FullName ) ); var selectLineLeaderExpression = SelectExpressionExtractor.Extract(lineLeaderQuery, entityIdProperty, "p"); return(selectLineLeaderExpression); }
/// <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) { // 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) { attributeValue = new AttributeValue(); attributeValue.IsSystem = false; attributeValue.AttributeId = attribute.Id; attributeValue.Value = value; attributeValueService.Save(attributeValue, currentPersonId); } } else { attributeValue.Value = value; attributeValueService.Save(attributeValue, currentPersonId); } } // Update cached value if (AttributeValues != null && AttributeValues.Keys.Contains(key)) { string attributeName = AttributeValues[key].Key; AttributeValues[key] = new KeyValuePair <string, string>(attributeName, value); } }
private string GetValue( string key, AttributeCache attributeCache, RockContext rockContext ) { var attributeValue = new AttributeValueService( rockContext ).GetByAttributeIdAndEntityId( attributeCache.Id, null ); var value = ( !string.IsNullOrEmpty( attributeValue?.Value ) ) ? attributeValue.Value : attributeCache.DefaultValue; AttributeValues.AddOrUpdate( key, value, ( k, v ) => value ); return value; }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; string livePlatformUrl = dataMap.GetString("Address") ?? "http://live.newpointe.org/api/v1/events/current"; //Check ChurchOnline Platform API to see if there is a live event using (WebClient wc = new WebClient()) { LivePlatformUrlJson = wc.DownloadString(livePlatformUrl); } dynamic isServiceLive = JsonConvert.DeserializeObject(LivePlatformUrlJson); string isLive = isServiceLive.response.item.isLive.ToString(); // specify which attribute key we want to work with var attributeKey = "LiveService"; //production var attributeValueService = new AttributeValueService(rockContext); // specify NULL as the EntityId since this is a GlobalAttribute var globalAttributeValue = attributeValueService.GetGlobalAttributeValue(attributeKey); if (globalAttributeValue != null) { // save updated value to database globalAttributeValue.Value = isLive; rockContext.SaveChanges(); } }
/// <summary> /// Shows the edit value. /// </summary> /// <param name="attributeId">The attribute id.</param> /// <param name="setValues">if set to <c>true</c> [set values].</param> protected void ShowEditValue(int attributeId, bool setValues) { if (_displayValueEdit) { phEditControls.Controls.Clear(); var attribute = Rock.Web.Cache.AttributeCache.Get(attributeId); if (attribute != null) { mdAttributeValue.Title = attribute.Name + " Value"; var attributeValue = new AttributeValueService(new RockContext()).GetByAttributeIdAndEntityId(attributeId, _entityId); string value = attributeValue != null && !string.IsNullOrWhiteSpace(attributeValue.Value) ? attributeValue.Value : attribute.DefaultValue; attribute.AddControl(phEditControls.Controls, value, string.Empty, setValues, true); SetValidationGroup(phEditControls.Controls, mdAttributeValue.ValidationGroup); if (setValues) { hfIdValues.Value = attribute.Id.ToString(); ShowDialog("AttributeValue", true); } } } }
/// <summary> /// Maps the RLC data to rooms, locations & classes /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapRLC(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var attributeValueService = new AttributeValueService(lookupContext); var attributeService = new AttributeService(lookupContext); int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id; // Get any previously imported RLCs foreach (var row in tableData) { int?rlcId = row["RLC_ID"] as int?; if (rlcId != null) { // Activity_ID // RLC_Name // Activity_Group_ID // Start_Age_Date // End_Age_Date // Is_Active // Room_Code // Room_Desc // Room_Name // Max_Capacity // Building_Name // set location.ForeignId to RLC_id // set group.ForeignId to Activity_id } } }
/// <summary> /// Loads the attribute values /// </summary> /// <param name="exportOptions">The export options.</param> /// <param name="rockContext">The rock context.</param> /// <param name="modelExportList">The model export list.</param> /// <param name="pagedEntityQry">The paged entity query.</param> public static void LoadAttributeValues(ExportOptions exportOptions, RockContext rockContext, IEnumerable <ModelExport> modelExportList, IQueryable <IEntity> pagedEntityQry) { if (exportOptions.AttributeList?.Any() != true) { return; } var attributeIdsList = exportOptions.AttributeList.Select(a => a.Id).ToList(); var attributeValuesQuery = new AttributeValueService(rockContext).Queryable() .Where(a => attributeIdsList.Contains(a.AttributeId)) .Where(a => pagedEntityQry.Any(p => p.Id == a.EntityId.Value)) .Select(a => new { EntityId = a.EntityId.Value, AttributeId = a.AttributeId, AttributeValue = a.Value }); var attributeValuesList = attributeValuesQuery.ToList(); var attributeValuesLookup = attributeValuesList.GroupBy(a => a.EntityId).ToDictionary(k => k.Key, v => v.Select(a => new AttributeValueCache { AttributeId = a.AttributeId, EntityId = a.EntityId, Value = a.AttributeValue })); Dictionary <string, object> defaultAttributeValues; if (exportOptions.AttributeReturnType == AttributeReturnType.Formatted) { defaultAttributeValues = exportOptions.AttributeList.ToDictionary(k => k.Key, v => ( object )v.DefaultValueAsFormatted); } else { defaultAttributeValues = exportOptions.AttributeList.ToDictionary(k => k.Key, v => v.DefaultValueAsType); } foreach (var modelExport in modelExportList) { var databaseAttributeValues = attributeValuesLookup.GetValueOrNull(modelExport.Id); modelExport.AttributesExport = new AttributesExport(); // initialize with DefaultValues modelExport.AttributesExport.AttributeValues = new Dictionary <string, object>(defaultAttributeValues); // update with values specific to Person if (databaseAttributeValues?.Any() == true) { foreach (var databaseAttributeValue in databaseAttributeValues) { var attributeCache = AttributeCache.Get(databaseAttributeValue.AttributeId); if (exportOptions.AttributeReturnType == AttributeReturnType.Formatted) { modelExport.AttributesExport.AttributeValues[attributeCache.Key] = databaseAttributeValue.ValueFormatted; } else { modelExport.AttributesExport.AttributeValues[attributeCache.Key] = databaseAttributeValue.ValueAsType; } } } } }
/// <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); } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection) { var settings = new SelectSettings(selection); var entityFields = GetGroupMemberAttributes(); var entityField = entityFields.FirstOrDefault(f => f.Name == settings.AttributeKey); if (entityField == null) { return(null); } var serviceInstance = new AttributeValueService(context); var entityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.GroupMember)); var valuesQuery = serviceInstance.Queryable() .Where(x => x.Attribute.Key == settings.AttributeKey && x.Attribute.EntityTypeId == entityTypeId) .Select(x => new { x.EntityId, x.Value }); var groupMemberService = new GroupMemberService(context); var resultQuery = groupMemberService.Queryable() .Select(gm => valuesQuery.FirstOrDefault(v => v.EntityId == gm.Id).Value); var exp = SelectExpressionExtractor.Extract(resultQuery, entityIdProperty, "gm"); return(exp); }
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(); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection) { var attributeGuid = selection.AsGuid(); var groupAttributeEntityFields = GetGroupAttributeEntityFields(); var entityField = groupAttributeEntityFields.FirstOrDefault(f => f.AttributeGuid == attributeGuid); if (entityField != null) { var serviceInstance = new AttributeValueService(context); var valuesQuery = serviceInstance.Queryable() .Where(x => x.Attribute.Guid == attributeGuid) .Select(x => new { x.EntityId, x.Value }); var groupMemberService = new GroupMemberService(context); var resultQuery = groupMemberService.Queryable() .Select(gm => valuesQuery.FirstOrDefault(v => v.EntityId == gm.GroupId).Value); return(SelectExpressionExtractor.Extract(resultQuery, entityIdProperty, "gm")); } return(null); }
/// <summary> /// Shows the edit value. /// </summary> /// <param name="attributeId">The attribute id.</param> /// <param name="setValues">if set to <c>true</c> [set values].</param> protected void ShowEditValue(int attributeId, bool setValues) { if (_displayValueEdit) { var attribute = Rock.Web.Cache.AttributeCache.Read(attributeId); hfIdValues.Value = attribute.Id.ToString(); lCaption.Text = attribute.Name; AttributeValueService attributeValueService = new AttributeValueService(); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId, _entityId).FirstOrDefault(); var fieldType = Rock.Web.Cache.FieldTypeCache.Read(attribute.FieldType.Id); Control editControl = fieldType.Field.EditControl(attribute.QualifierValues); editControl.ID = string.Format("attribute_field_{0}", attribute.Id); editControl.ClientIDMode = ClientIDMode.AutoID; if (setValues && attributeValue != null) { fieldType.Field.SetEditValue(editControl, attribute.QualifierValues, attributeValue.Value); } phEditControl.Controls.Clear(); phEditControl.Controls.Add(editControl); modalDetails.Show(); } }
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(); }
/// <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(); }
public BlockActionResult GetEditAttributeValue(Guid attributeGuid) { if (GetAttributeValue(AttributeKey.AllowSettingofValues).AsBooleanOrNull() != true) { return(ActionBadRequest("Setting values is not enabled.")); } var attribute = Rock.Web.Cache.AttributeCache.Get(attributeGuid); if (attribute == null) { return(ActionBadRequest()); } var entityId = GetEntityId(); var attributeValue = new AttributeValueService(new RockContext()).GetByAttributeIdAndEntityId(attribute.Id, entityId); string value = attributeValue != null && !string.IsNullOrWhiteSpace(attributeValue.Value) ? attributeValue.Value : attribute.DefaultValue; return(ActionOk(new { Attribute = PublicAttributeHelper.GetPublicAttributeForEdit(attribute), Value = PublicAttributeHelper.GetPublicEditValue(attribute, value) })); }
/// <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)); } } }
/// <summary> /// Handles the ItemDataBound event of the rptGroupMembers control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void rptGroupMembers_ItemDataBound(object sender, RepeaterItemEventArgs e) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var groupMember = e.Item.DataItem as GroupMember; var person = groupMember.Person; var lGroupMemberImage = e.Item.FindControl("lGroupMemberImage") as Literal; var cbSelectFamilyMember = e.Item.FindControl("cbSelectFamilyMember") as CheckBox; // Get all families that this person belongs to var families = person.GetFamilies().ToList(); var familyNames = ""; foreach (Group family in families) { if (families.Count > 1) { if (families.First() == family) { familyNames += ("(" + family.Name); } else if (families.Last() == family) { familyNames += (", " + family.Name + ")"); } else { familyNames += (", " + family.Name + ""); } } else if (families.Count == 1) { familyNames = ("(" + family.Name + ")"); } } familyNames = "<span style='font-size: 12px;'>" + familyNames + "</span>"; person.LoadAttributes(); var attributeSetting = GetAttributeValue("PersonAttribute"); var attribute = AttributeCache.Get(attributeSetting); var originalValue = person.GetAttributeValue(attribute.Key); if ((attribute.FieldType.Guid == Rock.SystemGuid.FieldType.DATE.AsGuid() || attribute.FieldType.Guid == Rock.SystemGuid.FieldType.DATE_TIME.AsGuid()) && !originalValue.IsNullOrWhiteSpace()) { cbSelectFamilyMember.Checked = true; } if (originalValue.AsBoolean() == true) { cbSelectFamilyMember.Checked = true; } // Person Info cbSelectFamilyMember.Text = ("<span style='font-weight: bold; font-size: 16px; margin-right: 10px;'>" + person.FullName + "</span><span>" + familyNames + "</span>"); }
/// <summary> /// Handles the Click event of the btnGenerateEnvelopeNumber 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 btnGenerateEnvelopeNumber_Click(object sender, EventArgs e) { var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); var maxEnvelopeNumber = new AttributeValueService(new RockContext()).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.ValueAsNumeric.HasValue) .Max(a => (int?)a.ValueAsNumeric); tbGivingEnvelopeNumber.Text = ((maxEnvelopeNumber ?? 0) + 1).ToString(); }
protected void btnSave_Click(object sender, EventArgs e) { //Get the old groupTypeId before we change it var stringGroupTypeId = group.GroupTypeId.ToString(); //Map group roles group.GroupTypeId = ddlGroupTypes.SelectedValue.AsInteger(); var groupMembers = group.Members; foreach (var role in group.GroupType.Roles) { var ddlRole = ( RockDropDownList )phRoles.FindControl(role.Id.ToString() + "_ddlRole"); var roleMembers = groupMembers.Where(gm => gm.GroupRoleId == role.Id); foreach (var member in roleMembers) { member.GroupRoleId = ddlRole.SelectedValue.AsInteger(); } } //Map attributes var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var groupMemberEntityId = new EntityTypeService(rockContext).Get(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id; var attributes = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == stringGroupTypeId && a.EntityTypeId == groupMemberEntityId ).ToList(); foreach (var attribute in attributes) { var ddlAttribute = ( RockDropDownList )phAttributes.FindControl(attribute.Id.ToString() + "_ddlAttribute"); if (ddlAttribute != null) { var newAttributeId = ddlAttribute.SelectedValue.AsInteger(); if (newAttributeId != 0) { foreach (var member in groupMembers) { var attributeEntity = attributeValueService.Queryable() .Where(av => av.EntityId == member.Id && av.AttributeId == attribute.Id) .FirstOrDefault(); if (attributeEntity != null) { attributeEntity.AttributeId = newAttributeId; } } } } } rockContext.SaveChanges(); nbSuccess.Visible = true; }
/// <summary> /// Gets a filter expression for an attribute value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <returns></returns> public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression) { Expression comparison = null; if (filterValues.Count > 1) { //// OR up the where clauses for each of the selected values // and make sure to wrap commas around things so we don't collide with partial matches // so it'll do something like this: // // WHERE ',' + Value + ',' like '%,bacon,%' // OR ',' + Value + ',' like '%,lettuce,%' // OR ',' + Value + ',' like '%,tomato,%' // should be either "Contains" or "Not Contains" ComparisonType comparisonType = filterValues[0].ConvertToEnum <ComparisonType>(ComparisonType.Contains); // No comparison value was specified, so we can filter if the Comparison Type using no value still makes sense if ((ComparisonType.IsBlank | ComparisonType.IsNotBlank).HasFlag(comparisonType)) { // Just checking if IsBlank or IsNotBlank, so let ComparisonExpression do its thing MemberExpression propertyExpression = Expression.Property(parameterExpression, this.AttributeValueFieldName); return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, AttributeConstantExpression(string.Empty))); } List <string> selectedValues = filterValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (var selectedValue in selectedValues) { var searchValue = "," + selectedValue + ","; var qryToExtract = new AttributeValueService(new Data.RockContext()).Queryable().Where(a => ("," + a.Value + ",").Contains(searchValue)); var valueExpression = FilterExpressionExtractor.Extract <AttributeValue>(qryToExtract, parameterExpression, "a"); if (comparisonType != ComparisonType.Contains) { valueExpression = Expression.Not(valueExpression); } if (comparison == null) { comparison = valueExpression; } else { comparison = Expression.Or(comparison, valueExpression); } } } if (comparison == null) { return(new NoAttributeFilterExpression()); } return(comparison); }
/// <summary> /// Gets a filter expression for an attribute value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <returns></returns> public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression) { Expression comparison = null; if (filterValues.Count > 1) { ComparisonType?comparisonType = filterValues[0].ConvertToEnumOrNull <ComparisonType>(); if (comparisonType.HasValue) { string compareToValue = filterValues[1]; MemberExpression propertyExpression = Expression.Property(parameterExpression, this.AttributeValueFieldName); if (!string.IsNullOrWhiteSpace(compareToValue)) { List <string> selectedValues = compareToValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (var selectedValue in selectedValues) { var searchValue = "," + selectedValue + ","; var qryToExtract = new AttributeValueService(new Data.RockContext()).Queryable().Where(a => ("," + a.Value + ",").Contains(searchValue)); var valueExpression = FilterExpressionExtractor.Extract <AttributeValue>(qryToExtract, parameterExpression, "a"); if (comparisonType.Value != ComparisonType.Contains) { valueExpression = Expression.Not(valueExpression); } if (comparison == null) { comparison = valueExpression; } else { comparison = Expression.Or(comparison, valueExpression); } } } else { // No comparison value was specified, so we can filter if the Comparison Type using no value still makes sense if ((ComparisonType.IsBlank | ComparisonType.IsNotBlank).HasFlag(comparisonType)) { // Just checking if IsBlank or IsNotBlank, so let ComparisonExpression do its thing return(ComparisonHelper.ComparisonExpression(comparisonType.Value, propertyExpression, AttributeConstantExpression(string.Empty))); } } } } if (comparison == null) { return(new Rock.Data.NoAttributeFilterExpression()); } return(comparison); }
protected void ShowEdit( int attributeId, bool setValues ) { AttributeService attributeService = new AttributeService(); var attribute = attributeService.Get( attributeId ); hfId.Value = attribute.Id.ToString(); lCaption.Text = attribute.Name; AttributeValueService attributeValueService = new AttributeValueService(); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attributeId, _entityId ).FirstOrDefault(); var fieldType = Rock.Web.Cache.FieldType.Read( attribute.FieldTypeId ); phEditControl.Controls.Clear(); phEditControl.Controls.Add(fieldType.Field.CreateControl((attributeValue != null ? attributeValue.Value : string.Empty), attribute.Required, setValues)); modalDetails.Show(); }
void rGrid_RowDataBound( object sender, GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.DataRow ) { Literal lValue = e.Row.FindControl( "lValue" ) as Literal; if ( lValue != null ) { int attributeId = ( int )rGrid.DataKeys[e.Row.RowIndex].Value; AttributeService attributeService = new AttributeService(); var attribute = attributeService.Get( attributeId ); var fieldType = Rock.Web.Cache.FieldType.Read( attribute.FieldTypeId ); AttributeValueService attributeValueService = new AttributeValueService(); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attributeId, _entityId ).FirstOrDefault(); if ( attributeValue != null ) lValue.Text = fieldType.Field.FormatValue( lValue, attributeValue.Value, true ); } } }
void lvAttributeValues_ItemDeleting( object sender, ListViewDeleteEventArgs e ) { var attributeValueService = new AttributeValueService(); var attributeValue = attributeValueService.Get( ( int )e.Keys["Id"] ); if ( attributeValue != null ) { attributeValueService.Delete( attributeValue, _currentPersonId ); attributeValueService.Save( attributeValue, _currentPersonId ); Rock.Attribute.Helper.LoadAttributes( _model ); } BindData(); }
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(); }
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(); }
void rGrid_RowDataBound( object sender, GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.DataRow ) { Literal lValue = e.Row.FindControl( "lValue" ) as Literal; HtmlAnchor aEdit = e.Row.FindControl( "aEdit" ) as HtmlAnchor; if ( lValue != null && aEdit != null ) { int attributeId = ( int )rGrid.DataKeys[e.Row.RowIndex].Value; AttributeService attributeService = new AttributeService(); var attribute = attributeService.Get( attributeId ); var fieldType = Rock.Web.Cache.FieldType.Read( attribute.FieldTypeId ); AttributeValueService attributeValueService = new AttributeValueService(); int? iEntityId = null; if ( entityId != "null" ) try { iEntityId = Int32.Parse( entityId ); } catch { } var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attributeId, iEntityId ); if ( attributeValue != null ) { string clientUpdateScript = fieldType.Field.ClientUpdateScript( this.Page, "0", attributeValue.Value, "attribute_value_" + BlockInstance.Id.ToString(), hfAttributeValue.ClientID ) + "(\"" + attributeValue.Value.EscapeQuotes() + "\");"; lValue.Text = fieldType.Field.FormatValue( lValue, attributeValue.Value, true ); aEdit.Attributes.Add( "onclick", string.Format( "editValue({0}, {1}, '{2}', '{3}');", attributeId, attributeValue.Id, attributeValue.Value.EscapeQuotes(), clientUpdateScript ) ); } else { string clientUpdateScript = fieldType.Field.ClientUpdateScript( this.Page, "0", string.Empty, "attribute_value_" + BlockInstance.Id.ToString(), hfAttributeValue.ClientID ) + "('');"; aEdit.Attributes.Add( "onclick", string.Format( "editValue({0}, 0, '', \"{1}\");", attributeId, clientUpdateScript ) ); } } } }
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(); }