/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { ddlCategoryFilter.Items.Clear(); ddlCategoryFilter.Items.Add("[All]"); AttributeService attributeService = new AttributeService(); var items = attributeService.Get(_entityTypeId, _entityQualifierColumn, _entityQualifierValue) .Where(a => a.Category != string.Empty && a.Category != null) .OrderBy(a => a.Category) .Select(a => a.Category) .Distinct() .ToList(); foreach (var item in items) { ListItem li = new ListItem(item); li.Selected = (!Page.IsPostBack && rFilter.GetUserValue("Category") == item); ddlCategoryFilter.Items.Add(li); } }
/// <summary> /// Handles the Add actions event. /// </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 gFilters_Add(object sender, EventArgs e) { var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); // reset editor edtFilter.Name = ""; edtFilter.Key = ""; edtFilter.AttributeId = null; edtFilter.IsFieldTypeEditable = true; edtFilter.SetAttributeFieldType(FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id, null); edtFilter.ReservedKeyNames = attributeService.Get(_blockTypeEntityId, "Id", _block.Id.ToString()) .Select(a => a.Key) .Distinct() .ToList(); mdFilter.Title = "Add Filter"; mdFilter.Show(); }
public BlockActionResult GetEditAttribute(Guid attributeGuid) { using (var rockContext = new RockContext()) { var attributeService = new AttributeService(rockContext); var attribute = attributeService.Get(attributeGuid); if (attribute == null) { return(ActionBadRequest()); } return(ActionOk(new EditAttributeViewModel { Attribute = PublicAttributeHelper.GetPublicEditableAttributeViewModel(attribute), EntityTypeQualifierColumn = attribute.EntityTypeQualifierColumn, EntityTypeQualifierValue = attribute.EntityTypeQualifierValue })); } }
/// <summary> /// Handles the Click event of the btnSaveAttribute 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 btnSaveAttribute_Click(object sender, EventArgs e) { using (new Rock.Data.UnitOfWorkScope()) { var attributeService = new AttributeService(); var attributeQualifierService = new AttributeQualifierService(); Rock.Model.Attribute attribute; int attributeId = ((hfIdAttribute.Value) != null && hfIdAttribute.Value != String.Empty) ? Int32.Parse(hfIdAttribute.Value) : 0; if (attributeId == 0) { attribute = new Rock.Model.Attribute(); attribute.IsSystem = false; attribute.EntityTypeId = _entityTypeId; attribute.EntityTypeQualifierColumn = _entityQualifier; attribute.EntityTypeQualifierValue = hfIdType.Value; attributeService.Add(attribute, CurrentPersonId); } else { Rock.Web.Cache.AttributeCache.Flush(attributeId); attribute = attributeService.Get(attributeId); } attribute.Key = tbAttributeKey.Text; attribute.Name = tbAttributeName.Text; attribute.Category = tbAttributeCategory.Text; attribute.Description = tbAttributeDescription.Text; attribute.FieldTypeId = Int32.Parse(ddlAttributeFieldType.SelectedValue); attribute.DefaultValue = tbAttributeDefaultValue.Text; attribute.IsGridColumn = cbAttributeGridColumn.Checked; attribute.IsRequired = cbAttributeRequired.Checked; attributeService.Save(attribute, CurrentPersonId); } rGridAttribute_Bind(hfIdType.Value); modalAttributes.Hide(); }
/// <summary> /// Saves the attributes. /// </summary> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="qualifierColumn">The qualifier column.</param> /// <param name="qualifierValue">The qualifier value.</param> /// <param name="viewStateAttributes">The view state attributes.</param> /// <param name="rockContext">The rock context.</param> private void SaveAttributes(int entityTypeId, string qualifierColumn, string qualifierValue, List <Attribute> viewStateAttributes, RockContext rockContext) { // Get the existing attributes for this entity type and qualifier value var attributeService = new AttributeService(rockContext); var attributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = viewStateAttributes.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { attributeService.Delete(attr); rockContext.SaveChanges(); Rock.Web.Cache.AttributeCache.Flush(attr.Id); } // Update the Attributes that were assigned in the UI foreach (var attributeState in viewStateAttributes) { Helper.SaveAttributeEdits(attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext); } }
/// <summary> /// Handles the Delete event of the gDefinedTypeAttributes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gDefinedTypeAttributes_Delete(object sender, RowEventArgs e) { Guid attributeGuid = ( Guid )e.RowKeyValue; var rockContext = new RockContext(); AttributeService attributeService = new AttributeService(rockContext); Attribute attribute = attributeService.Get(attributeGuid); if (attribute != null) { string errorMessage; if (!attributeService.CanDelete(attribute, out errorMessage)) { mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information); return; } attributeService.Delete(attribute); rockContext.SaveChanges(); } BindDefinedTypeAttributesGrid(); }
/// <summary> /// Handles the Delete event of the gDefinedTypeAttributes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gDefinedTypeAttributes_Delete(object sender, RowEventArgs e) { Guid attributeGuid = (Guid)e.RowKeyValue; AttributeService attributeService = new AttributeService(); Attribute attribute = attributeService.Get(attributeGuid); if (attribute != null) { string errorMessage; if (!attributeService.CanDelete(attribute, out errorMessage)) { mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information); return; } AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute, CurrentPersonId); attributeService.Save(attribute, CurrentPersonId); } BindDefinedTypeAttributesGrid(); }
/// <summary> /// Gs the defined type attributes_ show edit. /// </summary> /// <param name="attributeGuid">The attribute GUID.</param> protected void gDefinedTypeAttributes_ShowEdit(Guid attributeGuid) { pnlDetails.Visible = false; vsDetails.Enabled = false; pnlDefinedTypeAttributes.Visible = true; Attribute attribute; if (attributeGuid.Equals(Guid.Empty)) { attribute = new Attribute(); edtDefinedTypeAttributes.ActionTitle = ActionTitle.Add("attribute for defined type " + tbTypeName.Text); } else { AttributeService attributeService = new AttributeService(); attribute = attributeService.Get(attributeGuid); edtDefinedTypeAttributes.ActionTitle = ActionTitle.Edit("attribute for defined type " + tbTypeName.Text); } edtDefinedTypeAttributes.SetAttributeProperties(attribute, typeof(DefinedValue)); }
/// <summary> /// Haves the workflow action. /// </summary> /// <param name="guidValue">The guid value of the action.</param> /// <returns>True/False if the workflow contains the action</returns> private bool HaveWorkflowAction(string guidValue) { using (var rockContext = new RockContext()) { BlockService blockService = new BlockService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeValueService attributeValueService = new AttributeValueService(rockContext); var block = blockService.Get(Rock.SystemGuid.Block.BIO.AsGuid()); var attribute = attributeService.Get(Rock.SystemGuid.Attribute.BIO_WORKFLOWACTION.AsGuid()); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, block.Id); if (attributeValue == null || string.IsNullOrWhiteSpace(attributeValue.Value)) { return(false); } var workflowActionValues = attributeValue.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Guid guid = guidValue.AsGuid(); return(workflowActionValues.Any(w => w.AsGuid() == guid)); } }
/// <summary> /// Gs the workflow type attributes_ show edit. /// </summary> /// <param name="attributeGuid">The attribute GUID.</param> protected void gWorkflowTypeAttributes_ShowEdit(Guid attributeGuid) { pnlDetails.Visible = false; pnlWorkflowTypeAttributes.Visible = true; Attribute attribute; if (attributeGuid.Equals(Guid.Empty)) { attribute = new Attribute(); attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id; edtWorkflowTypeAttributes.ActionTitle = ActionTitle.Add("attribute for workflow type " + tbName.Text); } else { AttributeService attributeService = new AttributeService(); attribute = attributeService.Get(attributeGuid); edtWorkflowTypeAttributes.ActionTitle = ActionTitle.Edit("attribute for workflow type " + tbName.Text); } edtWorkflowTypeAttributes.SetAttributeProperties(attribute, typeof(Workflow)); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { IQueryable <Rock.Model.Attribute> query; AttributeService attributeService = new AttributeService(); if (_configuredType) { query = attributeService.Get(_entityTypeId, _entityQualifierColumn, _entityQualifierValue); } else { query = attributeService.GetByEntityTypeId(ddlEntityType.SelectedValueAsInt()); } List <int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().Where(v => v != 0).ToList(); if (selectedCategoryIds.Any()) { query = query. Where(a => a.Categories.Any(c => selectedCategoryIds.Contains(c.Id))); } SortProperty sortProperty = rGrid.SortProperty; if (sortProperty != null) { query = query. Sort(sortProperty); } else { query = query. OrderBy(a => a.Key); } rGrid.DataSource = query.ToList(); rGrid.DataBind(); }
/// <summary> /// Gs the workflow type attributes_ show edit. /// </summary> /// <param name="attributeGuid">The attribute GUID.</param> protected void gWorkflowTypeAttributes_ShowEdit(Guid attributeGuid) { pnlDetails.Visible = false; vsDetails.Enabled = false; pnlWorkflowTypeAttributes.Visible = true; Attribute attribute; if (attributeGuid.Equals(Guid.Empty)) { attribute = new Attribute(); edtWorkflowTypeAttributes.ActionTitle = ActionTitle.Add("attribute for workflow type " + tbName.Text); } else { AttributeService attributeService = new AttributeService(); attribute = attributeService.Get(attributeGuid); edtWorkflowTypeAttributes.ActionTitle = ActionTitle.Edit("attribute for workflow type " + tbName.Text); } edtWorkflowTypeAttributes.SetAttributeProperties(attribute); }
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 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(); }
protected void btnSave_Click(object sender, EventArgs e) { hfAreaGroupClicked.Value = "true"; using (var rockContext = new RockContext()) { var attributeService = new AttributeService(rockContext); if (checkinArea.Visible) { var groupTypeService = new GroupTypeService(rockContext); var groupType = groupTypeService.Get(checkinArea.GroupTypeGuid); if (groupType != null) { groupType.LoadAttributes(rockContext); checkinArea.GetGroupTypeValues(groupType); if (groupType.IsValid) { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes)) { var attribute = attributeService.Get(labelAttribute.Value.Guid); attributeService.Delete(attribute); } // Make sure default role is set if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any()) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; int binaryFileFieldTypeID = FieldTypeCache.Get(Rock.SystemGuid.FieldType.LABEL.AsGuid()).Id; foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupType.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if (!attribute.IsValid) { return; } attributeService.Add(attribute); } rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.Clear(); nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults(groupType.ValidationResults); } } } if (checkinGroup.Visible) { var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var group = groupService.Get(checkinGroup.GroupGuid); if (group != null) { group.LoadAttributes(rockContext); checkinGroup.GetGroupValues(group); // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList(); foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList()) { groupLocation.GroupLocationScheduleConfigs.Clear(); groupLocationService.Delete(groupLocation); group.GroupLocations.Remove(groupLocation); } var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList(); foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList()) { var groupLocation = new GroupLocation(); groupLocation.LocationId = item.LocationId; group.GroupLocations.Add(groupLocation); } // Set the new order foreach (var item in checkinGroup.Locations.OrderBy(l => l.Order).ToList()) { var groupLocation = group.GroupLocations.FirstOrDefault(gl => gl.LocationId == item.LocationId); groupLocation.Order = item.Order ?? 0; } if (group.IsValid) { rockContext.SaveChanges(); group.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.Clear(); nbSaveSuccess.Visible = true; BuildRows(); } else { ShowInvalidResults(group.ValidationResults); } } } } hfIsDirty.Value = "false"; }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { Group group; bool wasSecurityRole = false; using (new UnitOfWorkScope()) { GroupService groupService = new GroupService(); AttributeService attributeService = new AttributeService(); int groupId = int.Parse(hfGroupId.Value); if (groupId == 0) { group = new Group(); group.IsSystem = false; group.Name = string.Empty; } else { group = groupService.Get(groupId); wasSecurityRole = group.IsSecurityRole; } if ((ddlGroupType.SelectedValueAsInt() ?? 0) == 0) { ddlGroupType.ShowErrorMessage(Rock.Constants.WarningMessage.CannotBeBlank(GroupType.FriendlyTypeName)); return; } group.Name = tbName.Text; group.Description = tbDescription.Text; group.CampusId = ddlCampus.SelectedValue.Equals(None.IdValue) ? (int?)null : int.Parse(ddlCampus.SelectedValue); group.GroupTypeId = int.Parse(ddlGroupType.SelectedValue); group.ParentGroupId = gpParentGroup.SelectedValue.Equals(None.IdValue) ? (int?)null : int.Parse(gpParentGroup.SelectedValue); group.IsSecurityRole = cbIsSecurityRole.Checked; group.IsActive = cbIsActive.Checked; if (group.ParentGroupId == group.Id) { gpParentGroup.ShowErrorMessage("Group cannot be a Parent Group of itself."); return; } group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group); if (!Page.IsValid) { return; } if (!group.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { if (group.Id.Equals(0)) { groupService.Add(group, CurrentPersonId); } groupService.Save(group, CurrentPersonId); Rock.Attribute.Helper.SaveAttributeValues(group, CurrentPersonId); /* Take care of Group Member Attributes */ // delete GroupMemberAttributes that are no longer configured in the UI string qualifierValue = group.Id.ToString(); var groupMemberAttributesQry = attributeService.GetByEntityTypeId(new GroupMember().TypeId).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("GroupId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(qualifierValue)); var deletedGroupMemberAttributes = from attr in groupMemberAttributesQry where !(from d in GroupMemberAttributesState select d.Guid).Contains(attr.Guid) select attr; deletedGroupMemberAttributes.ToList().ForEach(a => { var attr = attributeService.Get(a.Guid); Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); }); // add/update the GroupMemberAttributes that are assigned in the UI foreach (var attributeState in GroupMemberAttributesState) { // remove old qualifiers in case they changed var qualifierService = new AttributeQualifierService(); foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList()) { qualifierService.Delete(oldQualifier, CurrentPersonId); qualifierService.Save(oldQualifier, CurrentPersonId); } Attribute attribute = groupMemberAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.Clone() as Rock.Model.Attribute; attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attribute.FromDictionary(attributeState.ToDictionary()); foreach (var qualifier in attributeState.AttributeQualifiers) { attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier); } } attribute.EntityTypeQualifierColumn = "GroupId"; attribute.EntityTypeQualifierValue = group.Id.ToString(); attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupMember)).Id; Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Save(attribute, CurrentPersonId); } }); } if (group != null && wasSecurityRole) { if (!group.IsSecurityRole) { // if this group was a SecurityRole, but no longer is, flush Rock.Security.Role.Flush(group.Id); Rock.Security.Authorization.Flush(); } } else { if (group.IsSecurityRole) { // new security role, flush Rock.Security.Authorization.Flush(); } } var qryParams = new Dictionary <string, string>(); qryParams["groupId"] = group.Id.ToString(); NavigateToPage(this.CurrentPage.Guid, qryParams); }
protected override void OnInit(EventArgs e) { base.OnInit(e); string entityQualifierColumn = AttributeValue("EntityQualifierColumn"); if (string.IsNullOrWhiteSpace(entityQualifierColumn)) { entityQualifierColumn = PageParameter("EntityQualifierColumn"); } string entityQualifierValue = AttributeValue("EntityQualifierValue"); if (string.IsNullOrWhiteSpace(entityQualifierValue)) { entityQualifierValue = PageParameter("EntityQualifierValue"); } // Get the context entity int?contextEntityTypeId = null; Rock.Data.IEntity contextEntity = null; foreach (KeyValuePair <string, Rock.Data.IEntity> entry in ContextEntities) { contextEntityTypeId = entry.Value.TypeId; contextEntity = entry.Value; // Should only be one. break; } if (contextEntityTypeId.HasValue && contextEntity != null) { ObjectCache cache = MemoryCache.Default; string cacheKey = string.Format("Attributes:{0}:{1}:{2}", contextEntityTypeId, entityQualifierColumn, entityQualifierValue); Dictionary <string, List <int> > cachedAttributes = cache[cacheKey] as Dictionary <string, List <int> >; if (cachedAttributes == null) { cachedAttributes = new Dictionary <string, List <int> >(); AttributeService attributeService = new AttributeService(); foreach (var item in attributeService .Get(contextEntityTypeId, entityQualifierColumn, entityQualifierValue) .OrderBy(a => a.Category) .ThenBy(a => a.Order) .Select(a => new { a.Category, a.Id })) { if (!cachedAttributes.ContainsKey(item.Category)) { cachedAttributes.Add(item.Category, new List <int>()); } cachedAttributes[item.Category].Add(item.Id); } CacheItemPolicy cacheItemPolicy = null; cache.Set(cacheKey, cachedAttributes, cacheItemPolicy); } Rock.Attribute.IHasAttributes model = contextEntity as Rock.Attribute.IHasAttributes; if (model != null) { var rootElement = new XElement("root"); foreach (string category in AttributeValue("AttributeCategories").SplitDelimitedValues(false)) { if (cachedAttributes.ContainsKey(category)) { var attributesElement = new XElement("attributes", new XAttribute("category-name", category) ); rootElement.Add(attributesElement); foreach (var attributeId in cachedAttributes[category]) { var attribute = Rock.Web.Cache.AttributeCache.Read(attributeId); if (attribute != null) { var values = model.AttributeValues[attribute.Key]; if (values != null && values.Count > 0) { attributesElement.Add(new XElement("attribute", new XAttribute("name", attribute.Name), new XCData(attribute.FieldType.Field.FormatValue(null, values[0].Value, attribute.QualifierValues, false) ?? string.Empty) )); } } } } } xDocument = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement); } } }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { MarketingCampaignAdType marketingCampaignAdType; MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService(); int marketingCampaignAdTypeId = int.Parse(hfMarketingCampaignAdTypeId.Value); if (marketingCampaignAdTypeId == 0) { marketingCampaignAdType = new MarketingCampaignAdType(); marketingCampaignAdTypeService.Add(marketingCampaignAdType, CurrentPersonId); } else { marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdTypeId); } marketingCampaignAdType.Name = tbName.Text; marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse(ddlDateRangeType.SelectedValue); if (!marketingCampaignAdType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { AttributeService attributeService = new AttributeService(); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(); CategoryService categoryService = new CategoryService(); marketingCampaignAdTypeService.Save(marketingCampaignAdType, CurrentPersonId); // get it back to make sure we have a good Id for it for the Attributes marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdType.Guid); var entityTypeId = EntityTypeCache.Read(typeof(MarketingCampaignAd)).Id; string qualifierColumn = "MarketingCampaignAdTypeId"; string qualifierValue = marketingCampaignAdType.Id.ToString(); // Get the existing attributes for this entity type and qualifier value var attributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = AttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); } // Update the Attributes that were assigned in the UI foreach (var attributeState in AttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, attributeService, attributeQualifierService, categoryService, entityTypeId, qualifierColumn, qualifierValue, CurrentPersonId); } }); } NavigateToParentPage(); }
public string UploadPhoto(int id) { RockContext context = new RockContext(); GroupService groupService = new GroupService(context); BinaryFileService binaryFileService = new BinaryFileService(context); AttributeService attributeService = new AttributeService(context); Group group = groupService.Get(id); if (group != null) { group.LoadAttributes(); if (group.Attributes.ContainsKey("GroupPhoto")) { Rock.Model.Attribute attribute = attributeService.Get(group.Attributes["GroupPhoto"].Id); string qualifierValue = attribute.EntityTypeQualifierValue; // Make sure a file was uploaded var files = HttpContext.Current.Request.Files; var uploadedFile = files.AllKeys.Select(fk => files[fk]).FirstOrDefault(); Guid binaryFileTypeGuid = attribute.AttributeQualifiers.AsQueryable().Where(aq => aq.Key == "binaryFileType").First().Value.AsGuid(); var binaryFileType = new BinaryFileTypeService(context).Get(binaryFileTypeGuid); if (uploadedFile == null) { GenerateResponse(HttpStatusCode.BadRequest, "No file was sent"); } if (binaryFileType == null) { GenerateResponse(HttpStatusCode.InternalServerError, "Invalid binary file type"); } if (!binaryFileType.IsAuthorized(Rock.Security.Authorization.EDIT, GetPerson())) { GenerateResponse(HttpStatusCode.Unauthorized, "Not authorized to upload this type of file"); } BinaryFile binaryFile = null; if (group.GetAttributeValue("GroupPhoto").AsGuidOrNull().HasValue) { binaryFile = binaryFileService.Get(group.GetAttributeValue("GroupPhoto").AsGuid()); } else { binaryFile = new BinaryFile(); binaryFileService.Add(binaryFile); } binaryFile.IsTemporary = false; binaryFile.BinaryFileTypeId = binaryFileType.Id; binaryFile.MimeType = uploadedFile.ContentType; binaryFile.FileName = Path.GetFileName(uploadedFile.FileName); binaryFile.ContentStream = FileUtilities.GetFileContentStream(uploadedFile); context.SaveChanges(); return(binaryFile.Url); } } throw new HttpResponseException(HttpStatusCode.NotFound); }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { bool hasValidationErrors = false; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService(rockContext); GroupService groupService = new GroupService(rockContext); AttributeService attributeService = new AttributeService(rockContext); GroupLocationService groupLocationService = new GroupLocationService(rockContext); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List <GroupType>(); foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList()) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType(); groupTypeUIList.Add(groupType); } var groupTypeDBList = new List <GroupType>(); var groupTypesToDelete = new List <GroupType>(); var groupsToDelete = new List <Group>(); var groupTypesToAddUpdate = new List <GroupType>(); var groupsToAddUpdate = new List <Group>(); GroupType parentGroupTypeDB = groupTypeService.Get(parentGroupTypeId); GroupType parentGroupTypeUI = parentGroupTypeDB.Clone(false); parentGroupTypeUI.ChildGroupTypes = groupTypeUIList; PopulateDeleteLists(groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI); PopulateAddUpdateLists(groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI); int binaryFileFieldTypeID = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id; int binaryFileTypeId = new BinaryFileTypeService(rockContext).Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id; RockTransactionScope.WrapTransaction(() => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach (var groupToDelete in groupsToDelete) { groupService.Delete(groupToDelete); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach (var groupTypeToDelete in groupTypesToDelete) { groupTypeService.Delete(groupTypeToDelete); } rockContext.SaveChanges(); // Add/Update grouptypes and groups that are in the UI // Note: We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes // since the ChildGroupTypes may not exist in the database yet foreach (GroupType groupTypeUI in groupTypesToAddUpdate) { GroupType groupTypeDB = groupTypeService.Get(groupTypeUI.Guid); if (groupTypeDB == null) { groupTypeDB = new GroupType(); groupTypeDB.Id = 0; groupTypeDB.Guid = groupTypeUI.Guid; } groupTypeDB.Name = groupTypeUI.Name; groupTypeDB.Order = groupTypeUI.Order; groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId; groupTypeDB.Attributes = groupTypeUI.Attributes; groupTypeDB.AttributeValues = groupTypeUI.AttributeValues; if (groupTypeDB.Id == 0) { groupTypeService.Add(groupTypeDB); } if (!groupTypeDB.IsValid) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid); groupTypeEditor.ForceContentVisible = true; return; } rockContext.SaveChanges(); groupTypeDB.SaveAttributeValues(); // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes groupTypeDB = groupTypeService.Get(groupTypeDB.Guid); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes(groupTypeDB)) { var attribute = attributeService.Get(labelAttributeDB.Value.Guid); Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); } rockContext.SaveChanges(); foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid]) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = binaryFileTypeId.ToString() }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; if (!attribute.IsValid) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid); groupTypeEditor.ForceContentVisible = true; return; } attributeService.Add(attribute); } rockContext.SaveChanges(); } // Add/Update Groups foreach (var groupUI in groupsToAddUpdate) { Group groupDB = groupService.Get(groupUI.Guid); if (groupDB == null) { groupDB = new Group(); groupDB.Guid = groupUI.Guid; } groupDB.Name = groupUI.Name; // delete any GroupLocations that were removed in the UI foreach (var groupLocationDB in groupDB.GroupLocations.ToList()) { if (!groupUI.GroupLocations.Select(a => a.LocationId).Contains(groupLocationDB.LocationId)) { groupLocationService.Delete(groupLocationDB); } } // add any GroupLocations that were added in the UI foreach (var groupLocationUI in groupUI.GroupLocations) { if (!groupDB.GroupLocations.Select(a => a.LocationId).Contains(groupLocationUI.LocationId)) { GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId }; groupDB.GroupLocations.Add(groupLocationDB); } } groupDB.Order = groupUI.Order; // get GroupTypeId from database in case the groupType is new groupDB.GroupTypeId = groupTypeService.Get(groupUI.GroupType.Guid).Id; groupDB.Attributes = groupUI.Attributes; groupDB.AttributeValues = groupUI.AttributeValues; if (groupDB.Id == 0) { groupService.Add(groupDB); } if (!groupDB.IsValid) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid); groupEditor.ForceContentVisible = true; return; } rockContext.SaveChanges(); groupDB.SaveAttributeValues(); } /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */ // save main parentGroupType with current UI ChildGroupTypes parentGroupTypeDB.ChildGroupTypes = new List <GroupType>(); parentGroupTypeDB.ChildGroupTypes.Clear(); foreach (var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes) { var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid); parentGroupTypeDB.ChildGroupTypes.Add(childGroupTypeDB); } rockContext.SaveChanges(); // loop thru all the other GroupTypes in the UI and save their childgrouptypes foreach (var groupTypeUI in groupTypesToAddUpdate) { var groupTypeDB = groupTypeService.Get(groupTypeUI.Guid); groupTypeDB.ChildGroupTypes = new List <GroupType>(); groupTypeDB.ChildGroupTypes.Clear(); foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes) { var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid); groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB); } } rockContext.SaveChanges(); }); if (!hasValidationErrors) { NavigateToParentPage(); } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="attributeMatrixTemplateId">The attribute matrix template identifier.</param> public void ShowDetail(int attributeMatrixTemplateId) { pnlView.Visible = true; AttributeMatrixTemplate attributeMatrixTemplate = null; var rockContext = new RockContext(); if (!attributeMatrixTemplateId.Equals(0)) { attributeMatrixTemplate = new AttributeMatrixTemplateService(rockContext).Get(attributeMatrixTemplateId); lActionTitle.Text = ActionTitle.Edit(AttributeMatrixTemplate.FriendlyTypeName).FormatAsHtmlTitle(); pdAuditDetails.SetEntity(attributeMatrixTemplate, ResolveRockUrl("~")); } if (attributeMatrixTemplate == null) { attributeMatrixTemplate = new AttributeMatrixTemplate { Id = 0 }; attributeMatrixTemplate.FormattedLava = AttributeMatrixTemplate.FormattedLavaDefault; lActionTitle.Text = ActionTitle.Add(AttributeMatrixTemplate.FriendlyTypeName).FormatAsHtmlTitle(); // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } hfAttributeMatrixTemplateId.Value = attributeMatrixTemplate.Id.ToString(); tbName.Text = attributeMatrixTemplate.Name; cbIsActive.Checked = attributeMatrixTemplate.IsActive; tbDescription.Text = attributeMatrixTemplate.Description; tbMinimumRows.Text = attributeMatrixTemplate.MinimumRows.ToString(); tbMaximumRows.Text = attributeMatrixTemplate.MaximumRows.ToString(); ceFormattedLava.Text = attributeMatrixTemplate.FormattedLava; var attributeService = new AttributeService(rockContext); AttributesState = attributeService.Get(new AttributeMatrixItem().TypeId, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString()).AsQueryable() .OrderBy(a => a.Order) .ThenBy(a => a.Name) .ToList(); BindAttributesGrid(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(AttributeMatrixTemplate.FriendlyTypeName); } if (readOnly) { lActionTitle.Text = ActionTitle.View(AttributeMatrixTemplate.FriendlyTypeName); btnCancel.Text = "Close"; } tbName.ReadOnly = readOnly; cbIsActive.Enabled = !readOnly; tbDescription.ReadOnly = readOnly; tbMinimumRows.ReadOnly = readOnly; tbMaximumRows.ReadOnly = readOnly; ceFormattedLava.ReadOnly = readOnly; btnSave.Visible = !readOnly; }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { BinaryFileType binaryFileType; var rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.AllowCaching = cbAllowCaching.Checked; binaryFileType.RequiresSecurity = cbRequiresSecurity.Checked; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(rockContext); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType); if (!binaryFileType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { rockContext.SaveChanges(); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString()); var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext); } // SaveAttributeValues for the BinaryFileType binaryFileType.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { AttributeMatrixTemplate attributeMatrixTemplate; var rockContext = new RockContext(); var attributeMatrixTemplateService = new AttributeMatrixTemplateService(rockContext); int attributeMatrixTemplateId = int.Parse(hfAttributeMatrixTemplateId.Value); if (attributeMatrixTemplateId == 0) { attributeMatrixTemplate = new AttributeMatrixTemplate(); attributeMatrixTemplateService.Add(attributeMatrixTemplate); } else { attributeMatrixTemplate = attributeMatrixTemplateService.Get(attributeMatrixTemplateId); } attributeMatrixTemplate.Name = tbName.Text; attributeMatrixTemplate.IsActive = cbIsActive.Checked; attributeMatrixTemplate.Description = tbDescription.Text; attributeMatrixTemplate.MinimumRows = tbMinimumRows.Text.AsIntegerOrNull(); attributeMatrixTemplate.MaximumRows = tbMaximumRows.Text.AsIntegerOrNull(); attributeMatrixTemplate.FormattedLava = ceFormattedLava.Text; // need WrapTransaction due to Attribute saves rockContext.WrapTransaction(() => { rockContext.SaveChanges(); /* Save Attributes */ var entityTypeIdAttributeMatrix = EntityTypeCache.GetId <AttributeMatrixItem>(); // Get the existing attributes for this entity type and qualifier value var attributeService = new AttributeService(rockContext); var regFieldService = new RegistrationTemplateFormFieldService(rockContext); var attributes = attributeService.Get(entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString()); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = AttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { foreach (var field in regFieldService.Queryable().Where(f => f.AttributeId.HasValue && f.AttributeId.Value == attr.Id).ToList()) { regFieldService.Delete(field); } attributeService.Delete(attr); rockContext.SaveChanges(); Rock.Web.Cache.AttributeCache.Flush(attr.Id); } // Update the Attributes that were assigned in the UI foreach (var attributeState in AttributesState) { Helper.SaveAttributeEdits(attributeState, entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString(), rockContext); } Rock.Web.Cache.AttributeCache.FlushEntityAttributes(); }); NavigateToParentPage(); }
/// <summary>Process all trips (events) from Service Reef.</summary> /// <param name="message">The message that is returned depending on the result.</param> /// <param name="state">The state of the process.</param> /// <returns><see cref="WorkerResultStatus"/></returns> public void Execute(IJobExecutionContext context) { RockContext dbContext = new RockContext(); PersonService personService = new PersonService(dbContext); PersonAliasService personAliasService = new PersonAliasService(dbContext); GroupService groupService = new GroupService(dbContext); GroupMemberService groupMemberService = new GroupMemberService(dbContext); AttributeService attributeService = new AttributeService(dbContext); AttributeValueService attributeValueService = new AttributeValueService(dbContext); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(dbContext); DefinedValueService definedValueService = new DefinedValueService(dbContext); DefinedTypeService definedTypeService = new DefinedTypeService(dbContext); LocationService locationService = new LocationService(dbContext); // Get the datamap for loading attributes JobDataMap dataMap = context.JobDetail.JobDataMap; String warnings = string.Empty; var total = 1; var processed = 0; try { DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||"); String SRApiKey = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey")); String SRApiSecret = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret")); String SRApiUrl = dataMap.GetString("ServiceReefAPIURL"); DefinedValueCache connectionStatus = DefinedValueCache.Get(dataMap.GetString("DefaultConnectionStatus").AsGuid(), dbContext); if (SRApiUrl.Last() != '/') { SRApiUrl += "/"; } Group group = groupService.Get(dataMap.GetString("ParentGroup").AsGuid()); GroupTypeCache parentGroupType = GroupTypeCache.Get(dataMap.Get("YearGroupType").ToString().AsGuid(), dbContext); GroupTypeCache groupType = GroupTypeCache.Get(dataMap.Get("TripGroupType").ToString().AsGuid(), dbContext); Rock.Model.Attribute attribute = attributeService.Get(dataMap.GetString("ServiceReefUserId").AsGuid()); Rock.Model.Attribute attribute2 = attributeService.Get(dataMap.GetString("ServiceReefProfileURL").AsGuid()); var entitytype = EntityTypeCache.Get(typeof(Group)).Id; // Setup the ServiceReef API Client var client = new RestClient(SRApiUrl); client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret); // Get all events from ServiceReef var request = new RestRequest("v1/events", Method.GET); request.AddParameter("pageSize", 100); if (dateRange.Start.HasValue) { request.AddParameter("startDate", dateRange.Start.Value.ToString("o")); } if (dateRange.End.HasValue) { request.AddParameter("endDate", dateRange.End.Value.ToString("o")); } request.AddParameter("page", 1); while (total > processed) { var response = client.Execute <Contracts.Events>(request); if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength); } if (response.Data != null && response.Data.PageInfo != null) { total = response.Data.PageInfo.TotalRecords; foreach (Contracts.Events.Result result in response.Data.Results) { // Process the event Group trip = null; Group trip2 = null; var startdate = result.StartDate; var parentgroup = string.Format("{0} Mission Trips", startdate.Year); if (result.EventId > 0) { trip = groupService.Queryable().Where(t => t.Name == parentgroup).FirstOrDefault(); trip2 = groupService.Queryable().Where(t => t.ForeignId == result.EventId && t.GroupTypeId == groupType.Id).FirstOrDefault(); } Guid guid = Guid.NewGuid(); Guid guid2 = Guid.NewGuid(); if (trip == null) { // Create trip parent Group Group tripPG = new Group(); tripPG.Name = parentgroup; tripPG.GroupTypeId = parentGroupType.Id; tripPG.ParentGroupId = group.Id; tripPG.IsSystem = false; tripPG.IsActive = true; tripPG.IsSecurityRole = false; tripPG.Order = 0; tripPG.Guid = guid; groupService.Add(tripPG); // Now save the trip parent group dbContext.SaveChanges(); trip = tripPG; } if (trip2 == null) { // Create the trip Group tripG = new Group(); tripG.Name = result.Name; tripG.GroupTypeId = groupType.Id; tripG.ParentGroupId = trip.Id; tripG.IsSystem = false; tripG.IsActive = true; tripG.IsSecurityRole = false; tripG.Order = 0; tripG.ForeignId = result.EventId; groupService.Add(tripG); // Now save the trip dbContext.SaveChanges(); trip2 = tripG; } trip2.LoadAttributes(); if (startdate != DateTime.MinValue) { trip2.SetAttributeValue("Year", startdate.Year.ToString()); trip2.SetAttributeValue("Month", startdate.ToString("MMMM")); trip2.SaveAttributeValues(); } dbContext.SaveChanges(); var eventRequest = new RestRequest("v1/events/{eventId}", Method.GET); eventRequest.AddUrlSegment("eventId", result.EventId.ToString()); var eventResult = client.Execute <Contracts.Event>(eventRequest); if (eventResult.Data != null && eventResult.Data.Categories.Count > 0) { foreach (Contracts.Event.CategorySimple categorysimple in eventResult.Data.Categories) { var option = categorysimple.Options.FirstOrDefault(); if (option != null) { trip2.SetAttributeValue(categorysimple.Name.RemoveAllNonAlphaNumericCharacters(), option.Name); trip2.SaveAttributeValues(); } } dbContext.SaveChanges(); } var amount = 1; var handled = 0; String rest = String.Format("v1/events/{0}/participants", result.EventId); var request2 = new RestRequest(rest, Method.GET); request2.AddParameter("pageSize", 100); request2.AddParameter("page", 1); // We haven't processed this before so get busy! while (amount > handled) { var response2 = client.Execute <Contracts.Participants>(request2); if (response2.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("ServiceReef API Response: " + response2.StatusDescription + " Content Length: " + response2.ContentLength); } if (response2.Data != null && response2.Data.PageInfo != null) { amount = response2.Data.PageInfo.TotalRecords; foreach (Contracts.Participants.Result result2 in response2.Data.Results) { Person person = null; if (result2.RegistrationStatus != "Draft") { if (result2.UserId > 0) { var memberRequest = new RestRequest("v1/members/{userId}", Method.GET); memberRequest.AddUrlSegment("userId", result2.UserId.ToString()); var memberResult = client.Execute <Contracts.Member>(memberRequest); if (memberResult.Data != null && memberResult.Data.ArenaId > 0) { Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault(); if (personMatch != null) { person = personMatch; } } } // 2. If we didn't get a person match via their Alias Id // then use their ServiceReef UserId attribute if (person == null && attribute != null) { var personIds = attributeValueService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value == result2.UserId.ToString()).Select(av => av.EntityId); if (personIds.Count() == 1) { person = personService.Get(personIds.FirstOrDefault().Value); } } // 3. If we STILL don't have a person match then // just use the standard person match/create logic if (person == null) { String street1 = null; String postalCode = null; if (result2.Address != null) { street1 = result2.Address.Address1; postalCode = result2.Address.Zip; } var email = result2.Email.Trim(); List <Person> matches = null; Location homelocation = new Location(); if (!email.IsValidEmail()) { email = null; matches = personService.Queryable() .Where(p => p.FirstName == result2.FirstName.Trim() && p.LastName == result2.LastName.Trim()).ToList(); if (matches.Count() > 0 && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { homelocation.Street1 = street1; homelocation.PostalCode = postalCode; locationService.Verify(homelocation, true); } foreach (Person match in matches) { Boolean addressMatches = false; // Check the address if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { if (match.GetHomeLocation(dbContext) != null) { if (match.GetHomeLocation(dbContext).Street1 == street1 && match.GetHomeLocation(dbContext).PostalCode.Split('-')[0] == postalCode) { addressMatches = true; } } } if (!addressMatches) { matches.Remove(person); } } } else { matches = personService.GetByMatch(result2.FirstName.Trim(), result2.LastName.Trim(), null, email, null, street1, postalCode).ToList(); } if (matches.Count > 1) { // Find the oldest member record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { // Find the oldest attendee record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { person = matches.OrderBy(p => p.Id).First(); } } } else if (matches.Count == 1) { person = matches.First(); } else { // Create the person Guid guid3 = Guid.NewGuid(); person = new Person(); person.FirstName = result2.FirstName.Trim(); person.LastName = result2.LastName.Trim(); if (email.IsValidEmail()) { person.Email = email; } person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; person.ConnectionStatusValueId = connectionStatus.Id; person.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; person.IsSystem = false; person.IsDeceased = false; person.IsEmailActive = true; person.Guid = guid3; var masteranswer = result2.MasterApplicationAnswers.Find(a => a.Question == "Gender"); var answer = result2.ApplicationAnswers.Find(a => a.Question == "Gender"); var flag = true; if (masteranswer != null) { var gender = masteranswer.Answer; if (!String.IsNullOrEmpty(gender)) { gender.Trim(); if (gender == "Male" || gender == "male") { person.Gender = Gender.Male; } else { person.Gender = Gender.Female; } flag = false; } } if (answer != null && flag == true) { var gender2 = answer.Answer; if (!String.IsNullOrEmpty(gender2)) { gender2.Trim(); if (gender2 == "Male" || gender2 == "male") { person.Gender = Gender.Male; } else { person.Gender = Gender.Female; } } else { person.Gender = Gender.Unknown; } } else if (flag == true) { person.Gender = Gender.Unknown; } Group family = PersonService.SaveNewPerson(person, dbContext); GroupLocation location = new GroupLocation(); location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id; location.Location = new Location() { Street1 = result2.Address.Address1, Street2 = result2.Address.Address2, City = result2.Address.City, State = result2.Address.State, PostalCode = result2.Address.Zip, Country = result2.Address.Country }; location.IsMappedLocation = true; family.CampusId = CampusCache.All().FirstOrDefault().Id; family.GroupLocations.Add(location); dbContext.SaveChanges(); } } Guid guid4 = Guid.NewGuid(); Guid guid5 = Guid.NewGuid(); var userid = result2.UserId; var profileurl = result2.ProfileUrl; person.LoadAttributes(); if (userid > 0) { person.SetAttributeValue(attribute.Key, result2.UserId.ToString()); } if (!String.IsNullOrEmpty(profileurl)) { person.SetAttributeValue(attribute2.Key, result2.ProfileUrl); } person.SaveAttributeValues(); dbContext.SaveChanges(); var member = groupService.GroupHasMember(trip2.Guid, person.Id); if (member == false) { Guid guid6 = Guid.NewGuid(); GroupMember participant = new GroupMember(); participant.PersonId = person.Id; participant.GroupId = trip2.Id; participant.IsSystem = false; participant.Guid = guid6; var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == trip2.GroupTypeId).FirstOrDefault().Id; participant.GroupRoleId = groupType.DefaultGroupRoleId.GetValueOrDefault(grouprole); if (result2.RegistrationStatus == "Approved") { participant.GroupMemberStatus = GroupMemberStatus.Active; } else if (result2.RegistrationStatus == "Cancelled") { participant.GroupMemberStatus = GroupMemberStatus.Inactive; } else { participant.GroupMemberStatus = GroupMemberStatus.Pending; } groupMemberService.Add(participant); dbContext.SaveChanges(); } } handled++; } } else { amount = 0; } var pageParam2 = request2.Parameters.Where(p => p.Name == "page").FirstOrDefault(); pageParam2.Value = (int)pageParam2.Value + 1; } processed++; } } else { total = 0; } // Update the page number for the next request var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault(); pageParam.Value = (int)pageParam.Value + 1; } } catch (Exception ex) { throw new Exception("ServiceReef Job Failed", ex); } finally { dbContext.SaveChanges(); } if (warnings.Length > 0) { throw new Exception(warnings); } context.Result = "Successfully imported " + processed + " trips."; }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { Rock.Model.Attribute attribute = null; RockTransactionScope.WrapTransaction(() => { var attributeService = new AttributeService(); // remove old qualifier values in case they changed if (edtAttribute.AttributeId.HasValue) { AttributeQualifierService attributeQualifierService = new AttributeQualifierService(); foreach (var oldQualifier in attributeQualifierService.GetByAttributeId(edtAttribute.AttributeId.Value).ToList()) { attributeQualifierService.Delete(oldQualifier, CurrentPersonId); attributeQualifierService.Save(oldQualifier, CurrentPersonId); } attribute = attributeService.Get(edtAttribute.AttributeId.Value); } if (attribute == null) { attribute = new Rock.Model.Attribute(); attributeService.Add(attribute, CurrentPersonId); } if (_configuredType) { attribute.EntityTypeId = _entityTypeId; attribute.EntityTypeQualifierColumn = _entityQualifierColumn; attribute.EntityTypeQualifierValue = _entityQualifierValue; } else { attribute.EntityTypeId = ddlAttrEntityType.SelectedValueAsInt(); attribute.EntityTypeQualifierColumn = tbAttrQualifierField.Text; attribute.EntityTypeQualifierValue = tbAttrQualifierValue.Text; } edtAttribute.GetAttributeProperties(attribute); // Controls will show warnings if (!attribute.IsValid) { return; } attributeService.Save(attribute, CurrentPersonId); }); if (attribute != null) { Rock.Web.Cache.AttributeCache.Flush(attribute.Id); if (!_entityTypeId.HasValue && _entityQualifierColumn == string.Empty && _entityQualifierValue == string.Empty && !_entityId.HasValue) { Rock.Web.Cache.GlobalAttributesCache.Flush(); } } } BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { GroupType groupType; GroupTypeService groupTypeService = new GroupTypeService(); AttributeService attributeService = new AttributeService(); int groupTypeId = int.Parse(hfGroupTypeId.Value); if (groupTypeId == 0) { groupType = new GroupType(); groupTypeService.Add(groupType, CurrentPersonId); } else { groupType = groupTypeService.Get(groupTypeId); } groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.GroupTerm = tbGroupTerm.Text; groupType.GroupMemberTerm = tbGroupMemberTerm.Text; groupType.DefaultGroupRoleId = ddlDefaultGroupRole.SelectedValueAsInt(); groupType.ShowInGroupList = cbShowInGroupList.Checked; groupType.ShowInNavigation = cbShowInNavigation.Checked; groupType.IconCssClass = tbIconCssClass.Text; groupType.IconSmallFileId = imgIconSmall.BinaryFileId; groupType.IconLargeFileId = imgIconLarge.BinaryFileId; groupType.TakesAttendance = cbTakesAttendance.Checked; groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum <AttendanceRule>(); groupType.AttendancePrintTo = ddlAttendancePrintTo.SelectedValueAsEnum <PrintTo>(); groupType.LocationSelectionMode = ddlLocationSelectionMode.SelectedValueAsEnum <LocationPickerMode>(); groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt(); groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked; groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId; groupType.ChildGroupTypes = new List <GroupType>(); groupType.ChildGroupTypes.Clear(); foreach (var item in ChildGroupTypesDictionary) { var childGroupType = groupTypeService.Get(item.Key); if (childGroupType != null) { groupType.ChildGroupTypes.Add(childGroupType); } } DefinedValueService definedValueService = new DefinedValueService(); groupType.LocationTypes = new List <GroupTypeLocationType>(); groupType.LocationTypes.Clear(); foreach (var item in LocationTypesDictionary) { var locationType = definedValueService.Get(item.Key); if (locationType != null) { groupType.LocationTypes.Add(new GroupTypeLocationType { LocationTypeValueId = locationType.Id }); } } if (!groupType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { groupTypeService.Save(groupType, CurrentPersonId); // get it back to make sure we have a good Id for it for the Attributes groupType = groupTypeService.Get(groupType.Guid); /* Take care of Group Type Attributes */ // delete GroupTypeAttributes that are no longer configured in the UI var groupTypeAttributesQry = attributeService.Get(new GroupType().TypeId, "Id", groupType.Id.ToString()); var selectedAttributes = GroupTypeAttributesState.Select(a => a.Guid); foreach (var attr in groupTypeAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); } string qualifierValue = groupType.Id.ToString(); // add/update the GroupTypeAttributes that are assigned in the UI foreach (var attributeState in GroupTypeAttributesState .Where(a => a.EntityTypeQualifierValue == null || a.EntityTypeQualifierValue.Trim() == string.Empty || a.EntityTypeQualifierValue.Equals(qualifierValue))) { // remove old qualifiers in case they changed var qualifierService = new AttributeQualifierService(); foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList()) { qualifierService.Delete(oldQualifier, CurrentPersonId); qualifierService.Save(oldQualifier, CurrentPersonId); } Attribute attribute = groupTypeAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.Clone() as Rock.Model.Attribute; attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attribute.FromDictionary(attributeState.ToDictionary()); foreach (var qualifier in attributeState.AttributeQualifiers) { attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier); } } attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = qualifierValue; attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupType)).Id; Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Save(attribute, CurrentPersonId); } /* Take care of Group Attributes */ // delete GroupAttributes that are no longer configured in the UI var groupAttributesQry = attributeService.Get(new Group().TypeId, "GroupTypeId", groupType.Id.ToString()); selectedAttributes = GroupAttributesState.Select(a => a.Guid); foreach (var attr in groupAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); } // add/update the GroupAttributes that are assigned in the UI foreach (var attributeState in GroupAttributesState .Where(a => a.EntityTypeQualifierValue == null || a.EntityTypeQualifierValue.Trim() == string.Empty || a.EntityTypeQualifierValue.Equals(qualifierValue))) { // remove old qualifiers in case they changed var qualifierService = new AttributeQualifierService(); foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList()) { qualifierService.Delete(oldQualifier, CurrentPersonId); qualifierService.Save(oldQualifier, CurrentPersonId); } Attribute attribute = groupAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.Clone() as Rock.Model.Attribute; attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attribute.FromDictionary(attributeState.ToDictionary()); foreach (var qualifier in attributeState.AttributeQualifiers) { attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier); } } attribute.EntityTypeQualifierColumn = "GroupTypeId"; attribute.EntityTypeQualifierValue = qualifierValue; attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(Group)).Id; Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Save(attribute, CurrentPersonId); } }); } NavigateToParentPage(); }
/// <summary> /// Shows the edit. /// </summary> /// <param name="attributeId">The attribute id.</param> protected void ShowEdit(int attributeId) { var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); var attributeModel = attributeService.Get(attributeId); if (attributeModel == null) { mdAttribute.Title = "Add Attribute".FormatAsHtmlTitle(); attributeModel = new Rock.Model.Attribute(); attributeModel.FieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id; if (!_isEntityTypeConfigured) { int entityTypeId = int.MinValue; if (int.TryParse(rFilter.GetUserPreference("Entity Type"), out entityTypeId) && entityTypeId > 0) { attributeModel.EntityTypeId = entityTypeId; } } else { attributeModel.EntityTypeId = _entityTypeId; attributeModel.EntityTypeQualifierColumn = _entityQualifierColumn; attributeModel.EntityTypeQualifierValue = _entityQualifierValue; } List <int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().ToList(); new CategoryService(rockContext).Queryable().Where(c => selectedCategoryIds.Contains(c.Id)).ToList().ForEach(c => attributeModel.Categories.Add(c)); edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Add(Rock.Model.Attribute.FriendlyTypeName); } else { if (attributeModel.EntityType != null && attributeModel.EntityType.IsIndexingSupported == true && attributeModel.EntityType.IsIndexingEnabled) { edtAttribute.IsIndexingEnabledVisible = true; } edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Edit(Rock.Model.Attribute.FriendlyTypeName); mdAttribute.Title = ("Edit " + attributeModel.Name).FormatAsHtmlTitle(); edtAttribute.IsIndexingEnabled = attributeModel.IsIndexEnabled; } Type type = null; if (attributeModel.EntityTypeId.HasValue && attributeModel.EntityTypeId > 0) { type = EntityTypeCache.Get(attributeModel.EntityTypeId.Value).GetEntityType(); } edtAttribute.ReservedKeyNames = attributeService.GetByEntityTypeQualifier(attributeModel.EntityTypeId, attributeModel.EntityTypeQualifierColumn, attributeModel.EntityTypeQualifierValue, true) .Where(a => a.Id != attributeId) .Select(a => a.Key) .Distinct() .ToList(); edtAttribute.SetAttributeProperties(attributeModel, type); edtAttribute.AttributeEntityTypeId = attributeModel.EntityTypeId; if (_isEntityTypeConfigured) { pnlEntityTypeQualifier.Visible = false; } else { pnlEntityTypeQualifier.Visible = true; ddlAttrEntityType.SetValue(attributeModel.EntityTypeId.HasValue ? attributeModel.EntityTypeId.Value.ToString() : "0"); tbAttrQualifierField.Text = attributeModel.EntityTypeQualifierColumn; tbAttrQualifierValue.Text = attributeModel.EntityTypeQualifierValue; } ShowDialog("Attribute", true); }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { MarketingCampaignAdType marketingCampaignAdType; MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService(); int marketingCampaignAdTypeId = int.Parse(hfMarketingCampaignAdTypeId.Value); if (marketingCampaignAdTypeId == 0) { marketingCampaignAdType = new MarketingCampaignAdType(); marketingCampaignAdTypeService.Add(marketingCampaignAdType, CurrentPersonId); } else { marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdTypeId); } marketingCampaignAdType.Name = tbName.Text; marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse(ddlDateRangeType.SelectedValue); // check for duplicates if (marketingCampaignAdTypeService.Queryable().Count(a => a.Name.Equals(marketingCampaignAdType.Name, StringComparison.OrdinalIgnoreCase) && !a.Id.Equals(marketingCampaignAdType.Id)) > 0) { tbName.ShowErrorMessage(WarningMessage.DuplicateFoundMessage("name", MarketingCampaignAdType.FriendlyTypeName)); return; } if (!marketingCampaignAdType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { marketingCampaignAdTypeService.Save(marketingCampaignAdType, CurrentPersonId); // get it back to make sure we have a good Id for it for the Attributes marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdType.Guid); // delete AdTypeAttributes that are no longer configured in the UI AttributeService attributeService = new AttributeService(); var qry = attributeService.GetByEntityTypeId(new MarketingCampaignAd().TypeId).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(marketingCampaignAdType.Id.ToString())); var deletedAttributes = from attr in qry where !(from d in AttributesState select d.Guid).Contains(attr.Guid) select attr; deletedAttributes.ToList().ForEach(a => { var attr = attributeService.Get(a.Guid); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); }); // add/update the AdTypes that are assigned in the UI foreach (var attributeState in AttributesState) { Attribute attribute = qry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.ToModel(); attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attributeState.CopyToModel(attribute); } attribute.EntityTypeQualifierColumn = "MarketingCampaignAdTypeId"; attribute.EntityTypeQualifierValue = marketingCampaignAdType.Id.ToString(); attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(new MarketingCampaignAd().TypeName).Id; attributeService.Save(attribute, CurrentPersonId); } }); BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { BinaryFileType binaryFileType; BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(); AttributeService attributeService = new AttributeService(); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType, CurrentPersonId); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.IconSmallFileId = imgIconSmall.ImageId; binaryFileType.IconLargeFileId = imgIconLarge.ImageId; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } if (!binaryFileType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { binaryFileTypeService.Save(binaryFileType, CurrentPersonId); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ // delete BinaryFileAttributes that are no longer configured in the UI string qualifierValue = binaryFileType.Id.ToString(); var BinaryFileAttributesQry = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(qualifierValue)); var deletedBinaryFileAttributes = from attr in BinaryFileAttributesQry where !(from d in BinaryFileAttributesState select d.Guid).Contains(attr.Guid) select attr; deletedBinaryFileAttributes.ToList().ForEach(a => { var attr = attributeService.Get(a.Guid); Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr, CurrentPersonId); attributeService.Save(attr, CurrentPersonId); }); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { // remove old qualifiers in case they changed var qualifierService = new AttributeQualifierService(); foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList()) { qualifierService.Delete(oldQualifier, CurrentPersonId); qualifierService.Save(oldQualifier, CurrentPersonId); } Attribute attribute = BinaryFileAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid)); if (attribute == null) { attribute = attributeState.Clone() as Rock.Model.Attribute; attributeService.Add(attribute, CurrentPersonId); } else { attributeState.Id = attribute.Id; attribute.FromDictionary(attributeState.ToDictionary()); foreach (var qualifier in attributeState.AttributeQualifiers) { attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier); } } attribute.EntityTypeQualifierColumn = "BinaryFileTypeId"; attribute.EntityTypeQualifierValue = binaryFileType.Id.ToString(); attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Save(attribute, CurrentPersonId); } }); } NavigateToParentPage(); }
protected override void OnInit(EventArgs e) { base.OnInit(e); string entityQualifierColumn = AttributeValue("EntityQualifierColumn"); if (string.IsNullOrWhiteSpace(entityQualifierColumn)) { entityQualifierColumn = PageParameter("EntityQualifierColumn"); } string entityQualifierValue = AttributeValue("EntityQualifierValue"); if (string.IsNullOrWhiteSpace(entityQualifierValue)) { entityQualifierValue = PageParameter("EntityQualifierValue"); } _category = AttributeValue("AttributeCategory"); if (string.IsNullOrWhiteSpace(_category)) { _category = PageParameter("AttributeCategory"); } // Get the context entity int?contextEntityTypeId = null; Rock.Data.IEntity contextEntity = null; foreach (KeyValuePair <string, Rock.Data.IEntity> entry in ContextEntities) { contextEntityTypeId = entry.Value.TypeId; contextEntity = entry.Value; // Should only be one. break; } if (contextEntityTypeId.HasValue && contextEntity != null) { ObjectCache cache = MemoryCache.Default; string cacheKey = string.Format("Attributes:{0}:{1}:{2}", contextEntityTypeId, entityQualifierColumn, entityQualifierValue); Dictionary <string, List <int> > cachedAttributes = cache[cacheKey] as Dictionary <string, List <int> >; if (cachedAttributes == null) { cachedAttributes = new Dictionary <string, List <int> >(); AttributeService attributeService = new AttributeService(); foreach (var item in attributeService .Get(contextEntityTypeId, entityQualifierColumn, entityQualifierValue) .OrderBy(a => a.Category) .ThenBy(a => a.Order) .Select(a => new { a.Category, a.Id })) { if (!cachedAttributes.ContainsKey(item.Category)) { cachedAttributes.Add(item.Category, new List <int>()); } cachedAttributes[item.Category].Add(item.Id); } CacheItemPolicy cacheItemPolicy = null; cache.Set(cacheKey, cachedAttributes, cacheItemPolicy); } Rock.Attribute.IHasAttributes model = contextEntity as Rock.Attribute.IHasAttributes; if (model != null) { if (cachedAttributes.ContainsKey(_category)) { foreach (var attributeId in cachedAttributes[_category]) { var attribute = Rock.Web.Cache.AttributeCache.Read(attributeId); if (attribute != null) { phAttributes.Controls.Add(/*(AttributeInstanceValues)*/ this.LoadControl("~/Blocks/Core/AttributeInstanceValues.ascx", model, attribute, CurrentPersonId)); } } } } } string script = @" Sys.Application.add_load(function () { $('div.context-attribute-values .delete').click(function(){ return confirm('Are you sure?'); }); }); "; Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmDelete", script, true); }