Simple PubNub CSharp example

PubNub_Publish_Subscribe
In this post I want to show you a very simple PubNub C# example that only does Subscribe / Publish / Unsubscribe.

PubNub is a new real-time cloud-based subscribe/publish API, it requires no servers, minimal setup and it has a cross-platform API including JS, PHP and C#.

I downloaded the sample solution, which includes PubNub clients for C# based languages, including MS Windows C#/.NET, Silveright, IIS, and Mono:

https://github.com/pubnub/c-sharp

Then this is what you have to do to make it work:

Go to http://pubnub.com/free-trial to activate a trial.

PubNub Free Trial

Activate the trial by clicking on the link in your email:

Email_PubNub2

You will be redirected to the Admin Portal:

Admin Portal PubNub2

Make note of the following keys:
– Subscribe key
– Publish key

The secret key is only needed for encrypted messages, which is not part of this demo.
Take the solution you downloaded from:

https://github.com/pubnub/c-sharp

Unzip and open the solution in:
\Downloads\c-sharp-master\c-sharp-master\csharp.net\3.4\PubNub.sln

Build the solution. Notice the PubNubMessaging.Core.exe in

\Downloads\c-sharp-master\c-sharp-master\csharp.net\3.4\PubNub-Messaging\bin\Debug\

Create a new Console Application, and add a reference to this PubNubMessaging.Core.Exe.

Now in Program.cs:

You only have to change the following constants:

// Make this up yourself
const string CHANNELNAME = “XXXXXXXXXXXXXXXX”;
// for example “pub-c-4743ca37-2480-425a-391f-ab01dbcd281a”
const string PUBLISH_KEY = “XXXXXXXXXXXXXXXXXXXXXXXXX”;
// for example “sub-c-cf6199f3-ba1a-11e2-89ba-02ee2dcab7ff”
const string SUBSCRIBE_KEY = “XXXXXXXXXXXXXXXXXXXXXXXXX”;

You can make up the Channel Name yourself.
The Publish key and Subscribe key are the keys you got in the Admin Portal.

If you want a more elaborate sample, create a new Console Application and add the package “PubNub C# Web Data Push API” to your application using the NuGet Package Manager. Then you will see the following files in your project:

PubNub.cs (the code that does the interfacing to PubNub for you)
PubNubExample.cs (the sample code)

And also a reference to “Newtonsoft.Json.dll”.
The only thing you have to do to make it work is to replace “demo”, “demo” with your Publish key and Subscribe key.

            pubnub = new Pubnub("demo", "demo", "", cipheryKey,
                (enableSSL.Trim().ToLower() == "y") ? true : false);

Happy messaging!