/// <summary> /// Reads the specified GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public static BlockTypeCache Read(Guid guid) { ObjectCache cache = MemoryCache.Default; object cacheObj = cache[guid.ToString()]; if (cacheObj != null) { return(Read((int)cacheObj)); } else { var blockTypeService = new BlockTypeService(); var blockTypeModel = blockTypeService.Get(guid); if (blockTypeModel != null) { blockTypeModel.LoadAttributes(); var blockType = new BlockTypeCache(blockTypeModel); var cachePolicy = new CacheItemPolicy(); AddChangeMonitor(cachePolicy, blockType.Path); cache.Set(BlockTypeCache.CacheKey(blockType.Id), blockType, cachePolicy); var guidCachePolicy = new CacheItemPolicy(); AddChangeMonitor(guidCachePolicy, blockType.Path); cache.Set(blockType.Guid.ToString(), blockType.Id, guidCachePolicy); return(blockType); } else { return(null); } } }
/// <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) { BlockType blockType; BlockTypeService blockTypeService = new BlockTypeService(); int blockTypeId = int.Parse(hfBlockTypeId.Value); if (blockTypeId == 0) { blockType = new BlockType(); blockTypeService.Add(blockType, CurrentPersonId); } else { BlockTypeCache.Flush(blockTypeId); blockType = blockTypeService.Get(blockTypeId); } blockType.Name = tbName.Text; blockType.Path = tbPath.Text; blockType.Description = tbDescription.Text; if (!blockType.IsValid) { // Controls will render the error messages return; } blockTypeService.Save(blockType, CurrentPersonId); BindGrid(); pnlDetails.Visible = false; pnlList.Visible = true; }
/// <summary> /// Shows the edit. /// </summary> /// <param name="blockTypeId">The block type id.</param> protected void ShowEdit(int blockTypeId) { pnlDetails.Visible = true; pnlList.Visible = false; BlockTypeService blockTypeService = new BlockTypeService(); BlockType blockType = blockTypeService.Get(blockTypeId); if (blockType != null) { lActionTitle.Text = ActionTitle.Edit(BlockType.FriendlyTypeName); hfBlockTypeId.Value = blockType.Id.ToString(); tbName.Text = blockType.Name; tbPath.Text = blockType.Path; tbDescription.Text = blockType.Description; } else { lActionTitle.Text = ActionTitle.Add(BlockType.FriendlyTypeName); hfBlockTypeId.Value = 0.ToString(); tbName.Text = string.Empty; tbPath.Text = string.Empty; tbDescription.Text = string.Empty; } }
/// <summary> /// Used to manually flush the attribute cache. /// </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 btnClearCache_Click(object sender, EventArgs e) { var msgs = new List <string>(); // Clear the static object that contains all auth rules (so that it will be refreshed) Rock.Security.Authorization.Flush(); msgs.Add("Authorizations have been cleared"); // Flush the static entity attributes cache Rock.Web.Cache.AttributeCache.FlushEntityAttributes(); msgs.Add("EntityAttributes have been cleared"); // Clear all cached items Rock.Web.Cache.RockMemoryCache.Clear(); msgs.Add("RockMemoryCache has been cleared"); // Flush Site Domains Rock.Web.Cache.SiteCache.Flush(); // Flush today's Check-in Codes Rock.Model.AttendanceCodeService.FlushTodaysCodes(); string webAppPath = Server.MapPath("~"); // Check for any unregistered entity types, field types, and block types EntityTypeService.RegisterEntityTypes(webAppPath); FieldTypeService.RegisterFieldTypes(webAppPath); BlockTypeService.RegisterBlockTypes(webAppPath, Page, false); msgs.Add("EntityTypes, FieldTypes, BlockTypes have been re-registered"); // Clear workflow trigger cache Rock.Workflow.TriggerCache.Refresh(); // Delete all cached files try { var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache")); foreach (var childDir in dirInfo.GetDirectories()) { childDir.Delete(true); } foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore")) { file.Delete(); } msgs.Add("Cached files have been deleted"); } catch (Exception ex) { nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning; nbMessage.Visible = true; nbMessage.Text = "The following error occurred when attempting to delete cached files: " + ex.Message; return; } nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success; nbMessage.Visible = true; nbMessage.Title = "Clear Cache"; nbMessage.Text = string.Format("<p>{0}</p>", msgs.AsDelimited("<br />")); }
/// <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) { BlockType blockType; var rockContext = new RockContext(); BlockTypeService blockTypeService = new BlockTypeService(rockContext); int blockTypeId = int.Parse(hfBlockTypeId.Value); if (blockTypeId == 0) { blockType = new BlockType(); blockTypeService.Add(blockType); } else { BlockTypeCache.Flush(blockTypeId); blockType = blockTypeService.Get(blockTypeId); } blockType.Name = tbName.Text; blockType.Path = tbPath.Text; blockType.Description = tbDescription.Text; if (!blockType.IsValid) { // Controls will render the error messages return; } rockContext.SaveChanges(); NavigateToParentPage(); }
/// <summary> /// Starts the block type compilation thread. /// </summary> private static void StartBlockTypeCompilationThread() { BlockTypeCompilationThread = new Thread(() => { // Set to background thread so that this thread doesn't prevent Rock from shutting down. Thread.CurrentThread.IsBackground = true; // Set priority to lowest so that RockPage.VerifyBlockTypeInstanceProperties() gets priority Thread.CurrentThread.Priority = ThreadPriority.Lowest; Stopwatch stopwatchCompileBlockTypes = Stopwatch.StartNew(); // get a list of all block types that are used by blocks var allUsedBlockTypeIds = new BlockTypeService(new RockContext()).Queryable() .Where(a => a.Blocks.Any()) .OrderBy(a => a.Category) .Select(a => a.Id).ToArray(); // Pass in a CancellationToken so we can stop compiling if Rock shuts down before it is done BlockTypeService.VerifyBlockTypeInstanceProperties(allUsedBlockTypeIds, _threadCancellationTokenSource.Token); Debug.WriteLine(string.Format("[{0,5:#} seconds] All block types Compiled", stopwatchCompileBlockTypes.Elapsed.TotalSeconds)); }); BlockTypeCompilationThread.Start(); }
/// <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) { BlockType blockType; BlockTypeService blockTypeService = new BlockTypeService(); int blockTypeId = int.Parse(hfBlockTypeId.Value); if (blockTypeId == 0) { blockType = new BlockType(); blockTypeService.Add(blockType, CurrentPersonId); } else { BlockTypeCache.Flush(blockTypeId); blockType = blockTypeService.Get(blockTypeId); } blockType.Name = tbName.Text; blockType.Path = tbPath.Text; blockType.Description = tbDescription.Text; if (!blockType.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { blockTypeService.Save(blockType, CurrentPersonId); }); NavigateToParentPage(); }
/// <summary> /// Loads the drop downs. /// </summary> public void LoadDropDowns() { int pageId = hfPageId.Value.AsInteger(); ddlZones.Items.Clear(); ddlMoveToZoneList.Items.Clear(); var page = Rock.Web.Cache.PageCache.Read(pageId); if (page != null) { var zoneNames = FindZoneNames(page); foreach (var zoneName in zoneNames) { var zoneBlockCount = page.Blocks.Where(a => a.Zone.Equals(zoneName, StringComparison.OrdinalIgnoreCase)).Count(); ddlZones.Items.Add(new ListItem(string.Format("{0} ({1})", zoneName, zoneBlockCount), zoneName)); ddlMoveToZoneList.Items.Add(new ListItem(zoneName, zoneName)); } // default to Main Zone (if there is one) ddlZones.SetValue("Main"); } var rockContext = new RockContext(); var commonBlockTypes = new BlockTypeService(rockContext).Queryable().Where(a => a.IsCommon).OrderBy(a => a.Name).AsNoTracking().ToList(); rptCommonBlockTypes.DataSource = commonBlockTypes; rptCommonBlockTypes.DataBind(); }
/// <summary> /// Loads the block types. /// </summary> private void LoadBlockTypes(bool registerBlockTypes) { if (registerBlockTypes) { // Add any unregistered blocks try { BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); } catch (Exception ex) { nbMessage.Text = "Error registering one or more block types"; nbMessage.Details = ex.Message + "<code>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</code>"; nbMessage.Visible = true; } } // Get a list of BlockTypes that does not include Mobile block types. var allExceptMobileBlockTypes = BlockTypeCache.All(); foreach (var cachedBlockType in BlockTypeCache.All().Where(b => string.IsNullOrEmpty(b.Path))) { try { var blockCompiledType = cachedBlockType.GetCompiledType(); if (typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockCompiledType)) { allExceptMobileBlockTypes.Remove(cachedBlockType); } } catch (Exception) { // Intentionally ignored } } var blockTypes = allExceptMobileBlockTypes.Select(b => new { b.Id, b.Name, b.Category, b.Description }).ToList(); ddlBlockType.Items.Clear(); // Add the categorized block types foreach (var blockType in blockTypes.Where(b => b.Category != "").OrderBy(b => b.Category).ThenBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", blockType.Category); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } // Add the uncategorized block types foreach (var blockType in blockTypes.Where(b => b.Category == null || b.Category == "").OrderBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", "Other (not categorized)"); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns() { var rockContext = new RockContext(); var commonBlockTypes = new BlockTypeService(rockContext).Queryable().Where(a => a.IsCommon).OrderBy(a => a.Name).AsNoTracking().ToList(); rptCommonBlockTypes.DataSource = commonBlockTypes; rptCommonBlockTypes.DataBind(); }
private static int LoadByGuid2(Guid guid, RockContext rockContext) { var blockTypeService = new BlockTypeService(rockContext); return(blockTypeService .Queryable().AsNoTracking() .Where(b => b.Guid.Equals(guid)) .Select(b => b.Id) .FirstOrDefault()); }
private static BlockTypeCache LoadById2(int id, RockContext rockContext) { var blockTypeService = new BlockTypeService(rockContext); var blockTypeModel = blockTypeService.Get(id); if (blockTypeModel != null) { return(new BlockTypeCache(blockTypeModel)); } return(null); }
/// <summary> /// Loads the block types. /// </summary> private void LoadBlockTypes(bool registerBlockTypes) { if (registerBlockTypes) { // Add any unregistered blocks try { BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); } catch (Exception ex) { nbMessage.Text = "Error registering one or more block types"; nbMessage.Details = ex.Message + "<code>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</code>"; nbMessage.Visible = true; } } // Load the block types using (var rockContext = new RockContext()) { Rock.Model.BlockTypeService blockTypeService = new Rock.Model.BlockTypeService(rockContext); var blockTypes = blockTypeService.Queryable().AsNoTracking() .Select(b => new { b.Id, b.Name, b.Category, b.Description }) .ToList(); ddlBlockType.Items.Clear(); // Add the categorized block types foreach (var blockType in blockTypes .Where(b => b.Category != "") .OrderBy(b => b.Category) .ThenBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", blockType.Category); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } // Add the uncategorized block types foreach (var blockType in blockTypes .Where(b => b.Category == null || b.Category == "") .OrderBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", "Other (not categorized)"); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } } }
/// <summary> /// Handles the Delete event of the gBlockTypes 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 gBlockTypes_Delete(object sender, RowEventArgs e) { BlockTypeService blockTypeService = new BlockTypeService(); BlockType blockType = blockTypeService.Get((int)gBlockTypes.DataKeys[e.RowIndex]["id"]); if (CurrentBlock != null) { blockTypeService.Delete(blockType, CurrentPersonId); blockTypeService.Save(blockType, CurrentPersonId); Rock.Web.Cache.BlockTypeCache.Flush(blockType.Id); } BindGrid(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (!Page.IsPostBack) { tbNameFilter.Text = gfSettings.GetUserPreference("Name"); tbPathFilter.Text = gfSettings.GetUserPreference("Path"); ddlCategoryFilter.SetValue(gfSettings.GetUserPreference("Category")); cbExcludeSystem.Checked = !string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Exclude System")); BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); BindGrid(); } base.OnLoad(e); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { BlockTypeService blockTypeService = new BlockTypeService(); SortProperty sortProperty = gBlockTypes.SortProperty; if (sortProperty != null) { gBlockTypes.DataSource = blockTypeService.Queryable().Sort(sortProperty).ToList(); } else { gBlockTypes.DataSource = blockTypeService.Queryable().OrderBy(b => b.Name).ToList(); } gBlockTypes.DataBind(); }
public IActionResult btnClearCache_Click() { var msgs = RockCache.ClearAllCachedItems(); // Flush today's Check-in Codes Rock.Model.AttendanceCodeService.FlushTodaysCodes(); #if false string webAppPath = Server.MapPath( "~" ); // Check for any unregistered entity types, field types, and block types EntityTypeService.RegisterEntityTypes( webAppPath ); FieldTypeService.RegisterFieldTypes( webAppPath ); BlockTypeService.RegisterBlockTypes( webAppPath, Page, false ); msgs.Add( "EntityTypes, FieldTypes, BlockTypes have been re-registered" ); // Delete all cached files try { var dirInfo = new DirectoryInfo( Path.Combine( webAppPath, "App_Data/Cache" ) ); foreach ( var childDir in dirInfo.GetDirectories() ) { childDir.Delete( true ); } foreach ( var file in dirInfo.GetFiles().Where( f => f.Name != ".gitignore" ) ) { file.Delete(); } msgs.Add( "Cached files have been deleted" ); } catch ( Exception ex ) { return new OkObjectResult( new { Error = true, Messages = new [] { $"The following error occurred when attempting to delete cahced files: {ex.Message}" } ); } #endif return new OkObjectResult( new { Error = false, Messages = msgs } ); } #endregion }
/// <summary> /// Used to manually flush the attribute cache. /// </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 btnClearCache_Click(object sender, EventArgs e) { var msgs = RockCache.ClearAllCachedItems(); // Flush today's Check-in Codes Rock.Model.AttendanceCodeService.FlushTodaysCodes(); string webAppPath = Server.MapPath("~"); // Check for any unregistered entity types, field types, and block types EntityTypeService.RegisterEntityTypes(); FieldTypeService.RegisterFieldTypes(); BlockTypeService.FlushRegistrationCache(); BlockTypeService.RegisterBlockTypes(webAppPath, Page, false); msgs.Add("EntityTypes, FieldTypes, BlockTypes have been re-registered"); // Delete all cached files try { var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache")); foreach (var childDir in dirInfo.GetDirectories()) { childDir.Delete(true); } foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore")) { file.Delete(); } msgs.Add("Cached files have been deleted"); } catch (Exception ex) { nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning; nbMessage.Visible = true; nbMessage.Text = "The following error occurred when attempting to delete cached files: " + ex.Message; return; } nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success; nbMessage.Visible = true; nbMessage.Title = "Clear Cache"; nbMessage.Text = string.Format("<p>{0}</p>", msgs.AsDelimited("<br />")); }
/// <summary> /// Used to manually flush the attribute cache. /// </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 btnClearCache_Click(object sender, EventArgs e) { // Clear all cached items Rock.Web.Cache.RockMemoryCache.Clear(); // Clear the static object that contains all auth rules (so that it will be refreshed) Rock.Security.Authorization.Flush(); // Flush the static entity attributes cache Rock.Web.Cache.AttributeCache.FlushEntityAttributes(); // Check for any unregistered entity types, field types, and block types string webAppPath = Server.MapPath("~"); EntityTypeService.RegisterEntityTypes(webAppPath); FieldTypeService.RegisterFieldTypes(webAppPath); BlockTypeService.RegisterBlockTypes(webAppPath, Page, false); // Delete all cached files try { var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache")); foreach (var childDir in dirInfo.GetDirectories()) { childDir.Delete(true); } foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore")) { file.Delete(); } } catch (Exception ex) { nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning; nbMessage.Visible = true; nbMessage.Text = "Cache has been cleared, but following error occurred when attempting to delete cached files: " + ex.Message; return; } nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success; nbMessage.Visible = true; nbMessage.Text = "The cache has been cleared."; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!IsPostBack) { int pageId = PageParameter("Page").AsInteger(); int siteId = PageParameter("SiteId").AsInteger(); BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); // Load page picker if (siteId != 0) { LoadPagePicker(siteId); } if (pageId != 0) { ShowDetail(pageId); } else { ShowPageEdit(pageId); } } else { if (pnlBlocks.Visible == true) { // // Rebind zones so postback events work correctly. // BindZones(); } if (Request["__EVENTTARGET"].ToStringSafe() == lbDragCommand.ClientID) { ProcessDragEvents(); } } }
/// <summary> /// Handles the Delete event of the gBlockTypes 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 gBlockTypes_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); BlockTypeService blockTypeService = new BlockTypeService(rockContext); BlockType blockType = blockTypeService.Get(e.RowKeyId); if (blockType != null) { string errorMessage; if (!blockTypeService.CanDelete(blockType, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } blockTypeService.Delete(blockType); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Expands the files. /// </summary> /// <param name="packageFiles">The package files.</param> private void ExpandFiles(IEnumerable <IPackageFile> packageFiles) { // Remove export.json file from the list of files to be unzipped var filesToUnzip = packageFiles.Where(f => !f.Path.Contains("export.json")).ToList(); var blockTypeService = new BlockTypeService(new RockContext()); var installedBlockTypes = blockTypeService.Queryable().Where(b => !string.IsNullOrEmpty(b.Path)); var webRoot = HttpContext.Current.Server.MapPath("~"); // Compare the packages files with currently installed block types, removing anything that already exists foreach (var blockType in installedBlockTypes) { var blockFileName = blockType.Path.Substring(blockType.Path.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase)); blockFileName = blockFileName.Replace('/', Path.DirectorySeparatorChar); filesToUnzip.RemoveAll(f => f.Path.Contains(blockFileName)); } foreach (var packageFile in filesToUnzip) { var path = Path.Combine(webRoot, packageFile.EffectivePath); var file = new FileInfo(path); // Err on the side of not being destructive for now. Consider refactoring to give user a choice // on whether or not to overwrite these files. if (file.Exists) { WarningMessages.Add(string.Format("Skipping '{0}', found duplicate file at '{1}'.", file.Name, path)); continue; } // Write each file out to disk using (var fileStream = new FileStream(path, FileMode.Create)) { var stream = packageFile.GetStream(); var bytes = stream.ReadAllBytes(); fileStream.Write(bytes, 0, bytes.Length); stream.Close(); } } }
/// <summary> /// Loads the drop downs. /// </summary> public void LoadDropDowns() { int pageId = hfPageId.Value.AsInteger(); ddlZones.Items.Clear(); ddlMoveToZoneList.Items.Clear(); var page = PageCache.Get(pageId); if (page != null) { // get the valid zones from the Layout for this page var zoneNames = FindZoneNames(page); foreach (var zoneName in zoneNames) { var zoneBlockCount = page.Blocks.Where(a => a.Zone.Equals(zoneName, StringComparison.OrdinalIgnoreCase)).Count(); ddlZones.Items.Add(new ListItem(string.Format("{0} ({1})", zoneName, zoneBlockCount), zoneName)); ddlMoveToZoneList.Items.Add(new ListItem(zoneName, zoneName)); } // get any zones from blocks that have a zone that isn't part of the layout, then add those the list, but not the MoveToZoneList _invalidPageZones = page.Blocks.Select(a => a.Zone).ToList().Where(z => !zoneNames.Contains(z)).ToArray(); foreach (var invalidPageZone in _invalidPageZones) { var zoneBlockCount = page.Blocks.Where(a => a.Zone.Equals(invalidPageZone, StringComparison.OrdinalIgnoreCase)).Count(); ddlZones.Items.Add(new ListItem(string.Format("{0} ({1})", invalidPageZone, zoneBlockCount), invalidPageZone)); } // default to Main Zone (if there is one) ddlZones.SetValue("Main"); } var rockContext = new RockContext(); var commonBlockTypes = new BlockTypeService(rockContext).Queryable().Where(a => a.IsCommon).OrderBy(a => a.Name).AsNoTracking().ToList(); rptCommonBlockTypes.DataSource = commonBlockTypes; rptCommonBlockTypes.DataBind(); }
/// <summary> /// Handles the Delete event of the gBlockTypes 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 gBlockTypes_Delete(object sender, RowEventArgs e) { RockTransactionScope.WrapTransaction(() => { BlockTypeService blockTypeService = new BlockTypeService(); BlockType blockType = blockTypeService.Get((int)e.RowKeyValue); if (blockType != null) { string errorMessage; if (!blockTypeService.CanDelete(blockType, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } blockTypeService.Delete(blockType, CurrentPersonId); blockTypeService.Save(blockType, CurrentPersonId); Rock.Web.Cache.BlockTypeCache.Flush(blockType.Id); } }); BindGrid(); }
/// <summary> /// Loads the block types. /// </summary> private void LoadBlockTypes() { // Add any unregistered blocks BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); // Load the block types Rock.Model.BlockTypeService blockTypeService = new Rock.Model.BlockTypeService(new RockContext()); var blockTypes = blockTypeService.Queryable() .Select(b => new { b.Id, b.Name, b.Category, b.Description }) .ToList(); ddlBlockType.Items.Clear(); // Add the categorized block types foreach (var blockType in blockTypes .Where(b => b.Category != "") .OrderBy(b => b.Category) .ThenBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", blockType.Category); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } // Add the uncategorized block types foreach (var blockType in blockTypes .Where(b => b.Category == null || b.Category == "") .OrderBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", "Other (not categorized)"); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } }
/// <summary> /// Gets the query. /// </summary> /// <returns></returns> private IQueryable <BlockType> GetQuery() { BlockTypeService blockTypeService = new BlockTypeService(new RockContext()); var blockTypes = blockTypeService.Queryable().AsNoTracking(); // Filter by Name string nameFilter = gfSettings.GetUserPreference("Name"); if (!string.IsNullOrEmpty(nameFilter.Trim())) { blockTypes = blockTypes.Where(b => b.Name.Contains(nameFilter.Trim())); } // Filter by Path string path = gfSettings.GetUserPreference("Path"); if (!string.IsNullOrEmpty(path.Trim())) { blockTypes = blockTypes.Where(b => b.Path.Contains(path.Trim())); } return(blockTypes); }
/// <summary> /// Scans for unregistered blocks. /// </summary> private void ScanForUnregisteredBlocks() { BlockTypeService blockTypeService = new BlockTypeService(); foreach (Rock.Model.BlockType blockType in blockTypeService.GetUnregisteredBlocks(Request.MapPath("~"))) { try { Control control = LoadControl(blockType.Path); if (control is Rock.Web.UI.RockBlock) { blockType.Name = Path.GetFileNameWithoutExtension(blockType.Path).SplitCase(); blockType.Description = Rock.Reflection.GetDescription(control.GetType()) ?? string.Empty; blockTypeService.Add(blockType, CurrentPersonId); blockTypeService.Save(blockType, CurrentPersonId); } } catch { // } } }
/// <summary> /// Returns Block Type object from cache. If block does not already exist in cache, it /// will be read and added to cache /// </summary> /// <param name="id"></param> /// <returns></returns> public static BlockTypeCache Read(int id) { string cacheKey = BlockTypeCache.CacheKey(id); ObjectCache cache = MemoryCache.Default; BlockTypeCache blockType = cache[cacheKey] as BlockTypeCache; if (blockType != null) { return(blockType); } else { var blockTypeService = new BlockTypeService(); var blockTypeModel = blockTypeService.Get(id); if (blockTypeModel != null) { blockTypeModel.LoadAttributes(); blockType = new BlockTypeCache(blockTypeModel); var cachePolicy = new CacheItemPolicy(); AddChangeMonitor(cachePolicy, blockType.Path); cache.Set(cacheKey, blockType, cachePolicy); var guidCachePolicy = new CacheItemPolicy(); AddChangeMonitor(guidCachePolicy, blockType.Path); cache.Set(blockType.Guid.ToString(), blockType.Id, guidCachePolicy); return(blockType); } else { return(null); } } }
public bool ImportPage(byte[] uploadedPackage, string fileName, int pageId, int siteId) { // Write .nupkg file to the PackageStaging folder... var path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/PackageStaging"), fileName); using (var file = new FileStream(path, FileMode.Create)) { file.Write(uploadedPackage, 0, uploadedPackage.Length); } var package = new ZipPackage(path); var packageFiles = package.GetFiles().ToList(); var exportFile = packageFiles.FirstOrDefault(f => f.Path.Contains("export.json")); Page page = null; // If export.json is present, deserialize data // * Are there any new BlockTypes to register? If so, save them first. // * Scrub out any `Id` and `Guid` fields that came over from export // * Save page data via PageService if (exportFile != null) { string json; using (var stream = exportFile.GetStream()) { json = stream.ReadToEnd(); } page = Page.FromJson(json); } // Validate package... // + Does it have any executable .dll files? Should those go to the bin folder, or into a plugins directory to be loaded via MEF? // - Does it have code or asset files that need to go on the file system? (Done) // - Does it have an export.json file? Should that be a requirement? (Done) // + Does it have any corresponding SQL, migrations, seed methods to run, etc. if (page != null) { var rockContext = new RockContext(); // Find new block types and save them prior to scrubbing data... var newBlockTypes = FindNewBlockTypes(page, new BlockTypeService(rockContext).Queryable()).ToList(); rockContext.WrapTransaction(() => { try { var blockTypeService = new BlockTypeService(rockContext); foreach (var blockType in newBlockTypes) { blockTypeService.Add(blockType); } rockContext.SaveChanges(); ValidateImportData(page, newBlockTypes); SavePages(rockContext, page, newBlockTypes, pageId, siteId); ExpandFiles(packageFiles); } catch (Exception e) { ErrorMessages.Add(e.Message); } }); // Clean up PackageStaging folder on successful import. var file = new FileInfo(path); file.Delete(); return(ErrorMessages.Count <= 0); } ErrorMessages.Add("The export package uploaded does not appear to have any data associated with it."); return(false); }
/// <summary> /// Handles the Click event of the btnAddBlock 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 btnAddBlock_Click(object sender, EventArgs e) { tbNewBlockName.Text = string.Empty; // Load the block types using (var rockContext = new RockContext()) { try { BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page); } catch { // ignore } Rock.Model.BlockTypeService blockTypeService = new Rock.Model.BlockTypeService(rockContext); var blockTypes = blockTypeService.Queryable().AsNoTracking() .Select(b => new { b.Id, b.Name, b.Category, b.Description }) .ToList(); ddlBlockType.Items.Clear(); // Add the categorized block types foreach (var blockType in blockTypes .Where(b => b.Category != string.Empty) .OrderBy(b => b.Category) .ThenBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", blockType.Category); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } // Add the uncategorized block types foreach (var blockType in blockTypes .Where(b => b.Category == null || b.Category == string.Empty) .OrderBy(b => b.Name)) { var li = new ListItem(blockType.Name, blockType.Id.ToString()); li.Attributes.Add("optiongroup", "Other (not categorized)"); li.Attributes.Add("title", blockType.Description); ddlBlockType.Items.Add(li); } } var htmlContentBlockType = BlockTypeCache.Read(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid()); ddlBlockType.SetValue(htmlContentBlockType.Id); rblAddBlockLocation.Items.Clear(); var page = PageCache.Read(hfPageId.Value.AsInteger()); var listItemPage = new ListItem(); listItemPage.Text = string.Format("Page ({0})", page.ToString()); listItemPage.Value = "Page"; listItemPage.Selected = true; var listItemLayout = new ListItem(); listItemLayout.Text = string.Format("Layout ({0})", page.Layout); listItemLayout.Value = "Layout"; listItemLayout.Selected = false; var listItemSite = new ListItem(); listItemSite.Text = string.Format("Site ({0})", page.Layout.Site); listItemSite.Value = "Site"; listItemSite.Selected = false; rblAddBlockLocation.Items.Add(listItemPage); rblAddBlockLocation.Items.Add(listItemLayout); rblAddBlockLocation.Items.Add(listItemSite); mdAddBlock.Title = "Add Block to " + ddlZones.SelectedValue + " Zone"; mdAddBlock.Show(); }