Feedback

C#PubNub C# V4 SDK 4.0.1.3

 

These docs are for PubNub 4.0 for C# which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.x for C#.

If you have questions about the PubNub for C# SDK, please contact us at support@pubnub.com.

For .Net 3.5/4.0/4.5/4.61

For Xamarin.Android, Xamarin.iOS and .Net Standard

For Universal Windows




using PubnubApi;
static public Pubnub pubnub;
 
static public void Main() {
    PNConfiguration config = new PNConfiguration();
    config.SubscribeKey = "demo";
    config.PublishKey = "demo";

    pubnub = new Pubnub(config);
    pubnub.AddListener(new SubscribeCallbackExt(
        (pubnubObj, message) => {
            // Handle new message stored in message.Message
            if (message != null) {
                if (message.Channel != null) {
                    // Message has been received on channel group stored in
                    // message.Channel()
                } else {
                    // Message has been received on channel stored in
                    // message.Subscription()
                }

                /*
                    log the following items with your favorite logger
                        - message.Message()
                        - message.Subscription()
                        - message.Timetoken()
                */
            }
        },
        (pubnubObj, presence) => { },
        (pubnubObj, status) => {
            if (status.Category == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                // This event happens when radio / connectivity is lost
            } else if (status.Category == PNStatusCategory.PNConnectedCategory) {
                // Connect event. You can do stuff like publish, and know you'll get it.
                // Or just use the connected event to confirm you are subscribed for
                // UI / internal notifications, etc

                pubnub.Publish()
                    .Channel("awesomeChannel")
                    .Message("hello!!")
                    .Async(new PNPublishResultExt((publishResult, publishStatus) => {
                        // Check whether request successfully completed or not.
                        if (!publishStatus.Error) {
                            // Message successfully published to specified channel.
                        } else {
                            // Request processing failed.

                            // Handle message publish error. Check 'Category' property to find out possible issue
                            // because of which request did fail.
                        }
                    }));
            }
            else if (status.Category == PNStatusCategory.PNReconnectedCategory) {
                // Happens as part of our regular operation. This event happens when
                // radio / connectivity is lost, then regained.
            } else if (status.Category == PNStatusCategory.PNDecryptionErrorCategory) {
                // Handle messsage decryption error. Probably client configured to
                // encrypt messages and on live data feed it received plain text.
            }
        }
    ));

    pubnub.Subscribe<string>()
        .Channels(new string[] {
            "awesomeChannel"
        })
        .Execute();
}
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Instantiate a new Pubnub instance. Only the SubscribeKey is mandatory. Also include PublishKey if you intend to publish from this instance, and the SecretKey if you wish to perform PAM administrative operations from this C# V4 instance.
 
For security reasons you should only include the secret-key on a highly secured server. The secret-key is only required for granting rights using our Access Manager.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = false;

Pubnub pubnub = new Pubnub(pnConfiguration);
SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
    (pubnubObj, message) => { 
        // Handle new message stored in message.Message 
    },
    (pubnubObj, presence) => { 
        // handle incoming presence data 
    },
    (pubnubObj, status) => {
        // the status object returned is always related to subscribe but could contain
        // information about subscribe, heartbeat, or errors
        // use the PNOperationType to switch on different options
        switch (status.Operation) {
            // let's combine unsubscribe and subscribe handling for ease of use
            case PNOperationType.PNSubscribeOperation:
            case PNOperationType.PNUnsubscribeOperation:
                // note: subscribe statuses never have traditional
                // errors, they just have categories to represent the
                // different issues or successes that occur as part of subscribe
                switch (status.Category) {
                    case PNStatusCategory.PNConnectedCategory:
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                    break;
                    case PNStatusCategory.PNReconnectedCategory:
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                    break;
                    case PNStatusCategory.PNDisconnectedCategory:
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                    break;
                    case PNStatusCategory.PNUnexpectedDisconnectCategory:
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                    break;
                    case PNStatusCategory.PNAccessDeniedCategory:
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                    break;
                    default:
                        // More errors can be directly specified by creating explicit cases for other
                        // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                    break;
                }
            break;
            case PNOperationType.PNHeartbeatOperation:
                // heartbeat operations can in fact have errors, so it is important to check first for an error.
                if (status.Error) {
                    // There was an error with the heartbeat operation, handle here
                } else {
                    // heartbeat operation was successful
                }
            break;
            default:
                // Encountered unknown status type
            break;
        }
    });

pubnub.AddListener(listenerSubscribeCallack);
SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
    (pubnubObj, message) => { },
    (pubnubObj, presence) => { },
    (pubnubObj, status) => { });

pubnub.AddListener(listenerSubscribeCallack);

// some time later
pubnub.RemoveListener(listenerSubscribeCallack);
CategoriesDescription
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
Call Time to verify the client connectivity to the origin:
pubnub.Time()
    .Async(new PNTimeResultExt(
        (result, status) => {
            // handle time result.
        }
    ));
pubnub.Subscribe<string>()
    .Channels(new string[] {
        // subscribe to channels
        "my_channel" 
     })
    .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Publish a message to a channel:
string[] arrayMessage = new string[] {
    "hello",
    "there"
};
 
pubnub.Publish()
    .Channel("suchChannel")
    .Message(arrayMessage.ToList())
    .Async(new PNPublishResultExt(
        (result, status) => {
            // handle publish result, status always present, result if successful
            // status.Error to see if error happened
        }
    ));
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.HereNow()
    // tailor the next two lines to example
    .Channels(new string[] { 
        "coolChannel",
        "coolChannel2"
     })
    .IncludeUUIDs(true)
    .Async(new PNHereNowResultEx(
        (result, status) => {
            if (status.Error) {
                // handle error
                return;
            }

            if (result.Channels != null && result.Channels.Count > 0) {
                foreach (KeyValuePair<string, PNHereNowChannelData> kvp in result.Channels) {
                    PNHereNowChannelData channelData = kvp.Value;
                    Console.WriteLine("---");
                    Console.WriteLine("channel:" + channelData.ChannelName);
                    Console.WriteLine("occupancy:" + channelData.Occupancy);
                    Console.WriteLine("Occupants:");
                    if (channelData.Occupants != null && channelData.Occupants.Count > 0) {
                        for (int index = 0; index < channelData.Occupants.Count; index++) {
                            PNHereNowOccupantData occupant = channelData.Occupants[index];
                            Console.WriteLine(string.Format("uuid: {0}", occupant.Uuid));
                            Console.WriteLine(string.Format("state:{1}", (occupant.State != null) ?
                            pubnub.JsonPluggableLibrary.SerializeToJsonString(occupant.State) : ""));
                        }
                    }
                }
            }
        }
    ));
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.Subscribe<string>()
    .Channels(new string[] {
        // subscribe to channels
        "my_channel" 
    })
    .WithPresence() // also subscribe to related presence information
    .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.History()
    .Channel("history_channel") // where to fetch history from
    .Count(100) // how many items to fetch
    .Async(new PNHistoryResultExt(
        (result, status) => {
        }
    ));
pubnub.Unsubscribe<string>()
     .Channels(new string[] {
        "my_channel"
     })
     .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

For more details, please see the Destroy section.

pubnub.Destroy();