C#C# V4 SDK 4.8.0.0

 

These docs are for PubNub 4.0 for C# which is our latest and greatest! For the docs of the 3.x versions of the SDK, please check the links: C#, Windows 8, Windows 8.1, ASP.Net, Windows Phone 8, Windows Phone 8.1, Xamarin.iOS, Xamarin.Android, Xamarin.Mac and C# PCL.

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 Core/.Net Standard

For Universal Windows



View Supported Platforms
using PubnubApi;
 Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
pnConfiguration.Uuid = "myUniqueUUID";

	Dictionary<string, string> message = new Dictionary<string, string>();
	message.Add("msg", "hello");

	Pubnub pubnub = new Pubnub(pnConfiguration);

	SubscribeCallbackExt subscribeCallback = new SubscribeCallbackExt(
		(pubnubObj, messageResult) => {
			if (messageResult != null) {
				Debug.WriteLine("In Example, SubscribeCallback received PNMessageResult");
				Debug.WriteLine("In Example, SubscribeCallback messsage channel = " + messageResult.Channel);
				Debug.WriteLine("In Example, SubscribeCallback messsage channelGroup = " + messageResult.Subscription);
				Debug.WriteLine("In Example, SubscribeCallback messsage publishTimetoken = " + messageResult.Timetoken);
				Debug.WriteLine("In Example, SubscribeCallback messsage publisher = " + messageResult.Publisher);
				string jsonString = messageResult.Message.ToString();
				Dictionary<string, string> msg = pubnub.JsonPluggableLibrary.DeserializeToObject<Dictionary<string,string>>(jsonString);
				Debug.WriteLine("msg: " + msg["msg"]);
			}
		},
		(pubnubObj, presencResult) => {
			if (presencResult != null) {
				Debug.WriteLine("In Example, SubscribeCallback received PNPresenceEventResult");
				Debug.WriteLine(presencResult.Channel + " " + presencResult.Occupancy + " " + presencResult.Event);
			}
		},
		(pubnubObj, statusResult) => {
			if (statusResult.Category == PNStatusCategory.PNConnectedCategory) {
				pubnub.Publish()
				.Channel("my_channel")
				.Message(message)
				.Execute(new PNPublishResultExt((publishResult, publishStatus) => {
					if (!publishStatus.Error) {
						Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
					} else {
						Debug.WriteLine(publishStatus.Error);
						Debug.WriteLine(publishStatus.ErrorData.Information);
					}
				}));
			}
		}
	);

	pubnub.AddListener(subscribeCallback);

	pubnub.Subscribe<string>()
		.Channels(new string[]{ 
			"my_channel" 
		}).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.

When you init with SecretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

 Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = false;
