On-Demand: Proxies
Want more control over your messages? In this tutorial, you will learn how our pre-built
proxies can be used to intercept messages, read them, and change them. The sky is the limit
with what can be done!
Note that this tutorial is specific to .NET (C#), but the principles are the same for any language.
For PHP, the proxy used in this tutorial is available as part of the
WebSync On-Demand PHP download.
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 On-Demand .NET download).
- Add a reference to
System.Runtime.Serialization (available as part of the .NET Framework).
Setting up a proxy
The first thing to do is create a proxy to handle WebSync message traffic.
- Create a new page called
RequestProxy.aspx and remove all HTML content.
- Call
Proxy.Invoke() in the code-behind and pass in a callback function.
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RequestProxy.aspx.cs" Inherits="Tutorials.RequestProxy" %>
Code-Behind:
using System;
using System.Runtime.Serialization;
using FM.WebSync.Core;
namespace Tutorials
{
public partial class RequestProxy : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProxyCallback callback = new ProxyCallback((args) =>
{
// modify messages
});
Proxy.Invoke(callback);
}
}
}
Right now, the proxy just relays messages without modifications. We'll make it more interesting in a moment.
Configuring the client
The JavaScript client has to be configured to target the proxy. In this example, we're
interested in proxying publications.
-
Modify the HTML page created in the WebSync On-Demand: Basic tutorial.
- Add a
url property to the publish() call and specify the path to the proxy.
function publishData() {
client.publish({
...
url: '/RequestProxy.aspx', // your proxy path
...
});
}
Yes, it's that easy. Now we have to make the proxy do something useful.
Modifying messages in the proxy
In this example, we're going to do take the incoming text make it upper-case.
- Define a
Data class for the purpose of deserialization.
- In the proxy callback, iterate over the messages and modify the
data property.
[DataContract]
private class Data
{
[DataMember(Name = "text")]
public string Text { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
ProxyCallback callback = new ProxyCallback((args) =>
{
foreach (Message message in args.Messages) // messages come in as array
{
if (message.IsPublish()) // type detection (currently always returns true)
{
// deserialize, modify, then reserialize the data
Data data = JSON.Deserialize<Data>(message.Data);
data.Text = data.Text.ToUpperInvariant();
message.Data = JSON.Serialize(data);
}
}
});
Proxy.Invoke(callback);
}
Testing
Open the page in a couple browser windows. Watch as the publications are upper-cased before delivery!