Server: Advanced
In this tutorial you will learn how to persist message data after it is published on the server.
Prerequisites
Configuring your project
Before you can start coding, you need to have the correct project references.
- Add a reference to
FM.WebSync.Core (available as part of the WebSync Server downloads).
- Add a reference to
FM.WebSync.Server (available as part of the WebSync Server downloads).
- Add a reference to
System.Runtime.Serialization (available as part of the .NET Framework).
Persisting messages in a handler method
A slightly more complicated example is persisting data incoming from client publications.
-
Modify the request handler created in the WebSync Server: Basic tutorial.
- Define a
Data class for the purpose of deserialization.
- Add a method called
PostPublish.
- In this method, iterate over the messages and persist the
data.text property.
using System;
using System.IO;
using System.Runtime.Serialization;
using FM.WebSync.Server;
using FM.WebSync.Core;
namespace Tutorials
{
[HandlerProvider(ProviderType.Basic)]
public class RequestHandler : Handler<RequestHandler>
{
[DataContract]
private class Data
{
[DataMember(Name = "text")]
public string Text { get; set; }
}
[HandlerEvent(HandlerEventType.AfterPublish, HandlerEventContinue.Immediate)]
public static void PostPublish(object sender, HandlerEventArgs e)
{
foreach (Message message in e.Messages)
{
Data data = JSON.Deserialize<Data>(message.Data);
// write to file
try
{
string directory = @"C:\WebSync\";
string file = "log.txt";
string path = directory + file;
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (!File.Exists(path))
File.WriteAllText(path, data.Text + Environment.NewLine);
else
File.AppendAllText(path, data.Text + Environment.NewLine);
}
catch (Exception)
{
// whoops! check your file system permissions
continue;
}
}
}
}
}
Testing
Open up your client page in a couple windows and check C:\WebSync\log.txt for a log of all published messages!