C#C# V4 Presence API Reference for Realtime Apps

Go to Publish & Subscribe


 

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.

Requires Presence add-on XRequires that the Presence 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.
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the HereNow() function in your application.
To call Here Now you can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDescription
    ChannelsArrayOptionalThe Channels to get the here now details.
    ChannelGroupsArrayOptionalThe ChannelGroups to get the here now details.
    IncludeStateboolOptionalIf true, the response will include the presence states of the users for Channels/ChannelGroups.
    IncludeUUIDsboolOptionalIf true, the response will include the UUIDs of the connected clients.
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    AsyncPNCallbackDeprecatedPNCallback of type PNHereNowResult.
    ExecutePNCallbackYesPNCallback of type PNHereNowResult.
pubnub.HereNow()
    // tailor the next two lines to example
    .Channels(new string[] { 
        "coolChannel",
        "coolChannel2"
     })
    .IncludeUUIDs(true)
    .Execute(new PNHereNowResultEx(
        (result, status) => {
            if (status.Error) {
                // handle error
                return;
            }

            if (result.Channels != null && result.Channels.Count > 0) {
                foreach (KeyValuePair<string, PNHereNowChannelData> kvp in result.Channels) {
                    PNHereNowChannelData channelData = kvp.Value;
                    Console.WriteLine("---");
                    Console.WriteLine("channel:" + channelData.ChannelName);
                    Console.WriteLine("occupancy:" + channelData.Occupancy);
                    Console.WriteLine("Occupants:");
                    if (channelData.Occupants != null && channelData.Occupants.Count > 0) {
                        for (int index = 0; index < channelData.Occupants.Count; index++) {
                            PNHereNowOccupantData occupant = channelData.Occupants[index];
                            Console.WriteLine(string.Format("uuid: {0}", occupant.Uuid));
                            Console.WriteLine(string.Format("state:{1}", (occupant.State != null) ?
                            pubnub.JsonPluggableLibrary.SerializeToJsonString(occupant.State) : ""));
                        }
                    }
                }
            }
        }
    ));
The HereNow() operation returns a PNHereNowResult which contains the following properties:
Property NameTypeDescription
TotalChannelsintTotal Channels.
TotalOccupancyintTotal Occupancy.
ChannelsDictionary<string, PNHereNowChannelData>A map with values of PNHereNowChannelData for each channel. See PNHereNowChannelData for more details.
Property NameTypeDescription
ChannelNamestringChannel name.
OccupancyintOccupancy of the channel.
OccupantsList<PNHereNowOccupantData>A list of PNHereNowOccupantData, see PNHereNowOccupantData for more details.
Property NameTypeDescription
UuidstringUUIDs of the user.
StateobjectState of the user.
  1. Requires Presence add-on XRequires that the Presence 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.
    pubnub.HereNow()
        .Channels(new string[] {
            // who is present on those channels?
            "my_channel"
        }) 
        .IncludeState(true) // include state with request (false by default)
        .IncludeUUIDs(true) // if false, only shows occupancy count
        .Execute(new PNHereNowResultEx(
            (result, status) => {
                //handle it
            }
        ));
    {
    	"status" : 200,
    	"message" : "OK",
    	"service" : "Presence",
    	"uuids" : [
    		{
    			"uuid" : "myUUID0"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID1"
    		},
    		{
    			"uuid" : "b9eb408c-bcec-4d34-b4c4-fabec057ad0d"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID2"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 24
    				}
    			},
    			"uuid" : "myUUID9"
    		}
    	],
    	"occupancy" : 5
    }
  2. Requires Presence add-on XRequires that the Presence 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.
    You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:
    pubnub.HereNow()
        .Channels(new string[] {
             // who is present on those channels?
            "my_channel"
        })
        .IncludeState(false) // include state with request (false by default)
        .IncludeUUIDs(false) // if false, only shows occupancy count
        .Execute(new PNHereNowResultEx(
            (result, status) => {
                //handle it
            }
        ));
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
  3. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked 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.
    You can return the list of UUIDs and occupancy for all channels by omitting the channel:
    pubnub.HereNow()
        .Channels(new string[] { 
             // who is present on those channels?
            "my_channel"
        })
        .IncludeState(false) // include state with request (false by default)
        .IncludeUUIDs(true) // if false, only shows occupancy count
        .Execute(new PNHereNowResultEx(
            (result, status) => {
                //handle it
            }
        ));
    {
        "total_channels" : 2,
        "total_occupancy" : 3,
        "channels" : {
            "lobby" : {
                "occupancy" : 1,
                "uuids" : [
                    "dara01"
                ]
            },
            "game01" : {
                "occupancy" : 2,
                "uuids" : [
                    "jason01",
                    "jason02"
                ]
            }
        }
    }
  4. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked 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.
    You can return only the occupancy information (Global Here Now) by omitting the channel name
    pubnub.HereNow()
        .IncludeState(true) // include state with request (false by default)
        .IncludeUUIDs(true) // if false, only shows occupancy count
        .Execute(new DemoHereNowResult());
    
    public class DemoHereNowResult : PNCallback<PNHereNowResult> {
        public override void OnResponse(PNHereNowResult result, PNStatus status) {
        }
    };
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
  5. pubnub.HereNow()
        .ChannelGroups(new string[] {
            // who is present on channel groups?    
            "cg1",
            "cg1",
            "cg3"
        })
        .IncludeState(true) // include state with request (false by default)
        .IncludeUUIDs(true) // if false, only shows occupancy count
        .Execute(new DemoHereNowResult());
    
    public class DemoHereNowResult : PNCallback<PNHereNowResult> {
        public override void OnResponse(PNHereNowResult result, PNStatus status) {
        }
    };
    {
    	occupancy : 4,
    	uuids : ['123123234t234f34fq3dq', '143r34f34t34fq34q34q3', '23f34d3f4rq34r34rq23q', 'w34tcw45t45tcw435tww3']
    }
