MediaService Notifications Example
Example of how to use a MediaService Notification
The MediaService class implements IMediaService. It provides access to operations involving IMedia.
Usage
Example usage of the MediaService notifications:
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
namespace MySite;
public class MediaNotificationHandler : INotificationHandler<MediaSavedNotification>
{
private readonly ILogger<MediaNotificationHandler> _logger;
public MediaNotificationHandler(ILogger<MediaNotificationHandler> logger)
{
_logger = logger;
}
public void Handle(MediaSavedNotification notification)
{
foreach (var mediaItem in notification.SavedEntities)
{
if (mediaItem.ContentType.Alias.Equals("Image"))
{
// Do something with the image, maybe send to Azure for AI analysis of image contents or something.
_logger.LogDebug($"Sending {mediaItem.Name} to analysis");
SendToAzure(mediaItem);
}
}
}
}
Returning messages to the user
You can return a custom message to the user. Use this to show information, a warning or maybe an error.
This is achieved using the Messages
property of the notification and a composer.
Example
This example returns an informational message to the user when a Media item is saved.
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
namespace MyProject
{
public class CustomComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.AddNotificationHandler<MediaSavedNotification, MediaNotificationTest>();
}
}
public class MediaNotificationTest : INotificationHandler<MediaSavedNotification>
{
public void Handle(MediaSavedNotification notification)
{
notification.Messages.Add(new EventMessage(
"Notification",
"You can return a message to the user, using the messages property on the notification.",
EventMessageType.Info));
}
}
}
Last updated
Was this helpful?