Configuration API for C# SDK

C# complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Request execution

Use try/catch when working with the C# SDK.

If a request has invalid parameters (for example, a missing required field), the SDK throws an exception. If the request reaches the server but fails (server error or network issue), the error details are available in the returned status.

try
{
PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
.Message("Why do Java developers wear glasses? Because they can't C#.")
.Channel("my_channel")
.ExecuteAsync();

PNStatus status = publishResponse.Status;

Console.WriteLine("Server status code : " + status.StatusCode.ToString());
}
catch (Exception ex)
{
Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
}

Configuration

PNConfiguration stores user-provided settings that control how the C# Software Development Kit (SDK) behaves. Use these properties to fine-tune client behavior and get a prototype running fast.

Method(s)

To create configuration instance you can use the following function in the C# SDK:


* required
ParameterDescription
SubscribeKey *
Type: string
SubscribeKey from Admin Portal.
PublishKey
Type: string
PublishKey from Admin Portal (only required if publishing).
SecretKey
Type: string
SecretKey required for access control operations.
UserId *
Type: UserId
UserId to use. The UserId object takes string as an argument. You should set a unique identifier for the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 92 alphanumeric characters.

If you don't set the UserId, you won't be able to connect to PubNub.
LogLevel
Type: PubnubLogLevel
Enum defining the level of severity captured in logs.

Available values:
  • PubnubLogLevel.Trace
  • PubnubLogLevel.Debug
  • PubnubLogLevel.Info
  • PubnubLogLevel.Warn
  • PubnubLogLevel.Error
Default: PubnubLogLevel.None (logging off). See Logging.
AuthKey
Type: string
If Access Manager is utilized, client will use this AuthKey in all restricted requests.
Secure
Type: bool
Use SSL.
SubscribeTimeout
Type: int
How long to keep the subscribe loop running before disconnect (seconds).
NonSubscribeRequestTimeout
Type: int
How long to wait for a response on non-subscribe operations (seconds).
FilterExpression
Type: string
Subscribe with a custom filter expression.
HeartbeatNotificationOption
Type: PNHeartbeatNotificationOption
Heartbeat notifications. Default: failures only (PNHeartbeatNotificationOption.FAILURES). Other options: all (PNHeartbeatNotificationOption.ALL) or none (PNHeartbeatNotificationOption.NONE).
Origin
Type: string
Custom Origin if needed.
To request a custom domain, contact support and follow the request process.
ReconnectionPolicy
Type: PNReconnectionPolicy
Custom reconnection configuration parameters. Default is PNReconnectionPolicy.EXPONENTIAL (subscribe only).

Available values:
  • PNReconnectionPolicy.NONE
  • PNReconnectionPolicy.LINEAR
  • PNReconnectionPolicy.EXPONENTIAL

For more information, refer to SDK connection lifecycle.
ConnectionMaxRetries
Type: int
Maximum reconnection attempts. If unset, the SDK does not reconnect. See Reconnection Policy.
PresenceTimeout
Type: int
How long the server considers the client alive for Presence. The SDK sends periodic heartbeats (for example, every 300 seconds) to keep the client active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the presence channel.
SetPresenceTimeoutWithCustomInterval
Type: int
How often the client sends heartbeat signals. More granular than PresenceTimeout. Recommended: (PresenceTimeout / 2) - 1.
Proxy
Type: Proxy
Instructs the SDK to use a Proxy configuration when communicating with PubNub servers.
RequestMessageCountThreshold
Type: Number
Threshold for messages per payload. Exceeding this triggers PNRequestMessageCountExceededCategory.
SuppressLeaveEvents
Type: bool
When true, the SDK does not send leave requests.
DedupOnSubscribe
Type: bool
When true, filters duplicate subscribe messages across regions.
MaximumMessagesCacheSize
Type: int
Used with DedupOnSubscribe to cache message size. Default: 100.
FileMessagePublishRetryLimit
Type: int
Retries for file message publish failures. Default: 5.
CryptoModule
Type: AesCbcCryptor(CipherKey)

LegacyCryptor(CipherKey)
The cryptography module used for encryption and decryption of messages and files. Takes the CipherKey parameter as argument.

For more information, refer to the CryptoModule section.
EnableEventEngine
Type: Boolean
True by default. Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which statuses it emits.
MaintainPresenceState
Type: Boolean
This option works only when EnableEventEngine is set to true.