Requires Presence add-on XRequires that the Presence 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.
You can obtain information about the current list of channels to which a UUID is subscribed to by calling the WhereNow() function in your application.
 
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.
To call WhereNow() you can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDescription
    UuidstringOptionalUuid.
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    AsyncCommandDeprecatedPNCallback of type PNWhereNowResult.
    ExecuteCommandYesPNCallback of type PNWhereNowResult.
You simply need to define the uuid and the callback function to be used to send the data to as in the example below.
pubnub.WhereNow()
    .Execute(new PNWhereNowResultExt(
        (result, status) => {
            // returns a pojo with channels
            // channel groups which I am part of.
        }
    ));
The WhereNow() operation returns a PNWhereNowResult which contain the following property:
Property NameTypeDescription
ChannelsList<string>The list of channels where the UUID is present.
pubnub.WhereNow()
    .Uuid("some-other-uuid") // uuid of the user we want to spy on.
    .Execute(new DemoWhereNowResult());

public class DemoWhereNowResult : PNCallback<PNWhereNowResult> {
    public override void OnResponse(PNWhereNowResult result, PNStatus status) {
        // returns a pojo with channels
        // channel groups which "some-other-uuid" part of.
    }
};
Requires Presence add-on XRequires that the Presence 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.
The state API is used to set/get key/value pairs specific to a subscriber Uuid.
State information is supplied as a Generic Dictionary object(Dictionary<string, object>) of key/value pairs.
  1. ParameterTypeRequiredDescription
    ChannelsArrayOptionalChannels to set state.
    ChannelGroupsArrayOptionalChannelGroups to set state.
    StateDictionary<string, object>OptionalState to set.
    UuidstringOptionalUuid
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    AsyncPNCallbackDeprecatedPNCallback of type PNSetStateResult.
    ExecutePNCallbackYesPNCallback of type PNSetStateResult.
  1. ParameterTypeRequiredDescription
    ChannelsArrayOptionalChannel name to fetch the state.
    ChannelGroupsArrayOptionalChannelGroups name to fetch the state.
    UuidstringOptionalUuid
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    AsyncPNCallbackDeprecatedPNCallback of type PNGetStateResult.
    ExecutePNCallbackYesPNCallback of type PNGetStateResult.
Dictionary<string, object> myState = new Dictionary<string, object>();
myState.Add("age", 20);
 
pubnub.SetPresenceState()
    .Channels(new string[] {
        "ch1",
        "ch2",
        "ch3"
    })
    .State(myState)
    .Execute(new PNSetStateResultExt(
        (result, status) => {
            // handle set state response
        }
    ));
pubnub.GetPresenceState()
    .Channels(new string[] {
        // channels to fetch state for
        "ch1",
        "ch2",
        "ch3"
    })
    .ChannelGroups(new string[] {
        // channel groups to fetch state for
        "cg1",
        "cg2",
        "cg3"
    }) 
    .Uuid("suchUUID") // uuid of user to fetch, or for own uuid
    .Execute(new PNGetStateResultExt(
        (result, status) => {
            // handle response
        }
    ));
The SetPresenceState() operation returns a PNSetStateResult which contains the following property:
Property NameTypeDescription
StateDictionary<string, object>Dictionary of UUIDs and the user states.
The GetPresenceState() operation returns a PNGetStateResult which contains the following property:
Property NameTypeDescription
StateByUUIDDictionary<string, object>Dictionary of UUIDs and the user states.
  1. Dictionary<string, object> myState = new Dictionary<string, object>();
    myState.Add("age", 20);
    
    pubnub.SetPresenceState()
        .ChannelGroups(new string[] {
            // apply on those channel groups
            "cg1",
            "cg2",
            "cg3"
        })
        .Channels(new string[] {
            // apply on those channels
            "ch1",
            "ch2",
            "ch3" 
        })
        .State(myState) // the new state   
        .Execute(new DemoPNSetStateResult());
    
    public class DemoPNSetStateResult : PNCallback<PNSetStateResult> {
        public override void OnResponse(PNSetStateResult result, PNStatus status) {
            // on new state for those channels
        }
    };
    The above code would return the following response to the client:
    {
    	first  : "Robert",
    	last   : "Plant",
    	age    : 59,
    	region : "UK"
    }

Go to Access Manager