C# complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Request executionWe recommend using try
and catch
statements when working with the C# SDK.
If there's an issue with the provided API parameter values, like missing a required parameter, the SDK throws an exception. However, if there is a server-side API execution issue or a network problem, the error details are contained within the 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
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.
To create configuration
instance you can use the following function in the C# SDK:
* required
Parameter DescriptionSubscribeKey
*
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 theUserId
, you won't be able to connect to PubNub. LogLevel
Type: PubnubLogLevel
Available values:
PubnubLogLevel.Trace
PubnubLogLevel.Debug
PubnubLogLevel.Info
PubnubLogLevel.Warn
PubnubLogLevel.Error
PubnubLogLevel.None
, which means logging is off.
AuthKey
Type: string
If Access Manager is utilized, client will use thisAuthKey
in all restricted requests. Secure
Type: bool
UseSSL
. SubscribeTimeout
Type: int
How long to keep thesubscribe
loop running before disconnect. The value is in seconds. NonSubscribeRequestTimeout
Type: int
Onnon subscribe
operations, how long to wait for server response. The value is in seconds. FilterExpression
Type: string
Feature to subscribe with a custom filter expression.HeartbeatNotificationOption
Type: PNHeartbeatNotificationOption
Heartbeat
notifications, by default, the SDK will alert on failed heartbeats (equivalent to: PNHeartbeatNotificationOption.FAILURES
).
PNHeartbeatNotificationOption.ALL
) or no heartbeats (PNHeartbeatNotificationOption.NONE
) are supported. Origin
Type: string
CustomOrigin
if needed.
ReconnectionPolicy
Type: PNReconnectionPolicy
PNReconnectionPolicy.EXPONENTIAL
(subscribe only).
Available values:
PNReconnectionPolicy.NONE
PNReconnectionPolicy.LINEAR
PNReconnectionPolicy.EXPONENTIAL
ConnectionMaxRetries
Type: int
The maximum number of reconnection attempts. If not provided, the SDK will not reconnect.For more information, refer to Reconnection Policy.
PresenceTimeout
Type: int
Defines how long the server considers the client alive for presence. This property works similarly to the concept of long polling by sending periodic requests to the PubNub server at a given interval (like every 300 seconds). These requests ensure the client remains active on subscribed channels.If no heartbeat is received within the timeout period, the client is marked inactive, triggering a "timeout" event on the presence channel.
SetPresenceTimeoutWithCustomInterval
Type: int
Specifies how often the client will send heartbeat signals to the server. This property offers more granular control over client activity tracking thanPresenceTimeout
.
Configure this property to achieve a shorter presence timeout if needed, with the interval typically recommended to be (PresenceTimeout / 2) - 1
.
Proxy
Type: Proxy
Instructs the SDK to use aProxy
configuration when communicating with PubNub servers. RequestMessageCountThreshold
Type: Number
PNRequestMessageCountExceededCategory
is thrown when the number of messages into the payload is above of requestMessageCountThreshold
. SuppressLeaveEvents
Type: bool
Whentrue
the SDK doesn't send out the leave requests. DedupOnSubscribe
Type: bool
Whentrue
duplicates of subscribe messages will be filtered out when devices cross regions. MaximumMessagesCacheSize
Type: int
It is used withDedupOnSubscribe
to cache message size.Default is 100
. FileMessagePublishRetryLimit
Type: int
The number of tries made in case of Publish File Message failure.Default is5
. CryptoModule
Type
:
AesCbcCryptor(CipherKey)
LegacyCryptor(CipherKey)
CipherKey
parameter as argument.
For more information, refer to the CryptoModule section.
EnableEventEngine
Type: Boolean
MaintainPresenceState
Type: Boolean
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
enableEventEngine = true
) Custom reconnection configuration parameters.
Available values:
RetryConfiguration.Linear(int delayInSecond, int maxRetry)
RetryConfiguration.Exponential(int minDelayInSecond, int maxDelayInSecond, int maxRetry)
LogVerbosity
Type: PNLogVerbosity
LogLevel
instead.
Set PNLogVerbosity.BODY
to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
PubnubLog
Type: IPubnubLog
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 toCryptoModule
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 toCryptoModule
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, useuserId
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
provides encrypt/decrypt functionality for messages and files. From the 6.18.0 release on, you can configure how the actual encryption/decryption algorithms work.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.
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 entropyYou 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 codeThis 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 UserIdAlways 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.
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
.
To Initialize
PubNub you can use the following method(s) in the C# SDK:
* required
Parameter DescriptionpnConfiguration
*
Type: PNConfiguration
Go to Configuration for more details. Sample code Initialize the PubNub client API Required UserIdAlways 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.
It returns the PubNub instance for invoking PubNub APIs like Publish()
, Subscribe()
, History()
, HereNow()
, etc.
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.
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:
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.
This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL
. Just initialize the client with Secure
set to true
. 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.
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.
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 secretKeyAnyone 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:
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.
Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the SecretKey
to sign all Access Manager messages to the PubNub Network.
PubNub SDKs provide several sources for real-time updates:
Subscription
object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.SubscriptionsSet
object can receive updates for all objects for which a list of subscription objects was created.To facilitate working with those real-time update sources, PubNub SDKs use local representations of server entities that allow you to subscribe and add handlers on a per-entity basis. For more information, refer to Publish & Subscribe.
UserIdThese functions are used to set/get a user ID on the fly.
Property(s)To set/get UserId
you can use the following property(s) in C# SDK:
* required
Property DescriptionUserId
*
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 UserIdAlways 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.
Setter and getter for users auth key.
Property(s)* required
Property DescriptionAuthKey
*
Type: string
If Access Manager is utilized, client will use thisAuthKey
in all restricted requests.
This method doesn't take any arguments.
Sample code Set auth key Get auth key ReturnsGet Auth key
returns the current authentication key.
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 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 or get message filters, you can use the following property. To learn more about filtering,refer to the Publish Messages documentation.
Property(s)* required
Property DescriptionFilterExpression
*
Type: string
PSV2 feature toSubscribe
with a custom filter expression.
pnConfiguration.FilterExpression;
This method doesn't take any arguments.
Sample code Set filter expression Required UserIdAlways 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4