Whether the custom presence state information set using pubnub.setPresenceState() should be sent every time the SDK sends a subscribe call.
RetryConfiguration
Type: RetryConfiguration
(When enableEventEngine = true) Custom reconnection configuration. Options:
  • RetryConfiguration.Linear(int delayInSecond, int maxRetry)
  • RetryConfiguration.Exponential(int minDelayInSecond, int maxDelayInSecond, int maxRetry)
See Reconnection Policy. Excluding endpoints is not supported.
LogVerbosity
Type: PNLogVerbosity
This parameter is deprecated, use LogLevel instead.

Set PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
PubnubLog
Type: IPubnubLog
This parameter is deprecated, use the SetLogger method to configure a custom logger that implements the IPubnubLogger interface.

Pass the instance of a class that implements IPubnubLog to capture logs for troubleshooting.
CipherKey
Type: string
This way of setting this parameter is deprecated, pass it to CryptoModule instead.

If cipher is passed, all communications to/from PubNub will be encrypted.
UseRandomInitializationVector
Type: bool
This way of setting this parameter is deprecated, pass it to CryptoModule instead.

When true the IV will be random for all requests and not just file upload. When false the IV will be hardcoded for all requests except File Upload. Default false.
Uuid *
Type: string
This parameter is deprecated, use userId instead.

UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.

CryptoModule

CryptoModule encrypts and decrypts messages and files. From 6.18.0 onward, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see Message Encryption and File Encryption.

If you do not explicitly set the CryptoModule in your app and have the CipherKey and UseRandomInitializationVector params set in PubNub config, the client defaults to using the legacy encryption.

For detailed encryption configuration, utility methods for encrypting/decrypting messages and files, and practical examples, see the dedicated Encryption page.

Legacy encryption with 128-bit cipher key entropy

You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Initialization

Include the code


Description

Initialize the PubNub client and set credentials such as PublishKey and SubscribeKey.

Method(s)

To Initialize PubNub you can use the following method(s) in the C# SDK:


* required
ParameterDescription
pnConfiguration *
Type: PNConfiguration
Go to Configuration for more details.

Sample code

Initialize the PubNub client API

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Returns

Returns a PubNub instance for APIs like Publish(), Subscribe(), History(), and HereNow().

Other examples

Initialize a non-secure client

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


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:

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Initializing with SSL enabled

This example shows how to enable Transport Layer Encryption (SSL). Initialize the client with Secure set to true, then subscribe and publish as usual.

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Secure your secretKey

Anyone with the SecretKey can grant and revoke permissions to your app. Never let your SecretKey be discovered, and to only exchange it / deliver it securely. Only use the SecretKey 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 Access Manager permissions, the API is initialized with the SecretKey as in the following example:

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


After initialization with SecretKey, the client can access Access Manager functions. The client signs Access Manager messages with the SecretKey.

Event listeners

PubNub SDKs provide several sources for real-time updates:

  • The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
  • The Subscription object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
  • The SubscriptionsSet object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see Publish & Subscribe.

UserId

Set or get the user ID at runtime.

Property(s)

To set/get UserId you can use the following property(s) in C# SDK:


* required
PropertyDescription
UserId *
Type: string
UserId to be used as a device identifier. If you don't set the UserId, you won't be able to connect to PubNub.
pubnub.GetCurrentUserId();

This method doesn't take any arguments.

Sample code

Set user ID

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Get user ID


Authentication key

Set and get the user authentication key.

Property(s)

pnConfiguration.AuthKey
* required
PropertyDescription
AuthKey *
Type: string
If Access Manager is utilized, client will use this AuthKey in all restricted requests.

This method doesn't take any arguments.

Sample code

Set auth key


Get auth key


Returns

Get Auth key returns the current authentication key.

Filter expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Stream filtering lets a subscriber receive only messages that match a filter. The client sets the filter, and the server applies it to block unmatched messages.

Use the following property to set or get message filters. For details, see Publish Messages.

Property(s)

FilterExpression
* required
PropertyDescription
FilterExpression *
Type: string
PSV2 feature to Subscribe with a custom filter expression.
pnConfiguration.FilterExpression;

This method doesn't take any arguments.

Sample code

Set filter expression

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.


Get filter expression


Last updated on