WebSync Tutorials - Frozen Mountain
Note: these tuturials are for WebSync 2 only.

If you are using WebSync 3, you want our WebSync 3 tutorials.

WebSync 2 Tutorials




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.
  1. Add a reference to FM.WebSync.Core (available as part of the WebSync Server downloads).
  2. Add a reference to FM.WebSync.Server (available as part of the WebSync Server downloads).
  3. 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.
  1. Modify the request handler created in the WebSync Server: Basic tutorial.
    1. Define a Data class for the purpose of deserialization.
    2. Add a method called PostPublish.
    3. 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!