Message Persistence API for C# SDK

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see Message Persistence.

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

  • Messages
  • Message reactions
  • Files (using the File Sharing API)
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.

1try
2{
3 PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
4 .Message("Why do Java developers wear glasses? Because they can't C#.")
5 .Channel("my_channel")
6 .ExecuteAsync();
7
8 PNStatus status = publishResponse.Status;
9
10 Console.WriteLine("Server status code : " + status.StatusCode.ToString());
11}
12catch (Exception ex)
13{
14 Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
15}

Fetch history​

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Fetch historical messages from one or more channels. Use IncludeMessageActions to include message actions.

You can control how messages are returned and in what order:

  • If you specify only Start, you receive messages older than that timetoken. Start is the newer boundary of the query (exclusive).
  • If you specify only End, you receive messages newer than or equal to that timetoken. End is the older boundary of the query (inclusive).
  • If you specify both Start and End, Start must be a higher timetoken than End. Results contain messages between those timetokens, excluding the message at Start and including the message at End.
How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

You can receive up to 100 messages for a single channel. For multiple channels (up to 500), you can receive up to 25 messages per channel. If more messages match the time range, make iterative calls and adjust the Start timetoken to page through the results.

Method(s)​

Use the following method(s) in the C# SDK:

1pubnub.FetchHistory()
2 .Channels(string[])
3 .IncludeMeta(bool)
4 .IncludeMessageType(bool)
5 .IncludeCustomMessageType(bool)
6 .IncludeUUID(bool)
7 .IncludeMessageActions(bool)
8 .Reverse(bool)
9 .Start(int)
10 .End(int)
11 .MaximumPerChannel(int)
12 .QueryParam(Dictionary<string, object>)
required
Channels required#
Type: string[]
Channels to fetch history messages from (up to 500).
IncludeMeta#
Type: bool
Whether to include the meta object (if provided at publish time) in the response.
IncludeMessageType#
Type: bool
Whether to include message type. Default is true.
IncludeCustomMessageType#
Type: bool
Whether to retrieve messages with the custom message type. See Retrieving Messages.
IncludeUUID#
Type: bool
Whether to receive the publisher uuid. Default is true.
IncludeMessageActions#
Type: bool
Retrieve history messages with message actions. If true, limited to one channel and 25 messages. Default is false.
Reverse#
Type: bool
Traverse from oldest to newest when set to true.
Start#
Type: long
Newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. Must be a higher timetoken value than End when both are provided.
End#
Type: long
Older boundary of the query (inclusive). Retrieval stops at this timetoken. Must be a lower timetoken value than Start when both are provided.
MaximumPerChannel#
Type: int
Number of historical messages to return. Default and maximum are 100 for a single channel, 25 for multiple channels, and 25 if IncludeMessageActions is true.
QueryParam#
Type: Dictionary<string, object>
Pass name/value pairs as query string parameters. Useful for adding custom debug information or additional parameters required by specific PubNub features.
Execute required#
Type: PNCallback
PNCallback of type PNFetchHistoryResult.
ExecuteAsync#
Type: None
Returns PNResult<PNFetchHistoryResult>.
Truncated response

If truncated, a more property is returned; make iterative calls adjusting parameters.

Sample code​

