C#C# V4 Storage & Playback API Reference for Realtime Apps

 

These docs are for PubNub 4.0 for C# which is our latest and greatest! For the docs of the 3.x versions of the SDK, please check the links: C#, Windows 8, Windows 8.1, ASP.Net, Windows Phone 8, Windows Phone 8.1, Xamarin.iOS, Xamarin.Android, Xamarin.Mac and C# PCL.

If you have questions about the PubNub for C# SDK, please contact us at support@pubnub.com.

PubNub's Storage & Playback feature enables developers to store messages as they are published, and retrieve them at a later time. Our storage layer is a time-series based database. Each published message is timestamped to the nearest 10 nanoseconds.

Learn more about our Storage & Playback feature here.


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

This function fetches historical messages of a channel.

PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated 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.

  • If you call fetchHistory() for a single channel it returns up to 25 messages by default. The count can be set to a maxium of 100 to return up to 100 messages.
  • If you call fetchHistory() for multiple channels it only returns a maximum of 25 messages per channel.
  • If you call fetchHistory() for one or more channels with includeMessageActions flag enabled, it returns a maximum of 25 messages per channel.
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 25 messages per channel even if there are more messages that meet the timetoken values.
To run Fetch History you can use the following method(s) in the C# V4 SDK
  1. ParameterTypeRequiredDescription
    Channelsstring[]YesSpecifies channel to return history messages from.
    IncludeMetaboolOptionalWhether meta (passed when Publishing the message) should be included in response or not.
    IncludeMessageActionsboolOptionalThe flag denoting to retrieve history messages with message actions.
    If true, the method is limited to one channel only.
    ReverseboolOptionalSetting to true will traverse the time line in reverse starting with the oldest message first.
    StartlongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    EndlongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    MaximumPerChannelintOptionalSpecifies the number of historical messages to return.
    Default/Maximum is 25 per channel.
    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.
Retrieve the last 25 messages on a channel:
pubnub.FetchHistory()
    .Channels(new string[] { "my_channel" })
    .IncludeMeta(true)
    .MaximumPerChannel(25)
    .Execute(new PNFetchHistoryResultExt((result, status) =>
    { 

    }));
{
"Messages":
    {"my_channel":
        [{
        "Timetoken":15717278253295153,
        "Entry":"sample message",
        "Meta":"",
        "Actions":null
        }]
    },
"More":null
}

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Removes the messages from the history of a specific channel.
 
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 Administration Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the C# V4 SDK.
  1. ParameterTypeRequiredDescription
    ChannelstringYesSpecifies channel messages to be deleted from history.
    StartlongOptionalTime token delimiting the Start of time slice (inclusive) to delete messages from.
    EndlongOptionalTime token 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.
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));
            }
        }
    ));
The DeleteMessages() operation returns a PNDeleteMessageResult which returns empty object.

  1. 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.
    pubnub.DeleteMessages()
        .Channel("history_channel")
        .Start(15526611838554309)
        .End(15526611838554310)
        .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));
                }
            }
        ));

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
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 the passed value in the ChannelsTimetokenparameter.
 For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
You can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    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 .
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));
		}
	}));
The operation returns a PNMessageCountResult which contains the following operations
MethodTypeDescription
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.
  1. pubnub.MessageCounts()
    	.Channels(new string[] { "message_count_channel", "message_count_channel2" })
    	.ChannelsTimetoken(new long[] { 15088506076921021, 15088506076921131 })
    	.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));
    		}
    	}));

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

This method is deprecated. Please use Fetch History instead.

This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated 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.
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 time token.
  • Retrieve a slice of the time line by providing both a Start AND End time token.
  • 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.
To run History you can use the following method(s) in the C# V4 SDK
  1. 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 time tokens should be included in response or not.
    StartlongOptionalTime token delimiting the Start of time slice (exclusive) to pull messages from.
    EndlongOptionalTime token 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.
Retrieve the last 100 messages on a channel:
pubnub.History()
    .Channel("history_channel") // where to fetch history from
    .Count(100) // how many items to fetch
    .Execute(new PNHistoryResultExt(
        (result, status) => {
        }
    ));
The History() operation returns a 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.
Property NameTypeDescription
TimetokenlongTimetoken of the message.
EntryobjectMessage.
  1. pubnub.History()
        .Channel("my_channel") // where to fetch history from
        .Count(3) // how many items to fetch
        .Reverse(true) // should go in reverse?
        .Execute(new PNHistoryResultExt(
            (result, status) => {
            }
        ));
    
    {
        "Messages":[
    	    {
                "Timetoken": 0,
                "Entry": "Pub1"
            },
    	    {
                "Timetoken": 0,
                "Entry": "Pub2"
            },	
    	    {
                "Timetoken": 0,
                "Entry": "Pub3"
            }
    	],
        "StartTimeToken": 13406746729185766,
        "EndTimeToken": 13406746780720711
    }
    
  2. pubnub.History()
        .Channel("my_channel") // where to fetch history from
        .Start(13847168620721752L) // first timestamp
        .Reverse(true) // should go in reverse?
        .Execute(new DemoHistoryResult());
    
    public class DemoHistoryResult : PNCallback<PNHistoryResult> {
        public override void OnResponse(PNHistoryResult result, PNStatus status) {
        }
    };
    
    {
        "Messages":[
            {
                "Timetoken": 0,
                "Entry": "Pub3"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub4"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub5"
            }
        ],
        "StartTimeToken": 13406746780720711,
        "EndTimeToken": 13406746845892666
    }
    
  3. 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?
        .Execute(new DemoHistoryResult());
    
    public class DemoHistoryResult : PNCallback<PNHistoryResult> {
        public override void OnResponse(PNHistoryResult result, PNStatus status) {
        }
    };
    
    {
        "Messages":[
            {
                "Timetoken": 0,
                "Entry": "Pub3"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub4"
            },
            {
                "Timetoken": 0,
                "Entry": "Pub5"
            }
        ],
        "StartTimeToken": 13406746780720711,
        "EndTimeToken": 13406746845892666
    }
    
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token 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 Storage & Playback 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
            }
        }
    }
  5. pubnub.History()
        .Channel("history_channel") // where to fetch history from
        .Count(100) // how many items to fetch
        .IncludeTimetoken(true) // include timetoken with each entry
        .Execute(new DemoHistoryResult());
    
    public class DemoHistoryResult : PNCallback<PNHistoryResult> {
        public override void OnResponse(PNHistoryResult result, PNStatus status) {
        }
    };