I’ve written a .NET server event handler. The problem is that when my code hits the Notifier.StartAsync
line:
using (var notifier = await Notifier.StartAsync(config))
the program just exits and stops - it never goes into a state where it’s waiting for changes. What am I doing wrong?
This is my code:
public class Program
{
public static void Main(string[] args) => MainAsync().Wait();
public static async Task MainAsync()
{
// Login the admin user
var credentials = Credentials.UsernamePassword(Constants.RealmUsername, Constants.RealmPassword, createUser: false);
var admin = await User.LoginAsync(credentials, new Uri($"https://{Constants.RealmUrl}"));
var config = new NotifierConfiguration(admin)
{
// Add all handlers that this notifier will invoke
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), Constants.NotifierDirectory),
Handlers = { new NotesHandler() }
};
config.WorkingDirectory = config.WorkingDirectory + "/" + RandomString(10);
// Start the notifier. Your handlers will be invoked for as
// long as the notifier is not disposed.
using (var notifier = await Notifier.StartAsync(config))
{
do
{
Console.WriteLine("Type in 'exit' to quit the app.");
}
while (Console.ReadLine() != "exit");
}
}
public static string RandomString(int length)
{
Random random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
class NotesHandler : RegexNotificationHandler
{
// The regular expression you provide restricts the observed Realm files
// to only the subset you are actually interested in. This is done to
// avoid the cost of computing the fine-grained change set if it's not
// necessary.
public NotesHandler() : base($"^/{Constants.NotesRealm}$")
{
}
// The HandleChangeAsync method is called for every observed Realm file
// whenever it has changes. It is called with a change event which contains
// a version of the Realm from before and after the change, as well as
// collections of all objects which were added, deleted, or modified in this change
public override async Task HandleChangeAsync(IChangeDetails details)
{
if (details.Changes.TryGetValue("Note", out var changeSetDetails) &&
changeSetDetails.Insertions.Length > 0)
{
try
{
var notes = changeSetDetails.Insertions
.Select(i => i.CurrentObject)
.Select(o => (string)(o.Title + Environment.NewLine + o.Description))
.ToArray();
if (notes.Length == 0)
{
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
}
}