### Get entities with GetEntities method and response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md This snippet shows the GetEntities method signature and a complete self-contained example that fetches entities of class "product" with sorting and limit. The example configures PubNub with demo keys)Skip execution requires a valid UserId and network access. The response JSON shows the expected successful output including entity details and pagination metadata when the request succeeds. ```csharp pubnub.DataSync.GetEntities(GetEntitiesParameters parameters) ``` ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.GetEntities(new GetEntitiesParameters { EntityClass = "product", Sort = "price:desc", Limit = 20, }); if (!response.Status.Error) { Console.WriteLine(response.Result.Data.Count); } else { Console.WriteLine($"Request can't be executed due to error: {response.Status.ErrorData.Information}"); } } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` ```json { "status": 200, "data": [ { "id": "product-sneaker-42", "entityClass": "product", "entityClassVersion": 1, "entityClassLevel": "SubKey", "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 }, "createdAt": "2026-07-13T09:15:00.000Z", "updatedAt": "2026-07-13T09:15:00.000Z", "eTag": "QrStUvWxYzAbCd" } ], "meta": { "next_cursor": null, "has_next": false, "limit": 20 } } ``` -------------------------------- ### Get Entity: Sample code with response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md Self-contained example that retrieves an entity by its Id. It includes the necessary imports, configuration, and error handling. The response shows the entity's data, including payload, timestamps, and eTag. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.GetEntity(new GetEntityParameters { Id = "product-sneaker-42", }); if (!response.Status.Error) { Console.WriteLine(response.Result.Id); } else { Console.WriteLine($"Request can't be executed due to error: {response.Status.ErrorData.Information}"); } } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` ```json { "status": 200, "data": { "id": "product-sneaker-42", "entityClass": "product", "entityClassVersion": 1, "entityClassLevel": "SubKey", "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 }, "createdAt": "2026-07-13T09:15:00.000Z", "updatedAt": "2026-07-13T09:15:00.000Z", "eTag": "QrStUvWxYzAbCd" } } ``` -------------------------------- ### Response for start timetoken retrieval (deprecated) Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/storage-and-playback.md Shows the JSON response for the previous example, containing messages Pub3, Pub4, and Pub5 with start and end timetokens. ```json { "Messages":[ { "Timetoken": 0, "Entry": "Pub3" }, { "Timetoken": 0, "Entry": "Pub4" }, { "Timetoken": 0, "Entry": "Pub5" } ], "StartTimeToken": 13406746780720711, "EndTimeToken": 13406746845892666 } ``` -------------------------------- ### Sample code: Create and subscribe a SubscriptionSet Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Complete example showing configuration, initialization, creating a single channel subscription, and creating a SubscriptionSet with channels, channel groups, and presence events enabled, then subscribing. ```csharp using PubnubApi; using PubnubApi.EndPoint; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); Subscription subscription1 = pubnub.Channel("channelName").Subscription(); subscription1.Subscribe(); SubscriptionSet subscriptionSet = pubnub.SubscriptionSet( new string[] { "channel1", "channel2" }, new string[] { "channel_group_1", "channel_group_2" }, SubscriptionOptions.ReceivePresenceEvents ); subscriptionSet.Subscribe(); ``` -------------------------------- ### Retrieve messages newer than a timetoken with Start() and Reverse(true) (deprecated) Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/storage-and-playback.md Fetches messages newer than a given start timetoken by paging from oldest to newest. Uses Start(13847168620721752L) and Reverse(true) to get messages after that point. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); PNResult historyResponse = await pubnub.History() .Channel("my_channel") // where to fetch history from .Start(13847168620721752L) // first timestamp .Reverse(true) // should go in reverse? .ExecuteAsync(); ``` -------------------------------- ### Unsubscribe sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Complete example showing how to create a subscription and subscription set, subscribe, and then unsubscribe. ```csharp using PubnubApi; using PubnubApi.EndPoint; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); Subscription subscription1 = pubnub.Channel("channelName").Subscription(); SubscriptionSet subscriptionSet = pubnub.SubscriptionSet( new string[] { "channel1", "channel2" }, new string[] { "channel_group_1", "channel_group_2" }, SubscriptionOptions.ReceivePresenceEvents ); subscription1.Subscribe(); subscriptionSet.Subscribe(); subscription1.Unsubscribe(); subscriptionSet.Unsubscribe(); ``` -------------------------------- ### Sample code for adding listeners Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Complete example showing how to add listeners to a subscription and a subscription set. It demonstrates using SubscribeCallbackExt for multiple event types and the onSignal event for signals. ```csharp using PubnubApi; using PubnubApi.EndPoint; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); Subscription subscription1 = pubnub.Channel("channelName").Subscription(); SubscriptionSet subscriptionSet = pubnub.SubscriptionSet( new string[] { "channel1", "channel2" }, new string[] { "channel_group_1", "channel_group_2" }, SubscriptionOptions.ReceivePresenceEvents ); SubscribeCallbackExt eventListener = new SubscribeCallbackExt( delegate(Pubnub pn, PNMessageResult messageEvent) { Console.WriteLine($"received message {messageEvent.Message}"); }, delegate(Pubnub pn, PNPresenceEventResult e) { Console.WriteLine("Presence event"); }, delegate(Pubnub pn, PNStatus s) { Console.WriteLine("Status event"); } ); subscription1.AddListener(eventListener); subscriptionSet.onSignal += (Pubnub pn, PNSignalResult signalEvent) => { Console.WriteLine($"Message received {signalEvent.Message}"); }; subscription1.Subscribe(); subscriptionSet.Subscribe(); ``` -------------------------------- ### Get subscribed channels response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/misc.md Example JSON response for GetSubscribedChannels, showing a list of channel names. ```json ["channel1", "channel2"] ``` -------------------------------- ### Retrieve messages until a timetoken with Start(-1) and End() (deprecated) Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/storage-and-playback.md Fetches messages until a given end timetoken by paging from newest to oldest. Uses Start(-1) and End(13847168819178600L) with Reverse(true) to get messages up to that point. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); PNResult 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(); ``` -------------------------------- ### Initialize PubNub client with UserId and keys Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration.md Creates a PNConfiguration with a UserId, subscribe and publish keys, and sets Secure to true, then creates a PubNub instance. You must set UserId to connect; otherwise, connection fails. Returns a Pubnub instance for APIs like Publish(), Subscribe(), History(), and HereNow(). ```csharp using PubnubApi; // Initialize PubNub using the configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Create the PubNub instance with the configuration Pubnub pubnub = new Pubnub(pnConfiguration); ``` -------------------------------- ### Get subscribed channel groups response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/misc.md Example JSON response for GetSubscribedChannelGroups, showing a list of channel group names. ```json ["channelGroup1", "channelGroup2"] ``` -------------------------------- ### Subscribe to a channel (old) - C# sample Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Complete example of initializing PubNub with configuration and subscribing to a channel. Listeners must be added before calling this method to handle responses. ```csharp using PubnubApi; using PubnubApi.EndPoint; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); pubnub.Subscribe() .Channels(new string[] { // subscribe to channels "my_channel" }) .Execute(); ``` -------------------------------- ### Get list of UUIDs subscribed to channel in C# Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/presence.md Complete example that gets a list of UUIDs subscribed to the specified channels using the Here Now API. It includes necessary imports, configuration, and console logging. The response includes occupancy and occupant state information. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult herenowResponse = await pubnub.HereNow() .Channels(new string[] { "coolChannel", "coolChannel2" }) .IncludeUUIDs(true) .ExecuteAsync(); PNHereNowResult herenowResult = herenowResponse.Result; PNStatus status = herenowResponse.Status; if (!status.Error && herenowResult != null) { foreach (KeyValuePair channelData in herenowResult.Channels) { Console.WriteLine("---"); Console.WriteLine("Channel: " + channelData.Value.ChannelName); Console.WriteLine("Occupancy: " + channelData.Value.Occupancy); if (channelData.Value.Occupants != null) { foreach (var occupant in channelData.Value.Occupants) { Console.WriteLine($"UUID: {occupant.Uuid}"); Console.WriteLine($"State: {(occupant.State != null ? pubnub.JsonPluggableLibrary.SerializeToJsonString(occupant.State) : "No state")}"); } } } } else { Console.WriteLine("Error occurred: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); } } catch (Exception ex) { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } ``` -------------------------------- ### Initialize PubNub with PNConfiguration Source: https://www.pubnub.com/docs/sdks/c-sharp.md Configures and initializes the PubNub client with subscribe and publish keys. Replace the demo keys with your own from the Admin Portal. This is the minimum configuration required to send and receive messages. ```csharp // Configure PubNub PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", // Use your own keys in production PublishKey = "demo", // Use your own keys in production Secure = true }; // Initialize PubNub pubnub = new Pubnub(pnConfiguration); Console.WriteLine("PubNub Initialized!"); ``` -------------------------------- ### Recursive history paging example (deprecated) Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/storage-and-playback.md Fetches all history messages by recursively calling the History API with the end timetoken as the start for the next page. Requires a valid timetoken or 0 as the start argument. Uses demo keys, which have Message Persistence disabled, so use your own keys. ```csharp using PubnubApi; 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(new UserId("myUniqueUserId")); 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 { 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 } } } ``` -------------------------------- ### Create Relationship - Full C# Sample Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md Self-contained reference example that configures PubNub)Skip initialization, creates a relationship between "seller-bob" and "product-sneaker-42" with class "ProductOwner" and version 1, and includes a payload with a "since" date. Prints the created relationship's Id or the error information. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.CreateRelationship(new CreateRelationshipParameters { EntityAId = "seller-bob", EntityBId = "product-sneaker-42", RelationshipClass = "ProductOwner", RelationshipClassVersion = 1, Payload = new Dictionary { { "since", "2026-07-13" }, }, }); if (!response.Status.Error) { Console.WriteLine(response.Result.Id); } else { Console.WriteLine($"Request can't be executed due to error: {response.Status.ErrorData.Information}"); } } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` -------------------------------- ### List channel files sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/files.md Initializes Pubnub with demo keys and retrieves the list of files for 'my_channel'. The response is serialized to JSON and printed, or the status is printed on error. ```csharp using PubnubApi; PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; Pubnub pubnub = new Pubnub(pnConfiguration); PNResult listFilesResponse = await pubnub.ListFiles() .Channel("my_channel") .ExecuteAsync(); PNListFilesResult listFilesResult = listFilesResponse.Result; PNStatus listFilesStatus = listFilesResponse.Status; if (!listFilesStatus.Error && listFilesResult != null) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesResult)); } else { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesStatus)); } ``` -------------------------------- ### Get Channel Members response JSON Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/objects.md Example JSON response from GetChannelMembers, showing ChannelMembers array with UuidMetadata and Custom fields, TotalCount, and Page cursor. ```json { "ChannelMembers": [ { "UuidMetadata": { "Uuid": "uuid-1", "Name": "John Doe", "Email": "jack@twitter.com", "ExternalId": "", "ProfileUrl": "", "Custom": null, "Updated": "2019-02-20T23:11:20.89375" }, "Custom": { "role": "admin" }, "Updated": "2020-06-17T17:05:25.987964Z" }, { "UuidMetadata": { "Uuid": "uuid-2", "Name": "Bob Cat", "Email": "bobc@example.com", "ExternalId": "", "ProfileUrl": "", "Custom": { "phone": "999-999-9999" }, "Updated": "2019-02-20T23:11:20.89375" }, "Custom": null, "Updated": "2020-06-17T17:05:25.987964Z" } ], "TotalCount": 2, "Page": { "Next": "MQ", "Prev": "" } } ``` -------------------------------- ### Add channels to a channel group - sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/channel-groups.md Self-contained example that adds channels to a channel group and logs the result. Uses ExecuteAsync to get a PNResult. ```csharp using PubnubApi; //Create configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo" }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult cgAddChResponse = await pubnub.AddChannelsToChannelGroup() .ChannelGroup("myChannelGroup") .Channels(new string[] { "channel1", "channel2", "channel3" }) .ExecuteAsync(); PNChannelGroupsAddChannelResult cgAddChResult = cgAddChResponse.Result; PNStatus cgAddChStatus = cgAddChResponse.Status; if (!cgAddChStatus.Error && cgAddChResult != null) { Console.WriteLine("Channels successfully added to the channel group."); } else { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(cgAddChStatus)); } } catch (Exception ex) { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } ``` -------------------------------- ### GetFileUrl() sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/files.md Complete example that initializes Pubnub, calls GetFileUrl() with a channel, file ID, and file name, then prints the result or status. Uses the demo keys and a sample file ID. ```csharp using PubnubApi; PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; Pubnub pubnub = new Pubnub(pnConfiguration); PNResult getFileUrlResponse = await pubnub.GetFileUrl() .Channel("my_channel") .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") .FileName("cat_picture.jpg") .ExecuteAsync(); PNFileUrlResult getFileUrlResult = getFileUrlResponse.Result; PNStatus getFileUrlStatus = getFileUrlResponse.Status; if (!getFileUrlStatus.Error && getFileUrlResult != null) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlResult)); } else { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus)); } ``` -------------------------------- ### Create a SubscriptionSet with channels, channelGroups, and options Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Creates a client-level SubscriptionSet to receive messages and events across multiple channels and channel groups. Requires either channels or channelGroups. Keep a strong reference to the subscription set to avoid garbage collection. ```csharp // client-based, general-scoped SubscriptionSet subscriptionSet = pubnub.SubscriptionSet( channels: string[], channelGroups: string[], options: SubscriptionOptions ) ``` -------------------------------- ### GetMessageActions response JSON Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/message-actions.md Example response from GetMessageActions, containing an array of message actions and a More object with pagination parameters (Start, End, Limit). The More object is present when the response is truncated. ```json { "MessageActions": [{ "MessageTimetoken":15610547826969050, "Action":{ "type":"reaction", "value":"smiley_face" }, "Uuid":"pn-5903a053-592c-4a1e-8bfd-81d92c962968", "ActionTimetoken":15717253483027900 }], "More": { "Start": 15610547826970050, "End": 15645905639093361, "Limit": 2 } } ``` -------------------------------- ### SendFile sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/files.md Self-contained example that uploads a file to a channel and prints the result or status. Requires a PubNub instance with SubscribeKey and PublishKey set to 'demo'. ```csharp using PubnubApi; PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult fileUploadResponse = await pubnub.SendFile() .Channel("my_channel") .File("path/to/your/file/cat_picture.jpg") .Message("Look at this photo!") .CustomMessageType("file-message") .ExecuteAsync(); PNFileUploadResult fileUploadResult = fileUploadResponse.Result; PNStatus fileUploadStatus = fileUploadResponse.Status; if (!fileUploadStatus.Error && fileUploadResult != null) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadResult)); } else { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadStatus)); } } catch (Exception ex) { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } ``` -------------------------------- ### Get Channel Members sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/objects.md Complete C# example that initializes PubNub, calls GetChannelMembers with channel 'my-channel', includes custom and UUID fields, and executes asynchronously. The response is stored in PNResult. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); // Get Members (uuids) for a specific channel PNResult getChannelMembersResponse = await pubnub.GetChannelMembers() .Channel("my-channel") .Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM }) .IncludeCount(true) .ExecuteAsync(); PNChannelMembersResult getChannelMembersResult = getChannelMembersResponse.Result; PNStatus status2 = getChannelMembersResponse.Status; ``` -------------------------------- ### Get User with GetUser Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md Retrieve a single user by Id. The method requires the Id parameter. The sample uses a self-contained setup with demo keys; the response returns the user object with its payload and server-generated metadata. ```csharp pubnub.DataSync.GetUser(GetUserParameters parameters) ``` ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.GetUser(new GetUserParameters { Id = "user-alice", }); if (!response.Status.Error) { Console.WriteLine(response.Result.Id); } else { Console.WriteLine($"Request can't be executed due to error: {response.Status.ErrorData.Information}"); } } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` ```json { "status": 200, "data": { "id": "user-alice", "entityClass": "User", "entityClassVersion": 1, "entityClassLevel": "Global", "payload": { "name": "Alice", "type": "shopper" }, "createdAt": "2026-07-13T09:00:00.000Z", "updatedAt": "2026-07-13T09:00:00.000Z", "eTag": "AbQdEfGhIjKlMn" } } ``` -------------------------------- ### Sample code for ManageMemberships Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/objects.md Complete example that configures PubNub, sets and removes memberships, and executes the request. The response is stored in PNResult. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); List setMembrshipList = [ new PNMembership() { Channel = "ch1", Custom = new Dictionary() { { "say", "hello" } } }, new PNMembership() { Channel = "ch2", Custom = new Dictionary() { { "say", "world" } } }, new PNMembership() { Channel = "ch3", Custom = new Dictionary() { { "say", "bye" } } } ]; List removeMembrshipList = [ "ch4" ]; PNResult manageMmbrshipsResponse = await pubnub.ManageMemberships() .Uuid("my-uuid") .Set(setMembrshipList) .Remove(removeMembrshipList) .Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM }) .IncludeCount(true) .Page(new PNPageObject() { Next = "", Prev = "" }) .Sort(new List() { "channel.id:asc" }) .ExecuteAsync(); PNMembershipsResult manageMmbrshipsResult = manageMmbrshipsResponse.Result; PNStatus status = manageMmbrshipsResponse.Status; ``` -------------------------------- ### Delete Entity - Full C# Sample Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md Self-contained reference example that configures PubNub, initializes it, and calls DeleteEntity with the Id "product-sneaker-42". Prints the returned status code or an error message on exception. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.DeleteEntity(new DeleteEntityParameters { Id = "product-sneaker-42", }); Console.WriteLine(response.Status.StatusCode); } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` -------------------------------- ### EncryptFile sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/encryption.md Sample code showing how to encrypt a file using CryptoModule's CreateAesCbcCryptor. The source and destination file paths are relative to the bin folder if no path is provided. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); string source_file = "cat_picture.jpg"; // checks bin folder if no path is provided string destination_file = "destination_cat_pic.jpg"; // checks bin folder if no path is provided var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); crypto.EncryptFile(source_file, destination_file); ``` -------------------------------- ### Get all UUID metadata - JSON response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/objects.md Example JSON response from GetAllUuidMetadata(), showing a paginated list of UUID metadata objects with fields like Uuid, Name, Email, Custom, and Updated, plus TotalCount and Page cursors. ```json { "Uuids": [ { "Uuid": "uuid-1", "Name": "John Doe", "Email": "jack@twitter.com", "ExternalId": null, "ProfileUrl": null, "Custom": null, "Updated": "2020-06-17T16:28:14.060718Z" }, { "Uuid": "uuid-2", "Name": "Bob Cat", "Email": "bobc@example.com", "ExternalId": null, "ProfileUrl": null, "Custom": { "phone": "999-999-9999" }, "Updated": "2020-06-17T16:42:22.906768Z" } ], "TotalCount": 2, "Page": { "Next": "MTI", "Prev": "" } } ``` -------------------------------- ### Create a SubscriptionSet from two subscriptions Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Shows how to create a SubscriptionSet by adding two individual subscriptions (one from a channel entity, one from a channel group entity) using the Add method. ```csharp using PubnubApi; using PubnubApi.EndPoint; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); // Create a subscription from a channel entity Subscription subscription1 = pubnub.Channel("channelName").Subscription(); // Create a subscription from a channel group entity Subscription subscription2 = pubnub.ChannelGroup("channelGroupName").Subscription(); // create a subscription set from individual entities SubscriptionSet subscriptionSet = subscription1.Add(subscription2); subscriptionSet.Subscribe(); ``` -------------------------------- ### Get all UUID metadata - sample code Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/objects.md Self-contained C# example that initializes PubNub with demo keys, calls GetAllUuidMetadata() with IncludeCustom and IncludeCount set to true, and prints the result or status. Requires the PubnubApi namespace and a valid UserId. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult getAllUuidMetadataResponse = await pubnub.GetAllUuidMetadata() .IncludeCustom(true) .IncludeCount(true) .ExecuteAsync(); PNGetAllUuidMetadataResult getAllUuidMetadataResult = getAllUuidMetadataResponse.Result; PNStatus status = getAllUuidMetadataResponse.Status; if (!status.Error && getAllUuidMetadataResult != null) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getAllUuidMetadataResult)); } else { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); } } catch (Exception ex) { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } ``` -------------------------------- ### Create a UserMetadata SDK entity Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe.md Returns a local UserMetadata SDK entity. The sample creates user metadata, attaches a SubscribeCallbackExt listener, and subscribes to receive messages, presence, and status events. ```csharp pubnub.UserMetadata(String) ``` ```csharp var userMetadata = pubnub.UserMetadata("userMetadata"); SubscribeCallbackExt userMetadataListener = new SubscribeCallbackExt( (pubnubObj, message) => { /*Message handling here*/ }, (pubnubObj, presence) => { /*Presence handling here*/ }, (pubnubObj, status) => { /*Status handling here*/ }); userMetadata.Subscription().AddListener(userMetadataListener); userMetadata.Subscription().Subscribe(); ``` -------------------------------- ### GetChannel sample with response Source: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/data-sync.md Self-contained C# example for getting a channel by ID using the DataSync API's GetChannel method. It configures a PubNub instance with demo keys, calls GetChannel with a channel ID, and logs the ID on success or error information on failure. The JSON response shows a successful query returning the channel metadata. ```csharp using PubnubApi; // Configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", PublishKey = "demo", Secure = true }; // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); try { PNResult response = await pubnub.DataSync.GetChannel(new GetChannelParameters { Id = "channel-summer-sale", }); if (!response.Status.Error) { Console.WriteLine(response.Result.Id); } else { Console.WriteLine($"Request can't be executed due to error: {response.Status.ErrorData.Information}"); } } catch (Exception ex) { Console.WriteLine($"Request can't be executed due to error: {ex.Message}"); } ``` ```json { "status": 200, "data": { "id": "channel-summer-sale", "entityClass": "Channel", "entityClassVersion": 1, "entityClassLevel": "Global", "payload": { "name": "Summer Sale", "type": "promotion" }, "createdAt": "2026-07-13T09:05:00.000Z", "updatedAt": "2026-07-13T09:05:00.000Z", "eTag": "GhIjKlMnOpQrSt" } } ```