Skip to content

.NET library for interacting with the Pusher HTTP API

License

Notifications You must be signed in to change notification settings

elverkilde/pusher-http-dotnet

 
 

Repository files navigation

Pusher Channels .NET HTTP API library

NuGet Badge Build

This is a .NET library for interacting with the Pusher Channels HTTP API.

Registering at http://pusher.com/channels and use the application credentials within your app as shown below.

Comprehensive documentation can be found at http://pusher.com/docs/channels.

Supported platforms

  • .NET Standard 1.3
  • .NET 4.5
  • Unity 2018.1

Note: from release 4.3.0 PusherServer.dll and PusherServer.Core.dll are equivalent. Applications should reference PusherServer.dll and not PusherServer.Core.dll. We have kept PusherServer.Core.dll for backwards compatibility but will be removing it in our next major release as it is now redundant.

Installation

NuGet Package

Install-Package PusherServer

How to use

Constructor

var options = new PusherOptions();
options.Cluster = APP_CLUSTER;

var pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET, options);

Please Note: the Cluster option is overridden by HostName option. So, if HostName is set then Cluster will be ignored.

Publishing/Triggering events

To trigger an event on one or more channels use the trigger function.

A single channel

ITriggerResult result = await pusher.TriggerAsync( "channel-1", "test_event", new { message = "hello world" } );

Multiple channels

ITriggerResult result = await pusher.TriggerAsync( new string[]{ "channel-1", "channel-2" ], "test_event", new { message: "hello world" } );

Batches

var events = new[]{
    new Event {Channel = "channel-1", EventName = "test_event", Data = "hello world"},
    new Event {Channel = "channel-1", EventName = "test_event", Data = "my name is bob"}
};

ITriggerResult result = await pusher.TriggerAsync(events);

Detecting event data that exceeds the 10KB threshold

Rather than relying on the server to validate message size you can now perform this client side before submitting a trigger event. Here is an example on how to do this:

IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions()
{
    HostName = Config.HttpHost,
    BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, // 10KB
});

try
{
     var events = new[]{
        new Event {Channel = "channel-1", EventName = "test_event-1", Data = "hello world"},
        new Event {Channel = "channel-2", EventName = "test_event-2", Data = new string('Q', 10 * 1024 + 1)},
    };
    await pusher.TriggerAsync(events);
}
catch (EventDataSizeExceededException eventDataSizeError)
{
    // Handle the error when event data exceeds 10KB
}

Excluding event recipients

In order to avoid the person that triggered the event also receiving it the trigger function can take an optional ITriggerOptions parameter which has a SocketId property. For more information see: https://pusher.com/docs/channels/server_api/excluding-event-recipients.

ITriggerResult result = await pusher.TriggerAsync(channel, event, data, new TriggerOptions() { SocketId = "1234.56" } );

Authenticating Private channels

To authorise your users to access private channels on Channels, you can use the Authenticate function:

var auth = pusher.Authenticate( channelName, socketId );
var json = auth.ToJson();

The json can then be returned to the client which will then use it for validation of the subscription with Channels.

For more information see: https://pusher.com/docs/channels/server_api/authenticating-users

Authenticating Presence channels

Using presence channels is similar to private channels, but you can specify extra data to identify that particular user:

var channelData = new PresenceChannelData() {
	user_id: "unique_user_id",
	user_info: new {
	  name = "Phil Leggetter"
	  twitter_id = "@leggetter"
	}
};
var auth = pusher.Authenticate( channelName, socketId, channelData );
var json = auth.ToJson();

The json can then be returned to the client which will then use it for validation of the subscription with Channels.

For more information see: https://pusher.com/docs/channels/server_api/authenticating-users

Application State

It is possible to query the state of your Pusher application using the generic Pusher.GetAsync( resource ) method and overloads.

For full details see: https://pusher.com/docs/channels/library_auth_reference/rest-api

List channels

You can get a list of channels that are present within your application:

IGetResult<ChannelsList> result = await pusher.GetAsync<ChannelsList>("/channels");

or

IGetResult<ChannelsList> result = await pusher.FetchStateForChannelsAsync<ChannelsList>();

You can provide additional parameters to filter the list of channels that is returned.

IGetResult<ChannelsList> result = await pusher.GetAsync<ChannelsList>("/channels", new { filter_by_prefix = "presence-" } );

or

IGetResult<ChannelsList> result = await pusher.FetchStateForChannelsAsync<ChannelsList>(new { filter_by_prefix = "presence-" } );

Fetch channel information

