PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

c-Sharp

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Files
    • Message Actions
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support

Message Persistence API for PubNub C# SDK

The PubNub Message Persistence Service provides real-time access to history for all messages published to PubNub. Each published message is timestamped to the nearest 10 nanoseconds, and is stored across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption, ensuring that they are not readable while stored on PubNub's network.

Messages can be stored for a configurable duration or forever, as controlled by the retention policy that is configured on your account. The following options are available: 1, 3, 5, 7, 15, or 30 days, and Forever.

Fetch History

Requires Message Persistence add-onRequires that the Message Persistence 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

This function fetches historical messages from one or multiple channels. The includeMessageActions flag also allows you to fetch message actions along with the messages.

It's possible to control how messages are returned and in what order.

  • if you specify only the start parameter (without end), you will receive messages that are older than the start timetoken
  • if you specify only the end parameter (without start), you will receive messages from that end timetoken and newer
  • if you specify values for both start and end parameters, you will retrieve messages between those timetokens (inclusive of the end value)

You will receive a maximum of 100 messages for a single channel or 25 messages for multiple channels (up to 500). If more messages meet the timetoken criteria, make iterative calls while adjusting the start timetoken to fetch the entire list of messages from storage.

Method(s)

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

pubnub.FetchHistory().Channels(string[]).IncludeMeta(bool).IncludeMessageType(bool).IncludeUUID(bool).IncludeMessageActions(bool).Reverse(bool).Start(int).End(int).MaximumPerChannel(int).QueryParam(Dictionary<string, object>)
ParameterTypeRequiredDescription
Channelsstring[]YesSpecifies channel to return history messages from. Maximum of 500 channels are allowed.
IncludeMetaboolOptionalWhether meta (passed when Publishing the message) should be included in response or not.
IncludeMessageTypeboolOptionalPass true to receive the message type with each history message. Default is true.
IncludeUUIDboolOptionalPass true to receive the publisher uuid with each history message. Default is true.
IncludeMessageActionsboolOptionalThe flag denoting to retrieve history messages with message actions. If true, the method is limited to one channel only. Default is false
ReverseboolOptionalSetting to true will traverse the time line in reverse starting with the oldest message first.
StartlongOptionalTimetoken delimiting the start of time slice (exclusive) to pull messages from.
EndlongOptionalTimetoken delimiting the end of time slice (inclusive) to pull messages from.
MaximumPerChannelintOptionalSpecifies the number of historical messages to return. Default and maximum is 100 for a single channel, 25 for multiple channels, and 25 if IncludeMessageActions is true.
QueryParamDictionary<string, object>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
ExecutePNCallbackYesPNCallback of type PNFetchHistoryResult.
ExecuteAsyncNoneOptionalReturns PNResult<PNFetchHistoryResult>.
Truncated response

If you fetch messages with messages actions, the number of messages in the response may be truncated when internal limits are hit. If the response is truncated, a more property will be returned with additional parameters. Send iterative calls to history adjusting the parameters to fetch more messages.

Basic Usage

Retrieve the last message on a channel:

PNResult<PNFetchHistoryResult> fetchHistoryResponse = await pubnub.FetchHistory()
    .Channels(new string[] { "my_channel" })
    .IncludeMeta(true)
    .MaximumPerChannel(25)
    .ExecuteAsync();

Returns

{
    "Messages":
        {
            "my_channel":
            [{
                "Timetoken":15717278253295153,
                "Entry":"sample message",
                "Meta":"",
                "Uuid":"user-1",
                "MessageType":null,
                "Actions":null
            }]
        },
    "More":null
}

Other Examples

  1. Retrieve the last 25 messages on a channel synchronously:

    pubnub.FetchHistory()
        .Channels(new string[] { "my_channel" })
        .IncludeMeta(true)
        .MaximumPerChannel(25)
        .Execute(new PNFetchHistoryResultExt((result, status) =>
        {
    
        }));
    

Delete Messages from History

Requires Message Persistence add-onRequires that the Message Persistence 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

Removes the messages from the history of a specific channel.

Note

There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.

Requires Initialization with secret key.

Method(s)

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