pnConfiguration.Uuid = "myUniqueUUID";
Pubnub pubnub = new Pubnub(pnConfiguration);
//Add listener to receive Publish/Signal messages and Presence/MessageAction/Object events
SubscribeCallbackExt generalSubscribeCallack = new SubscribeCallbackExt(
    delegate (Pubnub pubnubObj, PNMessageResult<object> message) {
        // Handle new message stored in message.Message
    },
    delegate (Pubnub pubnubObj, PNPresenceEventResult presence) {
        // handle incoming presence data
    },
    delegate (Pubnub pubnubObj, PNSignalResult<object> signal) {
        // handle incoming signal data
    },
    delegate (Pubnub pnObj, PNObjectEventResult objectEvent)
    {
        if (objectEvent.Type == "uuid")
        {
            /* handle user related event. */
        }
        else if (objectEvent.Type == "chanel")
        {
            /* handle space related event. */
        }
        else if (objectEvent.Type == "membership")
        {
            /* handle membership related event. */
        }
    },
    delegate (Pubnub pubnubObj, PNMessageActionEventResult msgAction) {
        // handle incoming message action events
    },
    delegate (Pubnub pnObj, PNStatus pnStatus)
    {
        /* handle state for any errors */
    }
);
pubnub.AddListener(generalSubscribeCallack);
//Add listener to receive Signal messages
SubscribeCallbackExt signalSubscribeCallback = new SubscribeCallbackExt(
    delegate (Pubnub pubnubObj, PNSignalResult<object> message) {
        // Handle new signal message stored in message.Message
    },
    delegate (Pubnub pubnubObj, PNStatus status)
    {
        // the status object returned is always related to subscribe but could contain
        // information about subscribe, heartbeat, or errors
    }
);
pubnub.AddListener(signalSubscribeCallback);
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
    delegate (Pubnub pnObj, PNObjectEventResult objectEvent)
    {
        string channelMetadataId = objectEvent.Channel; // The channel
        string uuidMetadataId = objectEvent.Uuid; // The UUID
        string objEvent = objectEvent.Event; // The event name that occurred
        string eventType = objectEvent.Type; // The event type that occurred
        PNUuidMetadataResult uuidMetadata = objectEvent.UuidMetadata; // UuidMetadata
        PNChannelMetadataResult channelMetadata = objectEvent.ChannelMetadata; // ChannelMetadata
    },
    delegate (Pubnub pnObj, PNStatus status)
    {

    }
);
pubnub.AddListener(eventListener);
public class DevSubscribeCallback : SubscribeCallback
    {
        public override void Message<T>(Pubnub pubnub, PNMessageResult<T> message)
        {
            // Handle new message stored in message.Message
        }

        public override void Presence(Pubnub pubnub, PNPresenceEventResult presence)
        {
            // handle incoming presence data
        }

        public override void Signal<T>(Pubnub pubnub, PNSignalResult<T> signal)
        {
            // Handle new signal message stored in signal.Message
        }

        public override void Status(Pubnub pubnub, PNStatus 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;
            }
        }

        public override void ObjectEvent(Pubnub pubnub, PNObjectEventResult objectEvent)
        {
            // handle incoming user, space and membership event data
        }

        public override void MessageAction(Pubnub pubnub, PNMessageActionEventResult messageAction)
        {
            // handle incoming message action events
        }
    }

// Usage of the above listener
DevSubscribeCallback regularListener = new DevSubscribeCallback();
pubnub.AddListener(regularListener);
SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
    (pubnubObj, message) => { },
    (pubnubObj, presence) => { },
    (pubnubObj, status) => { });

pubnub.AddListener(listenerSubscribeCallack);

// some time later
pubnub.RemoveListener(listenerSubscribeCallack);
CategoryDescription
PNNetworkIssuesCategoryThe SDK is not able to reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNUnknownCategoryPubNub SDK could return this Category if the captured error is insignificant client side error or not known type at the time of SDK development.
PNBadRequestCategoryPubNub C# SDK will send PNBadRequestCategory when some parameter is missing like subscribe key, publish key.
PNTimeoutCategoryProcessing has failed because of request time out.
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()
    .Execute(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())
    .Execute(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 you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
PNResult<PNHereNowResult> herenowResponse = await pubnub.HereNow()
                                                        // tailor the next two lines to example
                                                        .Channels(new string[] {
                                                            "coolChannel",
                                                            "coolChannel2"
                                                            })
                                                        .IncludeUUIDs(true)
                                                        .ExecuteAsync();
PNHereNowResult herenowResult = herenowResponse.Result;
PNStatus status = herenowResponse.Status;
if (status.Error)
{
    // handle error
    return;
}
if (herenowResult != null && herenowResult.Channels != null && herenowResult.Channels.Count > 0)
{
    foreach (KeyValuePair<string, PNHereNowChannelData> kvp in herenowResult.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:{0}", (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 you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
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
PNResult<PNHistoryResult> historyResponse = await pubnub.History()
    .Channel("history_channel") // where to fetch history from
    .Count(100) // how many items to fetch
    .ExecuteAsync();
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();