Configuration API for PubNub C# SDK
C# V4 complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Configuration
Description
PNConfiguration
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
Method(s)
To create configuration
instance you can use the following function in the C# V4 SDK:
new PNConfiguration();
Properties Type Required Description SubscribeKey
string Yes SubscribeKey
from Admin Portal.PublishKey
string Optional PublishKey
from Admin Portal (only required if publishing).SecretKey
string Optional SecretKey
(only required for access operations, keep away from Android).CipherKey
string Optional If cipher
is passed, all communications to/from PubNub will be encrypted.Uuid
string Yes UUID
to use. You should set a uniqueUUID
to identify the user or the device that connects to PubNub.
If you don't set theUUID
, you won't be able to connect to PubNub.LogVerbosity
PNLogVerbosity Yes Set PNLogVerbosity.BODY
to enable debugging. To disable debugging use the optionPNLogVerbosity.NONE
AuthKey
string Optional If Access Manager is utilized, client will use this AuthKey
in all restricted requests.Secure
bool Optional Use SSL
.SubscribeTimeout
int Optional How long to keep the subscribe
loop running before disconnect.The value is in seconds.NonSubscribeRequestTimeout
int Optional On non subscribe
operations, how long to wait for server response.The value is in seconds.FilterExpression
string Optional Feature to subscribe with a custom filter expression. HeartbeatNotificationOption
PNHeartbeatNotificationOption Optional Heartbeat
notifications, by default, the SDK will alert on failed heartbeats (equivalent to:PNHeartbeatNotificationOption.FAILURES
).
Other options such as all heartbeats (PNHeartbeatNotificationOption.ALL
) or no heartbeats (PNHeartbeatNotificationOption.NONE
) are supported.Origin
string Optional Custom Origin
if needed.ReconnectionPolicy
PNReconnectionPolicy Optional Set to PNReconnectionPolicy.LINEAR
for automatic reconnects. Use optionPNReconnectionPolicy.NONE
to disable automatic reconnects.
Use optionPNReconnectionPolicy.EXPONENTIAL
to set exponential retry interval.PresenceTimeout
int Optional The setting with set the custom presence server timeout.The value is in seconds. PresenceInterval
int Optional The setting with set the custom presence server timeout along with the custom interval to send the ping back to the server.The value is in seconds. Proxy
Proxy Optional Instruct the SDK to use a Proxy
configuration when communicating with PubNub servers.PubnubLog
IPubnubLog Optional Pass the instance of a class that implements IPubnubLog
to capture logs for troubleshooting.UseClassicHttpWebRequest
bool Optional Use HttpWebRequest
to support ASP.NET/MVC and other IIS hosting applications.EnableTelemetry
bool Optional Enables the SDK to capture analytics in terms of response time and sends them to PubNub server.
It is enabled by default.RequestMessageCountThreshold
Number Optional PNRequestMessageCountExceededCategory
is thrown when the number of messages into the payload is above ofrequestMessageCountThreshold
.SuppressLeaveEvents
bool Optional When true
the SDK doesn't send out the leave requests.DedupOnSubscribe
bool Optional When true
duplicates subscribe messages will be filtered out when devices cross regions.MaximumMessagesCacheSize
int Optional It is used with DedupOnSubscribe
to cache message size.Default is100
.FileMessagePublishRetryLimit
int Optional The number of tries made in case of Publish File Message failure.Default is 5
.UseRandomInitializationVector
bool Optional When true
the IV will be random for all requests and not just file upload. Whenfalse
the IV will be hardcoded for all requests except File Upload.Defaultfalse
.
Basic Usage
Note
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. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
// subscribeKey from Admin Portal
pnConfiguration.SubscribeKey = "SubscribeKey"; // required
// publishKey from Admin Portal (only required if publishing)
pnConfiguration.PublishKey = "PublishKey";
// secretKey (only required for access operations)
pnConfiguration.SecretKey = "SecretKey";
// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
pnConfiguration.CipherKey = "cipherKey";
// Uuid to be used as a device identifier, won't connect if not set
pnConfiguration.Uuid = "customUUID";
// Enable Debugging
pnConfigurationr.LogVebosity = PNLogVerbosity.BODY;
// if Access Manager is utilized, client will use this AuthKey in all restricted
// requests
pnConfiguration.AuthKey = "authKey";
// use SSL.
pnConfiguration.Secure = true;
// how long to keep the subscribe loop running before disconnect
pnConfiguration.SubscribeTimeout = 310;
// on non subscribe operations, how long to wait for server response
pnConfiguration.NonSubscribeRequestTimeout = 300;
// PSV2 feature to subscribe with a custom filter expression
pnConfiguration.FilterExpression = "such=wow";
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
pnConfiguration.HeartbeatNotificationOption = PNHeartbeatNotificationOption.All;
pnConfiguration.SetPresenceTimeoutWithCustomInterval(120, 59);
pnConfiguration.PresenceTimeout = 120;
// Use HttpWebRequest to support ASP.NET/MVC and other IIS hosting applications
pnConfiguration.UseClassicHttpWebRequest= true;
Initialization
using PubnubApi;
Description
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as PublishKey
and SubscribeKey
.
Method(s)
To Initialize
PubNub you can use the following method(s) in the C# V4 SDK:
new Pubnub(pnConfiguration);
Parameter Type Required Description pnConfiguration
PNConfiguration Yes Goto Configuration for more details.
Basic Usage
Initialize the PubNub client API:
Note
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. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = true;
pnConfiguration.Uuid = "myUniqueUUID";
Pubnub pubnub = new Pubnub(pnConfiguration);
Returns
It returns the PubNub instance for invoking PubNub APIs like Publish()
, Subscribe()
, History()
, HereNow()
, etc.
Other Examples
Initialize a non-secure client:
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.Secure = false; pnConfiguration.Uuid = "myUniqueUUID"; Pubnub pubnub = new Pubnub(pnConfiguration);
Initialization for a Read-Only client:
In the case where a client will only read messages and never publish to a channel, you can simply omit the
PublishKey
when initializing the client:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; Pubnub pubnub = new Pubnub(pnConfiguration);
-
Set a custom
UUID
to identify your users.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.PublishKey = "myPublishKey"; pnConfiguration.SubscribeKey = "mySubscribeKey"; pnConfiguration.Uuid = "myUniqueUUID"; Pubnub pubnub = new Pubnub(pnConfiguration);
Initializing with SSL Enabled:
This examples demonstrates how to enable PubNub Transport Layer Encryption with
SSL
. Just initialize the client withSecure
set totrue
. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.Secure = true; pnConfiguration.Uuid = "myUniqueUUID"; Pubnub pubnub = new Pubnub(pnConfiguration);
- Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Anyone with the
SecretKey
can grant and revoke permissions to your app. Never let yourSecretKey
be discovered, and to only exchange it / deliver it securely. Only use theSecretKey
on secure server-side platforms.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.For applications that will administer PAM permissions, the API is initialized with the
SecretKey
as in the following example:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.SecretKey = "my_secretkey"; pnConfiguration.Uuid = "myUniqueUUID"; pnConfiguration.Secure = true; Pubnub pubnub = new Pubnub(pnConfiguration);
Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the
SecretKey
to sign all PAM messages to the PubNub Network.
Event Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Method 1 to add listener
// Adding listener.
pubnub.AddListener(new SubscribeCallbackExt(
delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(pubMsg));
var channelName = pubMsg.Channel;
var channelGroupName = pubMsg.Subscription;
var pubTT = pubMsg.Timetoken;
var msg = pubMsg.Message;
var publisher = pubMsg.Publisher;
},
delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(presenceEvnt));
var action = presenceEvnt.Event; // Can be join, leave, state-change or timeout
var channelName = presenceEvnt.Channel; // The channel for which the message belongs
var occupancy = presenceEvnt.Occupancy; // No. of users connected with the channel
var state = presenceEvnt.State; // User State
var channelGroupName = presenceEvnt.Subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = presenceEvnt.Timestamp; // Publish timetoken
var timetoken = presenceEvnt.Timetoken; // Current timetoken
var uuid = presenceEvnt.Uuid; // UUIDs of users who are connected with the channel
},
delegate (Pubnub pnObj, PNSignalResult<object> signalMsg)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(signalMsg));
var channelName = signalMsg.Channel; // The channel for which the signal belongs
var channelGroupName = signalMsg.Subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = signalMsg.Timetoken; // Publish timetoken
var msg = signalMsg.Message; // The Payload
var publisher = signalMsg.Publisher; //The Publisher
},
delegate (Pubnub pnObj, PNObjectEventResult objectEventObj)
{
var channelName = objectEventObj.Channel; // Channel
var channelMetadata = objectEventObj.ChannelMetadata; //Channel Metadata
var uidMetadata = objectEventObj.UuidMetadata; // UUID metadata
var evnt = objectEventObj.Event; // Event
var type = objectEventObj.Type; // Event type
if (objectEventObj.Type == "uuid") {
/* got uuid metadata related event. */
}
else if (objectEventObj.Type == "channel") {
/* got channel metadata related event. */
}
else if (objectEventObj.Type == "membership") {
/* got membership related event. */
}
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(objectEventObj));
},
delegate (Pubnub pnObj, PNMessageActionEventResult msgActionEvent)
{
//handle message action
var channelName = msgActionEvent.Channel; // The channel for which the message belongs
var msgEvent = msgActionEvent.Action; // message action added or removed
var msgActionType = msgActionEvent.Event; // message action type
var messageTimetoken = msgActionEvent.MessageTimetoken; // The timetoken of the original message
var actionTimetoken = msgActionEvent.ActionTimetoken; //The timetoken of the message action
},
delegate (Pubnub pnObj, PNFileEventResult fileEvent)
{
//handle file message event
var channelName = fileEvent.Channel;
var chanelGroupName = fileEvent.Subscription;
var fieldId = (fileEvent.File != null) ? fileEvent.File.Id : null;
var fileName = (fileEvent.File != null) ? fileEvent.File.Name : null;
var fileUrl = (fileEvent.File != null) ? fileEvent.File.Url : null;
var fileMessage = fileEvent.Message;
var filePublisher = fileEvent.Publisher;
var filePubTT = fileEvent.Timetoken;
},
delegate (Pubnub pnObj, PNStatus pnStatus)
{
Console.WriteLine("{0} {1} {2}", pnStatus.Operation, pnStatus.Category, pnStatus.StatusCode);
var affectedChannelGroups = pnStatus.AffectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = pnStatus.AffectedChannels; // The channels affected in the operation, of type array.
var category = pnStatus.Category; //Returns PNConnectedCategory
var operation = pnStatus.Operation; //Returns PNSubscribeOperation
}
));
//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);
Method 2 to add listener
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);
Removing Listeners
SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
(pubnubObj, message) => { },
(pubnubObj, presence) => { },
(pubnubObj, status) => { });
pubnub.AddListener(listenerSubscribeCallack);
// some time later
pubnub.RemoveListener(listenerSubscribeCallack);
Listener status events
Category | Description |
---|---|
PNNetworkIssuesCategory | The 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. |
PNUnknownCategory | PubNub SDK could return this Category if the captured error is insignificant client side error or not known type at the time of SDK development. |
PNBadRequestCategory | PubNub C# SDK will send PNBadRequestCategory when some parameter is missing like subscribe key , publish key . |
PNTimeoutCategory | Processing 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). |
UUID
Description
These functions are used to set/get a user ID on the fly.
Property(s)
To set/get UUID
you can use the following property(s) in C# V4 SDK:
Uuid
Property | Type | Required | Description |
---|---|---|---|
Uuid | string | Yes | UUID to be used as a device identifier. If you don't set the UUID , you won't be able to connect to PubNub. |
pnConfiguration.Uuid;
This method doesn't take any arguments.
Basic Usage
Note
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. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.Uuid = "myUniqueUUID";
var customUUID = pnConfiguration.Uuid;
Authentication Key
Description
Setter and getter for users auth key.
Property(s)
AuthKey
Property | Type | Required | Description |
---|---|---|---|
AuthKey | string | Yes | If Access Manager is utilized, client will use this AuthKey in all restricted requests. |
pnConfiguration.AuthKey;
This method doesn't take any arguments.
Basic Usage
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.AuthKey = "authKey";
var sampleAuthKey = pnConfiguration.AuthKey;
Returns
Get Auth key
returns the current authentication key
.
Filter Expression
Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.
To set/get filters you can use the following property. To learn more about filtering,refer to the Publish Messages documentation.
Property(s)
FilterExpression
Property | Type | Required | Description |
---|---|---|---|
FilterExpression | string | Yes | PSV2 feature to Subscribe with a custom filter expression. |
pnConfiguration.FilterExpression;
This method doesn't take any arguments.
Basic Usage
Note
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. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.FilterExpression = "such=wow";
var sampleFilterExp = pnConfiguration.FilterExpression;