& Lt; ABP document & gt; notification system, and Reminder System

Source: Internet
Author: User

<ABP document> notification system and notification system

Document directory

 

Content of this section:

  • Introduction
    • Sending Mode
    • Notification Type
    • Notification data
    • Notification importance
    • Notification persistence
  • Subscription notification
  • Release notification
  • User notification Manager
  • Real-time notification
    • Client
  • Notification Storage
  • Notification Definition

 

Introduction

NotificationsNoticeA specific event occurs in the user system.Publish/SubscribeIt is based on the basic framework of real-time notification.

 

Sending Mode

There are two ways to send notifications to users:

  • UserSubscriptionA specific notification type, and then weReleaseA notification of this type is distributed to all subscribed users.Publish/SubscribeMode.
  • We canSend directlyA notification is sent to the target user (users ).

 

Notification Type

There are two types of notifications:

  • General notification: Any notification type. "If a user sends a friend request, notification me" is a notification of this type.
  • Entity notification: It is associated with a specific object. "If a user sends a comment to this image, notifying me" is an entity-based notification, because it is associated with a specific photo object, users may want to send notifications for some images, not all images.

Notification data

A notification usually contains a notification data. For example, "If a user sends a friend request, notify me" the notification may have two data attributes: the sender's name (who sent this friend request) and remarks (the information the sender wrote in the request) are obviously closely related to the notification data type and notification type, different notification types have different data types.

Notification data isOptional,Some notifications may not require data. You have provided predefined notification data types that are sufficient for most scenarios.MessageNotificationData,Localized and parameterized notification information can be usedLocalizableMessageNotificationDataIn the following sections, we will see examples.

 

Notification importance

There are five levels of notification importance, which are defined in icationicationseverity enumeration:Info,Success,Warn,ErrorAndFatal, Default value:Info.

Notification persistence

View the notification Storage section for more information.

 

Subscription notification

INotificationSubscriptionManager provides APIs for subscribing to notifications, for example:

