Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

Send basic in-app notifications using Javascript in Model Driven App Dataverse

Send basic in-app notifications using Javascript in Model Driven App Dataverse

The Final Result will be given below.

Watch video here or scroll down to read the article.

Step : 1 – Enable the Model Driven App Feature

First of all, you need to enable in-app Notification feature for your model driven app using Settings option in editing mode of your model driven app and Save it.

Step : 2 – Create a Reusable Script Library to use SendAppNotificationRequest

Create a re-usable script library to implement SendAppNotification Response. Create a new JS web resource and use the below script and upload the Web Resource.

var InAppNotificationWrapper= window.InAppNotificationWrapper || {};
InAppNotificationWrapper.SendAppNotificationRequest = function (
   title, 
   recipient, 
   body, 
   priority, 
   iconType, 
   toastType, 
   expiry, 
   overrideContent, 
   actions) 
{
    this.Title = title;
    this.Recipient = recipient;
    this.Body = body;
    this.Priority = priority;
    this.IconType = iconType;
    this.ToastType = toastType;
    this.Expiry = expiry;
    this.OverrideContent = overrideContent;
    this.Actions = actions;
};

InAppNotificationWrapper.SendAppNotificationRequest.prototype.getMetadata = function () {
    return {
        boundParameter: null,
        parameterTypes: {
            "Title": {
                "typeName": "Edm.String",
                "structuralProperty": 1
            },
            "Recipient": {
                "typeName": "mscrm.systemuser",
                "structuralProperty": 5
            },
            "Body": {
                "typeName": "Edm.String",
                "structuralProperty": 1
            },
            "Priority": {
                "typeName": "Edm.Int",
                "structuralProperty": 1
            },
            "IconType": {
                "typeName": "Edm.Int",
                "structuralProperty": 1
            },
            "ToastType": {
                "typeName": "Edm.Int",
                "structuralProperty": 1
            },
            "Expiry": {
                "typeName": "Edm.Int",
                "structuralProperty": 1
            },
            "OverrideContent": {
                "typeName": "mscrm.expando",
                "structuralProperty": 5
            },
            "Actions": {
                "typeName": "mscrm.expando",
                "structuralProperty": 5
            },
        },
        operationType: 0, 
        operationName: "SendAppNotification",
    };
};

Step : 3 – Create a JS script to end Notification

Now create another JS web resource with below code to send notification which will use above library function. You can call this below function on Page Load of any form.

//Send basic in-app notifications
function SendVersionNotification()
{
 // pass current login user guid
  var currentRecordId = Xrm.Utility.getGlobalContext().userSettings.userId;
  currentRecordId = currentRecordId.replace("{","").replace("}","");
  // replace GUID of USER with your desired user id 
  var SendAppNotificationRequest = new InAppNotificationWrapper.SendAppNotificationRequest(
      title = "Version Message",
      recipient = "/systemusers("+currentRecordId+")",
      body = "Your Health Care App is upgraded. Refresh to update.!",
      priority = 200000000,
      iconType = 100000000,
      toastType = 200000000,
  );
  
  Xrm.WebApi.online.execute(SendAppNotificationRequest).then(function (response) {
      if (response.ok) {
          console.log("Status: %s %s", response.status, response.statusText);
  
          return response.json();
      }
  })
  .then(function (responseBody) {
      console.log("Response Body: %s", responseBody.NotificationId);
  })
  .catch(function (error) {
      console.log(error.message);
  });
}

NOTE : You can use below priorities.

Normal200000000
High200000001

NOTE : you can use below icon Types

Icon TypeValueImage
Info100000000Info Icon
Success100000001Success Icon
Failure100000002Failure Icon
Warning100000003Warning Icon
Mention100000004Mention Icon
Custom100000005

NOTE : You can use below toast type.

Toast TypeBehaviorValue
TimedThe notification appears for a brief duration (the default is four seconds) and then disappears.200000000
HiddenThe notification appears only in the notification center and not as a toast notification.200000001

The Notification Table given below.

Display NameSchema NameDescription
TitleTitleThe title of the notification.
OwnerOwnerIdThe user who receives the notification. While this column can be set to either a user or team, you must only set this to a user. The notification can’t be set to a team.
BodyBodyDetails about the notification.
IconTypeIconTypeThe list of predefined icons. The default value is Info.
Toast TypeToastTypeThe list of notification behaviors. The default value is Timed.
PriorityPriorityEnables prioritization of notifications, which determines the order in which the notifications are displayed in the notification center.
Expiry (seconds)TTLInSecondsThe number of seconds from when the notification should be deleted if not already dismissed.
DataDataJSON that’s used for extensibility and parsing richer data into the notification. The maximum length is 5,000 characters.

You can also use markdowns in notifications as given below.

Text StyleMarkdown
Bold**Bold**
Italic_Italic_
Bullet list- Item 1\r- Item 2\r- Item 3
Numbered list1. Green\r2. Orange\r3. Blue
Hyperlinks
New Line
[Title](url)
with the body using \n\n\n\n.

If you want to call this using WEB API use bvelow code sample. This WEB API Call do not return any response.

POST [Organization URI]/api/data/v9.2/SendAppNotification
Content-Type: application/json; charset=utf-8
OData-MaxVersion: 4.0
OData-Version: 4.0
Accept: application/json

{
  "Title": "Welcome",
  "Body": "Welcome to the world of app notifications!",
  "Recipient": "/systemusers(<Guid of the user>)",
  "IconType": 100000000, // info
  "ToastType": 200000000 // timed
}

If you are using C# code to send in-app notification, use below code.

/// <summary>
/// Example of SendAppNotification
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="userId">The Id of the user to send the notification to.</param>
/// <returns>The app notification id</returns>
public static Guid SendAppNotificationExample(IOrganizationService service, Guid userId)
{
    var request = new OrganizationRequest()
    {
        RequestName = "SendAppNotification",
        Parameters = new ParameterCollection
        {
            ["Title"] = "Welcome",
            ["Recipient"] = new EntityReference("systemuser", userId),
            ["Body"] = "Welcome to the world of app notifications!",
            ["IconType"] = new OptionSetValue(100000000), //info
            ["ToastType"] = new OptionSetValue(200000000) //timed
        }
    };

    OrganizationResponse response = service.Execute(request);
    return (Guid)response.Results["NotificationId"];
}

You can use markdowns, action buttons inside notification also. Read the entire article HERE.

Hope this helps.