Retrieve the last message on a channel:

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14try
15{
show all 39 lines

Returns​

1{
2 "Messages":
3 {
4 "my_channel":
5 [{
6 "Timetoken":15717278253295153,
7 "Entry":"sample message",
8 "Meta":"",
9 "Uuid":"user-1",
10 "MessageType":0,
11 "CustomMessageType":"text-message",
12 "Actions":null
13 }]
14 },
15 "More":null
show all 16 lines

Other examples​

Retrieve the last 25 messages on a channel synchronously​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14pubnub.FetchHistory()
15 .Channels(new string[] { "my_channel" })
show all 21 lines

Delete messages from history​

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Remove messages from the history of a specific channel.

Required setting

To accept delete-from-history requests, enable the Delete-From-History setting for your key in the Admin Portal and initialize the SDK with a secret key.

How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

Method(s)​

To Delete Messages from History you can use the following method(s) in the C# SDK.

1pubnub.DeleteMessages()
2 .Channel(string)
3 .Start(long)
4 .End(long)
5 .QueryParam(Dictionary<string,object>)
required
Channel required#
Type: string
Channel to delete messages from.
Start#
Type: long
Newer boundary of the query (exclusive). Must be a higher timetoken value than End when both are provided.
End#
Type: long
Older boundary of the query (inclusive). Must be a lower timetoken value than Start when both are provided.
QueryParam#
Type: Dictionary<string, object>
Pass name/value pairs as query string parameters. Useful for adding custom debug information or additional parameters required by specific PubNub features.
AsyncDeprecated#
Type: PNCallback
PNCallback of type PNDeleteMessageResult.

This parameter is deprecated and will be removed in a future version. Please use the ExecuteAsync parameter instead.
Execute required#
Type: PNCallback
PNCallback of type PNDeleteMessageResult.
ExecuteAsync#
Type: None
Returns PNResult<PNDeleteMessageResult>.

Sample code​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNDeleteMessageResult> delMsgResponse = await pubnub.DeleteMessages()
15 .Channel("history_channel")
show all 32 lines

Returns​

The DeleteMessages() operation returns a PNResult<PNDeleteMessageResult> that contains an empty PNDeleteMessageResult object.

Other examples​

Delete messages sent in a particular timeframe​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14pubnub.DeleteMessages()
15 .Channel("history_channel")
show all 29 lines

Delete specific message from history​

To delete a specific message, set End to the message’s publish timetoken and set Start to that timetoken minus 1. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNDeleteMessageResult> delMsgResponse = await pubnub.DeleteMessages()
15 .Channel("history_channel")
show all 32 lines

Message counts​

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Return the number of messages published since a given time. The count is messages with a timetoken greater than or equal to ChannelsTimetoken.

Unlimited message retention

For keys with unlimited message retention enabled, only messages from the last 30 days are counted.

Method(s)​

You can use the following method(s) in the C# SDK:

1pubnub.MessageCounts()
2 .Channels(string[])
3 .ChannelsTimetoken(long[])
4 .QueryParam(Dictionary<string, object>)
required
Channels required#
Type: string[]
Channels to fetch the message count for.
ChannelsTimetoken required#
Type: long[]
Array of timetokens, in the same order as the channels list. Specify a single timetoken to apply it to all channels; otherwise, lengths must match or the function returns a PNStatus error.
QueryParam#
Type: Dictionary<string, object>
Pass name/value pairs as query string parameters. Useful for adding custom debug information or additional parameters required by specific PubNub features.
AsyncDeprecated#
Type: PNCallback
PNCallback of type PNMessageCountResult.

This parameter is deprecated and will be removed in a future version. Please use the ExecuteAsync parameter instead.
Execute required#
Type: PNCallback
PNCallback of type PNMessageCountResult.
ExecuteAsync#
Type: None
Returns PNResult<PNMessageCountResult>.

Sample code​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNMessageCountResult> msgCountResponse = await pubnub.MessageCounts()
15 .Channels(new string[] { "message_count_channel" })
show all 30 lines

Returns​

The operation returns a PNResult<PNMessageCountResult> which contains the following properties:

Property NameTypeDescription
ResultPNMessageCountResultReturns a PNMessageCountResult object.
StatusPNStatusReturns a PNStatus object

PNMessageCountResult contains the following properties:

Property NameTypeDescription
ChannelsDictionary<string, long>Collection of channels with message counts. channels without messages have a count of 0. channels with 10,000 messages or more have a count of 10000.

Other examples​

Retrieve count of messages for a single channel​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14pubnub.MessageCounts()
15 .Channels(new string[] { "message_count_channel" })
show all 28 lines

Retrieve count of messages using different timetokens for each channel​

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNMessageCountResult> msgCountResponse = await pubnub.MessageCounts()
15 .Channels(new string[] { "message_count_channel", "message_count_channel2" })
show all 30 lines

History (deprecated)​

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Deprecated

This method is deprecated and will be removed in a future version. Please use the fetchHistory() method instead.

Fetch historical messages for a channel.

Control how messages are returned and in what order:

For example, you can:

  • Search from the newest end of the timeline (default: Reverse = false).
  • Search from the oldest end of the timeline by setting Reverse to true.
  • Page through results by providing a Start or End timetoken.
  • Retrieve a slice of the timeline by providing both a Start and End timetoken.
  • Limit the number of messages using the Count parameter.

Method(s) (deprecated)​

To run History you can use the following method(s) in the C# SDK:

1pubnub.History()
2 .Channel(string)
3 .IncludeMeta(bool)
4 .Reverse(bool)
5 .IncludeTimetoken(bool)
6 .Start(long)
7 .End(long)
8 .count(int)
9 .QueryParam(Dictionary<string,object>)
required
Channel required#
Type: string
Channel to return history messages from.
IncludeMeta#
Type: bool
Whether to include the meta object (if provided at publish time) in the response.
Reverse#
Type: bool
Traverse from oldest to newest when set to true.
IncludeTimetoken#
Type: bool
Whether to include message timetokens in the response.
Start#
Type: long
Newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. Must be a higher timetoken value than End when both are provided.
End#
Type: long
Older boundary of the query (inclusive). Retrieval stops at this timetoken. Must be a lower timetoken value than Start when both are provided.
Count#
Type: int
Number of historical messages to return.
QueryParam#
Type: Dictionary<string, object>
Pass name/value pairs as query string parameters. Useful for adding custom debug information or additional parameters required by specific PubNub features.
AsyncDeprecated#
Type: PNCallback
PNCallback of type PNHistoryResult.

This parameter is deprecated and will be removed in a future version. Please use the ExecuteAsync parameter instead.
Execute required#
Type: PNCallback
PNCallback of type PNHistoryResult.
ExecuteAsync#
Type: None
Returns PNResult<PNHistoryResult>.
Using the reverse parameter

Messages are always returned sorted in ascending time direction from history regardless of Reverse. The Reverse direction matters when you have more than 100 (or Count, if it's set) messages in the time interval, in which case Reverse determines the end of the time interval from which it should start retrieving the messages.

Sample code (deprecated)​

Retrieve the last 100 messages on a channel:

1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNHistoryResult> historyResponse = await pubnub.History()
15 .Channel("history_channel") // where to fetch history from
show all 17 lines

Returns (deprecated)​

The History() operation returns a PNResult<PNHistoryResult> which contains the following properties:

Property NameTypeDescription
ResultPNHistoryResultReturns a PNHistoryResult object.
StatusPNStatusReturns a PNStatus object.

PNHistoryResult which contains the following properties:

Property NameTypeDescription
MessagesList<PNHistoryItemResult>List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
StartTimetokenlongStart timetoken.
EndTimetokenlongEnd timetoken.
PNHistoryItemResult (deprecated)​
Property NameTypeDescription
TimetokenlongTimetoken of the message.
EntryobjectMessage.

Other examples (deprecated)​

Retrieve the last 100 messages on a channel synchronously (deprecated)​
1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14pubnub.History()
15 .Channel("history_channel") // where to fetch history from
show all 20 lines
Use history() to retrieve the three oldest messages by retrieving from the time line in reverse (deprecated)​
1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNHistoryResult> historyResponse = await pubnub.History()
15 .Channel("my_channel") // where to fetch history from
show all 18 lines
Response (deprecated)​
1{
2 "Messages":[
3 {
4 "Timetoken": 0,
5 "Entry": "Pub1"
6 },
7 {
8 "Timetoken": 0,
9 "Entry": "Pub2"
10 },
11 {
12 "Timetoken": 0,
13 "Entry": "Pub3"
14 }
15 ],
show all 18 lines
Use history() to retrieve messages newer than a given timetoken by paging from oldest message to newest message starting at a single point in time (exclusive) (deprecated)​
1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNHistoryResult> historyResponse = await pubnub.History()
15 .Channel("my_channel") // where to fetch history from
show all 18 lines
Response (deprecated)​
1{
2 "Messages":[
3 {
4 "Timetoken": 0,
5 "Entry": "Pub3"
6 },
7 {
8 "Timetoken": 0,
9 "Entry": "Pub4"
10 },
11 {
12 "Timetoken": 0,
13 "Entry": "Pub5"
14 }
15 ],
show all 18 lines
Use history() to retrieve messages until a given timetoken by paging from newest message to oldest message until a specific end point in time (inclusive) (deprecated)​
1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNHistoryResult> historyResponse = await pubnub.History()
15 .Channel("my_channel") // where to fetch history from
show all 20 lines
Response (deprecated)​
1{
2 "Messages":[
3 {
4 "Timetoken": 0,
5 "Entry": "Pub3"
6 },
7 {
8 "Timetoken": 0,
9 "Entry": "Pub4"
10 },
11 {
12 "Timetoken": 0,
13 "Entry": "Pub5"
14 }
15 ],
show all 18 lines
History paging example (deprecated)​
Usage

You can call the method by passing 0 or a valid timetoken as the argument.

1using PubnubApi;
2
3public class PubnubRecursiveHistoryFetcher {
4 private static Pubnub pubnub;
5
6 public abstract class CallbackSkeleton {
7 public abstract void HandleResponse(PNHistoryResult result);
8 }
9
10 public PubnubRecursiveHistoryFetcher() {
11 // NOTICE: for demo/demo pub/sub keys Message Persistence is disabled,
12 // so use your pub/sub keys instead
13 PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
14 pnConfiguration.SubscribeKey = "demo";
15 pubnub = new Pubnub(pnConfiguration);
show all 59 lines
Include timetoken in history response (deprecated)​
1using PubnubApi;
2
3// Configuration
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11// Initialize PubNub
12Pubnub pubnub = new Pubnub(pnConfiguration);
13
14PNResult<PNHistoryResult> historyResponse = await pubnub.History()
15 .Channel("history_channel") // where to fetch history from
show all 18 lines

Was this page useful?

Last updated on