Retrieve information about a single channel:

IGetResult<object> result = await pusher.GetAsync<object>("/channels/my_channel" );

or

IGetResult<object> result = await pusher.FetchStateForChannelAsync<object>("my_channel");

Retrieve information about multiple channels:

IGetResult<object> result = await pusher.FetchStateForChannelsAsync<object>();

Note: object has been used above because as yet there isn't a defined class that the information can be serialized on to

Fetch a list of users on a presence channel

Retrieve a list of users that are on a presence channel:

IGetResult<object> result = await pusher.FetchUsersFromPresenceAsync<object>("/channels/presence-channel/users" );

or

IGetResult<object> result = await pusher.FetchUsersFromPresenceChannelAsync<object>("my_channel");

Note: object has been used above because as yet there isn't a defined class that the information can be serialized on to

WebHooks

Channels will trigger WebHooks based on the settings you have for your application. You can consume these and use them within your application as follows.

For more information see https://pusher.com/docs/channels/server_api/webhooks.

// How you get these depends on the framework you're using

// HTTP_X_PUSHER_SIGNATURE from HTTP Header
var receivedSignature = "value";

// Body of HTTP request
var receivedBody = "value";

var pusher = new Pusher(...);
var webHook = pusher.ProcessWebHook(receivedSignature, receivedBody);
if(webHook.IsValid)
{
  // The WebHook validated
  // Dictionary<string,string>[]
  var events = webHook.Events;

  foreach(var webHookEvent in webHook.Events)
  {
    var eventType = webHookEvent["name"];
    var channelName = webHookEvent["channel"];

    // depending on the type of event (eventType)
    // there may be other values in the Dictionary<string,string>
  }

}
else {
  // Log the validation errors to work out what the problem is
  // webHook.ValidationErrors
}

Debug tracing

Debug tracing is now off by default. To enable it use the new Pusher option: TraceLogger.

IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions()
{
    HostName = Config.HttpHost,
    TraceLogger = new DebugTraceLogger(),
});

Asynchronous programming

From v4.0.0 onwards, this library uses the async / await syntax from .NET 4.5+.

This means that you can now use the Channels .NET library asynchronously using the following code style:

using PusherServer;

var options = new PusherOptions();
options.Cluster = APP_CLUSTER;

var pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET, options);

Task<ITriggerResult> resultTask = pusher.TriggerAsync( "my-channel", "my-event", new { message = "hello world" } );

// You can do work here that doesn't rely on the result of TriggerAsync  
DoIndependentWork();

ITriggerResult result = await resultTask;

This also means that the library is now only officially compatible with .NET 4.5 and above (including .NET Core). If you need to support older versions of the .NET framework then you have a few options:

Please note that neither of these workarounds will be officially supported by Pusher.

Development Notes

  • Developed using Visual Studio Community 2017
  • PusherServer acceptance tests depends on PusherClient.
  • PusherServer has two variations, the original version for .NET, and a .NET Core version. The source files all live in the .NET Core folder, with links from the .NET project to these files to create the .NET version.

The Pusher application settings are now loaded from a JSON config file stored in the root of the source tree and named AppConfig.test.json. Make a copy of ./AppConfig.sample.json and name it AppConfig.test.json. Modify the contents of AppConfig.test.json with your test application settings. You should be good to run all the tests successfully.

Alternative environments

The solution can be opened and compiled in Xamarin Studio on OSX.

Alternatively, the solution can be built from the command line if Mono is installed. First of all, open up a terminal and navigate to the root directory of the solution. The second step is to restore the Nuget packages, which can be done with this command

nuget restore pusher-dotnet-server.sln

and finally build the solution, now that the packages have been restored

xbuild pusher-dotnet-server.sln

During the build, there will be a warning about a section called TestCaseManagementSettings in the GlobalSection. Please ignore this, as it is a Visual Studio specific setting.

Publish to NuGet

You should be familiar with creating and publishing NuGet packages.

From the pusher-dotnet-server directory:

  1. Update ./PusherServer/Properties/AssemblyInfo.cs and ./PusherServer.Core/Properties/AssemblyInfo.cs with new version number.
  2. Check and change any info required in PusherServer/PusherServer.nuspec.
  3. Run package.cmd to pack a package to deploy to NuGet.
  4. Run `tools/nuget.exe push PusherServer.{VERSION}.nupkg'.

License

This code is free to use under the terms of the MIT license.

About

.NET library for interacting with the Pusher HTTP API

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 99.7%
  • Other 0.3%