/// <summary> /// Saves the attributes. /// </summary> /// <param name="channelId">The channel identifier.</param> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="attributes">The attributes.</param> /// <param name="rockContext">The rock context.</param> private void SaveAttributes(int channelId, int entityTypeId, List <Attribute> attributes, RockContext rockContext) { string qualifierColumn = "ContentChannelId"; string qualifierValue = channelId.ToString(); AttributeService attributeService = new AttributeService(rockContext); // Get the existing attributes for this entity type and qualifier value var existingAttributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = attributes.Select(a => a.Guid); foreach (var attr in existingAttributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); int newOrder = 1000; // Update the Attributes that were assigned in the UI foreach (var attr in attributes.OrderBy(a => a.Order)) { // Artificially exaggerate the order so that all channel specific attributes are displayed after the content-type specific attributes (unless categorized) attr.Order = newOrder++; Rock.Attribute.Helper.SaveAttributeEdits(attr, entityTypeId, qualifierColumn, qualifierValue, rockContext); } AttributeCache.FlushEntityAttributes(); }
/// <summary> /// Handles the SaveClick event of the mdAttribute 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 mdAttribute_SaveClick(object sender, EventArgs e) { Rock.Model.Attribute attribute = null; if (_configuredType) { attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute, _entityTypeId, _entityQualifierColumn, _entityQualifierValue); } else { attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute, ddlAttrEntityType.SelectedValueAsInt(), tbAttrQualifierField.Text, tbAttrQualifierValue.Text); } // Attribute will be null if it was not valid if (attribute == null) { return; } AttributeCache.FlushEntityAttributes(); HideDialog(); BindGrid(); }
/// <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; } AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); rockContext.SaveChanges(); } AttributeCache.FlushEntityAttributes(); BindDefinedTypeAttributesGrid(); }
/// <summary> /// Saves the attributes. /// </summary> /// <param name="contentTypeId">The content type identifier.</param> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="attributes">The attributes.</param> /// <param name="rockContext">The rock context.</param> private void SaveAttributes(int contentTypeId, int entityTypeId, List <Attribute> attributes, RockContext rockContext) { string qualifierColumn = "ContentChannelTypeId"; string qualifierValue = contentTypeId.ToString(); AttributeService attributeService = new AttributeService(rockContext); // Get the existing attributes for this entity type and qualifier value var existingAttributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue); // Delete any of those attributes that were removed in the UI var selectedAttributeGuids = attributes.Select(a => a.Guid); foreach (var attr in existingAttributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); // Update the Attributes that were assigned in the UI foreach (var attr in attributes) { Rock.Attribute.Helper.SaveAttributeEdits(attr, entityTypeId, qualifierColumn, qualifierValue, rockContext); } AttributeCache.FlushEntityAttributes(); }
private DateTime GetDateTimeActivated(WorkflowAction action) { var dateActivated = RockDateTime.Now; // Use the current action type' guid as the key for a 'Delay Activated' attribute string AttrKey = action.ActionTypeCache.Guid.ToString(); // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute. // The first time this action runs on any workflow instance using this action instance, the // attribute will not exist and need to be created if (!action.Activity.Attributes.ContainsKey(AttrKey)) { var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = action.Activity.TypeId; attribute.EntityTypeQualifierColumn = "ActivityTypeId"; attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString(); attribute.Name = "Delay Activated"; attribute.Key = AttrKey; attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id; // Need to save the attribute now (using different context) so that an attribute id is returned. using (var newRockContext = new RockContext()) { new AttributeService(newRockContext).Add(attribute); newRockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); WorkflowActivityTypeCache.Flush(action.Activity.ActivityTypeId); } action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute)); var attributeValue = new AttributeValueCache(); attributeValue.AttributeId = attribute.Id; attributeValue.Value = dateActivated.ToString("o"); action.Activity.AttributeValues.Add(AttrKey, attributeValue); action.AddLogEntry(string.Format("Delay Activated at {0}", dateActivated), true); } else { // Check to see if this action instance has a value for the 'Delay Activated' attrbute DateTime?activated = action.Activity.GetAttributeValue(AttrKey).AsDateTime(); if (activated.HasValue) { return(activated.Value); } else { // If no value exists, set the value to the current time action.Activity.SetAttributeValue(AttrKey, dateActivated.ToString("o")); action.AddLogEntry(string.Format("Delay Activated at {0}", dateActivated), true); } } return(dateActivated); }
private double HoursElapsed(WorkflowAction action) { // Use the current action type' guid as the key for a 'DateTime Sent' attribute string AttrKey = action.ActionTypeCache.Guid.ToString() + "_DateTimeSent"; // Check to see if the action's activity does not yet have the the 'DateTime Sent' attribute. // The first time this action runs on any workflow instance using this action instance, the // attribute will not exist and need to be created if (!action.Activity.Attributes.ContainsKey(AttrKey)) { var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = action.Activity.TypeId; attribute.EntityTypeQualifierColumn = "ActivityTypeId"; attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString(); attribute.Name = "DateTime Sent"; attribute.Key = AttrKey; attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id; // Need to save the attribute now (using different context) so that an attribute id is returned. using (var newRockContext = new RockContext()) { new AttributeService(newRockContext).Add(attribute); newRockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); WorkflowActivityTypeCache.Flush(action.Activity.ActivityTypeId); } action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute)); var attributeValue = new AttributeValueCache(); attributeValue.AttributeId = attribute.Id; attributeValue.Value = RockDateTime.Now.ToString("o"); action.Activity.AttributeValues.Add(AttrKey, attributeValue); } else { // Check to see if this action instance has a value for the 'Delay Activated' attrbute DateTime?dateSent = action.Activity.GetAttributeValue(AttrKey).AsDateTime(); if (dateSent.HasValue) { // If a value does exist, check to see if the number of minutes to delay has passed // since the value was saved return(RockDateTime.Now.Subtract(dateSent.Value).TotalHours); } else { // If no value exists, set the value to the current time action.Activity.SetAttributeValue(AttrKey, RockDateTime.Now.ToString("o")); } } return(0.0D); }
/// <summary> /// Flushes the block type attributes. /// </summary> private void FlushBlockTypeAttributes() { // Flush BlockType, Block and Entity Attributes AttributeCache.FlushEntityAttributes(); BlockTypeCache.Flush(hfBlockTypeId.Value.AsInteger()); var blockTypeCache = BlockTypeCache.Read(hfBlockTypeId.Value.AsInteger()); foreach (var blockId in new BlockService(new RockContext()).GetByBlockTypeId(hfBlockTypeId.Value.AsInteger()).Select(a => a.Id).ToList()) { BlockCache.Flush(blockId); } }
private void RGrid_GridReorder(object sender, GridReorderEventArgs e) { var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); var qry = GetData(rockContext); var updatedAttributeIds = attributeService.Reorder(qry.ToList(), e.OldIndex, e.NewIndex); rockContext.SaveChanges(); foreach (int id in updatedAttributeIds) { AttributeCache.Flush(id); } AttributeCache.FlushEntityAttributes(); BindGrid(); }
/// <summary> /// Sets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetValue(string key, string value) { var rockContext = new Rock.Data.RockContext(); var attributeService = new AttributeService(rockContext); var attribute = attributeService.GetSystemSetting(key); bool isNew = false; if (attribute == null) { attribute = new Rock.Model.Attribute(); attribute.FieldTypeId = FieldTypeCache.Read(new Guid(SystemGuid.FieldType.TEXT)).Id; attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER; attribute.EntityTypeQualifierValue = string.Empty; attribute.Key = key; attribute.Name = key.SplitCase(); attribute.DefaultValue = value; attributeService.Add(attribute); isNew = true; } else { attribute.DefaultValue = value; } rockContext.SaveChanges(); AttributeCache.Flush(attribute.Id); if (isNew) { AttributeCache.FlushEntityAttributes(); } var settings = SystemSettings.Read(); var attributeCache = settings.Attributes.FirstOrDefault(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); if (attributeCache != null) { attributeCache.DefaultValue = value; } else { settings.Attributes.Add(AttributeCache.Read(attribute.Id)); } }
public override HttpResponseMessage Post([FromBody] Model.Attribute value) { // if any Categories are included in the Post, we'll need to fetch them from the database so that that EF inserts them into AttributeCategory correct if (value.Categories != null && value.Categories.Any()) { var fetchedCategories = new CategoryService(Service.Context as Rock.Data.RockContext).GetByIds(value.Categories.Select(a => a.Id).ToList()).ToList(); value.Categories.Clear(); foreach (var cat in fetchedCategories) { value.Categories.Add(cat); } } var result = base.Post(value); AttributeCache.FlushEntityAttributes(); return(result); }
/// <summary> /// Handles the Delete event of the rGrid 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 rGrid_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var attributeService = new Rock.Model.AttributeService(rockContext); Rock.Model.Attribute attribute = attributeService.Get(e.RowKeyId); if (attribute != null) { Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); rockContext.SaveChanges(); } AttributeCache.FlushEntityAttributes(); BindGrid(); }
/// <summary> /// Handles the Click event of the btnSaveDefinedTypeAttribute 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 btnSaveDefinedTypeAttribute_Click(object sender, EventArgs e) { var attribute = Rock.Attribute.Helper.SaveAttributeEdits( edtDefinedTypeAttributes, EntityTypeCache.Read(typeof(DefinedValue)).Id, "DefinedTypeId", hfDefinedTypeId.Value); // Attribute will be null if it was not valid if (attribute == null) { return; } pnlDetails.Visible = true; pnlDefinedTypeAttributes.Visible = false; AttributeCache.FlushEntityAttributes(); BindDefinedTypeAttributesGrid(); this.HideSecondaryBlocks(false); }
private string EmailStatus(WorkflowAction action) { // Use the current action type' guid as the key for a 'Email Status' attribute string AttrKey = action.ActionTypeCache.Guid.ToString() + "_EmailStatus"; // Check to see if the action's activity does not yet have the the 'Email Status' attribute. // The first time this action runs on any workflow instance using this action instance, the // attribute will not exist and need to be created if (!action.Activity.Attributes.ContainsKey(AttrKey)) { var attribute = new Rock.Model.Attribute(); attribute.EntityTypeId = action.Activity.TypeId; attribute.EntityTypeQualifierColumn = "ActivityTypeId"; attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString(); attribute.Name = "Email Status"; attribute.Key = AttrKey; attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id; // Need to save the attribute now (using different context) so that an attribute id is returned. using (var newRockContext = new RockContext()) { new AttributeService(newRockContext).Add(attribute); newRockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); WorkflowActivityTypeCache.Flush(action.Activity.ActivityTypeId); } action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute)); var attributeValue = new AttributeValueCache(); attributeValue.AttributeId = attribute.Id; attributeValue.Value = string.Empty; action.Activity.AttributeValues.Add(AttrKey, attributeValue); } else { return(action.Activity.GetAttributeValue(AttrKey)); } return(string.Empty); }
private static void CreateAttribute(string name, WorkflowAction action, RockContext rockContext) { Rock.Model.Attribute newAttribute = new Rock.Model.Attribute(); newAttribute.Key = name; newAttribute.Name = name; newAttribute.FieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id; newAttribute.Order = 0; newAttribute.AttributeQualifiers.Add(new AttributeQualifier() { Key = "ispassword", Value = "False" }); newAttribute.EntityTypeId = EntityTypeCache.Read(action.Activity.Workflow.GetType()).Id; newAttribute.EntityTypeQualifierColumn = "WorkflowTypeId"; newAttribute.EntityTypeQualifierValue = action.Activity.Workflow.WorkflowType.Id.ToString(); AttributeService attributeService = new AttributeService(rockContext); attributeService.Add(newAttribute); rockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); action.Activity.Workflow.LoadAttributes(); }
/// <summary> /// Saves the results. /// </summary> /// <param name="xResult">The x result.</param> /// <param name="workflow">The workflow.</param> /// <param name="rockContext">The rock context.</param> /// <param name="saveResponse">if set to <c>true</c> [save response].</param> public static void SaveResults(XDocument xResult, Rock.Model.Workflow workflow, RockContext rockContext, bool saveResponse = true) { bool createdNewAttribute = false; var newRockContext = new RockContext(); var service = new BackgroundCheckService(newRockContext); var backgroundCheck = service.Queryable() .Where(c => c.WorkflowId.HasValue && c.WorkflowId.Value == workflow.Id) .FirstOrDefault(); if (backgroundCheck != null && saveResponse) { // Clear any SSN nodes before saving XML to record foreach (var xSSNElement in xResult.Descendants("SSN")) { xSSNElement.Value = "XXX-XX-XXXX"; } backgroundCheck.ResponseXml = backgroundCheck.ResponseXml + string.Format(@" Response XML ({0}): ------------------------ {1} ", RockDateTime.Now.ToString(), xResult.ToString()); } var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault(); if (xOrderXML != null) { var xOrder = xOrderXML.Elements("Order").FirstOrDefault(); if (xOrder != null) { bool resultFound = false; // Find any order details with a status element string reportStatus = "Pass"; foreach (var xOrderDetail in xOrder.Elements("OrderDetail")) { var xStatus = xOrderDetail.Elements("Status").FirstOrDefault(); if (xStatus != null) { resultFound = true; if (xStatus.Value != "NO RECORD") { reportStatus = "Review"; break; } } } if (resultFound) { // If no records found, still double-check for any alerts if (reportStatus != "Review") { var xAlerts = xOrder.Elements("Alerts").FirstOrDefault(); if (xAlerts != null) { if (xAlerts.Elements("OrderId").Any()) { reportStatus = "Review"; } } } // Save the recommendation string recommendation = (from o in xOrder.Elements("Recommendation") select o.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(recommendation)) { if (SaveAttributeValue(workflow, "ReportRecommendation", recommendation, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { createdNewAttribute = true; } } // Save the report link Guid? binaryFileGuid = null; string reportLink = (from o in xOrder.Elements("ReportLink") select o.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(reportLink)) { if (SaveAttributeValue(workflow, "ReportLink", reportLink, FieldTypeCache.Read(Rock.SystemGuid.FieldType.URL_LINK.AsGuid()), rockContext)) { createdNewAttribute = true; } // Save the report binaryFileGuid = SaveFile(workflow.Attributes["Report"], reportLink, workflow.Id.ToString() + ".pdf"); if (binaryFileGuid.HasValue) { if (SaveAttributeValue(workflow, "Report", binaryFileGuid.Value.ToString(), FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()), rockContext, new Dictionary <string, string> { { "binaryFileType", "" } })) { createdNewAttribute = true; } } } // Save the status if (SaveAttributeValue(workflow, "ReportStatus", reportStatus, FieldTypeCache.Read(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext, new Dictionary <string, string> { { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" } })) { createdNewAttribute = true; } // Update the background check file if (backgroundCheck != null) { backgroundCheck.ResponseDate = RockDateTime.Now; backgroundCheck.RecordFound = reportStatus == "Review"; if (binaryFileGuid.HasValue) { var binaryFile = new BinaryFileService(newRockContext).Get(binaryFileGuid.Value); if (binaryFile != null) { backgroundCheck.ResponseDocumentId = binaryFile.Id; } } } } } } newRockContext.SaveChanges(); if (createdNewAttribute) { AttributeCache.FlushEntityAttributes(); } }
public static void SaveResults(RockContext rockContext, BackgroundCheck bgCheck, XElement xResult) { bool createdNewAttribute = false; if (xResult != null) { var xOrder = xResult.Elements("Order").FirstOrDefault(); if (xOrder != null) { bool resultFound = false; // Find any order details with a status element string reportStatus = "Pass"; foreach (var xOrderDetail in xOrder.Elements("OrderDetail")) { var goodStatus = (xOrderDetail.Attribute("ServiceCode")?.Value == "SSNTrace") ? "COMPLETE" : "NO RECORD"; var xStatus = xOrderDetail.Elements("Status").FirstOrDefault(); if (xStatus != null) { resultFound = true; if (xStatus.Value != goodStatus) { reportStatus = "Review"; break; } } } if (resultFound) { // If no records found, still double-check for any alerts if (reportStatus != "Review") { var xAlerts = xOrder.Elements("Alerts").FirstOrDefault(); if (xAlerts != null) { if (xAlerts.Elements("OrderId").Any()) { reportStatus = "Review"; } } } // Save the recommendation string recommendation = (from o in xOrder.Elements("Recommendation") select o.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(recommendation)) { if (SaveAttributeValue(bgCheck.Workflow, "ReportRecommendation", recommendation, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { createdNewAttribute = true; } } // Save the report link Guid? binaryFileGuid = null; string reportLink = (from o in xOrder.Elements("ReportLink") select o.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(reportLink)) { if (SaveAttributeValue(bgCheck.Workflow, "ReportLink", reportLink, FieldTypeCache.Read(Rock.SystemGuid.FieldType.URL_LINK.AsGuid()), rockContext)) { createdNewAttribute = true; } // Save the report binaryFileGuid = SaveFile(bgCheck.Workflow.Attributes["Report"], reportLink, bgCheck.Workflow.Id.ToString() + ".pdf"); if (binaryFileGuid.HasValue) { if (SaveAttributeValue(bgCheck.Workflow, "Report", binaryFileGuid.Value.ToString(), FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()), rockContext, new Dictionary <string, string> { { "binaryFileType", "" } })) { createdNewAttribute = true; } } } // Save the status if (SaveAttributeValue(bgCheck.Workflow, "ReportStatus", reportStatus, FieldTypeCache.Read(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext, new Dictionary <string, string> { { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" } })) { createdNewAttribute = true; } // Update the background check file if (bgCheck != null) { bgCheck.ResponseDate = RockDateTime.Now; bgCheck.RecordFound = reportStatus == "Review"; if (binaryFileGuid.HasValue) { var binaryFile = new BinaryFileService(rockContext).Get(binaryFileGuid.Value); if (binaryFile != null) { bgCheck.ResponseDocumentId = binaryFile.Id; } } } } } } rockContext.SaveChanges(); if (createdNewAttribute) { AttributeCache.FlushEntityAttributes(); } }
/// <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) { Site site; if (Page.IsValid) { var rockContext = new RockContext(); PageService pageService = new PageService(rockContext); SiteService siteService = new SiteService(rockContext); SiteDomainService siteDomainService = new SiteDomainService(rockContext); bool newSite = false; int siteId = hfSiteId.Value.AsInteger(); if (siteId == 0) { newSite = true; site = new Rock.Model.Site(); siteService.Add(site); } else { site = siteService.Get(siteId); } site.Name = tbSiteName.Text; site.Description = tbDescription.Text; site.Theme = ddlTheme.Text; site.DefaultPageId = ppDefaultPage.PageId; site.DefaultPageRouteId = ppDefaultPage.PageRouteId; site.LoginPageId = ppLoginPage.PageId; site.LoginPageRouteId = ppLoginPage.PageRouteId; site.ChangePasswordPageId = ppChangePasswordPage.PageId; site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId; site.CommunicationPageId = ppCommunicationPage.PageId; site.CommunicationPageRouteId = ppCommunicationPage.PageRouteId; site.RegistrationPageId = ppRegistrationPage.PageId; site.RegistrationPageRouteId = ppRegistrationPage.PageRouteId; site.PageNotFoundPageId = ppPageNotFoundPage.PageId; site.PageNotFoundPageRouteId = ppPageNotFoundPage.PageRouteId; site.ErrorPage = tbErrorPage.Text; site.GoogleAnalyticsCode = tbGoogleAnalytics.Text; site.RequiresEncryption = cbRequireEncryption.Checked; site.EnabledForShortening = cbEnableForShortening.Checked; site.EnableMobileRedirect = cbEnableMobileRedirect.Checked; site.MobilePageId = ppMobilePage.PageId; site.ExternalUrl = tbExternalURL.Text; site.AllowedFrameDomains = tbAllowedFrameDomains.Text; site.RedirectTablets = cbRedirectTablets.Checked; site.EnablePageViews = cbEnablePageViews.Checked; site.AllowIndexing = cbAllowIndexing.Checked; site.IsIndexEnabled = cbEnableIndexing.Checked; site.IndexStartingLocation = tbIndexStartingLocation.Text; site.PageHeaderContent = cePageHeaderContent.Text; int?existingIconId = null; if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId) { existingIconId = site.FavIconBinaryFileId; site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId; } var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>(); site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>(); // Remove any deleted domains foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList()) { site.SiteDomains.Remove(domain); siteDomainService.Delete(domain); } int order = 0; foreach (string domain in currentDomains) { SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault(); if (sd == null) { sd = new SiteDomain(); sd.Domain = domain; sd.Guid = Guid.NewGuid(); site.SiteDomains.Add(sd); } sd.Order = order++; } if (!site.DefaultPageId.HasValue && !newSite) { ppDefaultPage.ShowErrorMessage("Default Page is required."); return; } if (!site.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext); if (existingIconId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(existingIconId.Value); if (binaryFile != null) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } if (newSite) { Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE); } }); // add/update for the InteractionChannel for this site and set the RetentionPeriod var interactionChannelService = new InteractionChannelService(rockContext); int channelMediumWebsiteValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id; var interactionChannelForSite = interactionChannelService.Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault(); if (interactionChannelForSite == null) { interactionChannelForSite = new InteractionChannel(); interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId; interactionChannelForSite.ChannelEntityId = site.Id; interactionChannelService.Add(interactionChannelForSite); } interactionChannelForSite.Name = site.Name; interactionChannelForSite.RetentionDuration = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull(); interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Read <Rock.Model.Page>().Id; rockContext.SaveChanges(); foreach (int pageId in pageService.GetBySiteId(site.Id) .Select(p => p.Id) .ToList()) { PageCache.Flush(pageId); } SiteCache.Flush(site.Id); AttributeCache.FlushEntityAttributes(); // Create the default page is this is a new site if (!site.DefaultPageId.HasValue && newSite) { var siteCache = SiteCache.Read(site.Id); // Create the layouts for the site, and find the first one LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache); var layoutService = new LayoutService(rockContext); var layouts = layoutService.GetBySiteId(siteCache.Id); Layout layout = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase)); if (layout == null) { layout = layouts.FirstOrDefault(); } if (layout != null) { var page = new Page(); page.LayoutId = layout.Id; page.PageTitle = siteCache.Name + " Home Page"; page.InternalName = page.PageTitle; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault(); page.Order = lastPage != null ? lastPage.Order + 1 : 0; pageService.Add(page); rockContext.SaveChanges(); site = siteService.Get(siteCache.Id); site.DefaultPageId = page.Id; rockContext.SaveChanges(); SiteCache.Flush(site.Id); } } var qryParams = new Dictionary <string, string>(); qryParams["siteId"] = site.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
/// <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.RequiresViewSecurity = cbRequiresViewSecurity.Checked; binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger(); binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger(); binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum <Format>(); binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum <Resolution>(); binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>(); binaryFileType.PreferredRequired = cbPreferredRequired.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; } rockContext.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); }); AttributeCache.FlushEntityAttributes(); NavigateToParentPage(); }
protected void btnSave_Click(object sender, EventArgs e) { 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); bool AttributesUpdated = false; // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes)) { var attribute = attributeService.Get(labelAttribute.Value.Guid); Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); AttributesUpdated = true; } // 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.Read(Rock.SystemGuid.FieldType.BINARY_FILE.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); AttributesUpdated = true; } rockContext.SaveChanges(); GroupTypeCache.Flush(groupType.Id); Rock.CheckIn.KioskDevice.FlushAll(); if (AttributesUpdated) { AttributeCache.FlushEntityAttributes(); } nbSaveSuccess.Visible = true; BuildRows(); } } } 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()) { 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); } if (group.IsValid) { rockContext.SaveChanges(); group.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.FlushAll(); nbSaveSuccess.Visible = true; BuildRows(); } } } } hfIsDirty.Value = "false"; }
public override void Put(int id, [FromBody] Model.Attribute value) { base.Put(id, value); AttributeCache.Flush(id); AttributeCache.FlushEntityAttributes(); }
/// <summary> /// Sends a background request to Protect My Ministry /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="workflow">The Workflow initiating the request.</param> /// <param name="personAttribute">The person attribute.</param> /// <param name="ssnAttribute">The SSN attribute.</param> /// <param name="requestTypeAttribute">The request type attribute.</param> /// <param name="billingCodeAttribute">The billing code attribute.</param> /// <param name="errorMessages">The error messages.</param> /// <returns> /// True/False value of whether the request was successfully sent or not /// </returns> /// <exception cref="System.NotImplementedException"></exception> /// <remarks> /// Note: If the associated workflow type does not have attributes with the following keys, they /// will automatically be added to the workflow type configuration in order to store the results /// of the PMM background check request /// RequestStatus: The request status returned by PMM request /// RequestMessage: Any error messages returned by PMM request /// ReportStatus: The report status returned by PMM /// ReportLink: The location of the background report on PMM server /// ReportRecommendation: PMM's recomendataion /// Report (BinaryFile): The downloaded background report /// </remarks> public override bool SendRequest(RockContext rockContext, Model.Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List <string> errorMessages) { errorMessages = new List <string>(); try { // Check to make sure workflow is not null if (workflow == null) { errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid workflow."); return(false); } // Get the person that the request is for Person person = null; if (personAttribute != null) { Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull(); if (personAliasGuid.HasValue) { person = new PersonAliasService(rockContext).Queryable() .Where(p => p.Guid.Equals(personAliasGuid.Value)) .Select(p => p.Person) .FirstOrDefault(); person.LoadAttributes(rockContext); } } if (person == null) { errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for."); return(false); } string password = Encryption.DecryptString(GetAttributeValue("Password")); XElement rootElement = new XElement("OrderXML", new XElement("Method", "SEND ORDER"), new XElement("Authentication", new XElement("Username", GetAttributeValue("UserName")), new XElement("Password", password) ) ); if (GetAttributeValue("TestMode").AsBoolean()) { rootElement.Add(new XElement("TestMode", "YES")); } rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL"))); XElement orderElement = new XElement("Order"); rootElement.Add(orderElement); if (billingCodeAttribute != null) { string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key); Guid? campusGuid = billingCode.AsGuidOrNull(); if (campusGuid.HasValue) { var campus = CampusCache.Read(campusGuid.Value); if (campus != null) { billingCode = campus.Name; } } orderElement.Add(new XElement("BillingReferenceCode", billingCode)); } XElement subjectElement = new XElement("Subject", new XElement("FirstName", person.FirstName), new XElement("MiddleName", person.MiddleName), new XElement("LastName", person.LastName) ); orderElement.Add(subjectElement); if (person.SuffixValue != null) { subjectElement.Add(new XElement("Generation", person.SuffixValue.Value)); } if (person.BirthDate.HasValue) { subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy"))); } if (ssnAttribute != null) { string ssn = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key)).AsNumeric(); if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9) { subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-"))); } } if (person.Gender == Gender.Male) { subjectElement.Add(new XElement("Gender", "Male")); } if (person.Gender == Gender.Female) { subjectElement.Add(new XElement("Gender", "Female")); } string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber"); if (!string.IsNullOrWhiteSpace(dlNumber)) { subjectElement.Add(new XElement("DLNumber", dlNumber)); } if (!string.IsNullOrWhiteSpace(person.Email)) { subjectElement.Add(new XElement("EmailAddress", person.Email)); } var homelocation = person.GetHomeLocation(); if (homelocation != null) { subjectElement.Add(new XElement("CurrentAddress", new XElement("StreetAddress", homelocation.Street1), new XElement("City", homelocation.City), new XElement("State", homelocation.State), new XElement("Zipcode", homelocation.PostalCode) )); } XElement aliasesElement = new XElement("Aliases"); if (person.NickName != person.FirstName) { aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName))); } foreach (var previousName in person.GetPreviousNames()) { aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName))); } if (aliasesElement.HasElements) { subjectElement.Add(aliasesElement); } DefinedValueCache pkgTypeDefinedValue = null; string packageName = "BASIC"; string county = string.Empty; string state = string.Empty; string mvrJurisdiction = string.Empty; string mvrState = string.Empty; if (requestTypeAttribute != null) { pkgTypeDefinedValue = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid()); if (pkgTypeDefinedValue != null) { if (pkgTypeDefinedValue.Attributes == null) { pkgTypeDefinedValue.LoadAttributes(rockContext); } packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName"); county = pkgTypeDefinedValue.GetAttributeValue("DefaultCounty"); state = pkgTypeDefinedValue.GetAttributeValue("DefaultState"); Guid?mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue("MVRJurisdiction").AsGuidOrNull(); if (mvrJurisdictionGuid.HasValue) { var mvrJurisdictionDv = DefinedValueCache.Read(mvrJurisdictionGuid.Value); if (mvrJurisdictionDv != null) { mvrJurisdiction = mvrJurisdictionDv.Value; if (mvrJurisdiction.Length >= 2) { mvrState = mvrJurisdiction.Left(2); } } } if (homelocation != null) { if (!string.IsNullOrWhiteSpace(homelocation.County) && pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean()) { county = homelocation.County; } if (!string.IsNullOrWhiteSpace(homelocation.State)) { if (pkgTypeDefinedValue.GetAttributeValue("SendHomeState").AsBoolean()) { state = homelocation.State; } if (pkgTypeDefinedValue.GetAttributeValue("SendHomeStateMVR").AsBoolean()) { mvrState = homelocation.State; } } } } } if (!string.IsNullOrWhiteSpace(packageName)) { orderElement.Add(new XElement("PackageServiceCode", packageName, new XAttribute("OrderId", workflow.Id.ToString()))); if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) || packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", "combo"))); } } if (!string.IsNullOrWhiteSpace(county) || !string.IsNullOrWhiteSpace(state)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim"), new XElement("County", county), new XElement("State", state), new XElement("YearsToSearch", 7), new XElement("CourtDocsRequested", "NO"), new XElement("RushRequested", "NO"), new XElement("SpecialInstructions", "")) ); } if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", "MVR"), new XElement("JurisdictionCode", mvrJurisdiction), new XElement("State", mvrState)) ); } XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement); var requestDateTime = RockDateTime.Now; XDocument xResult = PostToWebService(xdoc, GetAttributeValue("RequestURL")); var responseDateTime = RockDateTime.Now; int?personAliasId = person.PrimaryAliasId; if (personAliasId.HasValue) { // Create a background check file using (var newRockContext = new RockContext()) { var backgroundCheckService = new BackgroundCheckService(newRockContext); var backgroundCheck = backgroundCheckService.Queryable() .Where(c => c.WorkflowId.HasValue && c.WorkflowId.Value == workflow.Id) .FirstOrDefault(); if (backgroundCheck == null) { backgroundCheck = new Rock.Model.BackgroundCheck(); backgroundCheck.PersonAliasId = personAliasId.Value; backgroundCheck.WorkflowId = workflow.Id; backgroundCheckService.Add(backgroundCheck); } backgroundCheck.RequestDate = RockDateTime.Now; // Clear any SSN nodes before saving XML to record foreach (var xSSNElement in xdoc.Descendants("SSN")) { xSSNElement.Value = "XXX-XX-XXXX"; } foreach (var xSSNElement in xResult.Descendants("SSN")) { xSSNElement.Value = "XXX-XX-XXXX"; } backgroundCheck.ResponseXml = string.Format(@" Request XML ({0}): ------------------------ {1} Response XML ({2}): ------------------------ {3} ", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString()); newRockContext.SaveChanges(); } } using (var newRockContext = new RockContext()) { var handledErrorMessages = new List <string>(); bool createdNewAttribute = false; if (_HTTPStatusCode == HttpStatusCode.OK) { var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault(); if (xOrderXML != null) { var xStatus = xOrderXML.Elements("Status").FirstOrDefault(); if (xStatus != null) { if (SaveAttributeValue(workflow, "RequestStatus", xStatus.Value, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null)) { createdNewAttribute = true; } } handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList()); var xErrors = xOrderXML.Elements("Errors").FirstOrDefault(); if (xErrors != null) { handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList()); } if (xResult.Root.Descendants().Count() > 0) { SaveResults(xResult, workflow, rockContext, false); } } } else { handledErrorMessages.Add("Invalid HttpStatusCode: " + _HTTPStatusCode.ToString()); } if (handledErrorMessages.Any()) { if (SaveAttributeValue(workflow, "RequestMessage", handledErrorMessages.AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null)) { createdNewAttribute = true; } } newRockContext.SaveChanges(); if (createdNewAttribute) { AttributeCache.FlushEntityAttributes(); } return(true); } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); errorMessages.Add(ex.Message); return(false); } }
public override void Delete(int id) { base.Delete(id); AttributeCache.Flush(id); AttributeCache.FlushEntityAttributes(); }
/// <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 wasSecurityRole = false; bool triggersUpdated = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); var roleGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()); int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue; int?parentGroupId = hfParentGroupId.Value.AsIntegerOrNull(); if (parentGroupId != null) { var allowedGroupIds = LineQuery.GetCellGroupIdsInLine(CurrentPerson, rockContext); if (!allowedGroupIds.Contains(parentGroupId.Value)) { nbMessage.Text = "You are not allowed to add a group to this parent group."; nbMessage.Visible = true; pnlEditDetails.Visible = false; btnSave.Enabled = false; return; } var parentGroup = groupService.Get(parentGroupId.Value); if (parentGroup != null) { CurrentGroupTypeId = parentGroup.GroupTypeId; if (!lppLeader.PersonId.HasValue) { nbMessage.Text = "A Leader is required."; nbMessage.Visible = true; return; } if (!GroupLocationsState.Any()) { nbMessage.Text = "A location is required."; nbMessage.Visible = true; return; } if (CurrentGroupTypeId == 0) { return; } Group group = new Group(); group.IsSystem = false; group.Name = string.Empty; // add/update any group locations that were added or changed in the UI (we already removed the ones that were removed above) foreach (var groupLocationState in GroupLocationsState) { GroupLocation groupLocation = group.GroupLocations.Where(l => l.Guid == groupLocationState.Guid).FirstOrDefault(); if (groupLocation == null) { groupLocation = new GroupLocation(); group.GroupLocations.Add(groupLocation); } else { groupLocationState.Id = groupLocation.Id; groupLocationState.Guid = groupLocation.Guid; var selectedSchedules = groupLocationState.Schedules.Select(s => s.Guid).ToList(); foreach (var schedule in groupLocation.Schedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList()) { groupLocation.Schedules.Remove(schedule); } } groupLocation.CopyPropertiesFrom(groupLocationState); var existingSchedules = groupLocation.Schedules.Select(s => s.Guid).ToList(); foreach (var scheduleState in groupLocationState.Schedules.Where(s => !existingSchedules.Contains(s.Guid)).ToList()) { var schedule = scheduleService.Get(scheduleState.Guid); if (schedule != null) { groupLocation.Schedules.Add(schedule); } } } GroupMember leader = new GroupMember(); leader.GroupMemberStatus = GroupMemberStatus.Active; leader.PersonId = lppLeader.PersonId.Value; leader.Person = new PersonService(rockContext).Get(lppLeader.PersonId.Value); leader.GroupRole = parentGroup.GroupType.Roles.Where(r => r.IsLeader).FirstOrDefault() ?? parentGroup.GroupType.DefaultGroupRole; group.Name = String.Format("{0}, {1}", leader.Person.NickName, leader.Person.LastName); group.Description = tbDescription.Text; group.CampusId = parentGroup.CampusId; group.GroupTypeId = CurrentGroupTypeId; group.ParentGroupId = parentGroupId; group.IsSecurityRole = false; group.IsActive = true; group.IsPublic = true; if (dpStartDate.SelectedDate.HasValue) { group.CreatedDateTime = dpStartDate.SelectedDate.Value; } group.Members.Add(leader); string iCalendarContent = string.Empty; // If unique schedule option was selected, but a schedule was not defined, set option to 'None' var scheduleType = rblScheduleSelect.SelectedValueAsEnum <ScheduleType>(ScheduleType.None); if (scheduleType == ScheduleType.Custom) { iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent); if (calEvent == null || calEvent.DTStart == null) { scheduleType = ScheduleType.None; } } if (scheduleType == ScheduleType.Weekly) { if (!dowWeekly.SelectedDayOfWeek.HasValue) { scheduleType = ScheduleType.None; } } int?oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull(); if (scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly) { if (!oldScheduleId.HasValue || group.Schedule == null) { group.Schedule = new Schedule(); } if (scheduleType == ScheduleType.Custom) { group.Schedule.iCalendarContent = iCalendarContent; group.Schedule.WeeklyDayOfWeek = null; group.Schedule.WeeklyTimeOfDay = null; } else { group.Schedule.iCalendarContent = null; group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek; group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime; } } else { // If group did have a unique schedule, delete that schedule if (oldScheduleId.HasValue) { var schedule = scheduleService.Get(oldScheduleId.Value); if (schedule != null && string.IsNullOrEmpty(schedule.Name)) { scheduleService.Delete(schedule); } } if (scheduleType == ScheduleType.Named) { group.ScheduleId = spSchedule.SelectedValueAsId(); } else { group.ScheduleId = null; } } group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group); group.GroupType = new GroupTypeService(rockContext).Get(group.GroupTypeId); if (group.ParentGroupId.HasValue) { group.ParentGroup = groupService.Get(group.ParentGroupId.Value); } if (!Page.IsValid) { return; } // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvGroup.IsValid = group.IsValid; if (!cvGroup.IsValid) { cvGroup.ErrorMessage = group.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />"); return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction(() => { var adding = group.Id.Equals(0); if (adding) { groupService.Add(group); } rockContext.SaveChanges(); if (adding) { // add ADMINISTRATE to the person who added the group Rock.Security.Authorization.AllowPerson(group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext); } group.SaveAttributeValues(rockContext); }); bool isNowSecurityRole = group.IsActive && (group.GroupTypeId == roleGroupTypeId); if (isNowSecurityRole) { // new security role, flush Rock.Security.Authorization.Flush(); } AttributeCache.FlushEntityAttributes(); pnlDetails.Visible = false; pnlSuccess.Visible = true; nbSuccess.Text = string.Format("Your group ({0}) has been created", group.Name); string linkedPage = LinkedPageRoute("RedirectPage"); int secondsBeforeRedirect = GetAttributeValue("SecondsBeforeRedirect").AsInteger() * 1000; ScriptManager.RegisterClientScriptBlock(upnlGroupDetail, typeof(UpdatePanel), "Redirect", string.Format("console.log('{0}'); setTimeout(function() {{ window.location.replace('{0}?GroupId={2}') }}, {1});", linkedPage, secondsBeforeRedirect, group.Id), true); } } }