pubnub.DeleteMessages().Channel(string).Start(long).End(long).QueryParam(Dictionary<string,object>)
ParameterTypeRequiredDescription
ChannelstringYesSpecifies channel messages to be deleted from history.
StartlongOptionalTimetoken delimiting the Start of time slice (inclusive) to delete messages from.
EndlongOptionalTimetoken delimiting the End of time slice (exclusive) to delete messages from.
QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
AsyncPNCallbackDeprecatedPNCallback of type PNDeleteMessageResult.
ExecutePNCallbackYesPNCallback of type PNDeleteMessageResult.
ExecuteAsyncNoneOptionalReturns PNResult<PNDeleteMessageResult>.

Basic Usage

PNResult<PNDeleteMessageResult> delMsgResponse = await pubnub.DeleteMessages()
    .Channel("history_channel")
    .Start(15088506076921021)
    .End(15088532035597390)
    .ExecuteAsync();

PNDeleteMessageResult delMsgResult = delMsgResponse.Result;
PNStatus status = delMsgResponse.Status;

if (status != null && status.Error)
{
    //Check for any error
    Console.WriteLine(status.ErrorData.Information);
}
else if (delMsgResult != null)
{
    //Expect empty object
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(delMsgResult));
}

Returns

The DeleteMessages() operation returns a PNResult<PNDeleteMessageResult> which returns empty PNDeleteMessageResult object.

Other Examples

  1. Delete messages sent in a particular timeframe

    pubnub.DeleteMessages()
        .Channel("history_channel")
        .Start(15088506076921021)
        .End(15088532035597390)
        .Execute(new PNDeleteMessageResultExt(
            (result, status) => {
                if (status != null && status.Error) {
                    //Check for any error
                    Console.WriteLine(status.ErrorData.Information);
                }
                else if (result != null) {
                    //Expect empty object
                    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                }
            }
        ));
    
  2. Delete specific message from history
    To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. e.g. if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.

    PNResult<PNDeleteMessageResult> delMsgResponse = await pubnub.DeleteMessages()
        .Channel("history_channel")
        .Start(15526611838554310)
        .End(15526611838554309)
        .ExecuteAsync();
    
    PNDeleteMessageResult delMsgResult = delMsgResponse.Result;
    PNStatus status = delMsgResponse.Status;
    
    if (status != null && status.Error)
    {
        //Check for any error
        Console.WriteLine(status.ErrorData.Information);
    }
    else if (delMsgResult != null)
    {
        //Expect empty object
        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(delMsgResult));
    }
    

Message Counts

Requires Message Persistence add-onRequires that the Message Persistence 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

Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than or equal to than the passed value in the ChannelsTimetokenparameter.

Note

For keys with unlimited message retention enabled, this method considers only messages published in the last 30 days.

Method(s)

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

pubnub.MessageCounts().Channels(string[]).ChannelsTimetoken(long[]).QueryParam(Dictionary<string, object>)
ParameterTypeRequiredDescription
Channelsstring[]YesThe channels to fetch the message count
ChannelsTimetokenlong[]YesArray of timetokens, in order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the function returns a PNStatuswith an error flag.
AsyncPNCallbackDeprecatedPNCallback of type PNMessageCountResult.
ExecutePNCallbackYesPNCallback of type PNMessageCountResult.
ExecuteAsyncNoneOptionalReturns PNResult<PNMessageCountResult>.

Basic Usage

PNResult<PNMessageCountResult> msgCountResponse = await pubnub.MessageCounts()
    .Channels(new string[] { "message_count_channel" })
    .ChannelsTimetoken(new long[] { 15088506076921021 })
    .ExecuteAsync();

PNMessageCountResult msgCountResult = msgCountResponse.Result;
PNStatus status = msgCountResponse.Status;

if (status != null && status.Error)
{
    //Check for any error
    Console.WriteLine(status.ErrorData.Information);
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(msgCountResult));
}

Returns

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

Property NameTypeDescription
ResultPNMessageCountResultReturns a PNMessageCountResult object.
StatusPNStatusReturns a PNStatus object

PNMessageCountResult contains the following properties:

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

