Skip to content

ChatterBox

This tutorial starts a chat application: registered users talk to each other in a public room or in private conversations, and always see who is online. It is about events, which are signals that one user's action sends to other users or to the application. It assumes that you know how to create an application, a business object and a form. If not, start with Hello World and Music Store.

In this tutorial you will:

  • Model users, groups, messages and notifications, with a user class that extends the built-in one
  • Write the small operations that the chat needs
  • Define roles and permissions
  • Create the events that tell the other users who has entered or left the chat

The tutorial prepares everything and ends where the events are created. Raising them from the forms, handling them in the other forms, and the JavaScript and the style sheets of the chat, are not covered on this page.


Create the application

Create an application from the Web Application template with .NET Core - Angular, as in Music Store, and name it ChatterBox.


The business model

Add a business object, ChatBO, with these classes and enumerations. Save after you add the enumerations, so that they appear in the list of types when you create attributes of those types.

Item Attributes
Status (enumeration) Offline, Online, Chatty, Reading
NotificationSubject (enumeration) NewMessage, StatusChanged
User Inherits ApplicationUser (set its Base Class, as in Extend the Application User). Adds Status (Status) and LastActivity (DateTime).
PrivateGroup GroupName (string), Chitter (User), Chatter (User). The identity is GroupName.
ChatMessage Text (string), Timestamp (DateTime), Sender (User), PrivateGroup (PrivateGroup; empty for a public message)
Notification Text (string), Subject (NotificationSubject), Recipient (User)

An attribute whose type is another class creates the association for you: type the attribute's name and Enter, search the type list for the class, and pick it. User sits below the many ApplicationUser... entries when you search for it.

The ChatBO model

Two settings need attention:

  • The key of PrivateGroup. Its key is the group name, a string. In Properties, set Identity to GroupName and uncheck Auto Assign Primary Key. Only int, long and Guid keys can be assigned automatically, and validation reports an error for a persisted class that tries it with another type.

Validation: the primary key must be int, long or Guid when it is auto assigned

  • Concurrency control. A chat should be quick, so you can uncheck Concurrency Control on the classes. That removes the version column and its checks.

Operations

Add these operations as in Music Store: select the class, open Operations, +, New Operation, replace the stub with the code, and save. Pay attention to which ones are static.

On User

/* Returns the currently logged in user, i.e. me */
static function Domain.User GetCurrent()
{
    return AppLib.Session.GetCurrentUser() as Domain.User;
}
/* Changes the Status of a User */
function void SetStatus(Domain.Status status)
{
    this.Status = status;
    this.LastActivity = DateTime.Now();

    this.Save();
}
/* Retrieves all Active Users (Available to Chat or Online) */
static function Collection[Domain.User] GetActiveUsers()
{
    return Domain.User.Find(x =>
        x.Status == Domain.Status.Chatty ||
        x.Status == Domain.Status.Online
    );
}
/* Retrieves the first Administrator found, to style the administrative messages */
static function Domain.User GetAdministrator()
{
    Domain.User admin =
        Domain.User.Find(x => x.Roles.First(y => y.Name == "Administrator") != null).First();

    return admin;
}

On PrivateGroup

/* Creates a unique name for a pair of users, ordering them alphabetically */
static function string GenerateGroupName(Domain.User chitter, Domain.User chatter)
{
    Collection[Domain.User] users = {chitter, chatter};
    return string.Join("_", users.OrderBy(x => x.UserName).Select(y => y.UserName));
}
/* Returns the other participant of this group, i.e. the one who is not me */
function Domain.User GetTheOtherPerson()
{
    if (this.Chitter == Domain.User.GetCurrent())
    {
        return this.Chatter;
    }

    return this.Chitter;
}
/* Returns the private groups in which the current user is a participant */
static function Collection[Domain.PrivateGroup] GetMyPrivateGroups()
{
    Collection[Domain.PrivateGroup] privateGroups =
        Domain.PrivateGroup.Find(x => x.Chitter == Domain.User.GetCurrent() || x.Chatter == Domain.User.GetCurrent()).Distinct();

    return privateGroups.OrderBy(x => x.GetTheOtherPerson().UserName);
}
/* Returns the private group of two users, and creates it if it does not exist yet */
static function Domain.PrivateGroup OpenPrivateGroup(Domain.User chitter, Domain.User chatter)
{
    //Generate the unique Name of this Private Group
    string groupName = Domain.PrivateGroup.GenerateGroupName(chitter, chatter);

    //Check whether it already exists
    Domain.PrivateGroup privateGroup = Domain.PrivateGroup.GetByKey(groupName, false);

    //If not, create it and save it
    if (privateGroup == null)
    {
        privateGroup = Domain.PrivateGroup.Create();
        privateGroup.Chitter = chitter;
        privateGroup.Chatter = chatter;
        privateGroup.GroupName = groupName;
        privateGroup.Save();
    }

    //Finally, return it to the caller
    return privateGroup;
}

