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 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 }} 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..56bcf4abd --- /dev/null +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerSample.cs @@ -0,0 +1,396 @@ +// 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 + } + + 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 SetAuthTokenSnippet() + { + // snippet.set_token + pubnub.SetAuthToken( + "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"); + + // 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/AccessManager/AccessManagerV2Sample.cs b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs new file mode 100644 index 000000000..318579860 --- /dev/null +++ b/src/PubnubApi.Snippets/AccessManager/AccessManagerV2Sample.cs @@ -0,0 +1,238 @@ +// 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..e51269672 --- /dev/null +++ b/src/PubnubApi.Snippets/ChannelGroup/ChannelGroupsSample.cs @@ -0,0 +1,83 @@ +// 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..0143131cf --- /dev/null +++ b/src/PubnubApi.Snippets/Configuration/ConfigurationSample.cs @@ -0,0 +1,172 @@ +// 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/Entities/EntitiesSample.cs b/src/PubnubApi.Snippets/Entities/EntitiesSample.cs new file mode 100644 index 000000000..b09b5e2ae --- /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/Files/FilesSample.cs b/src/PubnubApi.Snippets/Files/FilesSample.cs new file mode 100644 index 000000000..b006974ee --- /dev/null +++ b/src/PubnubApi.Snippets/Files/FilesSample.cs @@ -0,0 +1,160 @@ +// 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 diff --git a/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs new file mode 100644 index 000000000..4fd74223d --- /dev/null +++ b/src/PubnubApi.Snippets/GettingStarted/GettingStartedSample.cs @@ -0,0 +1,143 @@ +// snippet.using +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using PubnubApi; +// snippet.end + +namespace PubNubGetStarted +{ + public class Program + { + private static Pubnub pubnub; + + + public static async Task Main(string[] args) + { + // snippet.initialize_pubnub + // 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!"); + + // snippet.end + + // 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.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 + } + +} \ No newline at end of file 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/MessageActions/MessageActionsSample.cs b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs new file mode 100644 index 000000000..eeae12e62 --- /dev/null +++ b/src/PubnubApi.Snippets/MessageActions/MessageActionsSample.cs @@ -0,0 +1,81 @@ +// 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.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.GetMessageActions() + .Channel("my_channel") + .Execute(new PNGetMessageActionsResultExt((result, status) => + { + //result is of type PNGetMessageActionsResult. + })); + // snippet.end + } +} \ No newline at end of file diff --git a/src/PubnubApi.Snippets/Misc/MiscSample.cs b/src/PubnubApi.Snippets/Misc/MiscSample.cs new file mode 100644 index 000000000..bb55db678 --- /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 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..92e7a4e18 --- /dev/null +++ b/src/PubnubApi.Snippets/Publish/PublishSubscribeSample.cs @@ -0,0 +1,930 @@ +// 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 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 + 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 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) + { + 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 + } + )); + + //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 + { + 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 diff --git a/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj new file mode 100644 index 000000000..1b2dbafff --- /dev/null +++ b/src/PubnubApi.Snippets/PubnubApi.Snippets.csproj @@ -0,0 +1,30 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/PubnubApi.Snippets/Push/PushSample.cs b/src/PubnubApi.Snippets/Push/PushSample.cs new file mode 100644 index 000000000..2f8e11437 --- /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 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