From 06f28ad16dab7194e0a5d71be23d772b66c9a1f0 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Mon, 16 Jun 2025 15:09:39 +0200 Subject: [PATCH 01/17] add code snippets sub-project + implement Access Manager snippets --- .gitignore | 9 + src/Pubnub.sln | 43 ++ .../AccessManager/AccessManagerSample.cs | 387 ++++++++++++++++++ src/PubnubApi.Snippets/Program.cs | 3 + .../PubnubApi.Snippets.csproj | 31 ++ 5 files changed, 473 insertions(+) create mode 100644 src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs create mode 100644 src/PubnubApi.Snippets/Program.cs create mode 100644 src/PubnubApi.Snippets/PubnubApi.Snippets.csproj diff --git a/.gitignore b/.gitignore index 1aafb3eaf..756f54cd2 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,15 @@ src/.vs/Pubnub/v15/sqlite3/storage.ide /src/Api/PubnubApi/*.user /src/Api/PubnubApi/Settings.StyleCop +/src/PubnubApi.Snippets/bin/* +/src/PubnubApi.Snippets/bin/Debug/* +/src/PubnubApi.Snippets/obj/Debug/* +/src/PubnubApi.Snippets/bin/Release/* +/src/PubnubApi.Snippets/obj/Release/* +/src/PubnubApi.Snippets/obj/* +/src/PubnubApi.Snippets/*.user +/src/PubnubApi.Snippets/Settings.StyleCop + /src/Api/PubnubApiUWP/bin/* /src/Api/PubnubApiUWP/bin/Debug/* /src/Api/PubnubApiUWP/obj/Debug/* diff --git a/src/Pubnub.sln b/src/Pubnub.sln index 66f8f0ab3..0a464aa63 100644 --- a/src/Pubnub.sln +++ b/src/Pubnub.sln @@ -27,6 +27,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcceptanceTests", "UnitTest EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PubnubApiUnity", "Api\PubnubApiUnity\PubnubApiUnity.csproj", "{55D8FD89-D9CF-4A11-B997-948AFF801A43}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PubnubApi.Snippets", "PubnubApi.Snippets\PubnubApi.Snippets.csproj", "{87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug_Ubuntu|Any CPU = Debug_Ubuntu|Any CPU @@ -403,6 +405,46 @@ Global {55D8FD89-D9CF-4A11-B997-948AFF801A43}.Release|x64.Build.0 = Release|Any CPU {55D8FD89-D9CF-4A11-B997-948AFF801A43}.Release|x86.ActiveCfg = Release|Any CPU {55D8FD89-D9CF-4A11-B997-948AFF801A43}.Release|x86.Build.0 = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|Any CPU.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|Any CPU.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|ARM.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|ARM.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|ARM64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|ARM64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|x64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|x64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|x86.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug_Ubuntu|x86.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|ARM.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|ARM.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|ARM64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|x64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|x64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|x86.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Debug|x86.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|Any CPU.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|Any CPU.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|ARM.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|ARM.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|ARM64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|ARM64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|x64.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|x64.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|x86.ActiveCfg = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release_Ubuntu|x86.Build.0 = Debug|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|Any CPU.Build.0 = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|ARM.ActiveCfg = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|ARM.Build.0 = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|ARM64.ActiveCfg = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|ARM64.Build.0 = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|x64.ActiveCfg = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|x64.Build.0 = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|x86.ActiveCfg = Release|Any CPU + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -417,6 +459,7 @@ Global {C1449A27-2C29-40FF-BAD4-521BDFD323EB} = {D2051EEF-B0DA-43C4-8569-4D48FE76A5CB} {15805B6C-C474-4DD7-BD7F-150A7EA23F5C} = {D2051EEF-B0DA-43C4-8569-4D48FE76A5CB} {55D8FD89-D9CF-4A11-B997-948AFF801A43} = {F101EAB9-89CA-4ACB-A72B-0660F4C9CC38} + {87CCDCEB-CD31-4650-95FE-5BBC9CA0C0C8} = {D5BC8314-0679-4C5E-8B78-1CE761739794} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A640EAE8-CEFD-4AFB-86DE-4112005EB515} diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs new file mode 100644 index 000000000..4292a6e7f --- /dev/null +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -0,0 +1,387 @@ +//snippet.using +using PubnubApi; +//snippet.end + +class AccessManagerSample +{ + private static Pubnub pubnub; + + static void PubnubInit() + { + //snippet.pubnub_init + //Create configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo" + }; + //Create a new PubNub instance + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + + AccessManagerSample.pubnub = pubnub; + } + + static async Task BasicUsage() + { + //snippet.basic_usage + try + { + //Perform token granting operation + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUuid("my-authorized-uuid") + .Resources(new PNTokenResources + { + Channels = new Dictionary + { + { "my-channel", new PNTokenAuthValues { Read = true, Write = true } } + } + }) + .ExecuteAsync(); + + //Parse operation response + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + } + catch (Exception ex) + { + Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); + } + //snippet.end + } + + static async Task GrantTokenComplex() + { + //snippet.grant_token_complex + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUuid("my-authorized-uuid") + .Resources(new PNTokenResources() + { + Channels = new Dictionary() { + { "channel-a", new PNTokenAuthValues() { Read = true } }, + { "channel-b", new PNTokenAuthValues() { Read = true, Write = true } }, + { "channel-c", new PNTokenAuthValues() { Read = true, Write = true } }, + { "channel-d", new PNTokenAuthValues() { Read = true, Write = true } }}, + ChannelGroups = new Dictionary() { + { "channel-group-b", new PNTokenAuthValues() { Read = true } } }, + Uuids = new Dictionary() { + { "uuid-c", new PNTokenAuthValues() { Get = true } }, + { "uuid-d", new PNTokenAuthValues() { Get = true, Update = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenWithRegex() + { + //snippet.grant_token_regex + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUuid("my-authorized-uuid") + .Patterns(new PNTokenPatterns() + { + Channels = new Dictionary() { + { "channel-[A-Za-z0-9]", new PNTokenAuthValues() { Read = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenComplexWithRegex() + { + //snippet.grant_token_complex_with_regex + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUuid("my-authorized-uuid") + .Resources(new PNTokenResources() + { + Channels = new Dictionary() { + { "channel-a", new PNTokenAuthValues() { Read = true } }, + { "channel-b", new PNTokenAuthValues() { Read = true, Write = true } }, + { "channel-c", new PNTokenAuthValues() { Read = true, Write = true } }, + { "channel-d", new PNTokenAuthValues() { Read = true, Write = true } }}, + ChannelGroups = new Dictionary() { + { "channel-group-b", new PNTokenAuthValues() { Read = true } } }, + Uuids = new Dictionary() { + { "uuid-c", new PNTokenAuthValues() { Get = true } }, + { "uuid-d", new PNTokenAuthValues() { Get = true, Update = true } }} + }) + .Patterns(new PNTokenPatterns() + { + Channels = new Dictionary() { + { "channel-[A-Za-z0-9]", new PNTokenAuthValues() { Read = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenOldBasicUsage() + { + //snippet.basic_usage_old + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUserId("my-authorized-userId") + .Resources(new PNTokenResources() + { + Spaces = new Dictionary() { + { "my-space", new PNTokenAuthValues() { Read = true } } } // False to disallow + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + //PNAccessManagerTokenResult is a parsed and abstracted response from the server + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenOldComplex() + { + //snippet.grant_token_complex_old + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUserId("my-authorized-userId") + .Resources(new PNTokenResources() + { + Spaces = new Dictionary() { + { "space-a", new PNTokenAuthValues() { Read = true } }, + { "space-b", new PNTokenAuthValues() { Read = true, Write = true } }, + { "space-c", new PNTokenAuthValues() { Read = true, Write = true } }, + { "space-d", new PNTokenAuthValues() { Read = true, Write = true } }}, + Users = new Dictionary() { + { "user-c", new PNTokenAuthValues() { Get = true } }, + { "user-d", new PNTokenAuthValues() { Get = true, Update = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenOldWithRegex() + { + //snippet.grant_token_old_regex + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUserId("my-authorized-userId") + .Patterns(new PNTokenPatterns() + { + Spaces = new Dictionary() { + { "space-[A-Za-z0-9]", new PNTokenAuthValues() { Read = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task GrantTokenOldComplexWithRegex() + { + //snippet.grant_token_complex_old_with_regex + PNResult grantTokenResponse = await pubnub.GrantToken() + .TTL(15) + .AuthorizedUserId("my-authorized-userId") + .Resources(new PNTokenResources() + { + Spaces = new Dictionary() { + { "space-a", new PNTokenAuthValues() { Read = true } }, + { "space-b", new PNTokenAuthValues() { Read = true, Write = true } }, + { "space-c", new PNTokenAuthValues() { Read = true, Write = true } }, + { "space-d", new PNTokenAuthValues() { Read = true, Write = true } }}, + Users = new Dictionary() { + { "user-c", new PNTokenAuthValues() { Get = true } }, + { "user-d", new PNTokenAuthValues() { Get = true, Update = true } }} + }) + .Patterns(new PNTokenPatterns() + { + Spaces = new Dictionary() { + { "space-[A-Za-z0-9]", new PNTokenAuthValues() { Read = true } }} + }) + .ExecuteAsync(); + PNAccessManagerTokenResult grantTokenResult = grantTokenResponse.Result; + PNStatus grantTokenStatus = grantTokenResponse.Status; + if (!grantTokenStatus.Error && grantTokenResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); + } + //snippet.end + } + + static async Task RevokeTokenBasicUsage() + { + //snippet.revoke_token + PNResult revokeTokenResponse = await pubnub + .RevokeToken() + .Token("p0thisAkFl043rhDdHRsCkNDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") + .ExecuteAsync(); + PNAccessManagerRevokeTokenResult revokeTokenResult = revokeTokenResponse.Result; + PNStatus revokeTokenStatus = revokeTokenResponse.Status; + if (!revokeTokenStatus.Error && revokeTokenResult != null) + { + Console.WriteLine("Revoke token success"); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(revokeTokenStatus)); + } + //snippet.end + } + + static async Task ParseTokenBasicUsage() + { + //snippet.parse_token_usage + var parsedTokenContent = + pubnub.ParseToken( + "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"); + var parsedTokenJson = pubnub.JsonPluggableLibrary.SerializeToJsonString(parsedTokenContent); + //snippet.end + + /* + //snippet_parse_token_result + { + "Version":2, + "Timestamp":1619718521, + "TTL":15, + "AuthorizedUuid":"my_uuid", + "Resources":{ + "Uuids":{ + "uuid-id":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + }, + "Channels":{ + "channel-id":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + }, + "ChannelGroups":{ + "group-id":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + } + }, + "Patterns":{ + "Uuids":{ + "uuid-pattern":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + }, + "Channels":{ + "channel-pattern":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + }, + "ChannelGroups":{ + "group-pattern":{ + "Read":true, + "Write":true, + "Manage":true, + "Delete":true, + "Get":true, + "Update":true, + "Join":true + } + } + } + } + //snippet.end + */ + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Program.cs b/src/PubnubApi.Snippets/Program.cs new file mode 100644 index 000000000..e5dff12bc --- /dev/null +++ b/src/PubnubApi.Snippets/Program.cs @@ -0,0 +1,3 @@ +// See https://aka.ms/new-console-template for more information + +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj new file mode 100644 index 000000000..4d1bf2323 --- /dev/null +++ b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj @@ -0,0 +1,31 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + From 7222ad72e2cf7a2c2b0cc0014cb363f0672abb27 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 17 Jun 2025 16:28:03 +0200 Subject: [PATCH 02/17] add access v2, channel group, and config samples --- .../AccessManager/AccessManagerSample.cs | 4 +- .../AccessManager/AccessManagerV2Sample.cs | 236 ++++++++++++++++++ .../ChannelGroup/ChannelGroupsSample.cs | 81 ++++++ .../Configuration/ConfigurationSample.cs | 170 +++++++++++++ src/PubnubApi.Snippets/Files/FilesSample.cs | 6 + .../PubnubApi.Snippets.csproj | 3 - 6 files changed, 494 insertions(+), 6 deletions(-) create mode 100644 src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs create mode 100644 src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs create mode 100644 src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs create mode 100644 src/PubnubApi.Snippets/Files/FilesSample.cs diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs index 4292a6e7f..b555f82df 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -18,8 +18,6 @@ static void PubnubInit() //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); //snippet.end - - AccessManagerSample.pubnub = pubnub; } static async Task BasicUsage() @@ -304,7 +302,7 @@ static async Task ParseTokenBasicUsage() //snippet.end /* - //snippet_parse_token_result + //snippet.parse_token_result { "Version":2, "Timestamp":1619718521, diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs new file mode 100644 index 000000000..9c4066fd7 --- /dev/null +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs @@ -0,0 +1,236 @@ +//snippet.using +using PubnubApi; +//snippet.end + +public class AccessManagerV2Sample +{ + private static Pubnub pubnub; + + static void PubnubInit() + { + //snippet.pubnub_init + //Create configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo" + }; + //Create a new PubNub instance + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static async Task Grant() + { + //snippet.grant + PNResult grantResponse = await pubnub.Grant() + .Channels(new string[]{ + //channels to allow grant on + "ch1", + "ch2", + "ch3" + }) + .ChannelGroups(new string[] { + // groups to allow grant on + "cg1", + "cg2", + "cg3" + }) + .AuthKeys(new string[] { + // the keys we are provisioning + "key1", + "key2", + "key3" + }) + .Write(true) // allow those keys to write (false by default) + .Manage(true) // allow those keys to manage channel groups (false by default) + .Read(true) // allow keys to read the subscribe feed (false by default) + .Delete(true) // allow those keys to delete the subscribe feed (false by default) + .TTL(12337) // how long those keys will remain valid (0 for eternity) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static void GrantCallback() + { + //snippet.grant_callback + pubnub.Grant() + .Channels(new string[]{ + //channels to allow grant on + "ch1", + "ch2", + "ch3" + }) + .ChannelGroups(new string[] { + // groups to allow grant on + "cg1", + "cg2", + "cg3" + }) + .AuthKeys(new string[] { + // the keys we are provisioning + "key1", + "key2", + "key3" + }) + .Write(true) // allow those keys to write (false by default) + .Manage(true) // allow those keys to manage channel groups (false by default) + .Read(true) // allow keys to read the subscribe feed (false by default) + .Delete(true) // allow those keys to delete the subscribe feed (false by default) + .TTL(12337) // how long those keys will remain valid (0 for eternity) + .Execute(new PNAccessManagerGrantResultExt( + (result, status) => { + //PNAccessManagerGrantResult is a parsed and abstracted response from server + } + )); + //snippet.end + } + + static async Task GrantTTL() + { + //snippet.grant_ttl + PNResult grantResponse = await pubnub.Grant() + .Channels(new string[] { + "my_channel" + }) + .Write(false) + .Read(true) + .Delete(false) + .AuthKeys(new string[] { + "my_ro_authkey" + }) + .TTL(5) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantPresence() + { + //snippet.grant_presence + PNResult grantResponse = await pubnub.Grant() + .Channels(new string[] { + "my_channel-pnpres" + }) + .Write(true) + .Read(true) + .Delete(true) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantChannelGroup() + { + //snippet.grant_group + PNResult grantResponse = await pubnub.Grant() + .ChannelGroups(new string[] { + "cg1", + "cg2", + "cg3" + }) + .AuthKeys(new string[] { + "key1", + "key2", + "key3" + }) + .Write(true) + .Manage(true) + .Read(true) + .Delete(true) + .TTL(12337) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantWithAuthKey() + { + //snippet.grant_auth_key + PNResult grantResponse = await pubnub.Grant() + .Uuids(new string[] { + "my_uuid" + }) + .Get(true) + .Update(true) + .Delete(true) + .AuthKeys(new string[] { + "my_ro_authkey" + }) + .TTL(1440) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantAppLevel() + { + //snippet.grant_app_level + PNResult grantResponse = await pubnub.Grant() + .Write(true) + .Read(true) + .Delete(true) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantChannelLevel() + { + //snippet.grant_channel_level + PNResult grantResponse = await pubnub.Grant() + .Channels(new string[] { + "my_channel" + }) + .Write(true) + .Read(true) + .Delete(true) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } + + static async Task GrantUserLevel() + { + //snippet.grant_user_level + PNResult grantResponse = await pubnub.Grant() + .Channels(new string[] { + "my_channel" + }) + .Write(true) + .Read(true) + .Delete(true) + .AuthKeys(new string[]{ + "my_authkey" + }) + .TTL(5) + .ExecuteAsync(); + + PNAccessManagerGrantResult grantResult = grantResponse.Result; + PNStatus status = grantResponse.Status; + //PNAccessManagerGrantResult is a parsed and abstracted response from server + //snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs new file mode 100644 index 000000000..2a7e526ce --- /dev/null +++ b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs @@ -0,0 +1,81 @@ +//snippet.using +using PubnubApi; +//snippet.end + +public class ChannelGroupsSample +{ + private static Pubnub pubnub; + + static void PubnubInit() + { + //snippet.pubnub_init + //Create configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo" + }; + //Create a new PubNub instance + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static async Task AddToGroup() + { + //snippet.add_to_group + 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}"); + } + //snippet.end + } + + static async Task ListFromGroup() + { + //snippet.list + PNResult cgListChResponse = await pubnub.ListChannelsForChannelGroup() + .ChannelGroup("cg1") + .ExecuteAsync(); + //snippet.end + } + + static async Task RemoveFromGroup() + { + //snippet.remove + PNResult rmChFromCgResponse = await pubnub.RemoveChannelsFromChannelGroup() + .ChannelGroup("family") + .Channels(new string[] { + "son" + }) + .ExecuteAsync(); + //snippet.end + } + + static async Task DeleteGroup() + { + //snippet.delete + PNResult delCgResponse = await pubnub.DeleteChannelGroup() + .ChannelGroup("family") + .ExecuteAsync(); + //snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs new file mode 100644 index 000000000..c915a34d4 --- /dev/null +++ b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs @@ -0,0 +1,170 @@ +//snippet.using +using PubnubApi; +//snippet.end + +//snippet.using_crypto +using PubnubApi.Security.Crypto; +using PubnubApi.Security.Crypto.Cryptors; +//snippet.end + +public class ConfigurationSample +{ + private static Pubnub pubnub; + + static void PubnubInit() + { + //snippet.init_config + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + //snippet.end + + //snippet.crypto + // encrypts using 256-bit AES-CBC cipher (recommended) + // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers + pnConfiguration.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), + new List { new LegacyCryptor("enigma") }); + + // encrypts with 128-bit cipher key entropy (legacy) + // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers + pnConfiguration.CryptoModule = new CryptoModule(new LegacyCryptor("enigma"), + new List { new AesCbcCryptor("enigma") }); + //snippet.end + + //snippet.new_pubnub + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static void BasicUsage() + { + //snippet.basic_usage + // Create a configuration instance for PubNub + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", // Required + PublishKey = "demo", // Only required if publishing + SecretKey = "SecretKey", // Only required for access operations + Secure = true, // Enable SSL + AuthKey = "authKey", // If Access Manager is utilized + LogLevel = PubnubLogLevel.Debug, // Enable debugging + SubscribeTimeout = 310, // Subscribe loop timeout in seconds + NonSubscribeRequestTimeout = 300, // Non-subscribe request timeout + FilterExpression = "such=wow", // PSV2 filter expression + HeartbeatNotificationOption = PNHeartbeatNotificationOption.All, // Heartbeat notifications + PresenceTimeout = 120, // Presence timeout + }; + + // Configure presence timeout with custom interval + pnConfiguration.SetPresenceTimeoutWithCustomInterval(120, 59); + + // Encryption configuration (Optional) + pnConfiguration.CryptoModule = new CryptoModule( + new AesCbcCryptor("enigma"), + new List { new LegacyCryptor("enigma") }); + + // Initialize a new PubNub instance with the created confiiguration + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + + //snippet.user_id + pnConfiguration.UserId = new UserId("myUserId"); + //snippet.end + + //snippet.get_user_id + UserId currentUserId = pubnub.GetCurrentUserId(); + //snippet.end + } + + static void ChangeUserId() + { + //snippet.change_user_id + //Setting the initial UserId + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + //Changing to a new UserId + pnConfiguration.UserId = new UserId("myUserId"); + //snippet.end + } + + static void SetAndGetAuthKey() + { + //snippet.set_auth_key + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.AuthKey = "authKey"; + //snippet.end + + //snippet.get_auth_key + string sampleAuthKey = pnConfiguration.AuthKey; + //snippet.end + } + + static void FilterExpression() + { + //snippet.filter_expression + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.FilterExpression = "such=wow"; + //snippet.end + + //snippet.get_filter_expression + string filterExpression = pnConfiguration.FilterExpression; + //snippet.end + } + + static void InitWithUUID() + { + //snippet.init_with_uuid + // 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); + //snippet.end + } + + static void InitNonSecure() + { + //snippet.init_non_secure + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.PublishKey = "my_pubkey"; + pnConfiguration.SubscribeKey = "my_subkey"; + pnConfiguration.Secure = false; + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static void InitSecure() + { + //snippet.init_secure + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.PublishKey = "my_pubkey"; + pnConfiguration.SubscribeKey = "my_subkey"; + pnConfiguration.Secure = true; + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static void InitSecretKey() + { + //snippet.init_secret_key + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.PublishKey = "my_pubkey"; + pnConfiguration.SubscribeKey = "my_subkey"; + pnConfiguration.SecretKey = "my_secretkey"; + pnConfiguration.Secure = true; + + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + + static void InitReadOnly() + { + //snippet.init_read_only + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); + pnConfiguration.SubscribeKey = "my_subkey"; + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Files/FilesSample.cs b/src/PubnubApi.Snippets/Files/FilesSample.cs new file mode 100644 index 000000000..fce7ec24c --- /dev/null +++ b/src/PubnubApi.Snippets/Files/FilesSample.cs @@ -0,0 +1,6 @@ +namespace PubnubApi.Snippets.Files; + +public class FilesSample +{ + +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj index 4d1bf2323..c5c44e5ac 100644 --- a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj +++ b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj @@ -9,10 +9,7 @@ - - - From fb491e98cfd5e5b9d9699d4e9bf0393d63a8da2f Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 18 Jun 2025 14:37:39 +0200 Subject: [PATCH 03/17] add files samples --- src/PubnubApi.Snippets/Files/FilesSample.cs | 155 +++++++++++++++++++- 1 file changed, 154 insertions(+), 1 deletion(-) diff --git a/src/PubnubApi.Snippets/Files/FilesSample.cs b/src/PubnubApi.Snippets/Files/FilesSample.cs index fce7ec24c..f3285c5d4 100644 --- a/src/PubnubApi.Snippets/Files/FilesSample.cs +++ b/src/PubnubApi.Snippets/Files/FilesSample.cs @@ -1,6 +1,159 @@ -namespace PubnubApi.Snippets.Files; +//snippet.using +using PubnubApi; +//snippet.end public class FilesSample { + private static Pubnub pubnub; + + static void InitSample() + { + //snippet.init + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + Pubnub pubnub = new Pubnub(pnConfiguration); + //snippet.end + } + public static async Task SendFileBasicUsage() + { + //snippet.send_file_basic_usage + 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}"); + } + //snippet.end + } + + public static async Task ListFilesBasicUsage() + { + //snippet.list_files_basic_usage + 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)); + } + //snippet.end + } + + public static async Task GetFileUrlBasicUsage() + { + //snippet.get_file_url_basic_usage + 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)); + } + //snippet.end + } + + public static async Task DownloadFileBasicUsage(string downloadUrlFileName) + { + //snippet.download_file_basic_usage + PNResult fileDownloadResponse = await pubnub.DownloadFile() + .Channel("my_channel") + .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") + .FileName("cat_picture.jpg") + .ExecuteAsync(); + PNDownloadFileResult fileDownloadResult = fileDownloadResponse.Result; + PNStatus fileDownloadStatus = fileDownloadResponse.Status; + if (!fileDownloadStatus.Error && fileDownloadResult != null) + { + fileDownloadResult.SaveFileToLocal(downloadUrlFileName); //saves to bin folder if no path is provided + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadResult.FileName)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadStatus)); + } + //snippet.end + } + + public static async Task DeleteFileBasicUsage() + { + //snippet.delete_file_basic_usage + PNResult deleteFileResponse = await pubnub.DeleteFile() + .Channel("my_channel") + .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") + .FileName("cat_picture.jpg") + .ExecuteAsync(); + PNDeleteFileResult deleteFileResult = deleteFileResponse.Result; + PNStatus deleteFileStatus = deleteFileResponse.Status; + if (!deleteFileStatus.Error && deleteFileResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileStatus)); + } + //snippet.end + } + + public static async Task PublishFileMessageBasicUsage() + { + //snippet.publish_file_message_basic_usage + PNResult publishFileMsgResponse = await pubnub.PublishFileMessage() + .Channel("my_channel") + .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") + .FileName("cat_picture.jpg") //checks the bin folder if no path is provided + .Message("This is a sample message") + .CustomMessageType("file-message") + .ExecuteAsync(); + PNPublishFileMessageResult publishFileMsgResult = publishFileMsgResponse.Result; + PNStatus publishFileMsgStatus = publishFileMsgResponse.Status; + if (!publishFileMsgStatus.Error && publishFileMsgResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgStatus)); + } + //snippet.end + } } \ No newline at end of file From 9fd180e46e5718ad100b0e2e78d2d8bdec1377d5 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 18 Jun 2025 15:25:32 +0200 Subject: [PATCH 04/17] add spaces to snippet tags --- .../AccessManager/AccessManagerSample.cs | 52 +++++++------- .../AccessManager/AccessManagerV2Sample.cs | 44 ++++++------ .../ChannelGroup/ChannelGroupsSample.cs | 24 +++---- .../Configuration/ConfigurationSample.cs | 72 +++++++++---------- src/PubnubApi.Snippets/Files/FilesSample.cs | 32 ++++----- 5 files changed, 112 insertions(+), 112 deletions(-) diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs index b555f82df..f44050895 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -1,6 +1,6 @@ -//snippet.using +// snippet.using using PubnubApi; -//snippet.end +// snippet.end class AccessManagerSample { @@ -8,7 +8,7 @@ class AccessManagerSample static void PubnubInit() { - //snippet.pubnub_init + // snippet.pubnub_init //Create configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -17,12 +17,12 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static async Task BasicUsage() { - //snippet.basic_usage + // snippet.basic_usage try { //Perform token granting operation @@ -55,12 +55,12 @@ static async Task BasicUsage() { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } - //snippet.end + // snippet.end } static async Task GrantTokenComplex() { - //snippet.grant_token_complex + // snippet.grant_token_complex PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUuid("my-authorized-uuid") @@ -88,12 +88,12 @@ static async Task GrantTokenComplex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenWithRegex() { - //snippet.grant_token_regex + // snippet.grant_token_regex PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUuid("my-authorized-uuid") @@ -113,12 +113,12 @@ static async Task GrantTokenWithRegex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenComplexWithRegex() { - //snippet.grant_token_complex_with_regex + // snippet.grant_token_complex_with_regex PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUuid("my-authorized-uuid") @@ -151,12 +151,12 @@ static async Task GrantTokenComplexWithRegex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenOldBasicUsage() { - //snippet.basic_usage_old + // snippet.basic_usage_old PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUserId("my-authorized-userId") @@ -177,12 +177,12 @@ static async Task GrantTokenOldBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenOldComplex() { - //snippet.grant_token_complex_old + // snippet.grant_token_complex_old PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUserId("my-authorized-userId") @@ -208,12 +208,12 @@ static async Task GrantTokenOldComplex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenOldWithRegex() { - //snippet.grant_token_old_regex + // snippet.grant_token_old_regex PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUserId("my-authorized-userId") @@ -233,12 +233,12 @@ static async Task GrantTokenOldWithRegex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task GrantTokenOldComplexWithRegex() { - //snippet.grant_token_complex_old_with_regex + // snippet.grant_token_complex_old_with_regex PNResult grantTokenResponse = await pubnub.GrantToken() .TTL(15) .AuthorizedUserId("my-authorized-userId") @@ -269,12 +269,12 @@ static async Task GrantTokenOldComplexWithRegex() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(grantTokenStatus)); } - //snippet.end + // snippet.end } static async Task RevokeTokenBasicUsage() { - //snippet.revoke_token + // snippet.revoke_token PNResult revokeTokenResponse = await pubnub .RevokeToken() .Token("p0thisAkFl043rhDdHRsCkNDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") @@ -289,20 +289,20 @@ static async Task RevokeTokenBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(revokeTokenStatus)); } - //snippet.end + // snippet.end } static async Task ParseTokenBasicUsage() { - //snippet.parse_token_usage + // snippet.parse_token_usage var parsedTokenContent = pubnub.ParseToken( "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"); var parsedTokenJson = pubnub.JsonPluggableLibrary.SerializeToJsonString(parsedTokenContent); - //snippet.end + // snippet.end /* - //snippet.parse_token_result + // snippet.parse_token_result { "Version":2, "Timestamp":1619718521, @@ -379,7 +379,7 @@ static async Task ParseTokenBasicUsage() } } } - //snippet.end + // snippet.end */ } } \ No newline at end of file diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs index 9c4066fd7..bade97219 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs @@ -1,6 +1,6 @@ -//snippet.using +// snippet.using using PubnubApi; -//snippet.end +// snippet.end public class AccessManagerV2Sample { @@ -8,7 +8,7 @@ public class AccessManagerV2Sample static void PubnubInit() { - //snippet.pubnub_init + // snippet.pubnub_init //Create configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -17,12 +17,12 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static async Task Grant() { - //snippet.grant + // snippet.grant PNResult grantResponse = await pubnub.Grant() .Channels(new string[]{ //channels to allow grant on @@ -52,12 +52,12 @@ static async Task Grant() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static void GrantCallback() { - //snippet.grant_callback + // snippet.grant_callback pubnub.Grant() .Channels(new string[]{ //channels to allow grant on @@ -87,12 +87,12 @@ static void GrantCallback() //PNAccessManagerGrantResult is a parsed and abstracted response from server } )); - //snippet.end + // snippet.end } static async Task GrantTTL() { - //snippet.grant_ttl + // snippet.grant_ttl PNResult grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" @@ -109,12 +109,12 @@ static async Task GrantTTL() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantPresence() { - //snippet.grant_presence + // snippet.grant_presence PNResult grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel-pnpres" @@ -127,12 +127,12 @@ static async Task GrantPresence() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantChannelGroup() { - //snippet.grant_group + // snippet.grant_group PNResult grantResponse = await pubnub.Grant() .ChannelGroups(new string[] { "cg1", @@ -154,12 +154,12 @@ static async Task GrantChannelGroup() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantWithAuthKey() { - //snippet.grant_auth_key + // snippet.grant_auth_key PNResult grantResponse = await pubnub.Grant() .Uuids(new string[] { "my_uuid" @@ -176,12 +176,12 @@ static async Task GrantWithAuthKey() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantAppLevel() { - //snippet.grant_app_level + // snippet.grant_app_level PNResult grantResponse = await pubnub.Grant() .Write(true) .Read(true) @@ -191,12 +191,12 @@ static async Task GrantAppLevel() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantChannelLevel() { - //snippet.grant_channel_level + // snippet.grant_channel_level PNResult grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" @@ -209,12 +209,12 @@ static async Task GrantChannelLevel() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } static async Task GrantUserLevel() { - //snippet.grant_user_level + // snippet.grant_user_level PNResult grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" @@ -231,6 +231,6 @@ static async Task GrantUserLevel() PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; //PNAccessManagerGrantResult is a parsed and abstracted response from server - //snippet.end + // snippet.end } } \ No newline at end of file diff --git a/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs index 2a7e526ce..f476756c8 100644 --- a/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs +++ b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs @@ -1,6 +1,6 @@ -//snippet.using +// snippet.using using PubnubApi; -//snippet.end +// snippet.end public class ChannelGroupsSample { @@ -8,7 +8,7 @@ public class ChannelGroupsSample static void PubnubInit() { - //snippet.pubnub_init + // snippet.pubnub_init //Create configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -17,12 +17,12 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static async Task AddToGroup() { - //snippet.add_to_group + // snippet.add_to_group try { PNResult cgAddChResponse = await pubnub.AddChannelsToChannelGroup() @@ -46,36 +46,36 @@ static async Task AddToGroup() { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } - //snippet.end + // snippet.end } static async Task ListFromGroup() { - //snippet.list + // snippet.list PNResult cgListChResponse = await pubnub.ListChannelsForChannelGroup() .ChannelGroup("cg1") .ExecuteAsync(); - //snippet.end + // snippet.end } static async Task RemoveFromGroup() { - //snippet.remove + // snippet.remove PNResult rmChFromCgResponse = await pubnub.RemoveChannelsFromChannelGroup() .ChannelGroup("family") .Channels(new string[] { "son" }) .ExecuteAsync(); - //snippet.end + // snippet.end } static async Task DeleteGroup() { - //snippet.delete + // snippet.delete PNResult delCgResponse = await pubnub.DeleteChannelGroup() .ChannelGroup("family") .ExecuteAsync(); - //snippet.end + // snippet.end } } \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs index c915a34d4..8ad361534 100644 --- a/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs +++ b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs @@ -1,11 +1,11 @@ -//snippet.using +// snippet.using using PubnubApi; -//snippet.end +// snippet.end -//snippet.using_crypto +// snippet.using_crypto using PubnubApi.Security.Crypto; using PubnubApi.Security.Crypto.Cryptors; -//snippet.end +// snippet.end public class ConfigurationSample { @@ -13,11 +13,11 @@ public class ConfigurationSample static void PubnubInit() { - //snippet.init_config + // snippet.init_config PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); - //snippet.end + // snippet.end - //snippet.crypto + // snippet.crypto // encrypts using 256-bit AES-CBC cipher (recommended) // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers pnConfiguration.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), @@ -27,16 +27,16 @@ static void PubnubInit() // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers pnConfiguration.CryptoModule = new CryptoModule(new LegacyCryptor("enigma"), new List { new AesCbcCryptor("enigma") }); - //snippet.end + // snippet.end - //snippet.new_pubnub + // snippet.new_pubnub Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static void BasicUsage() { - //snippet.basic_usage + // snippet.basic_usage // Create a configuration instance for PubNub PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -63,54 +63,54 @@ static void BasicUsage() // Initialize a new PubNub instance with the created confiiguration Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end - //snippet.user_id + // snippet.user_id pnConfiguration.UserId = new UserId("myUserId"); - //snippet.end + // snippet.end - //snippet.get_user_id + // snippet.get_user_id UserId currentUserId = pubnub.GetCurrentUserId(); - //snippet.end + // snippet.end } static void ChangeUserId() { - //snippet.change_user_id + // snippet.change_user_id //Setting the initial UserId PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); //Changing to a new UserId pnConfiguration.UserId = new UserId("myUserId"); - //snippet.end + // snippet.end } static void SetAndGetAuthKey() { - //snippet.set_auth_key + // snippet.set_auth_key PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.AuthKey = "authKey"; - //snippet.end + // snippet.end - //snippet.get_auth_key + // snippet.get_auth_key string sampleAuthKey = pnConfiguration.AuthKey; - //snippet.end + // snippet.end } static void FilterExpression() { - //snippet.filter_expression + // snippet.filter_expression PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.FilterExpression = "such=wow"; - //snippet.end + // snippet.end - //snippet.get_filter_expression + // snippet.get_filter_expression string filterExpression = pnConfiguration.FilterExpression; - //snippet.end + // snippet.end } static void InitWithUUID() { - //snippet.init_with_uuid + // snippet.init_with_uuid // Initialize PubNub using the configuration PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -121,34 +121,34 @@ static void InitWithUUID() // Create the PubNub instance with the configuration Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static void InitNonSecure() { - //snippet.init_non_secure + // snippet.init_non_secure PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.Secure = false; Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static void InitSecure() { - //snippet.init_secure + // snippet.init_secure PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.Secure = true; Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static void InitSecretKey() { - //snippet.init_secret_key + // snippet.init_secret_key PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SubscribeKey = "my_subkey"; @@ -156,15 +156,15 @@ static void InitSecretKey() pnConfiguration.Secure = true; Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } static void InitReadOnly() { - //snippet.init_read_only + // snippet.init_read_only PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")); pnConfiguration.SubscribeKey = "my_subkey"; Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } } \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Files/FilesSample.cs b/src/PubnubApi.Snippets/Files/FilesSample.cs index f3285c5d4..32ef6fe41 100644 --- a/src/PubnubApi.Snippets/Files/FilesSample.cs +++ b/src/PubnubApi.Snippets/Files/FilesSample.cs @@ -1,6 +1,6 @@ -//snippet.using +// snippet.using using PubnubApi; -//snippet.end +// snippet.end public class FilesSample { @@ -8,7 +8,7 @@ public class FilesSample static void InitSample() { - //snippet.init + // snippet.init PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { SubscribeKey = "demo", @@ -17,12 +17,12 @@ static void InitSample() }; Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } public static async Task SendFileBasicUsage() { - //snippet.send_file_basic_usage + // snippet.send_file_basic_usage try { PNResult fileUploadResponse = await pubnub.SendFile() @@ -48,12 +48,12 @@ public static async Task SendFileBasicUsage() { Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); } - //snippet.end + // snippet.end } public static async Task ListFilesBasicUsage() { - //snippet.list_files_basic_usage + // snippet.list_files_basic_usage PNResult listFilesResponse = await pubnub.ListFiles() .Channel("my_channel") .ExecuteAsync(); @@ -67,12 +67,12 @@ public static async Task ListFilesBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesStatus)); } - //snippet.end + // snippet.end } public static async Task GetFileUrlBasicUsage() { - //snippet.get_file_url_basic_usage + // snippet.get_file_url_basic_usage PNResult getFileUrlResponse = await pubnub.GetFileUrl() .Channel("my_channel") .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") @@ -88,12 +88,12 @@ public static async Task GetFileUrlBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus)); } - //snippet.end + // snippet.end } public static async Task DownloadFileBasicUsage(string downloadUrlFileName) { - //snippet.download_file_basic_usage + // snippet.download_file_basic_usage PNResult fileDownloadResponse = await pubnub.DownloadFile() .Channel("my_channel") .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") @@ -110,12 +110,12 @@ public static async Task DownloadFileBasicUsage(string downloadUrlFileName) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadStatus)); } - //snippet.end + // snippet.end } public static async Task DeleteFileBasicUsage() { - //snippet.delete_file_basic_usage + // snippet.delete_file_basic_usage PNResult deleteFileResponse = await pubnub.DeleteFile() .Channel("my_channel") .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") @@ -131,12 +131,12 @@ public static async Task DeleteFileBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileStatus)); } - //snippet.end + // snippet.end } public static async Task PublishFileMessageBasicUsage() { - //snippet.publish_file_message_basic_usage + // snippet.publish_file_message_basic_usage PNResult publishFileMsgResponse = await pubnub.PublishFileMessage() .Channel("my_channel") .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770") @@ -154,6 +154,6 @@ public static async Task PublishFileMessageBasicUsage() { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgStatus)); } - //snippet.end + // snippet.end } } \ No newline at end of file From 486d00867e832c8b5e6f493dbf7fa9d5a19af4c1 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 18 Jun 2025 15:36:23 +0200 Subject: [PATCH 05/17] snippet formatting corrections, add message actions sample --- .../AccessManager/AccessManagerSample.cs | 2 + .../AccessManager/AccessManagerV2Sample.cs | 2 + .../ChannelGroup/ChannelGroupsSample.cs | 2 + .../Configuration/ConfigurationSample.cs | 2 + src/PubnubApi.Snippets/Files/FilesSample.cs | 1 + .../MessageActions/MessageActionsSample.cs | 83 +++++++++++++++++++ 6 files changed, 92 insertions(+) create mode 100644 src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs index f44050895..faf4d87de 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -1,5 +1,6 @@ // snippet.using using PubnubApi; + // snippet.end class AccessManagerSample @@ -17,6 +18,7 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); + // snippet.end } diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs index bade97219..318579860 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs @@ -1,5 +1,6 @@ // snippet.using using PubnubApi; + // snippet.end public class AccessManagerV2Sample @@ -17,6 +18,7 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); + // snippet.end } diff --git a/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs index f476756c8..e51269672 100644 --- a/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs +++ b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs @@ -1,5 +1,6 @@ // snippet.using using PubnubApi; + // snippet.end public class ChannelGroupsSample @@ -17,6 +18,7 @@ static void PubnubInit() }; //Create a new PubNub instance Pubnub pubnub = new Pubnub(pnConfiguration); + // snippet.end } diff --git a/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs index 8ad361534..0143131cf 100644 --- a/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs +++ b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs @@ -1,5 +1,6 @@ // snippet.using using PubnubApi; + // snippet.end // snippet.using_crypto @@ -31,6 +32,7 @@ static void PubnubInit() // snippet.new_pubnub Pubnub pubnub = new Pubnub(pnConfiguration); + // snippet.end } diff --git a/src/PubnubApi.Snippets/Files/FilesSample.cs b/src/PubnubApi.Snippets/Files/FilesSample.cs index 32ef6fe41..b006974ee 100644 --- a/src/PubnubApi.Snippets/Files/FilesSample.cs +++ b/src/PubnubApi.Snippets/Files/FilesSample.cs @@ -1,5 +1,6 @@ // snippet.using using PubnubApi; + // snippet.end public class FilesSample diff --git a/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs new file mode 100644 index 000000000..1e2f9b80d --- /dev/null +++ b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs @@ -0,0 +1,83 @@ +// snippet.using +using PubnubApi; + +//snippet.end + +public class MessageActionsSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + public static void AddMessageActionBasicUsage() + { + // snippet.add_message_action_basic_usage + try + { + pubnub.AddMessageAction() + .Channel("my_channel") + .MessageTimetoken(5610547826969050) // Replace with actual message timetoken + .Action(new PNMessageAction { Type = "reaction", Value = "smiley_face" }) + .Execute(new PNAddMessageActionResultExt((result, status) => + { + if (!status.Error && result != null) + { + Console.WriteLine("Message action added successfully."); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } + })); + } + catch (Exception ex) + { + Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); + } + // snippet.end + } + + public static void RemoveMessageActionBasicUsage() + { + // snippet.remove_message_action_basic_usage + Pubnub pubnub = null; // Assume initialized elsewhere + pubnub.RemoveMessageAction() + .Channel("my_channel") + .MessageTimetoken(15701761818730000) + .ActionTimetoken(15701775691010000) + .Uuid("mytestuuid") + .Execute(new PNRemoveMessageActionResultExt((result, status) => + { + //empty result of type PNRemoveMessageActionResult. + })); + // snippet.end + } + + public static void GetMessageActionsBasicUsage() + { + // snippet.get_message_actions_basic_usage + Pubnub pubnub = null; // Assume initialized elsewhere + pubnub.GetMessageActions() + .Channel("my_channel") + .Execute(new PNGetMessageActionsResultExt((result, status) => + { + //result is of type PNGetMessageActionsResult. + })); + // snippet.end + } +} \ No newline at end of file From d930d8115a98c0f02bb8ee492c3e39b0dfe4de50 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 18 Jun 2025 16:36:40 +0200 Subject: [PATCH 06/17] add misc samples --- src/PubnubApi.Snippets/Misc/MiscSample.cs | 133 ++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 src/PubnubApi.Snippets/Misc/MiscSample.cs diff --git a/src/PubnubApi.Snippets/Misc/MiscSample.cs b/src/PubnubApi.Snippets/Misc/MiscSample.cs new file mode 100644 index 000000000..c8c3dd386 --- /dev/null +++ b/src/PubnubApi.Snippets/Misc/MiscSample.cs @@ -0,0 +1,133 @@ +// snippet.using +using PubnubApi; + +//snippet.end + +public class MiscSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + //snippet.end + } + + public static void DestroyBasicUsage() + { + // snippet.destroy_basic_usage + // Destroy PubNub instance to clean up resources + pubnub.Destroy(); + + Console.WriteLine("PubNub instance destroyed successfully."); + // snippet.end + } + + public static void EncryptBasicUsage() + { + // snippet.encrypt_basic_usage + string stringToEncrypt = "hello world"; + var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); + crypto.Encrypt(stringToEncrypt); + // snippet.end + } + + public static void EncryptFileBasicUsage() + { + // snippet.encrypt_file_basic_usage + 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); + // snippet.end + } + + public static void EncryptFileBytesBasicUsage() + { + // snippet.encrypt_file_bytes_basic_usage + byte[] sourceBytes = System.IO.File.ReadAllBytes("cat_picture.jpg"); // checks bin folder if no path is provided + var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); + byte[] outputBytes = crypto.Encrypt(sourceBytes); + System.IO.File.WriteAllBytes("destination_cat_pic.jpg", outputBytes); // checks bin folder if no path is provided + // snippet.end + } + + public static void DecryptBasicUsage() + { + // snippet.decrypt_basic_usage + var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); + crypto.Decrypt("encryptedString"); + // snippet.end + } + + public static void DecryptFileBasicUsage() + { + // snippet.decrypt_file_basic_usage + string source_file = "encrypted_cat_pic.jpg"; // checks bin folder if no path is provided + string destination_file = "cat_pic_original.jpg"; // checks bin folder if no path is provided + var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); + crypto.DecryptFile(source_file, destination_file); + // snippet.end + } + + public static void DecryptFileBytesBasicUsage() + { + // snippet.decrypt_file_bytes_basic_usage + byte[] sourceBytes = System.IO.File.ReadAllBytes("encrypted_cat_pic.jpg"); // checks bin folder if no path is provided + var crypto = PubnubApi.Security.Crypto.CryptoModule.CreateAesCbcCryptor("test"); + byte[] outputBytes = crypto.Decrypt(sourceBytes); + System.IO.File.WriteAllBytes("cat_pic_original.jpg", outputBytes); // checks bin folder if no path is provided + // snippet.end + } + + public static void DisconnectBasicUsage() + { + // snippet.disconnect_basic_usage + pubnub.Disconnect(); + // snippet.end + } + + public static void GetSubscribedChannelGroupsBasicUsage() + { + // snippet.get_subscribed_channel_groups_basic_usage + List groups = pubnub.GetSubscribedChannelGroups(); + // snippet.end + } + + public static void GetSubscribedChannelsBasicUsage() + { + // snippet.get_subscribed_channels_basic_usage + List channels = pubnub.GetSubscribedChannels(); + // snippet.end + } + + public static void ReconnectBasicUsage() + { + // snippet.reconnect_basic_usage + pubnub.Reconnect(); + // snippet.end + } + + public static void TimeBasicUsage() + { + // snippet.time_basic_usage + pubnub.Time() + .Execute(new PNTimeResultExt( + (result, status) => { + // handle time result. + } + )); + // snippet.end + } +} \ No newline at end of file From 393357aeacd6d14f49282686af7634e5d4f95fac Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Mon, 23 Jun 2025 14:22:19 +0200 Subject: [PATCH 07/17] add missing SetAuthToken snippet, add entities and push samples --- .../AccessManager/AccessManagerSample.cs | 11 +- .../Entities/EntitiesSample.cs | 358 ++++++++++++++++++ src/PubnubApi.Snippets/Push/PushSample.cs | 170 +++++++++ 3 files changed, 538 insertions(+), 1 deletion(-) create mode 100644 src/PubnubApi.Snippets/Entities/EntitiesSample.cs create mode 100644 src/PubnubApi.Snippets/Push/PushSample.cs diff --git a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs index faf4d87de..56bcf4abd 100644 --- a/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -293,7 +293,16 @@ static async Task RevokeTokenBasicUsage() } // snippet.end } - + + static async Task SetAuthTokenSnippet() + { + // snippet.set_token + pubnub.SetAuthToken( + "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"); + + // snippet.end + } + static async Task ParseTokenBasicUsage() { // snippet.parse_token_usage diff --git a/src/PubnubApi.Snippets/Entities/EntitiesSample.cs b/src/PubnubApi.Snippets/Entities/EntitiesSample.cs new file mode 100644 index 000000000..8cc3d122f --- /dev/null +++ b/src/PubnubApi.Snippets/Entities/EntitiesSample.cs @@ -0,0 +1,358 @@ +// snippet.using +using PubnubApi; + +//snippet.end + +public class EntitiesSample +{ + private static Pubnub pubnub; + private static PNConfiguration config; + + static void Init() + { + // snippet.pubnub_init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + public static async Task GetAllUuidMetadataBasicUsage() + { + // snippet.get_all_uuid_metadata_basic_usage + 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}"); + } + // snippet.end + } + + public static async Task GetUuidMetadataBasicUsage() + { + // snippet.get_uuid_metadata_basic_usage + // Get Metadata for UUID set in the pubnub instance + PNResult getUuidSetMetadataResponse = await pubnub.GetUuidMetadata() + .ExecuteAsync(); + PNGetUuidMetadataResult getUuidSetMetadataResult = getUuidSetMetadataResponse.Result; + PNStatus uuidSetStatus = getUuidSetMetadataResponse.Status; + + // Get Metadata for a specific UUID + PNResult getSpecificUuidMetadataResponse = await pubnub.GetUuidMetadata() + .Uuid("my-uuid") + .ExecuteAsync(); + PNGetUuidMetadataResult getSpecificUuidMetadataResult = getSpecificUuidMetadataResponse.Result; + PNStatus specificUuidStatus = getSpecificUuidMetadataResponse.Status; + // snippet.end + } + + public static async Task SetUuidMetadataBasicUsage() + { + // snippet.set_uuid_metadata_basic_usage + // Set Metadata for UUID set in the pubnub instance + PNResult setUuidMetadataResponse = await pubnub.SetUuidMetadata() + .Uuid(config.Uuid) + .Name("John Doe") + .Email("john.doe@user.com") + .ExecuteAsync(); + PNSetUuidMetadataResult setUuidMetadataResult = setUuidMetadataResponse.Result; + PNStatus status = setUuidMetadataResponse.Status; + // snippet.end + } + + public static async Task RemoveUuidMetadataBasicUsage() + { + // snippet.remove_uuid_metadata_basic_usage + // Remove Metadata for UUID set in the pubnub instance + PNResult removeUuidMetadataResponse = await pubnub.RemoveUuidMetadata() + .ExecuteAsync(); + PNRemoveUuidMetadataResult removeUuidMetadataResult = removeUuidMetadataResponse.Result; + PNStatus status = removeUuidMetadataResponse.Status; + // snippet.end + } + + public static async Task GetAllChannelMetadataBasicUsage() + { + // snippet.get_all_channel_metadata_basic_usage + PNResult getAllChannelMetadataResponse = await pubnub.GetAllChannelMetadata() + .IncludeCount(true) + .IncludeCustom(true) + .ExecuteAsync(); + + PNGetAllChannelMetadataResult getAllChannelMetadataResult = getAllChannelMetadataResponse.Result; + PNStatus status2 = getAllChannelMetadataResponse.Status; + // snippet.end + } + + public static async Task GetChannelMetadataBasicUsage() + { + // snippet.get_channel_metadata_basic_usage + // Get Metadata for a specific channel + PNResult getChannelMetadataResponse = await pubnub.GetChannelMetadata() + .Channel("my-channel") + .IncludeCustom(true) + .ExecuteAsync(); + + PNGetChannelMetadataResult getChannelMetadataResult = getChannelMetadataResponse.Result; + PNStatus status = getChannelMetadataResponse.Status; + // snippet.end + } + + public static async Task SetChannelMetadataBasicUsage() + { + // snippet.set_channel_metadata_basic_usage + // Set Metadata for a specific channel + PNResult setChannelMetadataResponse = await pubnub.SetChannelMetadata() + .Channel("my-channel") + .Name("John Doe") + .Description("sample description") + .Custom(new Dictionary() { { "color", "blue" } }) + .IncludeCustom(true) + .ExecuteAsync(); + + PNSetChannelMetadataResult setChannelMetadataResult = setChannelMetadataResponse.Result; + PNStatus status = setChannelMetadataResponse.Status; + // snippet.end + } + + public static async Task SetChannelMetadataIterativeUpdate() + { + // snippet.set_channel_metadata_iterative_update + PNConfiguration config = new PNConfiguration(new UserId("example")) + { + PublishKey = "demo", + SubscribeKey = "demo", + }; + Pubnub pubnub = new Pubnub(config); + string channel = "team.red"; + string name = "Red Team"; + string description = "The channel for Red team."; + var customField = new Dictionary() + { + { "visible", "team" }, + }; + PNResult setChannelMetadataResponse = await pubnub.SetChannelMetadata() + .Channel(channel) + .Name(name) + .Description(description) + .Custom(customField) + .ExecuteAsync(); + Console.WriteLine("The channel has been created with name and description.\n"); + + // Fetch current object with custom fields + PNResult currentObjectResponse = await pubnub.GetChannelMetadata() + .Channel(channel) + .IncludeCustom(true) + .ExecuteAsync(); + var currentObject = currentObjectResponse.Result; + + // Initialize the custom field dictionary + Dictionary custom = currentObject?.Custom ?? new Dictionary(); + + + // Add or update the field + custom["edit"] = "admin"; + + // Writing the updated object back to the server + try + { + setChannelMetadataResponse = await pubnub.SetChannelMetadata() + .Channel(channel) + .Custom(custom) + .Name(currentObject?.Name) + .Description(currentObject?.Description) + .ExecuteAsync(); + Console.WriteLine($"Object has been updated.\n {setChannelMetadataResponse.Result}"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + // snippet.end + } + + public static async Task RemoveChannelMetadataBasicUsage() + { + // snippet.remove_channel_metadata_basic_usage + // Delete Metadata for a specific channel + PNResult removeChannelMetadataResponse = await pubnub.RemoveChannelMetadata() + .Channel("mychannel") + .ExecuteAsync(); + + PNRemoveChannelMetadataResult removeChannelMetadataResult = removeChannelMetadataResponse.Result; + PNStatus status = removeChannelMetadataResponse.Status; + // snippet.end + } + + public static async Task GetMembershipsBasicUsage() + { + // snippet.get_memberships_basic_usage + PNResult getMembershipsResponse = await pubnub.GetMemberships() + .Uuid("my-uuid") + .Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM }) + .IncludeCount(true) + .Page(new PNPageObject() { Next = "", Prev = "" }) + .ExecuteAsync(); + + PNMembershipsResult getMembeshipsResult = getMembershipsResponse.Result; + PNStatus status = getMembershipsResponse.Status; + // snippet.end + } + + public static async Task SetMembershipsBasicUsage() + { + // snippet.set_memberships_basic_usage + List setMembershipChannelMetadataIdList = + [ + new PNMembership() + { Channel = "my-channel", Custom = new Dictionary() { { "item", "book" } } } + ]; + + PNResult setMembershipsResponse = await pubnub.SetMemberships() + .Uuid("my-uuid") + .Channels(setMembershipChannelMetadataIdList) + .Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM }) + .IncludeCount(true) + .ExecuteAsync(); + + PNMembershipsResult setMembershipsResult = setMembershipsResponse.Result; + PNStatus status = setMembershipsResponse.Status; + // snippet.end + } + + public static async Task RemoveMembershipsBasicUsage() + { + // snippet.remove_memberships_basic_usage + List removeMembershipList = + [ + "my-channel", + "your-channel" + ]; + + PNResult removeMembershipsResponse = await pubnub.RemoveMemberships() + .Uuid("uuid") + .Channels(removeMembershipList) + .Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM }) + .IncludeCount(true) + .ExecuteAsync(); + + PNMembershipsResult removeMembershipsResult = removeMembershipsResponse.Result; + PNStatus status2 = removeMembershipsResponse.Status; + // snippet.end + } + + public static async Task ManageMembershipsBasicUsage() + { + // snippet.manage_memberships_basic_usage + 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; + // snippet.end + } + + public static async Task GetChannelMembersBasicUsage() + { + // snippet.get_channel_members_basic_usage + // 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; + // snippet.end + } + + public static async Task SetChannelMembersBasicUsage() + { + // snippet.set_channel_members_basic_usage + // Add Members (UUID) for a specific channel + List setMemberChannelList = + [ + new PNChannelMember() + { Uuid = "my-uuid", Custom = new Dictionary() { { "planet", "earth" } } } + ]; + + PNResult setChannelMembersResponse = await pubnub.SetChannelMembers() + .Channel("my-channel") + .Uuids(setMemberChannelList) + .Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM }) + .IncludeCount(true) + .ExecuteAsync(); + + PNChannelMembersResult setChannelMembersResult = setChannelMembersResponse.Result; + PNStatus status2 = setChannelMembersResponse.Status; + // snippet.end + } + + public static async Task RemoveChannelMembersBasicUsage() + { + // snippet.remove_channel_members_basic_usage + // Remove Members (UUID) for a specific channel + List removeChannelMemberList = + [ + "my-uuid", + "your-uuid" + ]; + + PNResult removeChannelMembersResponse = await pubnub.RemoveChannelMembers() + .Channel("my-channel") + .Uuids(removeChannelMemberList) + .Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM }) + .IncludeCount(true) + .ExecuteAsync(); + + PNChannelMembersResult removeChannelMembersResult = removeChannelMembersResponse.Result; + PNStatus status = removeChannelMembersResponse.Status; + // snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Push/PushSample.cs b/src/PubnubApi.Snippets/Push/PushSample.cs new file mode 100644 index 000000000..739834e77 --- /dev/null +++ b/src/PubnubApi.Snippets/Push/PushSample.cs @@ -0,0 +1,170 @@ +// snippet.using +using PubnubApi; + +//snippet.end + +public class PushSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.pubnub_init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + // snippet.add_device_to_channel_basic_usage + public class PushNotificationCallback : PNCallback + { + public override void OnResponse(PNPushAddChannelResult result, PNStatus status) + { + if (!status.Error && result != null) + { + Console.WriteLine("Push notifications added to channels successfully."); + } + else + { + Console.WriteLine("Failed to add push notifications: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } + } + } + + public static void AddDeviceToChannelBasicUsage() + { + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + try + { + // For FCM + pubnub.AddPushNotificationsOnChannels() + .PushType(PNPushType.FCM) + .Channels(new string[] { "ch1", "ch2", "ch3" }) + .DeviceId("googleDevice") + .Execute(new PushNotificationCallback()); + } + catch (Exception ex) + { + Console.WriteLine($"FCM operation failed due to error: {ex.Message}"); + } + + try + { + // For APNS2 + pubnub.AddPushNotificationsOnChannels() + .PushType(PNPushType.APNS2) + .Channels(new string[] { "ch1", "ch2", "ch3" }) + .DeviceId("appleDevice") + .Topic("myapptopic") + .Environment(PushEnvironment.Development) + .Execute(new PushNotificationCallback()); + } + catch (Exception ex) + { + Console.WriteLine($"APNS2 operation failed due to error: {ex.Message}"); + } + } + // snippet.end + + public static void ListChannelsForDeviceBasicUsage() + { + // snippet.list_channels_for_device_basic_usage + // for FCM/GCM + pubnub.AuditPushChannelProvisions() + .DeviceId("googleDevice") + .PushType(PNPushType.FCM) + .Execute(new PNPushListProvisionsResultExt((r, s) => + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + + // for APNS2 + pubnub.AuditPushChannelProvisions() + .DeviceId("appleDevice") + .PushType(PNPushType.APNS2) + .Topic("myapptopic") + .Environment(PushEnvironment.Development) + .Execute(new PNPushListProvisionsResultExt((r, s) => + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + // snippet.end + } + + public static void RemoveDeviceFromChannelBasicUsage() + { + // snippet.remove_device_from_channel_basic_usage + // for FCM/GCM + pubnub.RemovePushNotificationsFromChannels() + .DeviceId("googleDevice") + .Channels(new string[] { + "ch1", + "ch2", + "ch3" + }) + .PushType(PNPushType.FCM) + .Execute(new PNPushRemoveChannelResultExt((r, s) => + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + + // for APNS2 + pubnub.RemovePushNotificationsFromChannels() + .DeviceId("appleDevice") + .Channels(new string[] { + "ch1", + "ch2", + "ch3" + }) + .PushType(PNPushType.APNS2) + .Topic("myapptopic") + .Environment(PushEnvironment.Development) + .Execute(new PNPushRemoveChannelResultExt((r, s) => + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + // snippet.end + } + + public static void RemoveAllPushNotificationsBasicUsage() + { + // snippet.remove_all_push_notifications_basic_usage + // for FCM/GCM + pubnub.RemoveAllPushNotificationsFromDeviceWithPushToken() + .DeviceId("googleDevice") + .PushType(PNPushType.FCM) + .Execute(new PNPushRemoveAllChannelsResultExt((r, s) => { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + + // for APNS2 + pubnub.RemoveAllPushNotificationsFromDeviceWithPushToken() + .DeviceId("appleDevice") + .PushType(PNPushType.APNS2) + .Topic("myapptopic") + .Environment(PushEnvironment.Development) + .Execute(new PNPushRemoveAllChannelsResultExt((r, s) => { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); + })); + // snippet.end + } +} \ No newline at end of file From 8e49609568b290431c7c489ac59e6a90b235f994 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Mon, 23 Jun 2025 14:31:53 +0200 Subject: [PATCH 08/17] fix incorrect snippet endings --- src/PubnubApi.Snippets/Entities/EntitiesSample.cs | 2 +- src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs | 2 +- src/PubnubApi.Snippets/Misc/MiscSample.cs | 4 ++-- src/PubnubApi.Snippets/Push/PushSample.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/PubnubApi.Snippets/Entities/EntitiesSample.cs b/src/PubnubApi.Snippets/Entities/EntitiesSample.cs index 8cc3d122f..b09b5e2ae 100644 --- a/src/PubnubApi.Snippets/Entities/EntitiesSample.cs +++ b/src/PubnubApi.Snippets/Entities/EntitiesSample.cs @@ -1,7 +1,7 @@ // snippet.using using PubnubApi; -//snippet.end +// snippet.end public class EntitiesSample { diff --git a/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs index 1e2f9b80d..5d23dc9a2 100644 --- a/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs +++ b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs @@ -1,7 +1,7 @@ // snippet.using using PubnubApi; -//snippet.end +// snippet.end public class MessageActionsSample { diff --git a/src/PubnubApi.Snippets/Misc/MiscSample.cs b/src/PubnubApi.Snippets/Misc/MiscSample.cs index c8c3dd386..bb55db678 100644 --- a/src/PubnubApi.Snippets/Misc/MiscSample.cs +++ b/src/PubnubApi.Snippets/Misc/MiscSample.cs @@ -1,7 +1,7 @@ // snippet.using using PubnubApi; -//snippet.end +// snippet.end public class MiscSample { @@ -21,7 +21,7 @@ static void Init() // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); - //snippet.end + // snippet.end } public static void DestroyBasicUsage() diff --git a/src/PubnubApi.Snippets/Push/PushSample.cs b/src/PubnubApi.Snippets/Push/PushSample.cs index 739834e77..2f8e11437 100644 --- a/src/PubnubApi.Snippets/Push/PushSample.cs +++ b/src/PubnubApi.Snippets/Push/PushSample.cs @@ -1,7 +1,7 @@ // snippet.using using PubnubApi; -//snippet.end +// snippet.end public class PushSample { From 7393b96c2b1026e2a35530d8a913e7e68a6442d9 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Mon, 23 Jun 2025 17:12:10 +0200 Subject: [PATCH 09/17] add presence and pub/sub samples --- .../MessageActions/MessageActionsSample.cs | 2 - .../Presence/PresenceSample.cs | 304 +++++++ .../Publish/PublishSubscribeSample.cs | 764 ++++++++++++++++++ 3 files changed, 1068 insertions(+), 2 deletions(-) create mode 100644 src/PubnubApi.Snippets/Presence/PresenceSample.cs create mode 100644 src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs diff --git a/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs index 5d23dc9a2..eeae12e62 100644 --- a/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs +++ b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs @@ -55,7 +55,6 @@ public static void AddMessageActionBasicUsage() public static void RemoveMessageActionBasicUsage() { // snippet.remove_message_action_basic_usage - Pubnub pubnub = null; // Assume initialized elsewhere pubnub.RemoveMessageAction() .Channel("my_channel") .MessageTimetoken(15701761818730000) @@ -71,7 +70,6 @@ public static void RemoveMessageActionBasicUsage() public static void GetMessageActionsBasicUsage() { // snippet.get_message_actions_basic_usage - Pubnub pubnub = null; // Assume initialized elsewhere pubnub.GetMessageActions() .Channel("my_channel") .Execute(new PNGetMessageActionsResultExt((result, status) => diff --git a/src/PubnubApi.Snippets/Presence/PresenceSample.cs b/src/PubnubApi.Snippets/Presence/PresenceSample.cs new file mode 100644 index 000000000..dd2e46c92 --- /dev/null +++ b/src/PubnubApi.Snippets/Presence/PresenceSample.cs @@ -0,0 +1,304 @@ +// snippet.using +using PubnubApi; + +// snippet.end + +public class PresenceSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.pubnub_init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + public static async Task HereNowBasicUsage() + { + // snippet.here_now_basic_usage + 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}"); + } + // snippet.end + } + + public static void HereNowSynchronous() + { + // snippet.here_now_synchronous + 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 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) : "")); + } + } + } + } + } + )); + // snippet.end + } + + public static async Task HereNowReturningState() + { + // snippet.here_now_returning_state + PNResult herenowResponse = await 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 + .ExecuteAsync(); + + PNHereNowResult herenowResult = herenowResponse.Result; + PNStatus status = herenowResponse.Status; + //handle it + // snippet.end + } + + public static async Task HereNowReturnOccupancyOnly() + { + // snippet.here_now_return_occupancy_only + PNResult herenowResponse = await 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 + .ExecuteAsync(); + + PNHereNowResult herenowResult = herenowResponse.Result; + PNStatus status = herenowResponse.Status; + //handle it + // snippet.end + } + + public static async Task WhereNowBasicUsage() + { + // snippet.where_now_basic_usage + PNResult wherenowResponse = await pubnub.WhereNow() + .ExecuteAsync(); + + PNWhereNowResult wherenowResult = wherenowResponse.Result; + PNStatus status = wherenowResponse.Status; + // returns a pojo with channels + // channel groups which I am part of. + // snippet.end + } + + public static void WhereNowSynchronous() + { + // snippet.where_now_synchronous + pubnub.WhereNow() + .Execute(new PNWhereNowResultExt( + (result, status) => { + // returns a pojo with channels + // channel groups which I am part of. + } + )); + // snippet.end + } + + public static async Task WhereNowOtherUuid() + { + // snippet.where_now_other_uuid + PNResult wherenowResponse = await pubnub.WhereNow() + .Uuid("some-other-uuid") // uuid of the user we want to spy on. + .ExecuteAsync(); + + PNWhereNowResult wherenowResult = wherenowResponse.Result; + PNStatus status = wherenowResponse.Status; + // returns a pojo with channels + // channel groups which "some-other-uuid" part of.ere_now_example_1 + // snippet.end + } + + public static async Task SetPresenceStateBasicUsage() + { + // snippet.set_presence_state_basic_usage + Dictionary myState = new Dictionary(); + myState.Add("age", 20); + + PNResult setstateResponse = await pubnub.SetPresenceState() + .Channels(new string[] { + "ch1", + "ch2", + "ch3" + }) + .State(myState) + .ExecuteAsync(); + + PNSetStateResult setstateResult = setstateResponse.Result; + PNStatus status = setstateResponse.Status; + // handle set state response + // snippet.end + } + + public static async Task GetPresenceStateBasicUsage() + { + // snippet.get_presence_state_basic_usage + PNResult getstateResponse = await 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 + .ExecuteAsync(); + + PNGetStateResult getstateResult = getstateResponse.Result; + PNStatus status = getstateResponse.Status; + // handle response + // snippet.end + } + + public static void SetPresenceStateSynchronous() + { + // snippet.set_presence_state_synchronous + Dictionary myState = new Dictionary(); + myState.Add("age", 20); + + pubnub.SetPresenceState() + .Channels(new string[] { + "ch1", + "ch2", + "ch3" + }) + .State(myState) + .Execute(new PNSetStateResultExt( + (result, status) => { + // handle set state response + } + )); + // snippet.end + } + + public static void GetPresenceStateSynchronous() + { + // snippet.get_presence_state_synchronous + 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 + } + )); + // snippet.end + } + + public static async Task SetPresenceStateForChannelGroups() + { + // snippet.set_presence_state_for_channel_groups + Dictionary myState = new Dictionary(); + myState.Add("age", 20); + + PNResult setstateResponse = await 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 + .ExecuteAsync(); + + PNSetStateResult setstateResult = setstateResponse.Result; + PNStatus status = setstateResponse.Status; + // on new state for those channels + // snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs b/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs new file mode 100644 index 000000000..7a98f712c --- /dev/null +++ b/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs @@ -0,0 +1,764 @@ +// snippet.using +using PubnubApi; + +// snippet.end + +public class PublishSubscribeSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.pubnub_init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + public static async Task PublishBasicUsage() + { + // snippet.publish_basic_usage + try + { + // Publishing a message to a channel + Dictionary position = new Dictionary + { + { "lat", 32F }, + { "lng", 32F } + }; + + Console.WriteLine("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position)); + + PNResult publishResponse = await pubnub.Publish() + .Message(position) + .Channel("my_channel") + .CustomMessageType("text-message") + .ExecuteAsync(); + + PNPublishResult publishResult = publishResponse.Result; + PNStatus status = publishResponse.Status; + + if (!status.Error) + { + Console.WriteLine("pub timetoken: " + publishResult.Timetoken.ToString()); + Console.WriteLine("pub status code : " + status.StatusCode.ToString()); + } + else + { + Console.WriteLine("Error occurred: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } + } + catch (Exception ex) + { + Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); + } + // snippet.end + } + + public static void PublishSynchronous() + { + // snippet.publish_synchronous + //Publishing Dictionary + Dictionary position = new Dictionary(); + position.Add("lat", 32F); + position.Add("lng", 32F); + + Console.WriteLine("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position)); + + pubnub.Publish() + .Message(position) + .Channel("my_channel") + .CustomMessageType("text-message") + .Execute(new PNPublishResultExt( + (result, status) => { + Console.WriteLine("pub timetoken: " + result.Timetoken.ToString()); + Console.WriteLine("pub status code : " + status.StatusCode.ToString()); + } + )); + // snippet.end + } + + public static void PublishWithMetadata() + { + // snippet.publish_with_metadata + string[] arrayMessage = new string[] { + "hello", + "there" + }; + + pubnub.Publish() + .Message(arrayMessage.ToList()) + .Channel("suchChannel") + .ShouldStore(true) + .Meta(new Dictionary(){ { "someKey", "someValue" }}) + .UsePOST(true) + .CustomMessageType("text-message") + .Execute(new PNPublishResultExt( + (result, status) => { + // handle publish result, status always present, result if successful + // status.Error to see if error happened + } + )); + // snippet.end + } + + public static async Task PublishStoreForHours() + { + // snippet.publish_store_for_hours + var publishResult = await pubnub.Publish() + .Channel("coolChannel") + .Message("test") + .ShouldStore(true) + .Ttl(10) + .ExecuteAsync(); + // snippet.end + } + + // snippet.publish_mobile_payload + + public class MobilePayload + { + public Dictionary pn_apns; + public Dictionary pn_gcm; + public Dictionary full_game; + } + + public static void PublishMobilePayload() + { + Dictionary apnsData = new Dictionary(); + apnsData.Add("aps", new Dictionary() { + { "alert", "Game update 49ers touchdown" }, + { "badge", 2 } + }); + apnsData.Add("teams", new string[] { "49ers", "raiders" }); + apnsData.Add("score", new int[] { 7, 0 }); + + Dictionary gcmData = new Dictionary(); + gcmData.Add("data", new Dictionary() { + { + "summary", "Game update 49ers touchdown" + }, + { + "teams", new string[]{ "49ers", "raiders"} + }, + { + "score", new int[]{ 7, 0} + }, + { + "lastplay", "5yd run up the middle" + }, + }); + + MobilePayload mobilePayload = new MobilePayload(); + mobilePayload.pn_apns = apnsData; + mobilePayload.pn_gcm = gcmData; + mobilePayload.full_game = new Dictionary() { + { "date","2014.05.20" }, + { "foobar","Data that is not pertinent to devices" } + }; + + pubnub.Publish() + .Message(mobilePayload) + .Channel("my_channel") + .ShouldStore(true) + .CustomMessageType("text-message") + .Execute(new PNPublishResultExt( + (result, status) => { + // Check whether request successfully completed or not. + if (status.Error) { + // something bad happened. + Console.WriteLine($"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); + } else { + Console.WriteLine($"published with timetoken: {result.Timetoken}"); + } + } + )); + } + // snippet.end + + public static void FireBasicUsage() + { + // snippet.fire_basic_usage + string[] arrMessage = new string[] { + "hello", + "there" + }; + + pubnub.Fire() + .Message(arrMessage.ToList()) + .Channel("my-channel") + .UsePOST(true) + .Execute(new PNPublishResultExt( + (result, status) => { + if (status.Error) { + Console.WriteLine($"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); + } else { + Console.WriteLine($"published with timetoken: {result.Timetoken}"); + } + } + )); + // snippet.end + } + + public static void SignalBasicUsage() + { + // snippet.signal_basic_usage + Dictionary myMessage = new Dictionary(); + myMessage.Add("msg", "Hello Signals"); + + pubnub.Signal() + .Message(myMessage) + .Channel("foo") + .CustomMessageType("text-message") + .Execute(new PNPublishResultExt((result, status) => { + if (status.Error) { + Console.WriteLine(status.ErrorData.Information); + } else { + Console.WriteLine(result.Timetoken); + } + })); + // snippet.end + } + + public static void SubscribeBasicUsage() + { + // snippet.subscribe_basic_usage + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels + "my_channel" + }) + .Execute(); + // snippet.end + } + + public static void SubscribeWithLogging() + { + // snippet.subscribe_with_logging + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + // subscribeKey from admin panel + SubscribeKey = "my_subkey", // required + // publishKey from admin panel (only required if publishing) + PublishKey = "my_pubkey", + // logging level declaration + LogLevel = PubnubLogLevel.Debug + }; + + Pubnub pubnub = new Pubnub(pnConfiguration); + + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels + "my_channel" + }) + .Execute(); + // snippet.end + } + + public static void SubscribeMultipleChannels() + { + // snippet.subscribe_multiple_channels + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels information + "my_channel1", + "my_channel2" + }) + .Execute(); + // snippet.end + } + + public static void SubscribeWithPresence() + { + // snippet.subscribe_with_presence + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels + "my_channel" + }) + .WithPresence() // also subscribe to related presence information + .Execute(); + // snippet.end + } + + public static void SubscribeWithState() + { + // snippet.subscribe_with_state + pubnub.AddListener(new SubscribeCallbackExt( + (pubnubObj, message) => { }, + (pubnubObj, presence) => { }, + (pubnubObj, status) => { + if (status.Category == PNStatusCategory.PNConnectedCategory) { + Dictionary data = new Dictionary(); + data.Add("FieldA", "Awesome"); + data.Add("FieldB", 10); + + pubnub.SetPresenceState() + .Channels(new string[] { "awesomeChannel" }) + .ChannelGroups(new string[] { "awesomeChannelGroup" }) + .State(data) + .Execute(new PNSetStateResultExt( + (r, s) => { + // handle set state response + } + )); + } + } + )); + + pubnub.Subscribe() + .Channels(new string[] { + "awesomeChannel" + }) + .Execute(); + // snippet.end + } + + public static void SubscribeChannelGroup() + { + // snippet.subscribe_channel_group + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels + "ch1", + "ch2" + }) + .ChannelGroups(new string[] { + // subscribe to channel groups + "cg1", + "cg2" + }) + .WithTimetoken(1337L) // optional, pass a timetoken + .WithPresence() // also subscribe to related presence information + .Execute(); + // snippet.end + } + + public static void SubscribeChannelGroupPresence() + { + // snippet.subscribe_channel_group_presence + pubnub.Subscribe() + .ChannelGroups(new string[] { + // subscribe to channel groups + "cg1", + "cg2" + }) + .WithTimetoken(1337L) // optional, pass a timetoken + .WithPresence() // also subscribe to related presence information + .Execute(); + // snippet.end + } + + // snippet.subscribe_custom_type + public class Phone + { + public string Number { get; set; } + public string Extenion { get; set; } + + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public PhoneType PhoneType { get; set; } + } + + public enum PhoneType + { + Home, + Mobile, + Work + } + + public static void SubscribeWithCustomType() + { + Phone myPhone = new Phone() { + Number = "111-222-2222", + PhoneType = PhoneType.Mobile, + Extenion = "11" + }; + + pubnub.Publish() + .Message(myPhone) + .Channel("my_channel") + .ShouldStore(true) + .Execute(new PNPublishResultExt( + (result, status) => { + // Check whether request successfully completed or not. + if (status.Error) { + // something bad happened. + Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } else { + Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString()); + } + } + )); + + SubscribeCallbackExt objectListenerSubscribeCallack = new SubscribeCallbackExt( + (pubnubObj, message) => + { + //message.Message gives the Phone object because you subscribed to type Phone during subscribe. + }, + (pubnubObj, presence) => { }, + (pubnubObj, status) => { }); + + pubnub.AddListener(objectListenerSubscribeCallack); + pubnub.Subscribe() + .Channels(new string[] { + "my_channel" // subscribe to channels + }) + .Execute(); + + //If you are subscribing to multiple message types, then + SubscribeCallbackExt stringListenerSubscribeCallack = new SubscribeCallbackExt( + (pubnubObj, message) => + { + //message.Message gives the string object because you subscribed to type "string" during subscribe. + string phoneStringMessage = message.Message.ToString(); //this is your string message + //using pluggable JSON library from the Pubnub instance, but you can use any form of JSON deserialization you wish + var deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToObject(phoneStringMessage); + }, + (pubnubObj, presence) => { }, + (pubnubObj, status) => { }); + + pubnub.AddListener(stringListenerSubscribeCallack); + pubnub.Subscribe() + .Channels(new string[] { + "my_channel" // subscribe to channels + }) + .Execute(); + } + // snippet.end + + public static void CreateSubscriptionSetFromIndividual() + { + // snippet.create_subscription_set_from_individual + // 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(); + // snippet.end + } + + public static void WildcardSubscribe() + { + // snippet.wildcard_subscribe + pubnub.Subscribe() + .Channels(new string[] { + // subscribe to channels information + "foo.*" + }) + .Execute(); + // snippet.end + } + + public static void UnsubscribeBasicUsage() + { + // snippet.unsubscribe_basic_usage + pubnub.Unsubscribe() + .Channels(new string[] { + "my_channel" + }) + .Execute(); + // snippet.end + } + + public static void UnsubscribeMultipleChannels() + { + // snippet.unsubscribe_multiple_channels + pubnub.Unsubscribe() + .Channels(new string[] { + "ch1", + "ch2", + "ch3" + }) + .ChannelGroups(new string[] { + "cg1", + "cg2", + "cg3" + }) + .Execute(); + // snippet.end + } + + public static void UnsubscribeChannelGroup() + { + // snippet.unsubscribe_channel_group + pubnub.Unsubscribe() + .ChannelGroups(new string[] { + "cg1", + "cg2", + "cg3" + }) + .Execute(); + // snippet.end + } + + public static void UnsubscribeAllBasicUsage() + { + // snippet.unsubscribe_all_basic_usage + pubnub.UnsubscribeAll(); + // snippet.end + } + + public static void AddListenerMethod1() + { + // snippet.add_listener_method1 + // Adding listener. + pubnub.AddListener(new SubscribeCallbackExt( + delegate (Pubnub pnObj, PNMessageResult pubMsg) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(pubMsg)); + var channelName = pubMsg.Channel; + var channelGroupName = pubMsg.Subscription; + var pubTT = pubMsg.Timetoken; + var msg = pubMsg.Message; + var publisher = pubMsg.Publisher; + }, + delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(presenceEvnt)); + var action = presenceEvnt.Event; // Can be join, leave, state-change or timeout + var channelName = presenceEvnt.Channel; // The channel for which the message belongs + var occupancy = presenceEvnt.Occupancy; // No. of users connected with the channel + var state = presenceEvnt.State; // User State + var channelGroupName = presenceEvnt.Subscription; // The channel group or wildcard subscription match (if exists) + var publishTime = presenceEvnt.Timestamp; // Publish timetoken + var timetoken = presenceEvnt.Timetoken; // Current timetoken + var uuid = presenceEvnt.Uuid; // UUIDs of users who are connected with the channel + }, + delegate (Pubnub pnObj, PNSignalResult signalMsg) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(signalMsg)); + var channelName = signalMsg.Channel; // The channel for which the signal belongs + var channelGroupName = signalMsg.Subscription; // The channel group or wildcard subscription match (if exists) + var pubTT = signalMsg.Timetoken; // Publish timetoken + var msg = signalMsg.Message; // The Payload + var publisher = signalMsg.Publisher; //The Publisher + }, + delegate (Pubnub pnObj, PNObjectEventResult objectEventObj) + { + var channelName = objectEventObj.Channel; // Channel + var channelMetadata = objectEventObj.ChannelMetadata; //Channel Metadata + var uidMetadata = objectEventObj.UuidMetadata; // UUID metadata + var evnt = objectEventObj.Event; // Event + var type = objectEventObj.Type; // Event type + if (objectEventObj.Type == "uuid") { + /* got uuid metadata related event. */ + } + else if (objectEventObj.Type == "channel") { + /* got channel metadata related event. */ + } + else if (objectEventObj.Type == "membership") { + /* got membership related event. */ + } + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(objectEventObj)); + }, + delegate (Pubnub pnObj, PNMessageActionEventResult msgActionEvent) + { + //handle message action + var channelName = msgActionEvent.Channel; // The channel for which the message belongs + var msgEvent = msgActionEvent.Action; // message action added or removed + var msgActionType = msgActionEvent.Event; // message action type + var messageTimetoken = msgActionEvent.MessageTimetoken; // The timetoken of the original message + var actionTimetoken = msgActionEvent.ActionTimetoken; //The timetoken of the message action + }, + delegate (Pubnub pnObj, PNFileEventResult fileEvent) + { + //handle file message event + var channelName = fileEvent.Channel; + var chanelGroupName = fileEvent.Subscription; + var fieldId = (fileEvent.File != null) ? fileEvent.File.Id : null; + var fileName = (fileEvent.File != null) ? fileEvent.File.Name : null; + var fileUrl = (fileEvent.File != null) ? fileEvent.File.Url : null; + var fileMessage = fileEvent.Message; + var filePublisher = fileEvent.Publisher; + var filePubTT = fileEvent.Timetoken; + }, + delegate (Pubnub pnObj, PNStatus pnStatus) + { + Console.WriteLine("{0} {1} {2}", pnStatus.Operation, pnStatus.Category, pnStatus.StatusCode); + var affectedChannelGroups = pnStatus.AffectedChannelGroups; // The channel groups affected in the operation, of type array. + var affectedChannels = pnStatus.AffectedChannels; // The channels affected in the operation, of type array. + var category = pnStatus.Category; //Returns PNConnectedCategory + var operation = pnStatus.Operation; //Returns PNSubscribeOperation + } + )); + // snippet.end + } + + // snippet.add_listener_method2 + public class DevSubscribeCallback : SubscribeCallback + { + public override void Message(Pubnub pubnub, PNMessageResult message) + { + // Handle new message stored in message.Message + } + + public override void Presence(Pubnub pubnub, PNPresenceEventResult presence) + { + // handle incoming presence data + } + + public override void Signal(Pubnub pubnub, PNSignalResult signal) + { + // Handle new signal message stored in signal.Message + } + + public override void Status(Pubnub pubnub, PNStatus status) + { + // the status object returned is always related to subscribe but could contain + // information about subscribe, heartbeat, or errors + // use the PNOperationType to switch on different options + switch (status.Operation) + { + // let's combine unsubscribe and subscribe handling for ease of use + case PNOperationType.PNSubscribeOperation: + case PNOperationType.PNUnsubscribeOperation: + // note: subscribe statuses never have traditional + // errors, they just have categories to represent the + // different issues or successes that occur as part of subscribe + switch (status.Category) + { + case PNStatusCategory.PNConnectedCategory: + // this is expected for a subscribe, this means there is no error or issue whatsoever + break; + case PNStatusCategory.PNReconnectedCategory: + // this usually occurs if subscribe temporarily fails but reconnects. This means + // there was an error but there is no longer any issue + break; + case PNStatusCategory.PNDisconnectedCategory: + // this is the expected category for an unsubscribe. This means there + // was no error in unsubscribing from everything + break; + case PNStatusCategory.PNUnexpectedDisconnectCategory: + // this is usually an issue with the internet connection, this is an error, handle appropriately + break; + case PNStatusCategory.PNAccessDeniedCategory: + // this means that Access Manager does allow this client to subscribe to this + // channel and channel group configuration. This is another explicit error + break; + default: + // More errors can be directly specified by creating explicit cases for other + // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory` + break; + } + break; + case PNOperationType.PNHeartbeatOperation: + // heartbeat operations can in fact have errors, so it is important to check first for an error. + if (status.Error) + { + // There was an error with the heartbeat operation, handle here + } + else + { + // heartbeat operation was successful + } + break; + default: + // Encountered unknown status type + break; + } + } + + public override void ObjectEvent(Pubnub pubnub, PNObjectEventResult objectEvent) + { + // handle incoming user, space and membership event data + } + + public override void MessageAction(Pubnub pubnub, PNMessageActionEventResult messageAction) + { + // handle incoming message action events + } + + public override void File(Pubnub pubnub, PNFileEventResult fileEvent) + { + // handle incoming file messages + } + } + + public static void AddListenerMethod2() + { + // Usage of the above listener + DevSubscribeCallback regularListener = new DevSubscribeCallback(); + pubnub.AddListener(regularListener); + } + // snippet.end + + public static void RemoveListener() + { + // snippet.remove_listener + SubscribeCallbackExt listenerSubscribeCallback = new SubscribeCallbackExt( + (pubnubObj, message) => { }, + (pubnubObj, presence) => { }, + (pubnubObj, status) => { }); + + pubnub.AddListener(listenerSubscribeCallback); + + // some time later + pubnub.RemoveListener(listenerSubscribeCallback); + // snippet.end + } + + public static void AddConnectionStatusListener() + { + // snippet.add_connection_status_listener + SubscribeCallbackExt eventListener = new SubscribeCallbackExt( + delegate (Pubnub pn, PNStatus e) { + Console.WriteLine("Status event"); + } + ); + + pubnub.AddListener(eventListener); + // snippet.end + } + + public static void UnsubscribeNewBasicUsage() + { + // snippet.unsubscribe_new_basic_usage + 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(); + // snippet.end + } + + public static void UnsubscribeAllNewBasicUsage() + { + // snippet.unsubscribe_all_new_basic_usage + 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(); + + pubnub.UnsubscribeAll(); + // snippet.end + } +} \ No newline at end of file From 105c72aa615fc328414e49c71381f2a146f159ea Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 14:22:40 +0200 Subject: [PATCH 10/17] small corrections to pub/sub samples --- .../Publish/PublishSubscribeSample.cs | 412 ++++++++++++------ 1 file changed, 289 insertions(+), 123 deletions(-) diff --git a/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs b/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs index 7a98f712c..92e7a4e18 100644 --- a/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs +++ b/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs @@ -20,7 +20,7 @@ static void Init() // Initialize PubNub Pubnub pubnub = new Pubnub(pnConfiguration); - + // snippet.end } @@ -79,7 +79,8 @@ public static void PublishSynchronous() .Channel("my_channel") .CustomMessageType("text-message") .Execute(new PNPublishResultExt( - (result, status) => { + (result, status) => + { Console.WriteLine("pub timetoken: " + result.Timetoken.ToString()); Console.WriteLine("pub status code : " + status.StatusCode.ToString()); } @@ -90,7 +91,8 @@ public static void PublishSynchronous() public static void PublishWithMetadata() { // snippet.publish_with_metadata - string[] arrayMessage = new string[] { + string[] arrayMessage = new string[] + { "hello", "there" }; @@ -99,11 +101,12 @@ public static void PublishWithMetadata() .Message(arrayMessage.ToList()) .Channel("suchChannel") .ShouldStore(true) - .Meta(new Dictionary(){ { "someKey", "someValue" }}) + .Meta(new Dictionary() { { "someKey", "someValue" } }) .UsePOST(true) .CustomMessageType("text-message") .Execute(new PNPublishResultExt( - (result, status) => { + (result, status) => + { // handle publish result, status always present, result if successful // status.Error to see if error happened } @@ -122,9 +125,9 @@ public static async Task PublishStoreForHours() .ExecuteAsync(); // snippet.end } - + // snippet.publish_mobile_payload - + public class MobilePayload { public Dictionary pn_apns; @@ -135,7 +138,8 @@ public class MobilePayload public static void PublishMobilePayload() { Dictionary apnsData = new Dictionary(); - apnsData.Add("aps", new Dictionary() { + apnsData.Add("aps", new Dictionary() + { { "alert", "Game update 49ers touchdown" }, { "badge", 2 } }); @@ -143,15 +147,16 @@ public static void PublishMobilePayload() apnsData.Add("score", new int[] { 7, 0 }); Dictionary gcmData = new Dictionary(); - gcmData.Add("data", new Dictionary() { + gcmData.Add("data", new Dictionary() + { { "summary", "Game update 49ers touchdown" }, { - "teams", new string[]{ "49ers", "raiders"} + "teams", new string[] { "49ers", "raiders" } }, { - "score", new int[]{ 7, 0} + "score", new int[] { 7, 0 } }, { "lastplay", "5yd run up the middle" @@ -161,9 +166,10 @@ public static void PublishMobilePayload() MobilePayload mobilePayload = new MobilePayload(); mobilePayload.pn_apns = apnsData; mobilePayload.pn_gcm = gcmData; - mobilePayload.full_game = new Dictionary() { - { "date","2014.05.20" }, - { "foobar","Data that is not pertinent to devices" } + mobilePayload.full_game = new Dictionary() + { + { "date", "2014.05.20" }, + { "foobar", "Data that is not pertinent to devices" } }; pubnub.Publish() @@ -172,12 +178,17 @@ public static void PublishMobilePayload() .ShouldStore(true) .CustomMessageType("text-message") .Execute(new PNPublishResultExt( - (result, status) => { + (result, status) => + { // Check whether request successfully completed or not. - if (status.Error) { + if (status.Error) + { // something bad happened. - Console.WriteLine($"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); - } else { + Console.WriteLine( + $"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); + } + else + { Console.WriteLine($"published with timetoken: {result.Timetoken}"); } } @@ -188,7 +199,8 @@ public static void PublishMobilePayload() public static void FireBasicUsage() { // snippet.fire_basic_usage - string[] arrMessage = new string[] { + string[] arrMessage = new string[] + { "hello", "there" }; @@ -198,10 +210,15 @@ public static void FireBasicUsage() .Channel("my-channel") .UsePOST(true) .Execute(new PNPublishResultExt( - (result, status) => { - if (status.Error) { - Console.WriteLine($"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); - } else { + (result, status) => + { + if (status.Error) + { + Console.WriteLine( + $"error while publishing: {pubnub.JsonPluggableLibrary.SerializeToJsonString(status)}"); + } + else + { Console.WriteLine($"published with timetoken: {result.Timetoken}"); } } @@ -219,10 +236,14 @@ public static void SignalBasicUsage() .Message(myMessage) .Channel("foo") .CustomMessageType("text-message") - .Execute(new PNPublishResultExt((result, status) => { - if (status.Error) { + .Execute(new PNPublishResultExt((result, status) => + { + if (status.Error) + { Console.WriteLine(status.ErrorData.Information); - } else { + } + else + { Console.WriteLine(result.Timetoken); } })); @@ -233,14 +254,31 @@ public static void SubscribeBasicUsage() { // snippet.subscribe_basic_usage pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels "my_channel" - }) + }) .Execute(); // snippet.end } + public static void SubscribeNewBasicUsage() + { + // snippet.subscribe_basic_usage_new + 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(); + // snippet.end + } + public static void SubscribeWithLogging() { // snippet.subscribe_with_logging @@ -257,7 +295,8 @@ public static void SubscribeWithLogging() Pubnub pubnub = new Pubnub(pnConfiguration); pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels "my_channel" }) @@ -269,7 +308,8 @@ public static void SubscribeMultipleChannels() { // snippet.subscribe_multiple_channels pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels information "my_channel1", "my_channel2" @@ -282,7 +322,8 @@ public static void SubscribeWithPresence() { // snippet.subscribe_with_presence pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels "my_channel" }) @@ -295,10 +336,12 @@ public static void SubscribeWithState() { // snippet.subscribe_with_state pubnub.AddListener(new SubscribeCallbackExt( - (pubnubObj, message) => { }, - (pubnubObj, presence) => { }, - (pubnubObj, status) => { - if (status.Category == PNStatusCategory.PNConnectedCategory) { + (pubnubObj, message) => { }, + (pubnubObj, presence) => { }, + (pubnubObj, status) => + { + if (status.Category == PNStatusCategory.PNConnectedCategory) + { Dictionary data = new Dictionary(); data.Add("FieldA", "Awesome"); data.Add("FieldB", 10); @@ -308,7 +351,8 @@ public static void SubscribeWithState() .ChannelGroups(new string[] { "awesomeChannelGroup" }) .State(data) .Execute(new PNSetStateResultExt( - (r, s) => { + (r, s) => + { // handle set state response } )); @@ -317,7 +361,8 @@ public static void SubscribeWithState() )); pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { "awesomeChannel" }) .Execute(); @@ -328,12 +373,14 @@ public static void SubscribeChannelGroup() { // snippet.subscribe_channel_group pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels "ch1", "ch2" }) - .ChannelGroups(new string[] { + .ChannelGroups(new string[] + { // subscribe to channel groups "cg1", "cg2" @@ -348,7 +395,8 @@ public static void SubscribeChannelGroupPresence() { // snippet.subscribe_channel_group_presence pubnub.Subscribe() - .ChannelGroups(new string[] { + .ChannelGroups(new string[] + { // subscribe to channel groups "cg1", "cg2" @@ -358,7 +406,7 @@ public static void SubscribeChannelGroupPresence() .Execute(); // snippet.end } - + // snippet.subscribe_custom_type public class Phone { @@ -378,7 +426,8 @@ public enum PhoneType public static void SubscribeWithCustomType() { - Phone myPhone = new Phone() { + Phone myPhone = new Phone() + { Number = "111-222-2222", PhoneType = PhoneType.Mobile, Extenion = "11" @@ -389,12 +438,17 @@ public static void SubscribeWithCustomType() .Channel("my_channel") .ShouldStore(true) .Execute(new PNPublishResultExt( - (result, status) => { + (result, status) => + { // Check whether request successfully completed or not. - if (status.Error) { + if (status.Error) + { // something bad happened. - Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); - } else { + Console.WriteLine("error happened while publishing: " + + pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } + else + { Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString()); } } @@ -410,9 +464,10 @@ public static void SubscribeWithCustomType() pubnub.AddListener(objectListenerSubscribeCallack); pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { "my_channel" // subscribe to channels - }) + }) .Execute(); //If you are subscribing to multiple message types, then @@ -429,9 +484,10 @@ public static void SubscribeWithCustomType() pubnub.AddListener(stringListenerSubscribeCallack); pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { "my_channel" // subscribe to channels - }) + }) .Execute(); } // snippet.end @@ -456,7 +512,8 @@ public static void WildcardSubscribe() { // snippet.wildcard_subscribe pubnub.Subscribe() - .Channels(new string[] { + .Channels(new string[] + { // subscribe to channels information "foo.*" }) @@ -468,10 +525,11 @@ public static void UnsubscribeBasicUsage() { // snippet.unsubscribe_basic_usage pubnub.Unsubscribe() - .Channels(new string[] { + .Channels(new string[] + { "my_channel" - }) - .Execute(); + }) + .Execute(); // snippet.end } @@ -479,12 +537,14 @@ public static void UnsubscribeMultipleChannels() { // snippet.unsubscribe_multiple_channels pubnub.Unsubscribe() - .Channels(new string[] { + .Channels(new string[] + { "ch1", "ch2", "ch3" }) - .ChannelGroups(new string[] { + .ChannelGroups(new string[] + { "cg1", "cg2", "cg3" @@ -497,7 +557,8 @@ public static void UnsubscribeChannelGroup() { // snippet.unsubscribe_channel_group pubnub.Unsubscribe() - .ChannelGroups(new string[] { + .ChannelGroups(new string[] + { "cg1", "cg2", "cg3" @@ -513,12 +574,78 @@ public static void UnsubscribeAllBasicUsage() // snippet.end } + public static void AddListenerBasicUsage() + { + // snippet.add_listener_basic_usage + // Add event-specific listeners + // Add a listener to receive Message changes + Subscription subscription1 = pubnub.Channel("channelName").Subscription(); + + subscription1.onMessage += (Pubnub pn, PNMessageResult messageEvent) => + { + Console.WriteLine($"Message received {messageEvent.Message}"); + }; + + subscription1.Subscribe(); + + + // Add multiple listeners + 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, PNSignalResult e) { Console.WriteLine("Signal event"); }, + delegate(Pubnub pn, PNObjectEventResult e) { Console.WriteLine("Object event"); }, + delegate(Pubnub pn, PNMessageActionEventResult e) { Console.WriteLine("Message Action event"); }, + delegate(Pubnub pn, PNFileEventResult e) { Console.WriteLine("File event"); } + ); + + Channel firstChannel = pubnub.Channel("first"); + var subscription = firstChannel.Subscription(SubscriptionOptions.ReceivePresenceEvents); + subscription.AddListener(eventListener); + subscription.Subscribe(); + // snippet.end + } + + public static void AddListenersBasicUsage() + { + // snippet.add_listeners_basic_usage + 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(); + // snippet.end + } + public static void AddListenerMethod1() { // snippet.add_listener_method1 // Adding listener. pubnub.AddListener(new SubscribeCallbackExt( - delegate (Pubnub pnObj, PNMessageResult pubMsg) + delegate(Pubnub pnObj, PNMessageResult pubMsg) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(pubMsg)); var channelName = pubMsg.Channel; @@ -527,46 +654,52 @@ public static void AddListenerMethod1() var msg = pubMsg.Message; var publisher = pubMsg.Publisher; }, - delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt) + delegate(Pubnub pnObj, PNPresenceEventResult presenceEvnt) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(presenceEvnt)); var action = presenceEvnt.Event; // Can be join, leave, state-change or timeout var channelName = presenceEvnt.Channel; // The channel for which the message belongs var occupancy = presenceEvnt.Occupancy; // No. of users connected with the channel var state = presenceEvnt.State; // User State - var channelGroupName = presenceEvnt.Subscription; // The channel group or wildcard subscription match (if exists) + var channelGroupName = + presenceEvnt.Subscription; // The channel group or wildcard subscription match (if exists) var publishTime = presenceEvnt.Timestamp; // Publish timetoken - var timetoken = presenceEvnt.Timetoken; // Current timetoken + var timetoken = presenceEvnt.Timetoken; // Current timetoken var uuid = presenceEvnt.Uuid; // UUIDs of users who are connected with the channel }, - delegate (Pubnub pnObj, PNSignalResult signalMsg) + delegate(Pubnub pnObj, PNSignalResult signalMsg) { Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(signalMsg)); var channelName = signalMsg.Channel; // The channel for which the signal belongs - var channelGroupName = signalMsg.Subscription; // The channel group or wildcard subscription match (if exists) + var channelGroupName = + signalMsg.Subscription; // The channel group or wildcard subscription match (if exists) var pubTT = signalMsg.Timetoken; // Publish timetoken var msg = signalMsg.Message; // The Payload var publisher = signalMsg.Publisher; //The Publisher }, - delegate (Pubnub pnObj, PNObjectEventResult objectEventObj) + delegate(Pubnub pnObj, PNObjectEventResult objectEventObj) { var channelName = objectEventObj.Channel; // Channel var channelMetadata = objectEventObj.ChannelMetadata; //Channel Metadata var uidMetadata = objectEventObj.UuidMetadata; // UUID metadata var evnt = objectEventObj.Event; // Event var type = objectEventObj.Type; // Event type - if (objectEventObj.Type == "uuid") { - /* got uuid metadata related event. */ + if (objectEventObj.Type == "uuid") + { + /* got uuid metadata related event. */ } - else if (objectEventObj.Type == "channel") { + else if (objectEventObj.Type == "channel") + { /* got channel metadata related event. */ } - else if (objectEventObj.Type == "membership") { + else if (objectEventObj.Type == "membership") + { /* got membership related event. */ } + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(objectEventObj)); }, - delegate (Pubnub pnObj, PNMessageActionEventResult msgActionEvent) + delegate(Pubnub pnObj, PNMessageActionEventResult msgActionEvent) { //handle message action var channelName = msgActionEvent.Channel; // The channel for which the message belongs @@ -575,7 +708,7 @@ public static void AddListenerMethod1() var messageTimetoken = msgActionEvent.MessageTimetoken; // The timetoken of the original message var actionTimetoken = msgActionEvent.ActionTimetoken; //The timetoken of the message action }, - delegate (Pubnub pnObj, PNFileEventResult fileEvent) + delegate(Pubnub pnObj, PNFileEventResult fileEvent) { //handle file message event var channelName = fileEvent.Channel; @@ -587,18 +720,51 @@ public static void AddListenerMethod1() var filePublisher = fileEvent.Publisher; var filePubTT = fileEvent.Timetoken; }, - delegate (Pubnub pnObj, PNStatus pnStatus) + delegate(Pubnub pnObj, PNStatus pnStatus) { Console.WriteLine("{0} {1} {2}", pnStatus.Operation, pnStatus.Category, pnStatus.StatusCode); - var affectedChannelGroups = pnStatus.AffectedChannelGroups; // The channel groups affected in the operation, of type array. - var affectedChannels = pnStatus.AffectedChannels; // The channels affected in the operation, of type array. + var affectedChannelGroups = + pnStatus.AffectedChannelGroups; // The channel groups affected in the operation, of type array. + var affectedChannels = + pnStatus.AffectedChannels; // The channels affected in the operation, of type array. var category = pnStatus.Category; //Returns PNConnectedCategory var operation = pnStatus.Operation; //Returns PNSubscribeOperation } )); + + //Add listener to receive Signal messages + SubscribeCallbackExt signalSubscribeCallback = new SubscribeCallbackExt( + delegate (Pubnub pubnubObj, PNSignalResult message) { + // Handle new signal message stored in message.Message + }, + delegate (Pubnub pubnubObj, PNStatus status) + { + // the status object returned is always related to subscribe but could contain + // information about subscribe, heartbeat, or errors + } + ); + pubnub.AddListener(signalSubscribeCallback); + + //Add listener to receive Events + SubscribeCallbackExt eventListener = new SubscribeCallbackExt( + delegate (Pubnub pnObj, PNObjectEventResult objectEvent) + { + string channelMetadataId = objectEvent.Channel; // The channel + string uuidMetadataId = objectEvent.UuidMetadata.Uuid; // The UUID + string objEvent = objectEvent.Event; // The event name that occurred + string eventType = objectEvent.Type; // The event type that occurred + PNUuidMetadataResult uuidMetadata = objectEvent.UuidMetadata; // UuidMetadata + PNChannelMetadataResult channelMetadata = objectEvent.ChannelMetadata; // ChannelMetadata + }, + delegate (Pubnub pnObj, PNStatus status) + { + + } + ); + pubnub.AddListener(eventListener); // snippet.end } - + // snippet.add_listener_method2 public class DevSubscribeCallback : SubscribeCallback { @@ -625,51 +791,53 @@ public override void Status(Pubnub pubnub, PNStatus status) switch (status.Operation) { // let's combine unsubscribe and subscribe handling for ease of use - case PNOperationType.PNSubscribeOperation: - case PNOperationType.PNUnsubscribeOperation: - // note: subscribe statuses never have traditional - // errors, they just have categories to represent the - // different issues or successes that occur as part of subscribe - switch (status.Category) - { - case PNStatusCategory.PNConnectedCategory: - // this is expected for a subscribe, this means there is no error or issue whatsoever - break; - case PNStatusCategory.PNReconnectedCategory: - // this usually occurs if subscribe temporarily fails but reconnects. This means - // there was an error but there is no longer any issue - break; - case PNStatusCategory.PNDisconnectedCategory: - // this is the expected category for an unsubscribe. This means there - // was no error in unsubscribing from everything - break; - case PNStatusCategory.PNUnexpectedDisconnectCategory: - // this is usually an issue with the internet connection, this is an error, handle appropriately - break; - case PNStatusCategory.PNAccessDeniedCategory: - // this means that Access Manager does allow this client to subscribe to this - // channel and channel group configuration. This is another explicit error - break; - default: - // More errors can be directly specified by creating explicit cases for other - // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory` - break; - } - break; - case PNOperationType.PNHeartbeatOperation: - // heartbeat operations can in fact have errors, so it is important to check first for an error. - if (status.Error) - { - // There was an error with the heartbeat operation, handle here - } - else - { - // heartbeat operation was successful - } - break; - default: - // Encountered unknown status type - break; + case PNOperationType.PNSubscribeOperation: + case PNOperationType.PNUnsubscribeOperation: + // note: subscribe statuses never have traditional + // errors, they just have categories to represent the + // different issues or successes that occur as part of subscribe + switch (status.Category) + { + case PNStatusCategory.PNConnectedCategory: + // this is expected for a subscribe, this means there is no error or issue whatsoever + break; + case PNStatusCategory.PNReconnectedCategory: + // this usually occurs if subscribe temporarily fails but reconnects. This means + // there was an error but there is no longer any issue + break; + case PNStatusCategory.PNDisconnectedCategory: + // this is the expected category for an unsubscribe. This means there + // was no error in unsubscribing from everything + break; + case PNStatusCategory.PNUnexpectedDisconnectCategory: + // this is usually an issue with the internet connection, this is an error, handle appropriately + break; + case PNStatusCategory.PNAccessDeniedCategory: + // this means that Access Manager does allow this client to subscribe to this + // channel and channel group configuration. This is another explicit error + break; + default: + // More errors can be directly specified by creating explicit cases for other + // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory` + break; + } + + break; + case PNOperationType.PNHeartbeatOperation: + // heartbeat operations can in fact have errors, so it is important to check first for an error. + if (status.Error) + { + // There was an error with the heartbeat operation, handle here + } + else + { + // heartbeat operation was successful + } + + break; + default: + // Encountered unknown status type + break; } } @@ -716,9 +884,7 @@ public static void AddConnectionStatusListener() { // snippet.add_connection_status_listener SubscribeCallbackExt eventListener = new SubscribeCallbackExt( - delegate (Pubnub pn, PNStatus e) { - Console.WriteLine("Status event"); - } + delegate(Pubnub pn, PNStatus e) { Console.WriteLine("Status event"); } ); pubnub.AddListener(eventListener); @@ -761,4 +927,4 @@ public static void UnsubscribeAllNewBasicUsage() pubnub.UnsubscribeAll(); // snippet.end } -} \ No newline at end of file +} \ No newline at end of file From f071cccd0adce4caa42b79baf44e576ac57b55d3 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 15:23:53 +0200 Subject: [PATCH 11/17] cleanup, add logging and storage samples --- .../Logging/LoggingSample.cs | 50 +++ src/PubnubApi.Snippets/Program.cs | 3 - .../PubnubApi.Snippets.csproj | 4 - .../Storage/StorageAndPlaybackSample.cs | 340 ++++++++++++++++++ 4 files changed, 390 insertions(+), 7 deletions(-) create mode 100644 src/PubnubApi.Snippets/Logging/LoggingSample.cs delete mode 100644 src/PubnubApi.Snippets/Program.cs create mode 100644 src/PubnubApi.Snippets/Storage/StorageAndPlaybackSample.cs diff --git a/src/PubnubApi.Snippets/Logging/LoggingSample.cs b/src/PubnubApi.Snippets/Logging/LoggingSample.cs new file mode 100644 index 000000000..af409ef0a --- /dev/null +++ b/src/PubnubApi.Snippets/Logging/LoggingSample.cs @@ -0,0 +1,50 @@ +// snippet.using +using PubnubApi; + +// snippet.end +using System; +using System.Globalization; + +public class LoggingSample +{ + // snippet.custom_logger + // A custom logger that logs information on console. + // Use can implement logger that can log information using log4Net or file etc. + public class PubnubConsoleLogger : IPubnubLogger + { + public void Trace(string traceLog) => + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}"); + + public void Debug(string debugLog) => + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [DEBUG] {debugLog}"); + + public void Info(string infoLog) => + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [INFO] {infoLog}"); + + public void Warn(string warningLog) => + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [WARN] {warningLog}"); + + public void Error(string errorLog) => + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [ERROR] {errorLog}"); + } + // snippet.end + + public static void EnableLogging() + { + // snippet.enable_logging + var pubnubConfiguration = new PNConfiguration(new UserId("uniqueUserId")) + { + SubscribeKey = "[yourSubscribeKey]", + PublishKey = "[yourPublishKey]", + LogLevel = PubnubLogLevel.Debug, + }; + var pubnub = new Pubnub(pubnubConfiguration); + + var customLogger = new PubnubConsoleLogger(); + pubnub.SetLogger(customLogger); + + // To remove the custom logger. Use RemoveLogger(). + pubnub.RemoveLogger(customLogger); + // snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Program.cs b/src/PubnubApi.Snippets/Program.cs deleted file mode 100644 index e5dff12bc..000000000 --- a/src/PubnubApi.Snippets/Program.cs +++ /dev/null @@ -1,3 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj index c5c44e5ac..8682bc998 100644 --- a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj +++ b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj @@ -8,17 +8,13 @@ - - - - diff --git a/src/PubnubApi.Snippets/Storage/StorageAndPlaybackSample.cs b/src/PubnubApi.Snippets/Storage/StorageAndPlaybackSample.cs new file mode 100644 index 000000000..4adbe8cda --- /dev/null +++ b/src/PubnubApi.Snippets/Storage/StorageAndPlaybackSample.cs @@ -0,0 +1,340 @@ +// snippet.using +using PubnubApi; + +// snippet.end + +public class StorageAndPlaybackSample +{ + private static Pubnub pubnub; + + static void Init() + { + // snippet.pubnub_init + // Configuration + PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) + { + SubscribeKey = "demo", + PublishKey = "demo", + Secure = true + }; + + // Initialize PubNub + Pubnub pubnub = new Pubnub(pnConfiguration); + + // snippet.end + } + + public static async Task FetchHistoryBasicUsage() + { + // snippet.fetch_history_basic_usage + try + { + // Fetch historical messages + PNResult fetchHistoryResponse = await pubnub.FetchHistory() + .Channels(new string[] { "my_channel" }) + .IncludeMeta(true) + .IncludeCustomMessageType(true) + .MaximumPerChannel(25) + .ExecuteAsync(); + + PNFetchHistoryResult fetchHistoryResult = fetchHistoryResponse.Result; + PNStatus status = fetchHistoryResponse.Status; + + if (!status.Error && fetchHistoryResult != null) + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fetchHistoryResult)); + } + else + { + Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(status)); + } + } + catch (Exception ex) + { + Console.WriteLine($"Request cannot be executed due to error: {ex.Message}"); + } + // snippet.end + } + + public static void FetchHistorySynchronous() + { + // snippet.fetch_history_synchronous + pubnub.FetchHistory() + .Channels(new string[] { "my_channel" }) + .IncludeMeta(true) + .MaximumPerChannel(25) + .Execute(new PNFetchHistoryResultExt((result, status) => + { + + })); + // snippet.end + } + + public static async Task DeleteMessagesBasicUsage() + { + // snippet.delete_messages_basic_usage + PNResult 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)); + } + // snippet.end + } + + public static void DeleteMessagesSynchronous() + { + // snippet.delete_messages_synchronous + 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)); + } + } + )); + // snippet.end + } + + public static async Task DeleteSpecificMessage() + { + // snippet.delete_specific_message + PNResult delMsgResponse = await pubnub.DeleteMessages() + .Channel("history_channel") + .Start(15526611838554309) + .End(15526611838554310) + .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)); + } + // snippet.end + } + + public static async Task MessageCountsBasicUsage() + { + // snippet.message_counts_basic_usage + PNResult 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)); + } + // snippet.end + } + + public static void MessageCountsSynchronous() + { + // snippet.message_counts_synchronous + 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)); + } + })); + // snippet.end + } + + public static async Task MessageCountsMultipleChannels() + { + // snippet.message_counts_multiple_channels + PNResult 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)); + } + // snippet.end + } + + public static async Task HistoryBasicUsage() + { + // snippet.history_basic_usage + PNResult historyResponse = await pubnub.History() + .Channel("history_channel") // where to fetch history from + .Count(100) // how many items to fetch + .ExecuteAsync(); + // snippet.end + } + + public static void HistorySynchronous() + { + // snippet.history_synchronous + pubnub.History() + .Channel("history_channel") // where to fetch history from + .Count(100) // how many items to fetch + .Execute(new PNHistoryResultExt( + (result, status) => { + } + )); + // snippet.end + } + + public static async Task HistoryReverse() + { + // snippet.history_reverse + PNResult 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(); + // snippet.end + } + + public static async Task HistoryStartTimetoken() + { + // snippet.history_start_timetoken + PNResult historyResponse = await pubnub.History() + .Channel("my_channel") // where to fetch history from + .Start(13847168620721752L) // first timestamp + .Reverse(true) // should go in reverse? + .ExecuteAsync(); + // snippet.end + } + + public static async Task HistoryStartEndTimetoken() + { + // snippet.history_start_end_timetoken + 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(); + // snippet.end + } + + public static async Task HistoryIncludeTimetoken() + { + // snippet.history_include_timetoken + PNResult 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(); + // snippet.end + } + + // snippet.history_paging_example + 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 + } + } + } + // snippet.end +} \ No newline at end of file From a45cf85dd6ed24842a55cda23408221bbcb14b0b Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 15:53:23 +0200 Subject: [PATCH 12/17] add samples build step to workflow --- .github/workflows/run-tests.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 00f32b462..bbb2f726a 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -38,6 +38,8 @@ jobs: env: WORKSPACE_PATH: ${{ github.workspace }} run: .\\.github\\workflows\\release\\build-packages.ps1 + - name: Build samples project + run: dotnet build .\\src\\PubnubApi.Snippets\\PubnubApi.Snippets.csproj - name: Run unit tests env: PN_PUB_KEY: ${{ secrets.SDK_PUB_KEY }} From e4be44ce41aa18aa3a70c25ff7cbf9a8cdf1022f Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 16:03:29 +0200 Subject: [PATCH 13/17] exclude snippets from codacy analisys --- .codacy.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.codacy.yml b/.codacy.yml index dbc0982f7..e95ec5bdc 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -7,4 +7,5 @@ exclude_paths: - '**/netstandard2.0/**' - '**/Plugins/**' - '**/Scripts/PubnubExample.*' + - '**/PubnubApi.Snippets/**' \ No newline at end of file From 0bcdf1867b34b04425c378f14a709bcb50da77a8 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 16:45:36 +0200 Subject: [PATCH 14/17] test sample compilation --- src/PubnubApi.Snippets/Logging/LoggingSample.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PubnubApi.Snippets/Logging/LoggingSample.cs b/src/PubnubApi.Snippets/Logging/LoggingSample.cs index af409ef0a..cb860069f 100644 --- a/src/PubnubApi.Snippets/Logging/LoggingSample.cs +++ b/src/PubnubApi.Snippets/Logging/LoggingSample.cs @@ -13,7 +13,7 @@ public class LoggingSample public class PubnubConsoleLogger : IPubnubLogger { public void Trace(string traceLog) => - Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}"); + //Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}"); public void Debug(string debugLog) => Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [DEBUG] {debugLog}"); From 60b6e2dc941a8e026b9d758210a574a1d6655cb0 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 24 Jun 2025 17:12:28 +0200 Subject: [PATCH 15/17] remove test compilation error from sample --- src/PubnubApi.Snippets/Logging/LoggingSample.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PubnubApi.Snippets/Logging/LoggingSample.cs b/src/PubnubApi.Snippets/Logging/LoggingSample.cs index cb860069f..af409ef0a 100644 --- a/src/PubnubApi.Snippets/Logging/LoggingSample.cs +++ b/src/PubnubApi.Snippets/Logging/LoggingSample.cs @@ -13,7 +13,7 @@ public class LoggingSample public class PubnubConsoleLogger : IPubnubLogger { public void Trace(string traceLog) => - //Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}"); + Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}"); public void Debug(string debugLog) => Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [DEBUG] {debugLog}"); From b3bd5f473e1d07eac9e0459af7b972ac3bb97cb1 Mon Sep 17 00:00:00 2001 From: Mateusz Wiktor Date: Fri, 27 Jun 2025 10:42:07 +0200 Subject: [PATCH 16/17] Add new folders for AccessManager, ChannelGroup, Configuration, Files, GettingStarted, and Storage in project structure --- .../GettingStarted/GettingStartedSample.cs | 142 ++++++++++++++++++ .../PubnubApi.Snippets.csproj | 6 + 2 files changed, 148 insertions(+) create mode 100644 src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs diff --git a/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs new file mode 100644 index 000000000..80e513a57 --- /dev/null +++ b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs @@ -0,0 +1,142 @@ +// snippet.using +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using PubnubApi; +// snippet.end + +namespace PubNubGetStarted +{ + // snippet.complete_example + public class Program + { + private static Pubnub pubnub; + + // snippet.initialize_pubnub + public static async Task Main(string[] args) + { + // 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!"); + + // Add listeners + SetupListeners(); + + // Subscribe to channel + SubscribeToChannel("my_channel"); + + // Publish a test message + var message = new Dictionary { { "text", "Hello from C# Console!" } }; + await PublishMessageAsync("my_channel", message); + + // The application will continue to run and receive messages + // until the user presses a key to exit + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + + // Cleanup before exiting + pubnub.UnsubscribeAll(); + pubnub.Destroy(); + Console.WriteLine("PubNub Destroyed."); + } + // snippet.end + + // snippet.setup_event_listeners + // Set up listeners for messages, presence, and status events + static void SetupListeners() + { + var listener = new SubscribeCallbackExt( + // Handle Message Events + (pn, messageEvent) => + { + Console.WriteLine($"Message Received: Channel={messageEvent.Channel}, Message={messageEvent.Message}"); + + var messageData = messageEvent.Message as Dictionary; + if (messageData != null && messageData.ContainsKey("text")) + { + Console.WriteLine($"Parsed Text: {messageData["text"]}"); + } + }, + // Handle Presence Events (optional) + (pn, presenceEvent) => + { + Console.WriteLine($"Presence Event: Channel={presenceEvent.Channel}, Event={presenceEvent.Event}, UUID={presenceEvent.Uuid}"); + }, + // Handle Status Events + (pn, statusEvent) => + { + if (statusEvent.Category == PNStatusCategory.PNConnectedCategory) + { + Console.WriteLine($"Connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}"); + } + else if (statusEvent.Category == PNStatusCategory.PNSubscriptionChangedCategory) + { + Console.WriteLine($"Subscription changed,Now connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}"); + } + else if (statusEvent.Category == PNStatusCategory.PNDisconnectedCategory) + { + Console.WriteLine("Disconnected from PubNub."); + } + else if (statusEvent.Error) + { + Console.WriteLine($"PubNub Status Error: {statusEvent.ErrorData.Information}"); + } + } + ); + pubnub.AddListener(listener); + Console.WriteLine("PubNub Listeners Set Up."); + } + // snippet.end + + // snippet.create_subscription + // Subscribe to a channel to receive messages + static void SubscribeToChannel(string channelName) + { + pubnub.Subscribe() // Use object if message type is unknown/mixed + .Channels(new string[] { channelName }) + .WithPresence() // Enable presence events + .Execute(); + + Console.WriteLine($"Subscribed to channel: {channelName}"); + } + // snippet.end + + // snippet.publish_messages + // Publish a message to a channel using async/await + static async Task PublishMessageAsync(string channelName, Dictionary message) + { + try + { + var result = await pubnub.Publish() + .Channel(channelName) + .Message(message) + .ExecuteAsync(); + + if (!result.Status.Error) + { + Console.WriteLine($"Message Published! Timetoken: {result.Result.Timetoken}"); + } + else + { + Console.WriteLine($"Publish Error: {result.Status.ErrorData.Information}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Exception during publish: {ex.Message}"); + } + } + // snippet.end + } + // snippet.end +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj index 8682bc998..1b2dbafff 100644 --- a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj +++ b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj @@ -8,13 +8,19 @@ + + + + + + From da108706ff6705720f7fabd392901a00279393ef Mon Sep 17 00:00:00 2001 From: Mateusz Wiktor Date: Fri, 27 Jun 2025 11:01:12 +0200 Subject: [PATCH 17/17] Refactor GettingStartedSample.cs to improve snippet organization and clarity by adding snippet markers for initialization and ending, and removing redundant comments. --- .../GettingStarted/GettingStartedSample.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs index 80e513a57..4fd74223d 100644 --- a/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs +++ b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs @@ -8,14 +8,14 @@ namespace PubNubGetStarted { - // snippet.complete_example public class Program { private static Pubnub pubnub; - // snippet.initialize_pubnub + public static async Task Main(string[] args) - { + { + // snippet.initialize_pubnub // Configure PubNub PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) { @@ -29,6 +29,8 @@ public static async Task Main(string[] args) Console.WriteLine("PubNub Initialized!"); + // snippet.end + // Add listeners SetupListeners(); @@ -49,7 +51,6 @@ public static async Task Main(string[] args) pubnub.Destroy(); Console.WriteLine("PubNub Destroyed."); } - // snippet.end // snippet.setup_event_listeners // Set up listeners for messages, presence, and status events @@ -138,5 +139,5 @@ static async Task PublishMessageAsync(string channelName, Dictionary