On PrivateGroup and Notification

An instance may not be in the database yet when you need it. Give both classes this operation, which refreshes it when it can:

/* Re-fetch this instance from the database if possible */
function void TryRefresh()
{
    try
    {
        this.Refresh();
    }
    catch Exception x
    {
        //Hush, child....
    }
}

Save, then validate the business object. It should report no errors. GetTheOtherPerson is not in the tutorial's earlier text, but GetMyPrivateGroups needs it.


Roles and permissions

Chatters use the public and the private rooms, and administrators use only the private ones. To tell them apart, open Configuration, app, Security, and, as in My Store, part two:

  1. Add a permission named Chat.
  2. Add a role named Chatter and give it the Chat permission.

The forms

The chat uses three forms:

  • ChatRoom, the public room. Create it as an Empty Form on MasterPage, and in its Controller uncheck both availability boxes of the entry action and choose the permission Chat, so that only chatters can open it. Its model holds MyPublicMessage (string) and ChatMessages (a collection of ChatMessage). Its view has two layouts: one with the table of messages, a text area and a Send button, shown to chatters who are in the room, and one with a short text, shown to everyone else. A Conditional Formatting switches between them.
  • PrivateGroup, for a conversation of two people. Its model holds PrivateGroup, MyFriendsName, MyPrivateMessage and MyFriendsStatus. Its view is like the public room, with a header that shows who you are talking to and a Leave button. The template offers only MasterPage and MasterPageSignIn as master pages, so use MasterPage and open this form in a modal or a slide, as in Music Store.
  • MasterPage, which you change. Its model holds LoggedInUsers (users who are online), Me, Notifications, OpenPrivateGroup and PrivateGroups. Its view adds a list of the logged-in users, a list of missed notifications with delete, and the buttons Enter Chat and Leave Chat.

Note

The model items are domain properties and interface properties, as in Music Store. A property that holds a collection of a class is created as a domain property and then set with Define As Collection in its right-click menu.


Events

An event is a named signal. Code anywhere can raise it, and any form can listen for it. The Events page lists the events the platform already raises, such as SignIn and ApplicationStart, and the line you use to raise one: Events.SignIn.Raise();.

The Events page, with the events the platform provides

Create an event

Open Configuration, app, then Events. Click + and then New Event, and fill in the three parts:

  • Event Name. A unique name with no spaces. Type EnteredMainChatRoom. This event is raised when a user wants to be seen as available for chat, in the public room and in the private ones.
  • Parameters. What the event carries. Click Add..., name the parameter user, and type its data type, Domain.User. When the event is raised, the user who entered is sent with it.
  • Handler. An optional code body that runs everywhere in the application when the event is raised. It shows the signature that the parameters give: onEnteredMainChatRoom(Domain.User user). Leave it empty here.

Below the handler, Execute in parallel context is checked by default. With it checked, the event does not stop the flow that raised it: the event and the application run side by side. If you uncheck it, the application waits for the event to finish. Leave it checked for the chat events.

The EnteredMainChatRoom event with its user parameter

Save.

Entering and leaving the chat

When a user enters the chat, they get the status Chatty. When they leave it, they get Online: they have not signed out, they are just not in the mood to talk. Create the second event, LeftMainChatRoom, in the same way, with the same user parameter of type Domain.User, run in a parallel context, and with an empty handler.

The two events, together with SetStatus on User, are what the chat forms use. When a user presses Enter Chat, a controller action calls Domain.User.GetCurrent().SetStatus(Domain.Status.Chatty); and raises EnteredMainChatRoom with that user. Leave Chat does the opposite with Online and LeftMainChatRoom.