Other Examples

  1. Retrieve count of messages for a single channel

    pubnub.MessageCounts()
        .Channels(new string[] { "message_count_channel" })
        .ChannelsTimetoken(new long[] { 15088506076921021 })
        .Execute(new PNMessageCountResultExt(
        (result, status) => {
            if (status != null && status.Error)
            {
                //Check for any error
                Console.WriteLine(status.ErrorData.Information);
            }
            else
            {
                Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
            }
        }));
    
  2. Retrieve count of messages using different timetokens for each channel

    PNResult<PNMessageCountResult> msgCountResponse = await pubnub.MessageCounts()
        .Channels(new string[] { "message_count_channel", "message_count_channel2" })
        .ChannelsTimetoken(new long[] { 15088506076921021, 15088506076921131 })
        .ExecuteAsync();
    
    PNMessageCountResult msgCountResult = msgCountResponse.Result;
    PNStatus status = msgCountResponse.Status;
    
    if (status != null && status.Error)
    {
        //Check for any error
        Console.WriteLine(status.ErrorData.Information);
    }
    else
    {
        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(msgCountResult));
    }
    

History (deprecated)

Requires Message Persistence add-onRequires that the Message Persistence 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

This method is deprecated. Use fetch history instead.

Description

This function fetches historical messages of a channel.

It is possible to control how messages are returned and in what order, for example you can:

  • Search for messages starting on the newest end of the timeline (default behavior - Reverse = false)
  • Search for messages 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 time line by providing both a Start AND End timetoken.
  • Limit the number of messages to a specific quantity using the Count parameter.
Start & End parameter usage clarity:

If only the Start parameter is specified (without End), you will receive messages that are older than and up to that Start timetoken value. If only the End parameter is specified (without Start) you will receive messages that match that End timetoken value and newer Specifying values for both Start and End parameters will return messages between those timetoken values (inclusive on the End value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the Start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.

Method(s)

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

pubnub.History().Channel(string).IncludeMeta(bool).Reverse(bool).IncludeTimetoken(bool).Start(long).End(long).count(int).QueryParam(Dictionary<string,object>)
ParameterTypeRequiredDescription
ChannelstringYesSpecifies Channelto return history messages from.
IncludeMetaboolOptionalWhether meta (passed when Publishing the message) should be included in response or not.
ReverseboolOptionalSetting to true will traverse the time line in reverse starting with the oldest message first.
IncludeTimetokenboolOptionalWhether event dates timetokens should be included in response or not.
StartlongOptionalTimetoken delimiting the Start of time slice (exclusive) to pull messages from.
EndlongOptionalTimetoken delimiting the End of time slice (inclusive) to pull messages from.
CountintOptionalSpecifies the number of historical messages to return.
QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
AsyncPNCallbackDeprecatedPNCallback of type PNHistoryResult.
ExecutePNCallbackYesPNCallback of type PNHistoryResult.
ExecuteAsyncNoneOptionalReturns 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.

Basic Usage

Retrieve the last 100 messages on a channel:

PNResult<PNHistoryResult> historyResponse = await pubnub.History()
    .Channel("history_channel") // where to fetch history from
    .Count(100) // how many items to fetch
    .ExecuteAsync();

Returns

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
MessagesListList of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
StartTimetokenlongStart timetoken.
EndTimetokenlongEnd timetoken.

PNHistoryItemResult:

Property NameTypeDescription
TimetokenlongTimetoken of the message.
EntryobjectMessage.

Other Examples

  1. Retrieve the last 100 messages on a channel synchronously:

    pubnub.History()
        .Channel("history_channel") // where to fetch history from
        .Count(100) // how many items to fetch
        .Execute(new PNHistoryResultExt(
            (result, status) => {
            }
        ));
    
  2. Use History() to retrieve the three oldest messages by retrieving from the time line in reverse:

    PNResult<PNHistoryResult> historyResponse = await pubnub.History()
        .Channel("my_channel") // where to fetch history from
        .Count(3) // how many items to fetch
        .Reverse(true) // should go in reverse?
        .ExecuteAsync();
    

    Response:

    {
        "Messages":[
            {
                "Timetoken": 0,
                "Entry": "Pub1"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub2"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub3"
            }
        ],
        "StartTimeToken": 13406746729185766,
        "EndTimeToken": 13406746780720711
    }
    
  3. 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):

    PNResult<PNHistoryResult> historyResponse = await pubnub.History()
        .Channel("my_channel") // where to fetch history from
        .Start(13847168620721752L) // first timestamp
        .Reverse(true) // should go in reverse?
        .ExecuteAsync();
    

    Response:

    {
        "Messages":[
            {
                "Timetoken": 0,
                "Entry": "Pub3"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub4"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub5"
            }
        ],
        "StartTimeToken": 13406746780720711,
        "EndTimeToken": 13406746845892666
    }
    
  4. 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):

    PNResult<PNHistoryResult> historyResponse = await pubnub.History()
        .Channel("my_channel") // where to fetch history from
        .Count(100) // how many items to fetch
        .Start(-1) // first timestamp
        .End(13847168819178600L) // last timestamp
        .Reverse(true) // should go in reverse?
        .ExecuteAsync();
    

    Response:

    {
        "Messages":[
            {
                "Timetoken": 0,
                "Entry": "Pub3"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub4"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub5"
            }
        ],
        "StartTimeToken": 13406746780720711,
        "EndTimeToken": 13406746845892666
    }
    
  5. History Paging Example

    Usage!

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

    public class PubnubRecursiveHistoryFetcher {
        private static Pubnub pubnub;
    
        public abstract class CallbackSkeleton {
            public abstract void HandleResponse(PNHistoryResult result);
        }
    
        public PubnubRecursiveHistoryFetcher() {
            // NOTICE: for demo/demo pub/sub keys Message Persistence is disabled,
            // so use your pub/sub keys instead
            PNConfiguration pnConfiguration = new PNConfiguration();
            pnConfiguration.SubscribeKey = "demo";
            pubnub = new Pubnub(pnConfiguration);
        }
    
        static public void Main() {
            PubnubRecursiveHistoryFetcher fetcher = new PubnubRecursiveHistoryFetcher();
            GetAllMessages(new DemoCallbackSkeleton());
        }
    
        public static void GetAllMessages(CallbackSkeleton callback) {
            GetAllMessages(-1L, callback);
        }
    
        public static void GetAllMessages(long startTimestamp, CallbackSkeleton callback) {
            CountdownEvent latch = new CountdownEvent(1);
    
            pubnub.History()
                .Channel("history_channel") // where to fetch history from
                .Count(100) // how many items to fetch
                .Start(startTimestamp) // first timestamp
                .Execute(new DemoHistoryResult(callback));
        }
    
        public class DemoHistoryResult : PNCallback<PNHistoryResult> {
            CallbackSkeleton internalCallback;
            public DemoHistoryResult(CallbackSkeleton callback) {
                this.internalCallback = callback;
            }
            public override void OnResponse(PNHistoryResult result, PNStatus status) {
                if (!status.Error && result != null && result.Messages != null && result.Messages.Count > 0) {
                    Console.WriteLine(result.Messages.Count);
                    Console.WriteLine("start:" + result.StartTimeToken.ToString());
                    Console.WriteLine("end:" + result.EndTimeToken.ToString());
    
                    internalCallback.HandleResponse(result);
                    GetAllMessages(result.EndTimeToken, this.internalCallback);
                }
            }
        };
    
        public class DemoCallbackSkeleton : CallbackSkeleton {
            public override void HandleResponse(PNHistoryResult result) {
                //Handle the result
            }
        }
    }
    
  6. Include timetoken in history response:

    PNResult<PNHistoryResult> historyResponse = await pubnub.History()
        .Channel("history_channel") // where to fetch history from
        .Count(100) // how many items to fetch
        .IncludeTimetoken(true) // include timetoken with each entry
        .ExecuteAsync();
    
← Channel GroupsMobile Push →
  • Fetch History
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • Delete Messages from History
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • Message Counts
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • History (deprecated)
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
© PubNub Inc. - Privacy Policy