Public class MyService: ITransientDependency {private readonly INotificationSubscriptionManager _ icationicationsubscriptionmanager; public MyService (Inotifsubsubscriptionmanager notificationSubscriptionManager) {_ Icationsubsubscriptionmanager = notificationSubscriptionManager;} // subscribe to a general public async Task Subscribe_SentFrendshipRequest (int? TenantId, long userId ){Await _ icationicationsubscriptionmanager. SubscribeAsync (new UserIdentifier (tenantId, userId), "SentFrendshipRequest");} // Subscribe to an entity notification public async Task Subscribe_CommentPhoto (int? TenantId, long userId, Guid photoId ){Await _ icationicationsubscriptionmanager. SubscribeAsync (new UserIdentifier (tenantId, userId), "CommentPhoto", new EntityIdentifier (typeof(Photo), photoId ));}}

First, we injectINotificationSubscriptionManagerThe first method subscribes to a general notification. When someone sends a friend request, the user will receive the notification, and the second method subscribes toSpecific entity(Photo) related notifications. When someone writes a comment to a specific Photo, the user will receive a notification.

Each notification type should have a unique name (for exampleSentFrendshipRequestAndCommentPhoto).

INotificationSubscriptionManagerAndUnsubscribeAsync,IsSubscribedAsync,GetSubscriptionsAsynTo manage the subscription.

 

Release notification

InotificationherUsed to publish notifications, for example:

Public class MyService: ITransientDependency {private readonly INotificationPublisher _ notiticationPublisher; public MyService (Inotificationher notiticationPublisher) {_ NotiticationPublisher = notiticationPublisher;} // send a general notification to a specific user public async Task Publish_SentFrendshipRequest (string senderUserName, string friendshipMessage, UserIdentifier targetUserId ){Await _ notiticationPublisher. PublishAsync ("SentFrendshipRequest", new sentfrendshiprequesticationicationdata (senderUserName, friendshipMessage), userIds: new[] {TargetUserId });} // Send an entity notification to a specific user public async Task Publish_CommentPhoto (string commenterUserName, string comment, Guid photoId, UserIdentifier photoOwnerUserId ){Await _ notiticationPublisher. PublishAsync ("CommentPhoto", new CommentPhotoNotificationData (commenterUserName, comment), new EntityIdentifier (typeof (Photo), photoId), userIds: new[] {PhotoOwnerUserId });} // Send a general notification to the public async Task Publish_LowDisk (int remainingDiskInMb) user that subscribes to the current tenant (in the session) {// Example "LowDiskWarningMessage" content for English-> "Attention! Only {remainingDiskInMb} MBs left on the disk! "Var data = new partition (new LocalizableString ("LowDiskWarningMessage", "partition"); data ["remainingDiskInMb"] = remainingDiskInMb; await _ notiticationPublisher. PublishAsync ("System. LowDisk", Data, severity: icationicationseverity. Warn );}}

In the first example, we publish a notification to a single user,SentFrendshipRequestNotificationDataIt should inherit fromIcationicationdata, As shown below:

[Serializable]public class SentFrendshipRequestNotificationData : NotificationData{    public string SenderUserName { get; set; }    public string FriendshipMessage { get; set; }    public SentFrendshipRequestNotificationData(string senderUserName, string friendshipMessage)    {        SenderUserName = senderUserName;        FriendshipMessage = friendshipMessage;    }} 

In the second example, we send a notification to a specific user and pass a specific object. The notification data class does not need to be serializable (because the JSON sequencer is used by default ), however, we recommend that you mark it as serializable, because you may move in different applications and you may want to use a binary serializer in the future. Of course, as described above, the notification data is optional, and not all notifications require it.

NOTE: If we publish a notification to a specific user, this user does not need to subscribe to this notification.

In the third example, we do not define a special notification data class, but directly use the LocalizableMessageNotificationData class of the content, use dictionary-based data, and publish a "Warn" notification, localizableMessageNotificationData can store dictionary-based arbitrary data (if the custom notification data class inherits the icationicationdata class, it can also be used). We use "remainingDiskInMb" as the localization parameter, localized information can contain these parameters (for example, "Attention!" In the example! Only {remainingDiskInMb} MBs left on the disk !"), We can see in the client section that if it is localized.

 

User notification Manager

Iusericationicationmanager is used to manage user notifications. It can be used to get, update, or delete a user notification. You can use it to prepare a notification list page for your application.

 

Real-time notification

Although you can use iusericationicationmanager to query notifications, we usually want to push a real-time notification to the client.

The notification system uses IRealTimeNotifier to send real-time notifications to users. This can be implemented using any type of real-time communication system. We can use a separately implemented SignalR package. The launch template has installed SignalR, view the SignalR Integration document for more information.

Note: The notification system uses a background job to call IRealTimeNotifier asynchronously. Therefore, the notification may be delayed a little.

 

Client

When you receive a real-time notification, you can use the following method to register the event to receive the notification when the client triggers a global event:

abp.event.on('abp.notifications.received', function (userNotification) {    console.log(userNotification);}); 

Every time a real-time notification is received, the events of the abp. Events. received ed event are triggered. You can register the event as above to get notifications, and view the javascript event bus document to get more information about the events. A Json example of the "System. LowDisk" notification received:

{    "userId": 2,    "state": 0,    "notification": {        "notificationName": "System.LowDisk",        "data": {            "message": {                "sourceName": "MyLocalizationSourceName",                "name": "LowDiskWarningMessage"            },            "type": "Abp.Notifications.LocalizableMessageNotificationData",            "properties": {                "remainingDiskInMb": "42"            }        },        "entityType": null,        "entityTypeName": null,        "entityId": null,        "severity": 0,        "creationTime": "2016-02-09T17:03:32.13",        "id": "0263d581-3d8a-476b-8e16-4f6a6f10a632"    },    "id": "4a546baf-bf17-4924-b993-32e420a8d468"}

In this object:

  • UserId: Current User ID. Generally, you do not need this because you know the current user.
  • State: the enumerated value of UserNotificationState, 0: Unread (Unread), 1: Read (Read ).
  • Notification: notification Details:
    • NotificationName: the unique name of the notification (also used for publishing ).
    • Data: Notification data. In this example, we use LocalizableMessageNotificationData (consistent with the previous release example ):
      • Message: localized message information. We can use sourceName and name to localize messages on the interface.
      • Type: Notification data type, full type name, including namespace. When processing notification data, we can check this type.
      • Properties: dictionary-based custom attributes.
    • EntityType, entityTypeName, and entityId: entity information (if this is an entity real-time notification)
    • Severity: A NotificationSeverity enumeration value, 0: Info, 1: Success, 2: Warn, 3: Error, 4: Fatal.
    • Id: Notification Id.
  • Id: user notification Id.

Of course, you will not only log this notification. You can use the notification data to display the notification information to the user, for example:

abp.event.on('abp.notifications.received', function (userNotification) {    if (userNotification.notification.data.type === 'Abp.Notifications.LocalizableMessageNotificationData') {        var localizedText = abp.localization.localize(            userNotification.notification.data.message.name,            userNotification.notification.data.message.sourceName        );        $.each(userNotification.notification.data.properties, function (key, value) {            localizedText = localizedText.replace('{' + key + '}', value);        });        alert('New localized notification: ' + localizedText);    } else if (userNotification.notification.data.type === 'Abp.Notifications.MessageNotificationData') {        alert('New simple notification: ' + userNotification.notification.data.message);    }});

In order to process the notification data, we should check this data type. In this example, the message is retrieved from the notification data. If it is a localized message (LocalizableMessageNotificationData ), we localize the message and replace the parameter. If it is a simple message (MessageNotificationData), we can directly obtain the message. Of course, in a real project, we will not use the alert function, we can use abp. notify api to display good UI notifications.

If you want to implement the above logic, there is a more easy and flexible way. When you receive a push notification, you only need a line of code to display the UI notification:

abp.event.on('abp.notifications.received', function (userNotification) {    abp.notifications.showUiNotifyForUserNotification(userNotification);});

This shows a UI notification, as shown below (the pushed System. LowDisk notification described above ):

It can work on the notification Data Type of the content (LocalizableMessageNotificationData and MessageNotificationData). If you are a custom notification data type, you should register the data format as follows:

Abp. Communications. messageFormatters ['myproject. mynotificationype '] = function (userNotification) {return...; // format and return a message here };

 

Therefore, showUiNotifyForUserNotification allows you to create displayed messages for your data type. If you only need messages in the format, you can directly use abp. configurications. getFormattedMessageFromUserNotification

(UserNotification), which is internally showUiNotifyForUserNotification.

The launch template contains the code that displays the UI notification after receiving a push message.

 

Notification Storage

The notification system uses inotifstore store for persistent notifications. Only after this interface is implemented can the notification system work normally. You can implement it yourself or useModule-zero.

 

Notification Definition

You do not need to define a notification before using it. You only need to use any notification name, But defining it may bring you additional benefits, for example, after definition, you can check all notifications in your application. In this case, we can define a notification provider for our module, as shown below:

public class MyAppNotificationProvider : NotificationProvider{    public override void SetNotifications(INotificationDefinitionContext context)    {        context.Manager.Add(            new NotificationDefinition(                "App.NewUserRegistered",                displayName: new LocalizableString("NewUserRegisteredNotificationDefinition", "MyLocalizationSourceName"),                permissionDependency: new SimplePermissionDependency("App.Pages.UserManagement")                )            );    }}

 

"ABC. newUserRegistered is the unique name of the notification. We define a localized displayName (which can be displayed when the notification is subscribed to on the UI). Finally, we declare that this notification only has "App. pages. userManagerment "allows users to be available.

There are other parameters here. You can check it in the Code. The definition of a notification is only required by the name.

After defining this notification provider, we should register it in the module's PreInitialize event, as shown below:

public class AbpZeroTemplateCoreModule : AbpModule{    public override void PreInitialize()    {        Configuration.Notifications.Providers.Add<MyAppNotificationProvider>();    }    //...}

 

Finally, you can inject in your application and use INotificationDefinitionManager to get notification definitions. Then you may want to prepare a page that allows users to subscribe to these notifications by themselves.

 

Kid1412 Appendix: http://www.aspnetboilerplate.com/Pages/Documents/Notification-System

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.