Skip to content

Instantly share code, notes, and snippets.

@davidknipe
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidknipe/a90835c859e9c5013e31 to your computer and use it in GitHub Desktop.
Save davidknipe/a90835c859e9c5013e31 to your computer and use it in GitHub Desktop.
Restricting the total number of items in an EPiServer media folder
using System.Linq;
using EPiServer.Core;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using InitializationModule = EPiServer.Web.InitializationModule;
namespace EPiServer.Templates.Alloy.ValidateItemsInFolder
{
[InitializableModule]
[ModuleDependency(typeof(InitializationModule))]
public class ValidateFileCountInit : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
IContentEvents events = ServiceLocator.Current.GetInstance<IContentEvents>();
events.CreatingContent += ValidateFileCount;
events.MovingContent += ValidateFileCount;
}
private void ValidateFileCount(object sender, ContentEventArgs e)
{
// Check if it's a media item
if (!(e.Content is MediaData)) return;
// Should never happen but always worth being defensive
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
if (repo == null) return;
// Get the folder we are trying to create the media item in
var targetFolder = e is MoveContentEventArgs ? e.TargetLink : e.Content.ParentLink;
if (targetFolder == null) return;
// Check for the total number of media items in the target folder
var childItems = repo.GetChildren<MediaData>(targetFolder);
const int maxFileCount = 100; // << Pick a sensible number based on requirements/testing
if (childItems == null || childItems.Count() <= maxFileCount)
return;
// Get the translated error message
var lang = ServiceLocator.Current.GetInstance<LocalizationService>();
string errorMessage;
if (!lang.TryGetString("/errors/toomanyfiles", out errorMessage))
{
errorMessage = "Too many media items in this folder, please create a sub-folder or move media items out of the folder before re-trying";
}
// Set up the error
e.CancelAction = true;
e.CancelReason = errorMessage;
}
public void Preload(string[] parameters) { } // This can be removed if using EPiServer 8+
public void Uninitialize(InitializationEngine context)
{
IContentEvents events = ServiceLocator.Current.GetInstance<IContentEvents>();
events.CreatingContent -= ValidateFileCount;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment