diff --git a/.github/workflows/run-tests-macos-mono.yml b/.github/workflows/run-tests-macos-mono.yml deleted file mode 100644 index a4f335a7c..000000000 --- a/.github/workflows/run-tests-macos-mono.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: "Unit and Integration Test: macOS (Mono)" -on: - pull_request: - push: - branches: - - main - -jobs: - check: - runs-on: macos-13 - env: - DOTNET_NOLOGO: true - - steps: - - uses: actions/checkout@v4 - with: - submodules: 'recursive' - - - name: Download dotnet framework - uses: actions/setup-dotnet@v4 - with: - dotnet-version: | - 3.1.426 - 7.0.410 - - - name: Download dotnet build-script tools - run: dotnet tool restore - - - name: Install mono - run: | - ./tools/mono-install.sh - - - name: Run Unit tests using mono - run: ./build.sh --target=Test.NetFramework.Unit.WithRetry - - - name: Run Integration tests using mono - run: ./build.sh --target=Test.NetFramework.Integration.WithRetry diff --git a/nuget/io.ably.nuspec b/nuget/io.ably.nuspec index ee72efde9..1e0e48e36 100644 --- a/nuget/io.ably.nuspec +++ b/nuget/io.ably.nuspec @@ -20,26 +20,33 @@ + + + + + + + diff --git a/src/IO.Ably.Android/IO.Ably.Android.csproj b/src/IO.Ably.Android/IO.Ably.Android.csproj index c9288aeaa..a812f9749 100644 --- a/src/IO.Ably.Android/IO.Ably.Android.csproj +++ b/src/IO.Ably.Android/IO.Ably.Android.csproj @@ -17,6 +17,8 @@ v11.0 + true + obj/Generated true @@ -51,9 +53,16 @@ - + + + ..\packages\MessagePack.3.1.4\lib\netstandard2.0\MessagePack.dll + True + + + ..\packages\MessagePack.Annotations.3.1.4\lib\netstandard2.0\MessagePack.Annotations.dll + ..\packages\Microsoft.Bcl.Async.1.0.168\lib\portable-net45+win8+wpa81\Microsoft.Threading.Tasks.dll @@ -65,9 +74,6 @@ - - ..\packages\MsgPack.Cli.0.9.2\lib\MonoAndroid10\MsgPack.dll - ..\packages\Newtonsoft.Json.13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll @@ -87,8 +93,8 @@ ..\packages\System.Threading.Channels.4.5.0\lib\netstandard2.0\System.Threading.Channels.dll True - - ..\packages\System.Threading.Tasks.Extensions.4.5.0\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll True @@ -107,6 +113,10 @@ Designer + + + + {412deb5f-7936-4027-8bf8-977f23d465ed} @@ -114,7 +124,6 @@ - - + + + ..\packages\MessagePack.3.1.4\lib\netstandard2.0\MessagePack.dll + True + + + ..\packages\MessagePack.Annotations.3.1.4\lib\netstandard2.0\MessagePack.Annotations.dll + + + ..\packages\Microsoft.Bcl.AsyncInterfaces.8.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\packages\Microsoft.NET.StringTools.17.11.4\lib\netstandard2.0\Microsoft.NET.StringTools.dll + ..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.8.0.0\lib\net462\System.Collections.Immutable.dll + + + ..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll + ..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Net.Http.dll - - ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll ..\packages\System.Threading.Channels.4.6.0\lib\netstandard2.0\System.Threading.Channels.dll - - ..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll @@ -98,6 +126,8 @@ + + @@ -112,5 +142,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + diff --git a/src/IO.Ably.NETFramework/app.config b/src/IO.Ably.NETFramework/app.config index 0a15aa816..15011511c 100644 --- a/src/IO.Ably.NETFramework/app.config +++ b/src/IO.Ably.NETFramework/app.config @@ -1,15 +1,19 @@ - + - - + + - - + + + + + + - + diff --git a/src/IO.Ably.NETFramework/packages.config b/src/IO.Ably.NETFramework/packages.config index 63e0caaa8..d060e18b7 100644 --- a/src/IO.Ably.NETFramework/packages.config +++ b/src/IO.Ably.NETFramework/packages.config @@ -1,10 +1,21 @@  + + + + + - + + + + + + + - + \ No newline at end of file diff --git a/src/IO.Ably.NETStandard20/IO.Ably.NETStandard20.csproj b/src/IO.Ably.NETStandard20/IO.Ably.NETStandard20.csproj index 52acb688c..667aa2ae3 100644 --- a/src/IO.Ably.NETStandard20/IO.Ably.NETStandard20.csproj +++ b/src/IO.Ably.NETStandard20/IO.Ably.NETStandard20.csproj @@ -7,6 +7,8 @@ false IO.Ably IO.Ably + true + $(BaseIntermediateOutputPath)Generated @@ -34,8 +36,6 @@ - - @@ -45,14 +45,14 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/IO.Ably.NetFramework.sln b/src/IO.Ably.NetFramework.sln index 7703a1bf5..dfff13033 100644 --- a/src/IO.Ably.NetFramework.sln +++ b/src/IO.Ably.NetFramework.sln @@ -31,8 +31,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.Tests.NETFramework" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Tests.Shared", "IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.shproj", "{1609F12C-8216-4E7C-ADE0-240BFE160242}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{EEAD196C-8D90-4402-9EAC-273F0DF5EFCB}" @@ -43,7 +41,6 @@ Global IO.Ably.Shared\IO.Ably.Shared.projitems*{2d265650-b1ec-4f8d-b043-a2e3dcc23fd8}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{3553e1b2-8f1f-4e83-9524-08e702c14fcf}*SharedItemsImports = 13 IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{567feef7-41af-42f2-ad34-546a278355b1}*SharedItemsImports = 4 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution AppStore|Any CPU = AppStore|Any CPU @@ -279,7 +276,6 @@ Global {2D265650-B1EC-4F8D-B043-A2E3DCC23FD8} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {567FEEF7-41AF-42F2-AD34-546A278355B1} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {1609F12C-8216-4E7C-ADE0-240BFE160242} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {EEAD196C-8D90-4402-9EAC-273F0DF5EFCB} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} EndGlobalSection diff --git a/src/IO.Ably.NetStandard.sln b/src/IO.Ably.NetStandard.sln index 9ceaf9a9a..4d987bec1 100644 --- a/src/IO.Ably.NetStandard.sln +++ b/src/IO.Ably.NetStandard.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28729.10 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33213.308 MinimumVisualStudioVersion = 15.0.26730.10 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1EA29F05-BF68-4BA8-A58F-C7C131E3FC62}" ProjectSection(SolutionItems) = preProject @@ -14,9 +14,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".Solution Items", ".Solutio CommonAssemblyInfo.cs = CommonAssemblyInfo.cs ..\nuget\io.ably.nuspec = ..\nuget\io.ably.nuspec IO.Ably.ruleset = IO.Ably.ruleset + IO.Ably.Tests.ruleset = IO.Ably.Tests.ruleset ..\README.md = ..\README.md stylecop.json = stylecop.json - IO.Ably.Tests.ruleset = IO.Ably.Tests.ruleset EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Ably", "Ably", "{8A0F718E-2168-4CC7-8F7B-A65508B52B0F}" @@ -27,20 +27,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.NETStandard20", "IO EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.Tests.DotNET", "IO.Ably.Tests.DotNET\IO.Ably.Tests.DotNET.csproj", "{4805A9DA-3412-4BE8-8B95-5A0EFDA1AC01}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Tests.Shared", "IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.shproj", "{1609F12C-8216-4E7C-ADE0-240BFE160242}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{D8CAACFA-FE6E-46BC-9B23-8AA3B2055125}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{D8CAACFA-FE6E-46BC-9B23-8AA3B2055125}" EndProject Global - GlobalSection(SharedMSBuildProjectFiles) = preSolution - IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{1609f12c-8216-4e7c-ade0-240bfe160242}*SharedItemsImports = 13 - IO.Ably.Shared\IO.Ably.Shared.projitems*{3553e1b2-8f1f-4e83-9524-08e702c14fcf}*SharedItemsImports = 13 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 - EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution AppStore|Any CPU = AppStore|Any CPU AppStore|ARM = AppStore|ARM @@ -274,7 +267,6 @@ Global GlobalSection(NestedProjects) = preSolution {48EA337F-AE7B-4001-BD8C-DA1668FC6CBD} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {4805A9DA-3412-4BE8-8B95-5A0EFDA1AC01} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {1609F12C-8216-4E7C-ADE0-240BFE160242} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {D8CAACFA-FE6E-46BC-9B23-8AA3B2055125} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} @@ -282,4 +274,10 @@ Global GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F69D4156-FC22-4B8E-AD72-2A7323D42CC4} EndGlobalSection + GlobalSection(SharedMSBuildProjectFiles) = preSolution + IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{1609f12c-8216-4e7c-ade0-240bfe160242}*SharedItemsImports = 13 + IO.Ably.Shared\IO.Ably.Shared.projitems*{3553e1b2-8f1f-4e83-9524-08e702c14fcf}*SharedItemsImports = 13 + IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{4805a9da-3412-4be8-8b95-5a0efda1ac01}*SharedItemsImports = 5 + IO.Ably.Shared\IO.Ably.Shared.projitems*{48ea337f-ae7b-4001-bd8c-da1668fc6cbd}*SharedItemsImports = 5 + EndGlobalSection EndGlobal diff --git a/src/IO.Ably.Package.sln b/src/IO.Ably.Package.sln index baf2c5f2d..dbbd45d06 100644 --- a/src/IO.Ably.Package.sln +++ b/src/IO.Ably.Package.sln @@ -30,8 +30,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.NETStandard20", "IO EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{55FD7D98-585B-4304-9B3F-3F518DB5CBFF}" EndProject Global @@ -41,7 +39,6 @@ Global IO.Ably.Shared\IO.Ably.Shared.projitems*{3180aa9d-9800-4eb2-87f0-ada47e2fff3d}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{3553e1b2-8f1f-4e83-9524-08e702c14fcf}*SharedItemsImports = 13 IO.Ably.Shared\IO.Ably.Shared.projitems*{8bb7b13c-e9f4-4d1b-bccc-af890a23ece6}*SharedItemsImports = 4 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -144,7 +141,6 @@ Global {8BB7B13C-E9F4-4D1B-BCCC-AF890A23ECE6} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {48EA337F-AE7B-4001-BD8C-DA1668FC6CBD} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {55FD7D98-585B-4304-9B3F-3F518DB5CBFF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/src/IO.Ably.PackagePush.sln b/src/IO.Ably.PackagePush.sln index c4d4596dc..1b7974f83 100644 --- a/src/IO.Ably.PackagePush.sln +++ b/src/IO.Ably.PackagePush.sln @@ -25,8 +25,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.iOS", "IO.Ably.iOS\ EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{53CA3FD4-E11A-4368-A7A5-BCAB40D08BED}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.NETStandard20", "IO.Ably.NETStandard20\IO.Ably.NETStandard20.csproj", "{97ED15E5-6546-4437-BF4F-B929700CE922}" @@ -42,7 +40,6 @@ Global IO.Ably.Shared\IO.Ably.Shared.projitems*{3553e1b2-8f1f-4e83-9524-08e702c14fcf}*SharedItemsImports = 13 IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{567feef7-41af-42f2-ad34-546a278355b1}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{8bb7b13c-e9f4-4d1b-bccc-af890a23ece6}*SharedItemsImports = 4 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution AppStore|Any CPU = AppStore|Any CPU @@ -406,7 +403,6 @@ Global GlobalSection(NestedProjects) = preSolution {8BB7B13C-E9F4-4D1B-BCCC-AF890A23ECE6} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {53CA3FD4-E11A-4368-A7A5-BCAB40D08BED} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {97ED15E5-6546-4437-BF4F-B929700CE922} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {F0010AA8-63C3-47D7-95E9-A5D1D04DA325} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs deleted file mode 100644 index 2004a0587..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MsgPack; -using MsgPack.Serialization; - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class CapabilityMessagePackSerializer : MessagePackSerializer - { - public CapabilityMessagePackSerializer(SerializationContext ownerContext) - : base(ownerContext) - { - } - - protected override void PackToCore(Packer packer, Capability objectTree) - { - packer.Pack(objectTree.ToJson()); - } - - protected override Capability UnpackFromCore(Unpacker unpacker) - { - MessagePackObject obj = string.Empty; - if (unpacker.ReadObject(out obj)) - { - return new Capability(obj.ToString()); - } - - return new Capability(); - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs deleted file mode 100644 index 843708df9..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using MsgPack; -using MsgPack.Serialization; - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class DateTimeOffsetMessagePackSerializer : MessagePackSerializer - { - public DateTimeOffsetMessagePackSerializer(SerializationContext ownerContext) - : base(ownerContext) { } - - protected override void PackToCore(Packer packer, DateTimeOffset objectTree) - { - packer.Pack((long)objectTree.ToUnixTimeInMilliseconds()); - } - - protected override DateTimeOffset UnpackFromCore(Unpacker unpacker) - { - var data = unpacker.LastReadData; - return data.AsInt64().FromUnixTimeInMilliseconds(); - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Auth_TokenDetailsSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Auth_TokenDetailsSerializer.cs deleted file mode 100644 index 3ca97609a..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Auth_TokenDetailsSerializer.cs +++ /dev/null @@ -1,272 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_Auth_TokenDetailsSerializer : MsgPack.Serialization.MessagePackSerializer - { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer _serializer2; - - private MsgPack.Serialization.MessagePackSerializer> _serializer3; - - public IO_Ably_Auth_TokenDetailsSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) - { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - this._serializer1 = context.GetSerializer(MsgPack.Serialization.DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethod(context, MsgPack.Serialization.DateTimeMemberConversionMethod.Default)); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer2 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer3 = context.GetSerializer>(schema2); - } - - protected override void PackToCore(MsgPack.Packer packer, TokenDetails objectTree) - { - packer.PackMapHeader(6); - this._serializer0.PackTo(packer, "token"); - this._serializer0.PackTo(packer, objectTree.Token); - this._serializer0.PackTo(packer, "keyName"); - this._serializer0.PackTo(packer, objectTree.KeyName); - this._serializer0.PackTo(packer, "expires"); - this._serializer1.PackTo(packer, objectTree.Expires); - this._serializer0.PackTo(packer, "issued"); - this._serializer1.PackTo(packer, objectTree.Issued); - this._serializer0.PackTo(packer, "capability"); - this._serializer2.PackTo(packer, objectTree.Capability); - this._serializer0.PackTo(packer, "clientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - } - - protected override TokenDetails UnpackFromCore(MsgPack.Unpacker unpacker) - { - TokenDetails result = default(TokenDetails); - result = new TokenDetails(); - { - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable4 = default(string); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(TokenDetails), "MemberName"); - if (((nullable4 == null) - == false)) - { - key = nullable4; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "clientId")) - { - string nullable9 = default(string); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(TokenDetails), "System.String ClientId"); - if (((nullable9 == null) - == false)) - { - result.ClientId = nullable9; - } - } - else - { - if ((key == "keyName")) - { - string keyNameValue = null; - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - keyNameValue = this._serializer0.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable10 = default(MsgPack.Unpacker); - disposable10 = unpacker.ReadSubtree(); - try - { - keyNameValue = this._serializer0.UnpackFrom(disposable10); - } - finally - { - if (((disposable10 == null) - == false)) - { - disposable10.Dispose(); - } - } - } - if (((keyNameValue == null) - == false)) - { - result.KeyName = keyNameValue; - } - } - else if ((key == "capability")) - { - IO.Ably.Capability nullable8 = default(IO.Ably.Capability); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable8 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable8 = this._serializer2.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (((nullable8 == null) - == false)) - { - result.Capability = nullable8; - } - } - else - { - if ((key == "issued")) - { - System.Nullable nullable7 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable7 = this._serializer3.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try - { - nullable7 = this._serializer3.UnpackFrom(disposable3); - } - finally - { - if (((disposable3 == null) - == false)) - { - disposable3.Dispose(); - } - } - } - if (nullable7.HasValue) - { - result.Issued = nullable7.Value; - } - } - else - { - if ((key == "expires")) - { - System.Nullable nullable6 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable6 = this._serializer3.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable6 = this._serializer3.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (nullable6.HasValue) - { - result.Expires = nullable6.Value; - } - } - else - { - if ((key == "token")) - { - string nullable5 = default(string); - nullable5 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(TokenDetails), "System.String Token"); - if (((nullable5 == null) - == false)) - { - result.Token = nullable5; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) - { - return whenTrue; - } - else - { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_CapabilitySerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_CapabilitySerializer.cs deleted file mode 100644 index 8d166b5fc..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_CapabilitySerializer.cs +++ /dev/null @@ -1,59 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_CapabilitySerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - - public IO_Ably_CapabilitySerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - } - - - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Capability objectTree) - { - packer.PackString(objectTree.ToJson()); - } - - protected override IO.Ably.Capability UnpackFromCore(MsgPack.Unpacker unpacker) - { - var itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - - if (unpacker.LastReadData.IsRaw) - { - var capability = unpacker.LastReadData.ToString(); - return new Capability(capability); - } - - return new Capability(); - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionDetailsMessageSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionDetailsMessageSerializer.cs deleted file mode 100644 index 250f33936..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionDetailsMessageSerializer.cs +++ /dev/null @@ -1,258 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_ConnectionDetailsMessageSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer> _serializer1; - - private MsgPack.Serialization.MessagePackSerializer _serializer2; - - public IO_Ably_ConnectionDetailsMessageSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer>(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer(schema2); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.ConnectionDetails objectTree) { - packer.PackMapHeader(7); - this._serializer0.PackTo(packer, "clientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - this._serializer0.PackTo(packer, "connectionKey"); - this._serializer0.PackTo(packer, objectTree.ConnectionKey); - this._serializer0.PackTo(packer, "connectionStateTtl"); - this._serializer1.PackTo(packer, objectTree.ConnectionStateTtl); - this._serializer0.PackTo(packer, "maxFrameSize"); - this._serializer2.PackTo(packer, objectTree.MaxFrameSize); - this._serializer0.PackTo(packer, "maxInboundRate"); - this._serializer2.PackTo(packer, objectTree.MaxInboundRate); - this._serializer0.PackTo(packer, "maxMessageSize"); - this._serializer2.PackTo(packer, objectTree.MaxMessageSize); - this._serializer0.PackTo(packer, "serverId"); - this._serializer0.PackTo(packer, objectTree.ServerId); - } - - protected override IO.Ably.ConnectionDetails UnpackFromCore(MsgPack.Unpacker unpacker) { - IO.Ably.ConnectionDetails result = default(IO.Ably.ConnectionDetails); - result = new IO.Ably.ConnectionDetails(); - if (unpacker.IsArrayHeader) { - int unpacked = default(int); - int itemsCount = default(int); - itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - string nullable = default(string); - if ((unpacked < itemsCount)) { - nullable = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String clientId"); - } - if (((nullable == null) - == false)) { - result.ClientId = nullable; - } - unpacked = (unpacked + 1); - string nullable0 = default(string); - if ((unpacked < itemsCount)) { - nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String connectionKey"); - } - if (((nullable0 == null) - == false)) { - result.ConnectionKey = nullable0; - } - unpacked = (unpacked + 1); - System.Nullable nullable1 = default(System.Nullable); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(2); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable1 = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable = default(MsgPack.Unpacker); - disposable = unpacker.ReadSubtree(); - try { - nullable1 = this._serializer1.UnpackFrom(disposable); - } - finally { - if (((disposable == null) - == false)) { - disposable.Dispose(); - } - } - } - } - if (nullable1.HasValue) { - result.ConnectionStateTtl = nullable1; - } - unpacked = (unpacked + 1); - System.Nullable nullable2 = default(System.Nullable); - if ((unpacked < itemsCount)) { - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxFrameSize"); - } - if (nullable2.HasValue) { - result.MaxFrameSize = nullable2.Value; - } - unpacked = (unpacked + 1); - System.Nullable nullable3 = default(System.Nullable); - if ((unpacked < itemsCount)) { - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxInboundRate"); - } - if (nullable3.HasValue) { - result.MaxInboundRate = nullable3.Value; - } - unpacked = (unpacked + 1); - System.Nullable nullable4 = default(System.Nullable); - if ((unpacked < itemsCount)) { - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxMessageSize"); - } - if (nullable4.HasValue) { - result.MaxMessageSize = nullable4.Value; - } - unpacked = (unpacked + 1); - string nullable5 = default(string); - if ((unpacked < itemsCount)) { - nullable5 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String serverId"); - } - if (((nullable5 == null) - == false)) { - result.ServerId = nullable5; - } - unpacked = (unpacked + 1); - } - else { - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) { - string key = default(string); - string nullable6 = default(string); - nullable6 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "MemberName"); - if (((nullable6 == null) - == false)) { - key = nullable6; - } - else { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "serverId")) { - string nullable13 = default(string); - nullable13 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String serverId"); - if (((nullable13 == null) - == false)) { - result.ServerId = nullable13; - } - } - else { - if ((key == "maxMessageSize")) { - System.Nullable nullable12 = default(System.Nullable); - nullable12 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxMessageSize"); - if (nullable12.HasValue) { - result.MaxMessageSize = nullable12.Value; - } - } - else { - if ((key == "maxInboundRate")) { - System.Nullable nullable11 = default(System.Nullable); - nullable11 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxInboundRate"); - if (nullable11.HasValue) { - result.MaxInboundRate = nullable11.Value; - } - } - else { - if ((key == "maxFrameSize")) { - System.Nullable nullable10 = default(System.Nullable); - nullable10 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, typeof(IO.Ably.ConnectionDetails), "Int64 maxFrameSize"); - if (nullable10.HasValue) { - result.MaxFrameSize = nullable10.Value; - } - } - else { - if ((key == "connectionStateTtl")) { - System.Nullable nullable9 = default(System.Nullable); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable9 = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); - disposable0 = unpacker.ReadSubtree(); - try { - nullable9 = this._serializer1.UnpackFrom(disposable0); - } - finally { - if (((disposable0 == null) - == false)) { - disposable0.Dispose(); - } - } - } - if (nullable9.HasValue) { - result.ConnectionStateTtl = nullable9; - } - } - else { - if ((key == "connectionKey")) { - string nullable8 = default(string); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String connectionKey"); - if (((nullable8 == null) - == false)) { - result.ConnectionKey = nullable8; - } - } - else { - if ((key == "clientId")) { - string nullable7 = default(string); - nullable7 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ConnectionDetails), "System.String clientId"); - if (((nullable7 == null) - == false)) { - result.ClientId = nullable7; - } - } - else { - unpacker.Skip(); - } - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionTypesSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionTypesSerializer.cs deleted file mode 100644 index 1bdc04678..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ConnectionTypesSerializer.cs +++ /dev/null @@ -1,193 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_ConnectionTypesSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_ConnectionTypesSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.ConnectionTypes objectTree) { - packer.PackMapHeader(3); - this._serializer0.PackTo(packer, "all"); - this._serializer1.PackTo(packer, objectTree.All); - this._serializer0.PackTo(packer, "plain"); - this._serializer1.PackTo(packer, objectTree.Plain); - this._serializer0.PackTo(packer, "tls"); - this._serializer1.PackTo(packer, objectTree.Tls); - } - - protected override IO.Ably.ConnectionTypes UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.ConnectionTypes result = default(IO.Ably.ConnectionTypes); - result = new IO.Ably.ConnectionTypes(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable2 = default(string); - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.ConnectionTypes), "MemberName"); - if (((nullable2 == null) - == false)) - { - key = nullable2; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "tls")) - { - IO.Ably.ResourceCount nullable5 = default(IO.Ably.ResourceCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable5 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable5 = this._serializer1.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (((nullable5 == null) - == false)) - { - result.Tls = nullable5; - } - } - else - { - if ((key == "plain")) - { - IO.Ably.ResourceCount nullable4 = default(IO.Ably.ResourceCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable4 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try - { - nullable4 = this._serializer1.UnpackFrom(disposable3); - } - finally - { - if (((disposable3 == null) - == false)) - { - disposable3.Dispose(); - } - } - } - if (((nullable4 == null) - == false)) - { - result.Plain = nullable4; - } - } - else - { - if ((key == "all")) - { - IO.Ably.ResourceCount nullable3 = default(IO.Ably.ResourceCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable3 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable3 = this._serializer1.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (((nullable3 == null) - == false)) - { - result.All = nullable3; - } - } - else - { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ErrorInfoSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ErrorInfoSerializer.cs deleted file mode 100644 index c13724514..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ErrorInfoSerializer.cs +++ /dev/null @@ -1,150 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_ErrorInfoSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer> _serializer2; - - public IO_Ably_ErrorInfoSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer>(schema2); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.ErrorInfo objectTree) { - packer.PackMapHeader(3); - this._serializer0.PackTo(packer, "code"); - this._serializer1.PackTo(packer, objectTree.Code); - this._serializer0.PackTo(packer, "message"); - this._serializer0.PackTo(packer, objectTree.Message); - this._serializer0.PackTo(packer, "statusCode"); - this._serializer2.PackTo(packer, objectTree.StatusCode); - } - - protected override IO.Ably.ErrorInfo UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.ErrorInfo result = default(IO.Ably.ErrorInfo); - result = new IO.Ably.ErrorInfo(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable3 = default(string); - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.ErrorInfo), - "MemberName"); - if (((nullable3 == null) - == false)) - { - key = nullable3; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "statusCode")) - { - System.Nullable nullable7 = - default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable7 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); - disposable0 = unpacker.ReadSubtree(); - try - { - nullable7 = this._serializer2.UnpackFrom(disposable0); - } - finally - { - if (((disposable0 == null) - == false)) - { - disposable0.Dispose(); - } - } - } - if (nullable7.HasValue) - { - result.StatusCode = nullable7; - } - } - else - { - if ((key == "message")) - { - string nullable5 = default(string); - nullable5 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.ErrorInfo), "System.String message"); - if (((nullable5 == null) - == false)) - { - result.Message = nullable5; - } - } - else - { - if ((key == "code")) - { - System.Nullable nullable4 = default(System.Nullable); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt32Value(unpacker, - typeof(IO.Ably.ErrorInfo), "Int32 code"); - if (nullable4.HasValue) - { - result.Code = nullable4.Value; - } - } - else - { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_InboundMessageTrafficSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_InboundMessageTrafficSerializer.cs deleted file mode 100644 index 3436658ce..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_InboundMessageTrafficSerializer.cs +++ /dev/null @@ -1,193 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_InboundMessageTrafficSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_InboundMessageTrafficSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.InboundMessageTraffic objectTree) { - packer.PackMapHeader(3); - this._serializer0.PackTo(packer, "all"); - this._serializer1.PackTo(packer, objectTree.All); - this._serializer0.PackTo(packer, "realtime"); - this._serializer1.PackTo(packer, objectTree.Realtime); - this._serializer0.PackTo(packer, "rest"); - this._serializer1.PackTo(packer, objectTree.Rest); - } - - protected override IO.Ably.InboundMessageTraffic UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.InboundMessageTraffic result = default(IO.Ably.InboundMessageTraffic); - result = new IO.Ably.InboundMessageTraffic(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable4 = default(string); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.InboundMessageTraffic), "MemberName"); - if (((nullable4 == null) - == false)) - { - key = nullable4; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "rest")) - { - IO.Ably.MessageTypes nullable9 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable9 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable8 = default(MsgPack.Unpacker); - disposable8 = unpacker.ReadSubtree(); - try - { - nullable9 = this._serializer1.UnpackFrom(disposable8); - } - finally - { - if (((disposable8 == null) - == false)) - { - disposable8.Dispose(); - } - } - } - if (((nullable9 == null) - == false)) - { - result.Rest = nullable9; - } - } - else - { - if ((key == "realtime")) - { - IO.Ably.MessageTypes nullable8 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable8 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable7 = default(MsgPack.Unpacker); - disposable7 = unpacker.ReadSubtree(); - try - { - nullable8 = this._serializer1.UnpackFrom(disposable7); - } - finally - { - if (((disposable7 == null) - == false)) - { - disposable7.Dispose(); - } - } - } - if (((nullable8 == null) - == false)) - { - result.Realtime = nullable8; - } - } - else - { - if ((key == "all")) - { - IO.Ably.MessageTypes nullable5 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable5 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable5 = this._serializer1.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (((nullable5 == null) - == false)) - { - result.All = nullable5; - } - } - else - { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageCountSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageCountSerializer.cs deleted file mode 100644 index f26a891c6..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageCountSerializer.cs +++ /dev/null @@ -1,103 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_MessageCountSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_MessageCountSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.MessageCount objectTree) { - packer.PackMapHeader(2); - this._serializer0.PackTo(packer, "count"); - this._serializer1.PackTo(packer, objectTree.Count); - this._serializer0.PackTo(packer, "data"); - this._serializer1.PackTo(packer, objectTree.Data); - } - - protected override IO.Ably.MessageCount UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.MessageCount result = default(IO.Ably.MessageCount); - result = new IO.Ably.MessageCount(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable1 = default(string); - nullable1 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.MessageCount), - "MemberName"); - if (((nullable1 == null) - == false)) - { - key = nullable1; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "data")) - { - System.Nullable nullable3 = default(System.Nullable); - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.MessageCount), "Double Data"); - if (nullable3.HasValue) - { - result.Data = nullable3.Value; - } - } - else - { - if ((key == "count")) - { - System.Nullable nullable2 = default(System.Nullable); - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.MessageCount), "Double Count"); - if (nullable2.HasValue) - { - result.Count = nullable2.Value; - } - } - else - { - unpacker.Skip(); - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageSerializer.cs deleted file mode 100644 index 2d5e971d6..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageSerializer.cs +++ /dev/null @@ -1,294 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System.Linq; -using MsgPack; - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - - public class IO_Ably_MessageSerializer : MsgPack.Serialization.MessagePackSerializer - { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer> _serializer2; - - public IO_Ably_MessageSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) - { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer>(schema2); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Message objectTree) - { - var nonNullFields = new bool[] - { - objectTree.ClientId.IsNotEmpty(), - objectTree.ConnectionId.IsNotEmpty(), - objectTree.Data != null, - objectTree.Encoding.IsNotEmpty(), - objectTree.Id.IsNotEmpty(), - objectTree.Name.IsNotEmpty(), - objectTree.Timestamp != null, - }.Count(x => x); - - packer.PackMapHeader(nonNullFields); - if (objectTree.ClientId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "clientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - } - if (objectTree.ConnectionId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "connectionId"); - this._serializer0.PackTo(packer, objectTree.ConnectionId); - } - if (objectTree.Data != null) - { - this._serializer0.PackTo(packer, "data"); - this._serializer1.PackTo(packer, objectTree.Data); - } - if (objectTree.Encoding.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "encoding"); - this._serializer0.PackTo(packer, objectTree.Encoding); - } - if (objectTree.Id.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "id"); - this._serializer0.PackTo(packer, objectTree.Id); - } - if (objectTree.Name.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "name"); - this._serializer0.PackTo(packer, objectTree.Name); - } - if (objectTree.Timestamp != null) - { - this._serializer0.PackTo(packer, "timestamp"); - this._serializer2.PackTo(packer, objectTree.Timestamp); - } - } - - protected override IO.Ably.Message UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.Message result = default(IO.Ably.Message); - result = new IO.Ably.Message(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable7 = default(string); - nullable7 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.Message), - "MemberName"); - if (((nullable7 == null) - == false)) - { - key = nullable7; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "timestamp")) - { - System.Nullable nullable15 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable15 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable15 = this._serializer2.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (nullable15.HasValue) - { - result.Timestamp = nullable15; - } - } - else - { - if ((key == "name")) - { - string nullable14 = default(string); - nullable14 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Message), "System.String name"); - if (((nullable14 == null) - == false)) - { - result.Name = nullable14; - } - } - else - { - if ((key == "id")) - { - string nullable13 = default(string); - nullable13 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Message), "System.String id"); - if (((nullable13 == null) - == false)) - { - result.Id = nullable13; - } - } - else - { - if ((key == "encoding")) - { - string nullable12 = default(string); - nullable12 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Message), "System.String encoding"); - if (((nullable12 == null) - == false)) - { - result.Encoding = nullable12; - } - } - else - { - if ((key == "data")) - { - object nullable10 = default(object); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable10 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable10 = this._serializer1.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (((nullable10 == null) - == false)) - { - if (nullable10 is MsgPack.MessagePackObject) - { - nullable10 = ((MessagePackObject) nullable10).ToObject(); - if (nullable10 is MessagePackObject[]) - { - result.Data = - ((MessagePackObject[])nullable10).Select(x => x.ToObject()).ToArray(); - } - else - { - result.Data = nullable10; - } - } - else - { - result.Data = nullable10; - } - } - } - else - { - if ((key == "connectionId")) - { - string nullable9 = default(string); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Message), "System.String connectionId"); - if (((nullable9 == null) - == false)) - { - result.ConnectionId = nullable9; - } - } - else - { - if ((key == "clientId")) - { - string nullable8 = default(string); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Message), "System.String clientId"); - if (((nullable8 == null) - == false)) - { - result.ClientId = nullable8; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) - { - return whenTrue; - } - else - { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageTypesSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageTypesSerializer.cs deleted file mode 100644 index 860a08d46..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_MessageTypesSerializer.cs +++ /dev/null @@ -1,193 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_MessageTypesSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_MessageTypesSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.MessageTypes objectTree) { - packer.PackMapHeader(3); - this._serializer0.PackTo(packer, "all"); - this._serializer1.PackTo(packer, objectTree.All); - this._serializer0.PackTo(packer, "messages"); - this._serializer1.PackTo(packer, objectTree.Messages); - this._serializer0.PackTo(packer, "presence"); - this._serializer1.PackTo(packer, objectTree.Presence); - } - - protected override IO.Ably.MessageTypes UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.MessageTypes result = default(IO.Ably.MessageTypes); - result = new IO.Ably.MessageTypes(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable2 = default(string); - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.MessageTypes), - "MemberName"); - if (((nullable2 == null) - == false)) - { - key = nullable2; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "presence")) - { - IO.Ably.MessageCount nullable5 = default(IO.Ably.MessageCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable5 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable5 = this._serializer1.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (((nullable5 == null) - == false)) - { - result.Presence = nullable5; - } - } - else - { - if ((key == "messages")) - { - IO.Ably.MessageCount nullable4 = default(IO.Ably.MessageCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable4 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try - { - nullable4 = this._serializer1.UnpackFrom(disposable3); - } - finally - { - if (((disposable3 == null) - == false)) - { - disposable3.Dispose(); - } - } - } - if (((nullable4 == null) - == false)) - { - result.Messages = nullable4; - } - } - else - { - if ((key == "all")) - { - IO.Ably.MessageCount nullable3 = default(IO.Ably.MessageCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable3 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable3 = this._serializer1.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (((nullable3 == null) - == false)) - { - result.All = nullable3; - } - } - else - { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_OutboundMessageTrafficSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_OutboundMessageTrafficSerializer.cs deleted file mode 100644 index 04d77f13a..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_OutboundMessageTrafficSerializer.cs +++ /dev/null @@ -1,233 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_OutboundMessageTrafficSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_OutboundMessageTrafficSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.OutboundMessageTraffic objectTree) { - packer.PackMapHeader(4); - this._serializer0.PackTo(packer, "all"); - this._serializer1.PackTo(packer, objectTree.All); - this._serializer0.PackTo(packer, "webhook"); - this._serializer1.PackTo(packer, objectTree.Webhook); - this._serializer0.PackTo(packer, "realtime"); - this._serializer1.PackTo(packer, objectTree.Realtime); - this._serializer0.PackTo(packer, "rest"); - this._serializer1.PackTo(packer, objectTree.Rest); - } - - protected override IO.Ably.OutboundMessageTraffic UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.OutboundMessageTraffic result = default(IO.Ably.OutboundMessageTraffic); - result = new IO.Ably.OutboundMessageTraffic(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable4 = default(string); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.OutboundMessageTraffic), "MemberName"); - if (((nullable4 == null) - == false)) - { - key = nullable4; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "rest")) - { - IO.Ably.MessageTypes nullable9 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable9 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable8 = default(MsgPack.Unpacker); - disposable8 = unpacker.ReadSubtree(); - try - { - nullable9 = this._serializer1.UnpackFrom(disposable8); - } - finally - { - if (((disposable8 == null) - == false)) - { - disposable8.Dispose(); - } - } - } - if (((nullable9 == null) - == false)) - { - result.Rest = nullable9; - } - } - else - { - if ((key == "realtime")) - { - IO.Ably.MessageTypes nullable8 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable8 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable7 = default(MsgPack.Unpacker); - disposable7 = unpacker.ReadSubtree(); - try - { - nullable8 = this._serializer1.UnpackFrom(disposable7); - } - finally - { - if (((disposable7 == null) - == false)) - { - disposable7.Dispose(); - } - } - } - if (((nullable8 == null) - == false)) - { - result.Realtime = nullable8; - } - } - else - { - if ((key == "webhook")) - { - IO.Ably.MessageTypes nullable7 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable7 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable6 = default(MsgPack.Unpacker); - disposable6 = unpacker.ReadSubtree(); - try - { - nullable7 = this._serializer1.UnpackFrom(disposable6); - } - finally - { - if (((disposable6 == null) - == false)) - { - disposable6.Dispose(); - } - } - } - if (((nullable7 == null) - == false)) - { - result.Webhook = nullable7; - } - } - else - { - if ((key == "all")) - { - IO.Ably.MessageTypes nullable5 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable5 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable5 = this._serializer1.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (((nullable5 == null) - == false)) - { - result.All = nullable5; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessageSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessageSerializer.cs deleted file mode 100644 index dca097acd..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessageSerializer.cs +++ /dev/null @@ -1,313 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System.Linq; -using MsgPack; - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_PresenceMessageSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer _serializer2; - - private MsgPack.Serialization.MessagePackSerializer> _serializer3; - - private MsgPack.Serialization.MessagePackSerializer> _serializer4; - - public IO_Ably_PresenceMessageSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - this._serializer1 = context.GetSerializer(MsgPack.Serialization.EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(context, typeof(IO.Ably.PresenceAction), MsgPack.Serialization.EnumMemberSerializationMethod.ByUnderlyingValue)); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer2 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer3 = context.GetSerializer>(schema2); - MsgPack.Serialization.PolymorphismSchema schema3 = default(MsgPack.Serialization.PolymorphismSchema); - schema3 = null; - this._serializer4 = context.GetSerializer>(schema3); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.PresenceMessage objectTree) - { - var nonNullFields = new bool[] - { - objectTree.Id.IsNotEmpty(), - objectTree.ClientId.IsNotEmpty(), - objectTree.ConnectionId.IsNotEmpty(), - objectTree.Data != null, - objectTree.Encoding.IsNotEmpty(), - objectTree.Timestamp != null, - }.Count(x => x) + 1; //one for action - - packer.PackMapHeader(nonNullFields); - if (objectTree.Id.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "id"); - this._serializer0.PackTo(packer, objectTree.Id); - } - this._serializer0.PackTo(packer, "action"); - this._serializer1.PackTo(packer, objectTree.Action); - if (objectTree.ClientId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "clientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - } - if (objectTree.ConnectionId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "connectionId"); - this._serializer0.PackTo(packer, objectTree.ConnectionId); - } - if (objectTree.Data != null) - { - this._serializer0.PackTo(packer, "data"); - this._serializer2.PackTo(packer, objectTree.Data); - } - if (objectTree.Encoding.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "encoding"); - this._serializer0.PackTo(packer, objectTree.Encoding); - } - if (objectTree.Timestamp != null) - { - this._serializer0.PackTo(packer, "timestamp"); - this._serializer3.PackTo(packer, objectTree.Timestamp); - } - } - - protected override IO.Ably.PresenceMessage UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.PresenceMessage result = default(IO.Ably.PresenceMessage); - result = new IO.Ably.PresenceMessage(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable6 = default(string); - nullable6 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.PresenceMessage), "MemberName"); - if (((nullable6 == null) - == false)) - { - key = nullable6; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "timestamp")) - { - System.Nullable nullable13 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable13 = this._serializer3.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable13 = this._serializer3.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (nullable13.HasValue) - { - result.Timestamp = nullable13; - } - } - else - { - if ((key == "encoding")) - { - string nullable12 = default(string); - nullable12 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.PresenceMessage), "System.String encoding"); - if (((nullable12 == null) - == false)) - { - result.Encoding = nullable12; - } - } - else - { - if ((key == "data")) - { - object nullable11 = default(object); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable11 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try - { - nullable11 = this._serializer2.UnpackFrom(disposable3); - } - finally - { - if (((disposable3 == null) - == false)) - { - disposable3.Dispose(); - } - } - } - if (((nullable11 == null) - == false)) - { - if (nullable11 is MsgPack.MessagePackObject) - { - result.Data = ((MessagePackObject) nullable11).ToObject(); - } - else if (nullable11 is MessagePackObject[]) - { - result.Data = - ((MessagePackObject[]) nullable11).Select(x => x.ToObject()).ToArray(); - } - else - { - result.Data = nullable11; - } - } - } - else - { - if ((key == "connectionId")) - { - string nullable10 = default(string); - nullable10 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.PresenceMessage), "System.String connectionId"); - if (((nullable10 == null) - == false)) - { - result.ConnectionId = nullable10; - } - } - else - { - if ((key == "clientId")) - { - string nullable9 = default(string); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.PresenceMessage), "System.String clientId"); - if (((nullable9 == null) - == false)) - { - result.ClientId = nullable9; - } - } - else - { - if ((key == "action")) - { - System.Nullable nullable8 = - default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable8 = this._serializer4.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable8 = this._serializer4.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (nullable8.HasValue) - { - result.Action = nullable8.Value; - } - } - else - { - if ((key == "id")) - { - string nullable7 = default(string); - nullable7 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.PresenceMessage), "System.String id"); - if (((nullable7 == null) - == false)) - { - result.Id = nullable7; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessage_ActionTypeSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessage_ActionTypeSerializer.cs deleted file mode 100644 index 6af23c006..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_PresenceMessage_ActionTypeSerializer.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_PresenceMessage_ActionTypeSerializer : MsgPack.Serialization.EnumMessagePackSerializer { - - public IO_Ably_PresenceMessage_ActionTypeSerializer(MsgPack.Serialization.SerializationContext context) : - this(context, MsgPack.Serialization.EnumSerializationMethod.ByUnderlyingValue) { - } - - public IO_Ably_PresenceMessage_ActionTypeSerializer(MsgPack.Serialization.SerializationContext context, MsgPack.Serialization.EnumSerializationMethod enumSerializationMethod) : - base(context, enumSerializationMethod) { - } - - protected override void PackUnderlyingValueTo(MsgPack.Packer packer, IO.Ably.PresenceAction enumValue) { - packer.Pack(((int)(enumValue))); - } - - protected override IO.Ably.PresenceAction UnpackFromUnderlyingValue(MsgPack.MessagePackObject messagePackObject) { - return ((IO.Ably.PresenceAction)(messagePackObject.AsInt32())); - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_RequestCountSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_RequestCountSerializer.cs deleted file mode 100644 index ae41b20dd..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_RequestCountSerializer.cs +++ /dev/null @@ -1,118 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_RequestCountSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_RequestCountSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.RequestCount objectTree) { - packer.PackMapHeader(3); - this._serializer0.PackTo(packer, "failed"); - this._serializer1.PackTo(packer, objectTree.Failed); - this._serializer0.PackTo(packer, "refused"); - this._serializer1.PackTo(packer, objectTree.Refused); - this._serializer0.PackTo(packer, "succeeded"); - this._serializer1.PackTo(packer, objectTree.Succeeded); - } - - protected override IO.Ably.RequestCount UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.RequestCount result = default(IO.Ably.RequestCount); - result = new IO.Ably.RequestCount(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable2 = default(string); - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.RequestCount), - "MemberName"); - if (((nullable2 == null) - == false)) - { - key = nullable2; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "succeeded")) - { - System.Nullable nullable5 = default(System.Nullable); - nullable5 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.RequestCount), "Double Succeeded"); - if (nullable5.HasValue) - { - result.Succeeded = nullable5.Value; - } - } - else - { - if ((key == "refused")) - { - System.Nullable nullable4 = default(System.Nullable); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.RequestCount), "Double Refused"); - if (nullable4.HasValue) - { - result.Refused = nullable4.Value; - } - } - else - { - if ((key == "failed")) - { - System.Nullable nullable3 = default(System.Nullable); - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.RequestCount), "Double Failed"); - if (nullable3.HasValue) - { - result.Failed = nullable3.Value; - } - } - else - { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ResourceCountSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ResourceCountSerializer.cs deleted file mode 100644 index 0ab79736f..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_ResourceCountSerializer.cs +++ /dev/null @@ -1,148 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_ResourceCountSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - public IO_Ably_ResourceCountSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.ResourceCount objectTree) { - packer.PackMapHeader(5); - this._serializer0.PackTo(packer, "mean"); - this._serializer1.PackTo(packer, objectTree.Mean); - this._serializer0.PackTo(packer, "min"); - this._serializer1.PackTo(packer, objectTree.Min); - this._serializer0.PackTo(packer, "opened"); - this._serializer1.PackTo(packer, objectTree.Opened); - this._serializer0.PackTo(packer, "peak"); - this._serializer1.PackTo(packer, objectTree.Peak); - this._serializer0.PackTo(packer, "refused"); - this._serializer1.PackTo(packer, objectTree.Refused); - } - - protected override IO.Ably.ResourceCount UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.ResourceCount result = default(IO.Ably.ResourceCount); - result = new IO.Ably.ResourceCount(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable4 = default(string); - nullable4 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.ResourceCount), "MemberName"); - if (((nullable4 == null) - == false)) - { - key = nullable4; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "refused")) - { - System.Nullable nullable9 = default(System.Nullable); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackNullableDoubleValue(unpacker, - typeof(IO.Ably.ResourceCount), "Double Refused"); - if (nullable9.HasValue) - { - result.Refused = nullable9.Value; - } - } - else - { - if ((key == "peak")) - { - System.Nullable nullable8 = default(System.Nullable); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackNullableDoubleValue(unpacker, - typeof(IO.Ably.ResourceCount), "Double Peak"); - if (nullable8.HasValue) - { - result.Peak = nullable8.Value; - } - } - else - { - if ((key == "opened")) - { - System.Nullable nullable7 = default(System.Nullable); - nullable7 = MsgPack.Serialization.UnpackHelpers.UnpackNullableDoubleValue(unpacker, - typeof(IO.Ably.ResourceCount), "Double Opened"); - if (nullable7.HasValue) - { - result.Opened = nullable7.Value; - } - } - else - { - if ((key == "min")) - { - System.Nullable nullable6 = default(System.Nullable); - nullable6 = MsgPack.Serialization.UnpackHelpers.UnpackNullableDoubleValue(unpacker, - typeof(IO.Ably.ResourceCount), "Double Min"); - if (nullable6.HasValue) - { - result.Min = nullable6.Value; - } - } - else - { - if ((key == "mean")) - { - System.Nullable nullable5 = default(System.Nullable); - nullable5 = MsgPack.Serialization.UnpackHelpers.UnpackNullableDoubleValue(unpacker, - typeof(IO.Ably.ResourceCount), "Double Mean"); - if (nullable5.HasValue) - { - result.Mean = nullable5.Value; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_StatsSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_StatsSerializer.cs deleted file mode 100644 index 70209b9b5..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_StatsSerializer.cs +++ /dev/null @@ -1,443 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers -{ - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_StatsSerializer : MsgPack.Serialization.MessagePackSerializer - { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer _serializer2; - - private MsgPack.Serialization.MessagePackSerializer _serializer3; - - private MsgPack.Serialization.MessagePackSerializer _serializer4; - - private MsgPack.Serialization.MessagePackSerializer _serializer5; - private MsgPack.Serialization.MessagePackSerializer _serializer6; - - public IO_Ably_StatsSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) - { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer(schema2); - MsgPack.Serialization.PolymorphismSchema schema3 = default(MsgPack.Serialization.PolymorphismSchema); - schema3 = null; - this._serializer3 = context.GetSerializer(schema3); - MsgPack.Serialization.PolymorphismSchema schema4 = default(MsgPack.Serialization.PolymorphismSchema); - schema4 = null; - this._serializer4 = context.GetSerializer(schema4); - MsgPack.Serialization.PolymorphismSchema schema5 = default(MsgPack.Serialization.PolymorphismSchema); - schema5 = null; - this._serializer5 = context.GetSerializer(schema5); - MsgPack.Serialization.PolymorphismSchema schema6 = default(MsgPack.Serialization.PolymorphismSchema); - schema6 = null; - this._serializer6 = context.GetSerializer(schema6); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Stats objectTree) - { - packer.PackMapHeader(9); - this._serializer0.PackTo(packer, "all"); - this._serializer1.PackTo(packer, objectTree.All); - this._serializer0.PackTo(packer, "apiRequests"); - this._serializer2.PackTo(packer, objectTree.ApiRequests); - this._serializer0.PackTo(packer, "channels"); - this._serializer3.PackTo(packer, objectTree.Channels); - this._serializer0.PackTo(packer, "connections"); - this._serializer4.PackTo(packer, objectTree.Connections); - this._serializer0.PackTo(packer, "inbound"); - this._serializer5.PackTo(packer, objectTree.Inbound); - this._serializer0.PackTo(packer, "intervalId"); - this._serializer0.PackTo(packer, objectTree.IntervalId); - this._serializer0.PackTo(packer, "outbound"); - this._serializer6.PackTo(packer, objectTree.Outbound); - this._serializer0.PackTo(packer, "persisted"); - this._serializer1.PackTo(packer, objectTree.Persisted); - this._serializer0.PackTo(packer, "tokenRequests"); - this._serializer2.PackTo(packer, objectTree.TokenRequests); - } - - protected override IO.Ably.Stats UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.Stats result = default(IO.Ably.Stats); - result = new IO.Ably.Stats(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable8 = default(string); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.Stats), - "MemberName"); - if (((nullable8 == null) - == false)) - { - key = nullable8; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "tokenRequests")) - { - IO.Ably.RequestCount nullable17 = default(IO.Ably.RequestCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable17 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable16 = default(MsgPack.Unpacker); - disposable16 = unpacker.ReadSubtree(); - try - { - nullable17 = this._serializer2.UnpackFrom(disposable16); - } - finally - { - if (((disposable16 == null) - == false)) - { - disposable16.Dispose(); - } - } - } - if (((nullable17 == null) - == false)) - { - result.TokenRequests = nullable17; - } - } - else - { - if ((key == "persisted")) - { - IO.Ably.MessageTypes nullable16 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable16 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable15 = default(MsgPack.Unpacker); - disposable15 = unpacker.ReadSubtree(); - try - { - nullable16 = this._serializer1.UnpackFrom(disposable15); - } - finally - { - if (((disposable15 == null) - == false)) - { - disposable15.Dispose(); - } - } - } - if (((nullable16 == null) - == false)) - { - result.Persisted = nullable16; - } - } - else - { - if ((key == "outbound")) - { - IO.Ably.OutboundMessageTraffic nullable15 = default(IO.Ably.OutboundMessageTraffic); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable15 = this._serializer6.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable14 = default(MsgPack.Unpacker); - disposable14 = unpacker.ReadSubtree(); - try - { - nullable15 = this._serializer6.UnpackFrom(disposable14); - } - finally - { - if (((disposable14 == null) - == false)) - { - disposable14.Dispose(); - } - } - } - if (((nullable15 == null) - == false)) - { - result.Outbound = nullable15; - } - } - else - { - if ((key == "intervalId")) - { - string nullable14 = default(string); - nullable14 = - MsgPack.Serialization.UnpackHelpers - .UnpackStringValue(unpacker, - typeof(IO.Ably.Stats - ), "System.String intervalId"); - if (((nullable14 == null) - == false)) - { - result.IntervalId = nullable14; - } - } - else - { - if ((key == "inbound")) - { - IO.Ably.InboundMessageTraffic nullable13 = default(IO.Ably.InboundMessageTraffic); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable13 = this._serializer5.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable12 = default(MsgPack.Unpacker); - disposable12 = unpacker.ReadSubtree(); - try - { - nullable13 = this._serializer5.UnpackFrom(disposable12); - } - finally - { - if (((disposable12 == null) - == false)) - { - disposable12.Dispose(); - } - } - } - if (((nullable13 == null) - == false)) - { - result.Inbound = nullable13; - } - } - else - { - if ((key == "connections")) - { - IO.Ably.ConnectionTypes nullable12 = default(IO.Ably.ConnectionTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable12 = this._serializer4.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable11 = default(MsgPack.Unpacker); - disposable11 = unpacker.ReadSubtree(); - try - { - nullable12 = this._serializer4.UnpackFrom(disposable11); - } - finally - { - if (((disposable11 == null) - == false)) - { - disposable11.Dispose(); - } - } - } - if (((nullable12 == null) - == false)) - { - result.Connections = nullable12; - } - } - else - { - if ((key == "channels")) - { - IO.Ably.ResourceCount nullable11 = default(IO.Ably.ResourceCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable11 = this._serializer3.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable10 = default(MsgPack.Unpacker); - disposable10 = unpacker.ReadSubtree(); - try - { - nullable11 = this._serializer3.UnpackFrom(disposable10); - } - finally - { - if (((disposable10 == null) - == false)) - { - disposable10.Dispose(); - } - } - } - if (((nullable11 == null) - == false)) - { - result.Channels = nullable11; - } - } - else - { - if ((key == "apiRequests")) - { - IO.Ably.RequestCount nullable10 = default(IO.Ably.RequestCount); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable10 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable9 = default(MsgPack.Unpacker); - disposable9 = unpacker.ReadSubtree(); - try - { - nullable10 = this._serializer2.UnpackFrom(disposable9); - } - finally - { - if (((disposable9 == null) - == false)) - { - disposable9.Dispose(); - } - } - } - if (((nullable10 == null) - == false)) - { - result.ApiRequests = nullable10; - } - } - else - { - if ((key == "all")) - { - IO.Ably.MessageTypes nullable9 = default(IO.Ably.MessageTypes); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions - .NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable9 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable8 = default(MsgPack.Unpacker); - disposable8 = unpacker.ReadSubtree(); - try - { - nullable9 = this._serializer1.UnpackFrom(disposable8); - } - finally - { - if (((disposable8 == null) - == false)) - { - disposable8.Dispose(); - } - } - } - if (((nullable9 == null) - == false)) - { - result.All = nullable9; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) - { - return whenTrue; - } - else - { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_TokenRequestSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_TokenRequestSerializer.cs deleted file mode 100644 index ad7f26279..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_TokenRequestSerializer.cs +++ /dev/null @@ -1,306 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System.Linq; - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_TokenRequestSerializer : MsgPack.Serialization.MessagePackSerializer - { - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer> _serializer2; - - private MsgPack.Serialization.MessagePackSerializer> _serializer3; - private MsgPack.Serialization.MessagePackSerializer _serializer4; - - public IO_Ably_TokenRequestSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) - { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer>(schema2); - MsgPack.Serialization.PolymorphismSchema schema3 = default(MsgPack.Serialization.PolymorphismSchema); - schema3 = null; - this._serializer3 = context.GetSerializer>(schema3); - this._serializer4 = context.GetSerializer(null); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.TokenRequest objectTree) - { - var nonNullFields = new bool[] - { - objectTree.Capability != null, - objectTree.ClientId.IsNotEmpty(), - objectTree.KeyName != null, - objectTree.Mac.IsNotEmpty(), - objectTree.Nonce.IsNotEmpty(), - objectTree.Timestamp.HasValue, - objectTree.Ttl.HasValue, - }.Count(x => x); //One for MsgSerial and one for Action as this is always serialised - - packer.PackMapHeader(nonNullFields); - if (objectTree.Capability != null) - { - this._serializer0.PackTo(packer, "capability"); - this._serializer1.PackTo(packer, objectTree.Capability); - } - if (objectTree.ClientId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "clientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - } - if (objectTree.KeyName.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "keyName"); - this._serializer0.PackTo(packer, objectTree.KeyName); - } - if (objectTree.Mac.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "mac"); - this._serializer0.PackTo(packer, objectTree.Mac); - } - if (objectTree.Nonce.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "nonce"); - this._serializer0.PackTo(packer, objectTree.Nonce); - } - if (objectTree.Timestamp.HasValue) - { - this._serializer0.PackTo(packer, "timestamp"); - this._serializer4.PackTo(packer, objectTree.Timestamp.Value.ToUnixTimeInMilliseconds()); - } - if (objectTree.Ttl.HasValue) - { - this._serializer0.PackTo(packer, "ttl"); - this._serializer4.PackTo(packer, (long)objectTree.Ttl.Value.TotalMilliseconds); - } - } - - protected override IO.Ably.TokenRequest UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.TokenRequest result = default(IO.Ably.TokenRequest); - result = new IO.Ably.TokenRequest(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable6 = default(string); - nullable6 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), - "MemberName"); - if (((nullable6 == null) - == false)) - { - key = nullable6; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "ttl")) - { - System.Nullable nullable13 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable13 = this._serializer3.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try - { - nullable13 = this._serializer3.UnpackFrom(disposable4); - } - finally - { - if (((disposable4 == null) - == false)) - { - disposable4.Dispose(); - } - } - } - if (nullable13.HasValue) - { - result.Ttl = nullable13; - } - } - else - { - if ((key == "timestamp")) - { - System.Nullable nullable12 = - default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable12 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try - { - nullable12 = this._serializer2.UnpackFrom(disposable3); - } - finally - { - if (((disposable3 == null) - == false)) - { - disposable3.Dispose(); - } - } - } - if (nullable12.HasValue) - { - result.Timestamp = nullable12; - } - } - else - { - if ((key == "nonce")) - { - string nullable11 = default(string); - nullable11 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.TokenRequest), "System.String Nonce"); - if (((nullable11 == null) - == false)) - { - result.Nonce = nullable11; - } - } - else - { - if ((key == "mac")) - { - string nullable10 = default(string); - nullable10 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.TokenRequest), "System.String Mac"); - if (((nullable10 == null) - == false)) - { - result.Mac = nullable10; - } - } - else - { - if ((key == "keyName")) - { - string nullable9 = default(string); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.TokenRequest), "System.String KeyName"); - if (((nullable9 == null) - == false)) - { - result.KeyName = nullable9; - } - } - else - { - if ((key == "clientId")) - { - string nullable8 = default(string); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.TokenRequest), "System.String ClientId"); - if (((nullable8 == null) - == false)) - { - result.ClientId = nullable8; - } - } - else - { - if ((key == "capability")) - { - IO.Ably.Capability nullable7 = default(IO.Ably.Capability); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable7 = this._serializer1.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try - { - nullable7 = this._serializer1.UnpackFrom(disposable2); - } - finally - { - if (((disposable2 == null) - == false)) - { - disposable2.Dispose(); - } - } - } - if (((nullable7 == null) - == false)) - { - result.Capability = nullable7; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) - { - return whenTrue; - } - else - { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessageSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessageSerializer.cs deleted file mode 100644 index 76118f495..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessageSerializer.cs +++ /dev/null @@ -1,598 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System.Linq; - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class IO_Ably_Types_ProtocolMessageSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer _serializer2; - - private MsgPack.Serialization.MessagePackSerializer> _serializer3; - - private MsgPack.Serialization.MessagePackSerializer> _serializer4; - - private MsgPack.Serialization.MessagePackSerializer _serializer5; - - private MsgPack.Serialization.MessagePackSerializer> _serializer6; - - private MsgPack.Serialization.MessagePackSerializer _serializer7; - - private MsgPack.Serialization.MessagePackSerializer _serializer8; - - private MsgPack.Serialization.MessagePackSerializer _serializer9; - - private MsgPack.Serialization.MessagePackSerializer> _serializer10; - - private MsgPack.Serialization.MessagePackSerializer> _serializer11; - - public IO_Ably_Types_ProtocolMessageSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - this._serializer1 = context.GetSerializer(MsgPack.Serialization.EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(context, typeof(IO.Ably.Types.ProtocolMessage.MessageAction), MsgPack.Serialization.EnumMemberSerializationMethod.ByUnderlyingValue)); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer2 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer3 = context.GetSerializer>(schema2); - MsgPack.Serialization.PolymorphismSchema schema3 = default(MsgPack.Serialization.PolymorphismSchema); - schema3 = null; - this._serializer4 = context.GetSerializer>(schema3); - MsgPack.Serialization.PolymorphismSchema schema4 = default(MsgPack.Serialization.PolymorphismSchema); - schema4 = null; - this._serializer5 = context.GetSerializer(schema4); - MsgPack.Serialization.PolymorphismSchema schema5 = default(MsgPack.Serialization.PolymorphismSchema); - schema5 = null; - this._serializer6 = context.GetSerializer>(schema5); - MsgPack.Serialization.PolymorphismSchema schema6 = default(MsgPack.Serialization.PolymorphismSchema); - schema6 = null; - this._serializer7 = context.GetSerializer(schema6); - MsgPack.Serialization.PolymorphismSchema schema7 = default(MsgPack.Serialization.PolymorphismSchema); - schema7 = null; - this._serializer8 = context.GetSerializer(schema7); - MsgPack.Serialization.PolymorphismSchema schema8 = default(MsgPack.Serialization.PolymorphismSchema); - schema8 = null; - this._serializer9 = context.GetSerializer(schema8); - MsgPack.Serialization.PolymorphismSchema schema9 = default(MsgPack.Serialization.PolymorphismSchema); - schema9 = null; - this._serializer10 = context.GetSerializer>(schema9); - MsgPack.Serialization.PolymorphismSchema schema10 = default(MsgPack.Serialization.PolymorphismSchema); - schema10 = null; - this._serializer11 = context.GetSerializer>(schema10); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Types.ProtocolMessage objectTree) - { - var nonNullFields = new bool [] - { - objectTree.Channel.IsNotEmpty(), - objectTree.ChannelSerial.IsNotEmpty(), - objectTree.ConnectionDetails != null, - objectTree.ConnectionId.IsNotEmpty(), - objectTree.ConnectionSerial != null, - objectTree.Count != null, - objectTree.Error != null, - objectTree.Flags != null, - objectTree.Id.IsNotEmpty(), - objectTree.Timestamp != null, - objectTree.Messages != null && objectTree.Messages.Any(x => x.IsEmpty == false), - objectTree.Presence != null && objectTree.Presence.Any() - }.Count(x => x) + 2; //One for MsgSerial and one for Action as this is always serialised - - packer.PackMapHeader(nonNullFields); - this._serializer0.PackTo(packer, "action"); - this._serializer1.PackTo(packer, objectTree.Action); - if (objectTree.Channel.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "channel"); - this._serializer0.PackTo(packer, objectTree.Channel); - } - if (objectTree.ChannelSerial.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "channelSerial"); - this._serializer0.PackTo(packer, objectTree.ChannelSerial); - } - if (objectTree.ConnectionDetails != null) - { - this._serializer0.PackTo(packer, "connectionDetails"); - this._serializer2.PackTo(packer, objectTree.ConnectionDetails); - } - if (objectTree.ConnectionId.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "connectionId"); - this._serializer0.PackTo(packer, objectTree.ConnectionId); - } - if (objectTree.ConnectionSerial != null) - { - this._serializer0.PackTo(packer, "connectionSerial"); - this._serializer3.PackTo(packer, objectTree.ConnectionSerial); - } - if (objectTree.Count != null) - { - this._serializer0.PackTo(packer, "count"); - this._serializer4.PackTo(packer, objectTree.Count); - } - if (objectTree.Error != null) - { - this._serializer0.PackTo(packer, "error"); - this._serializer5.PackTo(packer, objectTree.Error); - } - if (objectTree.Flags != null) - { - this._serializer0.PackTo(packer, "flags"); - this._serializer6.PackTo(packer, objectTree.Flags); - } - if (objectTree.Id.IsNotEmpty()) - { - this._serializer0.PackTo(packer, "id"); - this._serializer0.PackTo(packer, objectTree.Id); - } - this._serializer0.PackTo(packer, "msgSerial"); - this._serializer8.PackTo(packer, objectTree.MsgSerial); - if (objectTree.Messages != null && objectTree.Messages.Any(x => x.IsEmpty == false)) - { - this._serializer0.PackTo(packer, "messages"); - this._serializer7.PackTo(packer, objectTree.Messages.Where(x => x.IsEmpty == false).ToArray()); - } - if (objectTree.Presence != null && objectTree.Presence.Any()) - { - this._serializer0.PackTo(packer, "presence"); - this._serializer9.PackTo(packer, objectTree.Presence); - } - if (objectTree.Timestamp != null) - { - this._serializer0.PackTo(packer, "timestamp"); - this._serializer10.PackTo(packer, objectTree.Timestamp); - } - } - - protected override IO.Ably.Types.ProtocolMessage UnpackFromCore(MsgPack.Unpacker unpacker) - { - IO.Ably.Types.ProtocolMessage result = default(IO.Ably.Types.ProtocolMessage); - result = new IO.Ably.Types.ProtocolMessage(); - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) - { - string key = default(string); - string nullable14 = default(string); - nullable14 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Types.ProtocolMessage), "MemberName"); - if (((nullable14 == null) - == false)) - { - key = nullable14; - } - else - { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "timestamp")) - { - System.Nullable nullable29 = default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable29 = this._serializer10.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable12 = default(MsgPack.Unpacker); - disposable12 = unpacker.ReadSubtree(); - try - { - nullable29 = this._serializer10.UnpackFrom(disposable12); - } - finally - { - if (((disposable12 == null) - == false)) - { - disposable12.Dispose(); - } - } - } - if (nullable29.HasValue) - { - result.Timestamp = nullable29; - } - } - else - { - if ((key == "presence")) - { - IO.Ably.PresenceMessage[] nullable28 = default(IO.Ably.PresenceMessage[]); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable28 = this._serializer9.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable11 = default(MsgPack.Unpacker); - disposable11 = unpacker.ReadSubtree(); - try - { - nullable28 = this._serializer9.UnpackFrom(disposable11); - } - finally - { - if (((disposable11 == null) - == false)) - { - disposable11.Dispose(); - } - } - } - if (((nullable28 == null) - == false)) - { - result.Presence = nullable28; - } - } - else - { - if ((key == "msgSerial")) - { - System.Nullable nullable27 = default(System.Nullable); - nullable27 = MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value(unpacker, - typeof(IO.Ably.Types.ProtocolMessage), "Int64 msgSerial"); - if (nullable27.HasValue) - { - result.MsgSerial = nullable27.Value; - } - } - else - { - if ((key == "messages")) - { - IO.Ably.Message[] nullable26 = default(IO.Ably.Message[]); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable26 = this._serializer7.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable10 = default(MsgPack.Unpacker); - disposable10 = unpacker.ReadSubtree(); - try - { - nullable26 = this._serializer7.UnpackFrom(disposable10); - } - finally - { - if (((disposable10 == null) - == false)) - { - disposable10.Dispose(); - } - } - } - if (((nullable26 == null) - == false)) - { - result.Messages = nullable26; - } - } - else - { - if ((key == "id")) - { - string nullable25 = default(string); - nullable25 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, - typeof(IO.Ably.Types.ProtocolMessage), "System.String id"); - if (((nullable25 == null) - == false)) - { - result.Id = nullable25; - } - } - else - { - if ((key == "flags")) - { - System.Nullable nullable24 = - default(System.Nullable); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable24 = this._serializer6.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable9 = default(MsgPack.Unpacker); - disposable9 = unpacker.ReadSubtree(); - try - { - nullable24 = this._serializer6.UnpackFrom(disposable9); - } - finally - { - if (((disposable9 == null) - == false)) - { - disposable9.Dispose(); - } - } - } - if (nullable24.HasValue) - { - result.Flags = nullable24; - } - } - else - { - if ((key == "error")) - { - IO.Ably.ErrorInfo nullable23 = default(IO.Ably.ErrorInfo); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable23 = this._serializer5.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable8 = default(MsgPack.Unpacker); - disposable8 = unpacker.ReadSubtree(); - try - { - nullable23 = this._serializer5.UnpackFrom(disposable8); - } - finally - { - if (((disposable8 == null) - == false)) - { - disposable8.Dispose(); - } - } - } - if (((nullable23 == null) - == false)) - { - result.Error = nullable23; - } - } - else - { - if ((key == "count")) - { - System.Nullable nullable22 = default(System.Nullable); - nullable22 = - MsgPack.Serialization.UnpackHelpers.UnpackNullableInt32Value( - unpacker, typeof(IO.Ably.Types.ProtocolMessage), - "System.Nullable`1[System.Int32] count"); - if (nullable22.HasValue) - { - result.Count = nullable22; - } - } - else - { - if ((key == "connectionSerial")) - { - System.Nullable nullable21 = default(System.Nullable); - nullable21 = - MsgPack.Serialization.UnpackHelpers.UnpackNullableInt64Value( - unpacker, typeof(IO.Ably.Types.ProtocolMessage), - "System.Nullable`1[System.Int64] connectionSerial"); - if (nullable21.HasValue) - { - result.ConnectionSerial = nullable21; - } - } - else - { - if ((key == "connectionId")) - { - string nullable19 = default(string); - nullable19 = - MsgPack.Serialization.UnpackHelpers.UnpackStringValue( - unpacker, typeof(IO.Ably.Types.ProtocolMessage), - "System.String connectionId"); - if (((nullable19 == null) - == false)) - { - result.ConnectionId = nullable19; - } - } - else - { - if ((key == "connectionDetails")) - { - IO.Ably.ConnectionDetails nullable18 = - default(IO.Ably.ConnectionDetails); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization.SerializationExceptions - .NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable18 = this._serializer2.UnpackFrom(unpacker); - } - else - { - MsgPack.Unpacker disposable7 = - default(MsgPack.Unpacker); - disposable7 = unpacker.ReadSubtree(); - try - { - nullable18 = - this._serializer2.UnpackFrom(disposable7); - } - finally - { - if (((disposable7 == null) - == false)) - { - disposable7.Dispose(); - } - } - } - if (((nullable18 == null) - == false)) - { - result.ConnectionDetails = nullable18; - } - } - else - { - if ((key == "channelSerial")) - { - string nullable17 = default(string); - nullable17 = - MsgPack.Serialization.UnpackHelpers - .UnpackStringValue(unpacker, - typeof(IO.Ably.Types.ProtocolMessage), - "System.String channelSerial"); - if (((nullable17 == null) - == false)) - { - result.ChannelSerial = nullable17; - } - } - else - { - if ((key == "channel")) - { - string nullable16 = default(string); - nullable16 = - MsgPack.Serialization.UnpackHelpers - .UnpackStringValue(unpacker, - typeof(IO.Ably.Types.ProtocolMessage - ), "System.String channel"); - if (((nullable16 == null) - == false)) - { - result.Channel = nullable16; - } - } - else - { - if ((key == "action")) - { - System.Nullable - < - IO.Ably.Types.ProtocolMessage. - MessageAction> nullable15 = - default( - System.Nullable - < - IO.Ably.Types. - ProtocolMessage - . - MessageAction - >); - if ((unpacker.Read() == false)) - { - throw MsgPack.Serialization - .SerializationExceptions - .NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) - { - nullable15 = - this._serializer11.UnpackFrom( - unpacker); - } - else - { - MsgPack.Unpacker disposable6 = - default(MsgPack.Unpacker); - disposable6 = unpacker.ReadSubtree(); - try - { - nullable15 = - this._serializer11.UnpackFrom( - disposable6); - } - finally - { - if (((disposable6 == null) - == false)) - { - disposable6.Dispose(); - } - } - } - if (nullable15.HasValue) - { - result.Action = nullable15.Value; - } - } - else - { - unpacker.Skip(); - } - } - } - } - } - - } - } - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -} -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member \ No newline at end of file diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessage_MessageActionSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessage_MessageActionSerializer.cs deleted file mode 100644 index f51db9f80..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/IO_Ably_Types_ProtocolMessage_MessageActionSerializer.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_Types_ProtocolMessage_MessageActionSerializer : MsgPack.Serialization.EnumMessagePackSerializer { - - public IO_Ably_Types_ProtocolMessage_MessageActionSerializer(MsgPack.Serialization.SerializationContext context) : - this(context, MsgPack.Serialization.EnumSerializationMethod.ByUnderlyingValue) { - } - - public IO_Ably_Types_ProtocolMessage_MessageActionSerializer(MsgPack.Serialization.SerializationContext context, MsgPack.Serialization.EnumSerializationMethod enumSerializationMethod) : - base(context, enumSerializationMethod) { - } - - protected override void PackUnderlyingValueTo(MsgPack.Packer packer, IO.Ably.Types.ProtocolMessage.MessageAction enumValue) { - packer.Pack(((int)(enumValue))); - } - - protected override IO.Ably.Types.ProtocolMessage.MessageAction UnpackFromUnderlyingValue(MsgPack.MessagePackObject messagePackObject) { - return ((IO.Ably.Types.ProtocolMessage.MessageAction)(messagePackObject.AsInt32())); - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/System_Net_HttpStatusCodeSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/System_Net_HttpStatusCodeSerializer.cs deleted file mode 100644 index 78f5cbe98..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/GeneratedSerializers/System_Net_HttpStatusCodeSerializer.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - -#pragma warning disable SA1600 // Elements should be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class System_Net_HttpStatusCodeSerializer : MsgPack.Serialization.EnumMessagePackSerializer { - - public System_Net_HttpStatusCodeSerializer(MsgPack.Serialization.SerializationContext context) : - this(context, MsgPack.Serialization.EnumSerializationMethod.ByName) { - } - - public System_Net_HttpStatusCodeSerializer(MsgPack.Serialization.SerializationContext context, MsgPack.Serialization.EnumSerializationMethod enumSerializationMethod) : - base(context, enumSerializationMethod) { - } - - protected override void PackUnderlyingValueTo(MsgPack.Packer packer, System.Net.HttpStatusCode enumValue) { - packer.Pack(((int)(enumValue))); - } - - protected override System.Net.HttpStatusCode UnpackFromUnderlyingValue(MsgPack.MessagePackObject messagePackObject) { - return ((System.Net.HttpStatusCode)(messagePackObject.AsInt32())); - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs b/src/IO.Ably.Shared.MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs deleted file mode 100644 index 708e4c1d8..000000000 --- a/src/IO.Ably.Shared.MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using MsgPack; -using MsgPack.Serialization; - -namespace IO.Ably.CustomSerialisers -{ -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member -#pragma warning disable SA1600 // Elements should be documented - public class TimespanMessagePackSerializer : MessagePackSerializer - { - public TimespanMessagePackSerializer(SerializationContext ownerContext) - : base(ownerContext) { } - - protected override void PackToCore(Packer packer, TimeSpan objectTree) - { - packer.Pack((long)objectTree.TotalMilliseconds); - } - - protected override TimeSpan UnpackFromCore(Unpacker unpacker) - { - var data = unpacker.LastReadData; - return TimeSpan.FromMilliseconds(data.AsInt64()); - } - } -#pragma warning restore SA1600 // Elements should be documented -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} diff --git a/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.projitems b/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.projitems deleted file mode 100644 index 1512baca9..000000000 --- a/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.projitems +++ /dev/null @@ -1,36 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - eebf3249-3ca3-4078-a188-f8b916c3f4c2 - - - IO.Ably.Shared.MsgPack - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.shproj b/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.shproj deleted file mode 100644 index 274ffd8cf..000000000 --- a/src/IO.Ably.Shared.MsgPack/IO.Ably.Shared.MsgPack.shproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - eebf3249-3ca3-4078-a188-f8b916c3f4c2 - 14.0 - - - - - - - - diff --git a/src/IO.Ably.Shared.MsgPack/MsgPackHelper.cs b/src/IO.Ably.Shared.MsgPack/MsgPackHelper.cs deleted file mode 100644 index 3b18a34a6..000000000 --- a/src/IO.Ably.Shared.MsgPack/MsgPackHelper.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.IO; -using IO.Ably.CustomSerialisers; -using MsgPack; -using MsgPack.Serialization; - -namespace IO.Ably -{ - internal static class MsgPackHelper - { - private static readonly SerializationContext Context; - - static MsgPackHelper() - { - Context = GetContext(); - } - - private static SerializationContext GetContext() - { - var context = new SerializationContext() { SerializationMethod = SerializationMethod.Map }; - context.Serializers.Register(new DateTimeOffsetMessagePackSerializer(context)); - context.Serializers.Register(new TimespanMessagePackSerializer(context)); - context.Serializers.Register(new IO_Ably_CapabilitySerializer(context)); - context.Serializers.Register(new IO_Ably_TokenRequestSerializer(context)); - context.Serializers.Register(new IO_Ably_Auth_TokenDetailsSerializer(context)); - context.Serializers.Register(new IO_Ably_ConnectionDetailsMessageSerializer(context)); - context.Serializers.Register(new IO_Ably_ErrorInfoSerializer(context)); - context.Serializers.Register(new IO_Ably_MessageCountSerializer(context)); - context.Serializers.Register(new IO_Ably_MessageTypesSerializer(context)); - context.Serializers.Register(new IO_Ably_RequestCountSerializer(context)); - context.Serializers.Register(new IO_Ably_ResourceCountSerializer(context)); - context.Serializers.Register(new IO_Ably_ConnectionTypesSerializer(context)); - context.Serializers.Register(new IO_Ably_OutboundMessageTrafficSerializer(context)); - context.Serializers.Register(new IO_Ably_InboundMessageTrafficSerializer(context)); - context.Serializers.Register(new IO_Ably_MessageSerializer(context)); - context.Serializers.Register(new IO_Ably_PresenceMessageSerializer(context)); - context.Serializers.Register(new IO_Ably_PresenceMessage_ActionTypeSerializer(context)); - context.Serializers.Register(new IO_Ably_StatsSerializer(context)); - context.Serializers.Register(new IO_Ably_Types_ProtocolMessageSerializer(context)); - context.Serializers.Register(new IO_Ably_Types_ProtocolMessage_MessageActionSerializer(context)); - context.Serializers.Register(new System_Net_HttpStatusCodeSerializer(context)); - - return context; - } - - public static byte[] Serialise(object obj) - { - var serialiser = Context.GetSerializer(obj.GetType()); - using (var ms = new MemoryStream()) - { - serialiser.Pack(ms, obj, PackerCompatibilityOptions.None); - return ms.ToArray(); - } - } - - public static object Deserialise(byte[] byteArray, Type objectType) - { - if (byteArray == null || byteArray.Length == 0) - { - return null; - } - - using (var ms = new MemoryStream(byteArray)) - { - var serialiser = Context.GetSerializer(objectType); - return serialiser.Unpack(ms); - } - } - - public static object DeserialiseMsgPackObject(byte[] byteArray) - { - return Deserialise(byteArray, typeof(MessagePackObject)); - } - - public static T Deserialise(byte[] byteArray) - { - return (T)Deserialise(byteArray, typeof(T)); - } - } -} diff --git a/src/IO.Ably.Shared/AblyAuth.cs b/src/IO.Ably.Shared/AblyAuth.cs index 67cbbc7b3..277e22167 100644 --- a/src/IO.Ably.Shared/AblyAuth.cs +++ b/src/IO.Ably.Shared/AblyAuth.cs @@ -483,11 +483,7 @@ private static TokenRequest GetTokenRequest(object callbackResult) private async Task CallAuthUrl(AuthOptions mergedOptions, TokenParams @params) { var url = mergedOptions.AuthUrl; -#if MSGPACK - var protocol = Options.UseBinaryProtocol == false ? Protocol.Json : Protocol.MsgPack; -#else - var protocol = Defaults.Protocol; -#endif + var protocol = Options.UseBinaryProtocol ? Protocol.MsgPack : Protocol.Json; var authRequest = new AblyRequest(url.ToString(), mergedOptions.AuthMethod, protocol); if (mergedOptions.AuthMethod == HttpMethod.Get) diff --git a/src/IO.Ably.Shared/AblyRest.cs b/src/IO.Ably.Shared/AblyRest.cs index 8abb88d48..698ca89ad 100644 --- a/src/IO.Ably.Shared/AblyRest.cs +++ b/src/IO.Ably.Shared/AblyRest.cs @@ -115,7 +115,7 @@ public LocalDevice Device internal set => _device = value; // The setting is only for testing purposes } - internal Protocol Protocol => Options.UseBinaryProtocol == false ? Protocol.Json : Defaults.Protocol; + internal Protocol Protocol => Options.UseBinaryProtocol ? Protocol.MsgPack : Protocol.Json; internal ClientOptions Options { get; } @@ -452,7 +452,7 @@ public async Task CanConnectToAbly() try { // We don't want to retry the internet check url. - var request = new AblyRequest(Defaults.InternetCheckUrl, HttpMethod.Get) { SkipRetry = true }; + var request = new AblyRequest(Defaults.InternetCheckUrl, HttpMethod.Get, Protocol) { SkipRetry = true }; var response = await ExecuteHttpRequest(request).TimeoutAfter(Defaults.MaxHttpOpenTimeout, AblyResponse.EmptyResponse); var success = response.TextResponse.SafeTrim().EqualsTo(Defaults.InternetCheckOkMessage); if (success == false) diff --git a/src/IO.Ably.Shared/ClientOptions.cs b/src/IO.Ably.Shared/ClientOptions.cs index ed3a546d5..9f9d56d38 100644 --- a/src/IO.Ably.Shared/ClientOptions.cs +++ b/src/IO.Ably.Shared/ClientOptions.cs @@ -15,9 +15,7 @@ public class ClientOptions : AuthOptions private string _realtimeHost; private string _restHost; private Func _nowFunc; -#if MSGPACK - private bool _useBinaryProtocol; -#endif + private bool _useBinaryProtocol = Defaults.MsgPackEnabled; // Default to true for better performance private string[] _fallbackHosts; /// @@ -257,23 +255,15 @@ public string[] GetFallbackHosts() public int TlsPort { get; set; } = Defaults.TlsPort; /// - /// If false, forces the library to use the JSON encoding for REST and Realtime operations, - /// If true, the MsgPack binary format is used (if available in the current build - /// Default: false. + /// If false, forces the library to use the JSON encoding for REST and Realtime operations. + /// If true, the MsgPack binary format is used for improved performance and reduced bandwidth usage. + /// Binary protocol typically results in 20-30% smaller message sizes and faster serialization. + /// Default: true. /// public bool UseBinaryProtocol { -#if MSGPACK get { return _useBinaryProtocol; } -#else - get { return false; } -#endif - -#if MSGPACK set { _useBinaryProtocol = value; } -#else - set { _ = value; } -#endif } /// diff --git a/src/IO.Ably.Shared/CustomSerialisers/MessageDataConverter.cs b/src/IO.Ably.Shared/CustomSerialisers/MessageDataConverter.cs index e20f7c9a7..a769b0c1b 100644 --- a/src/IO.Ably.Shared/CustomSerialisers/MessageDataConverter.cs +++ b/src/IO.Ably.Shared/CustomSerialisers/MessageDataConverter.cs @@ -1,7 +1,7 @@ using System; using Newtonsoft.Json; -namespace IO.Ably.Shared.CustomSerialisers +namespace IO.Ably.CustomSerialisers { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member #pragma warning disable SA1600 // Elements should be documented diff --git a/src/IO.Ably.Shared/DataRequestQuery.cs b/src/IO.Ably.Shared/DataRequestQuery.cs index 4b52bdba7..d4e48d8b7 100644 --- a/src/IO.Ably.Shared/DataRequestQuery.cs +++ b/src/IO.Ably.Shared/DataRequestQuery.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using System.Runtime.Serialization; +using MessagePack; namespace IO.Ably { diff --git a/src/IO.Ably.Shared/Defaults.cs b/src/IO.Ably.Shared/Defaults.cs index e0fbbc06a..a93b6b940 100644 --- a/src/IO.Ably.Shared/Defaults.cs +++ b/src/IO.Ably.Shared/Defaults.cs @@ -62,14 +62,8 @@ internal static Func NowFunc() return () => DateTimeOffset.UtcNow; } -#if MSGPACK - internal const Protocol DefaultProtocol = IO.Ably.Protocol.MsgPack; + // MsgPack encoding is enabled by default, value is set to ClientOptions.UseBinaryProtocol internal const bool MsgPackEnabled = true; -#else - internal const Protocol Protocol = IO.Ably.Protocol.Json; - internal const bool MsgPackEnabled = false; - -#endif static Defaults() { diff --git a/src/IO.Ably.Shared/Http/AblyHttpClient.cs b/src/IO.Ably.Shared/Http/AblyHttpClient.cs index c94f36658..a1faf7b83 100644 --- a/src/IO.Ably.Shared/Http/AblyHttpClient.cs +++ b/src/IO.Ably.Shared/Http/AblyHttpClient.cs @@ -317,13 +317,13 @@ private void LogResponse(AblyResponse ablyResponse, string url) logMessage.AppendLine($"Type: {ablyResponse.Type}"); logMessage.AppendLine("---- Response Body ----"); - if (ablyResponse.Type != ResponseType.Binary) + if (ablyResponse.Type == ResponseType.Binary) { - logMessage.AppendLine(ablyResponse.TextResponse); + logMessage.AppendLine(MsgPackHelper.DecodeMsgPackObject(ablyResponse.Body)); } - else if (ablyResponse.Body != null) + else { - logMessage.AppendLine(ablyResponse.Body.GetText()); + logMessage.AppendLine(ablyResponse.TextResponse); } Logger.Debug(logMessage.ToString()); @@ -392,13 +392,18 @@ private HttpRequestMessage GetRequestMessage(AblyRequest request, string host) message.Headers.TryAddWithoutValidation(header.Key, header.Value); } -#if MSGPACK - if(request.Protocol == Protocol.MsgPack) - message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(GetHeaderValue(request.Protocol))); -#endif + // Set Accept headers based on protocol preference + if (request.Protocol == Protocol.MsgPack) + { + // Prefer msgpack + message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(GetHeaderValue(Protocol.MsgPack))); + } + else + { + // Prefer JSON + message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(GetHeaderValue(Protocol.Json))); + } - // Always accept JSON - message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(GetHeaderValue(Protocol.Json))); if (message.Method == HttpMethod.Post || message.Method == HttpMethod.Put) { if (request.PostParameters.Any() && request.RequestBody.Length == 0) diff --git a/src/IO.Ably.Shared/Http/AblyRequest.cs b/src/IO.Ably.Shared/Http/AblyRequest.cs index a30216fe6..22e81faeb 100644 --- a/src/IO.Ably.Shared/Http/AblyRequest.cs +++ b/src/IO.Ably.Shared/Http/AblyRequest.cs @@ -8,7 +8,7 @@ internal class AblyRequest { private ChannelOptions _channelOptions; - public AblyRequest(string path, HttpMethod method, Protocol protocol = Defaults.Protocol) + public AblyRequest(string path, HttpMethod method, Protocol protocol) { Url = path; QueryParameters = new Dictionary(); diff --git a/src/IO.Ably.Shared/HttpPaginatedResponse.cs b/src/IO.Ably.Shared/HttpPaginatedResponse.cs index 5f750e763..fa128b8be 100644 --- a/src/IO.Ably.Shared/HttpPaginatedResponse.cs +++ b/src/IO.Ably.Shared/HttpPaginatedResponse.cs @@ -76,9 +76,19 @@ internal HttpPaginatedResponse(AblyResponse response, int limit, PaginatedReques ExecuteDataQueryFunc = executeDataQueryFunc; - if (response.TextResponse.IsNotEmpty()) + string jsonData; + if (response.Type == ResponseType.Binary) { - var data = JToken.Parse(response.TextResponse); + jsonData = MsgPackHelper.ToJsonString(response.Body); + } + else + { + jsonData = response.TextResponse; + } + + if (jsonData.IsNotEmpty()) + { + var data = JToken.Parse(jsonData); if (data is JArray arr) { foreach (var token in arr) diff --git a/src/IO.Ably.Shared/IO.Ably.Shared.projitems b/src/IO.Ably.Shared/IO.Ably.Shared.projitems index 22326a497..a6023178b 100644 --- a/src/IO.Ably.Shared/IO.Ably.Shared.projitems +++ b/src/IO.Ably.Shared/IO.Ably.Shared.projitems @@ -28,6 +28,15 @@ + + + + + + + + + diff --git a/src/IO.Ably.Shared/MessageEncoders/MessageHandler.cs b/src/IO.Ably.Shared/MessageEncoders/MessageHandler.cs index cf86d5925..8e95bfdcc 100644 --- a/src/IO.Ably.Shared/MessageEncoders/MessageHandler.cs +++ b/src/IO.Ably.Shared/MessageEncoders/MessageHandler.cs @@ -20,36 +20,41 @@ internal class MessageHandler private readonly Protocol _protocol; - private static List DefaultEncoders { get; } = new List + internal static List AllEncoders { get; } = new List { new JsonEncoder(), new Utf8Encoder(), new CipherEncoder(), new VcDiffEncoder(), Base64Encoder, }; + internal List Encoders { get; } + private ILogger Logger { get; } public MessageHandler(ILogger logger, Protocol protocol) { Logger = logger; _protocol = protocol; + if (IsMsgPack()) + { + Encoders = AllEncoders.Where(encoder => encoder != Base64Encoder).ToList(); // No need for Base64Encoder for MsgPack + } + else + { + Encoders = AllEncoders; + } } private IEnumerable ParsePresenceMessages(AblyResponse response, DecodingContext context) { - if (response.Type != ResponseType.Json) + if (response.Type == ResponseType.Json) { - throw new AblyException( - $"Response of type '{response.Type}' is invalid because MsgPack support was not enabled for this build."); + var messages = JsonHelper.Deserialize>(response.TextResponse); + ProcessMessages(messages, context); + return messages; } - var messages = JsonHelper.Deserialize>(response.TextResponse); - ProcessMessages(messages, context); - return messages; - -#if MSGPACK var payloads = MsgPackHelper.Deserialise(response.Body, typeof(List)) as List; - ProcessMessages(payloads, options); + ProcessMessages(payloads, context); return payloads; -#endif } private IEnumerable ParseMessagesResponse(AblyResponse response, DecodingContext context) @@ -61,31 +66,40 @@ private IEnumerable ParseMessagesResponse(AblyResponse response, Decodi return messages; } -#if MSGPACK var payloads = MsgPackHelper.Deserialise(response.Body, typeof(List)) as List; - ProcessMessages(payloads, options); + ProcessMessages(payloads, context); return payloads; -#else - throw new AblyException($"Response of type '{response.Type}' is invalid because MsgPack support was not enabled for this build."); - -#endif } - private static void ProcessMessages(IEnumerable payloads, DecodingContext context) where T : IMessage + private void ProcessMessages(IEnumerable payloads, DecodingContext context) where T : IMessage { // TODO: What happens with rest request where we can't decode messages - _ = DecodePayloads(context, payloads as IEnumerable); + _ = DecodePayloads(context, payloads as IEnumerable, Encoders); } public void SetRequestBody(AblyRequest request) { request.RequestBody = GetRequestBody(request); -#if MSGPACK - if (_protocol == Protocol.MsgPack && Logger.IsDebug) + if (IsMsgPack() && Logger.IsDebug) { LogRequestBody(request.RequestBody); } -#endif + } + + private void LogRequestBody(byte[] requestBody) + { + if (Logger.IsDebug && requestBody != null) + { + try + { + var msgPackObject = MsgPackHelper.DecodeMsgPackObject(requestBody); + Logger.Debug("Request body (MsgPack): " + msgPackObject); + } + catch (Exception ex) + { + Logger.Error("Error logging request body", ex); + } + } } private byte[] GetRequestBody(AblyRequest request) @@ -102,19 +116,16 @@ private byte[] GetRequestBody(AblyRequest request) request.ChannelOptions); } -#if MSGPACK byte[] result; - if (_protocol == Protocol.Json || !Defaults.MsgPackEnabled) + if (IsMsgPack()) { - result = JsonHelper.Serialize(request.PostData).GetBytes(); + result = MsgPackHelper.Serialise(request.PostData); } else { - result = MsgPackHelper.Serialise(request.PostData); + result = JsonHelper.Serialize(request.PostData).GetBytes(); } -#else - byte[] result = JsonHelper.Serialize(request.PostData).GetBytes(); -#endif + if (Logger.IsDebug) { Logger.Debug("Request body: " + result.GetText()); @@ -126,31 +137,35 @@ private byte[] GetRequestBody(AblyRequest request) private byte[] GetMessagesRequestBody(IEnumerable payloads, ChannelOptions options) { EncodePayloads(new DecodingContext(options), payloads); -#if MSGPACK - if (_protocol == Protocol.MsgPack) + byte[] result; + if (IsMsgPack()) { - return MsgPackHelper.Serialise(payloads); + result = MsgPackHelper.Serialise(payloads); } -#endif - return JsonHelper.Serialize(payloads).GetBytes(); + else + { + result = JsonHelper.Serialize(payloads).GetBytes(); + } + + return result; } - internal static Result EncodePayloads(DecodingContext context, IEnumerable payloads) + internal Result EncodePayloads(DecodingContext context, IEnumerable payloads) { var result = Result.Ok(); foreach (var payload in payloads) { - result = Result.Combine(result, EncodePayload(payload, context)); + result = Result.Combine(result, EncodePayload(payload, context, Encoders)); } return result; } - internal static Result EncodePayload(IMessage payload, DecodingContext context, IEnumerable encoders = null) + internal Result EncodePayload(IMessage payload, DecodingContext context, IEnumerable encoders) { ValidatePayloadDataType(payload); var result = Result.Ok(); - foreach (var encoder in encoders ?? DefaultEncoders) + foreach (var encoder in encoders) { var encodeResult = encoder.Encode(payload, context); if (encodeResult.IsSuccess) @@ -197,7 +212,7 @@ Type GetNullableType(Type type) internal static Result DecodePayload(IMessage payload, DecodingContext context, IEnumerable encoders = null, ILogger logger = null) { - var actualEncoders = (encoders ?? DefaultEncoders).ToList(); + var actualEncoders = (encoders ?? AllEncoders).ToList(); var pp = context.PreviousPayload; // We take a chance that this will not be modified but replaced var (processResult, decodedPayload) = Decode(); @@ -309,7 +324,7 @@ public PaginatedResult ParsePaginatedResponse(AblyRequest request, AblyRes } else { - result?.Items.AddRange(ParseOther(response)); + result?.Items.AddRange(ParseOther(response, _protocol)); } return result; @@ -325,22 +340,20 @@ public T ParseResponse(AblyRequest request, AblyResponse response) where T : { LogResponse(response); - var responseText = response.TextResponse; -#if MSGPACK - if (_protocol == Protocol.MsgPack) + if (IsMsgPack()) { return (T)MsgPackHelper.Deserialise(response.Body, typeof(T)); } -#endif - return JsonHelper.Deserialize(responseText); + + return JsonHelper.Deserialize(response.TextResponse); } - private static Result DecodePayloads(DecodingContext context, IEnumerable payloads, IEnumerable encoders = null) + private Result DecodePayloads(DecodingContext context, IEnumerable payloads, IEnumerable encoders) { var result = Result.Ok(); foreach (var payload in payloads) { - result = Result.Combine(result, DecodePayload(payload, context, encoders)); + result = Result.Combine(result, DecodePayload(payload, context, encoders, Logger)); } return result; @@ -360,12 +373,11 @@ private void LogResponse(AblyResponse response) try { var responseBody = response.TextResponse; -#if MSGPACK - if (_protocol == Protocol.MsgPack && response.Body != null) + if (IsMsgPack() && response.Body != null) { - responseBody = MsgPackHelper.DeserialiseMsgPackObject(response.Body).ToString(); + responseBody = MsgPackHelper.DecodeMsgPackObject(response.Body); } -#endif + Logger.Debug($"Response: {responseBody}"); } catch (Exception ex) @@ -375,15 +387,14 @@ private void LogResponse(AblyResponse response) } } - private static IEnumerable ParseOther(AblyResponse response) + private static IEnumerable ParseOther(AblyResponse response, Protocol protocol) { var body = response.TextResponse; -#if MSGPACK - if (_protocol == Protocol.MsgPack) + if (protocol == Protocol.MsgPack) { - return (List)MsgPackHelper.Deserialise(response.Body, typeof(List)); + return (List)MsgPackHelper.Deserialise(response.Body, typeof(List)); } -#endif + return JsonHelper.Deserialize>(body) ?? new List(); } @@ -405,15 +416,11 @@ public ProtocolMessage ParseRealtimeData(RealtimeTransportData data) { ProtocolMessage protocolMessage; -#if MSGPACK - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - if (IsMsgPack() && Defaults.MsgPackEnabled) + if (IsMsgPack()) { - - protocolMessage = (ProtocolMessage) MsgPackHelper.Deserialise(data.Data, typeof(ProtocolMessage)); + protocolMessage = (ProtocolMessage)MsgPackHelper.Deserialise(data.Data, typeof(ProtocolMessage)); } else -#endif { protocolMessage = JsonHelper.Deserialize(data.Text); } @@ -469,7 +476,7 @@ public Result DecodeMessages( foreach (var message in messages ?? Enumerable.Empty()) { SetMessageIdConnectionIdAndTimestamp(message, index); - var decodeResult = DecodePayload(message, context, DefaultEncoders) + var decodeResult = DecodePayload(message, context, Encoders, Logger) .IfFailure(error => Logger.Warning($"Error decoding message with id: {message.Id}. Error: {error.Message}. Exception: {error.InnerException?.Message}")); result = Result.Combine(result, decodeResult); @@ -507,15 +514,12 @@ public RealtimeTransportData GetTransportData(ProtocolMessage protocolMessage) { RealtimeTransportData data; -#if MSGPACK - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - if (IsMsgPack() && Defaults.MsgPackEnabled) + if (IsMsgPack()) { var bytes = MsgPackHelper.Serialise(protocolMessage); - data = new RealtimeTransportData(bytes) {Original = protocolMessage}; + data = new RealtimeTransportData(bytes) { Original = protocolMessage }; } else -#endif { var text = JsonHelper.Serialize(protocolMessage); data = new RealtimeTransportData(text) { Original = protocolMessage }; @@ -524,18 +528,16 @@ public RealtimeTransportData GetTransportData(ProtocolMessage protocolMessage) return data; } -#if MSGPACK private bool IsMsgPack() { return _protocol == Protocol.MsgPack; } -#endif internal static T FromEncoded(T encoded, ChannelOptions options = null) where T : IMessage { var context = options.ToDecodingContext(); - var result = DecodePayload(encoded, context, logger: DefaultLogger.LoggerInstance); + var result = DecodePayload(encoded, context, AllEncoders, DefaultLogger.LoggerInstance); if (result.IsFailure) { throw new AblyException(result.Error); @@ -550,7 +552,7 @@ internal static T[] FromEncodedArray(T[] encodedArray, ChannelOptions options var context = options.ToDecodingContext(); foreach (var encoded in encodedArray) { - DecodePayload(encoded, context, logger: DefaultLogger.LoggerInstance); + DecodePayload(encoded, context, AllEncoders, DefaultLogger.LoggerInstance); } return encodedArray; diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyGeneratedResolver.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyGeneratedResolver.cs new file mode 100644 index 000000000..1ce719227 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyGeneratedResolver.cs @@ -0,0 +1,9 @@ +using MessagePack; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ + [GeneratedMessagePackResolver] + internal partial class AblyGeneratedResolver + { + } +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyResolver.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyResolver.cs new file mode 100644 index 000000000..bf7d2fdf2 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/AblyResolver.cs @@ -0,0 +1,86 @@ +using System; +using MessagePack; +using MessagePack.Formatters; +using Newtonsoft.Json.Linq; +using IO.Ably.Types; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ +#pragma warning disable SA1600 // Elements should be documented +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + + /// + /// Custom resolver for Ably-specific types that require special serialization handling. + /// + public class AblyResolver : IFormatterResolver + { + public static readonly AblyResolver Instance = new AblyResolver(); + + private AblyResolver() + { + } + + public IMessagePackFormatter GetFormatter() + { + return FormatterCache.Formatter; + } + + private static class FormatterCache + { + public static readonly IMessagePackFormatter Formatter; + + static FormatterCache() + { + Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); + } + + private static object GetFormatterHelper(Type t) + { + if (t == typeof(DateTimeOffset)) + { + return new DateTimeOffsetFormatter(); + } + + if (t == typeof(DateTimeOffset?)) + { + return new MessagePack.Formatters.NullableFormatter(); + } + + if (t == typeof(TimeSpan)) + { + return new TimespanFormatter(); + } + + if (t == typeof(TimeSpan?)) + { + return new MessagePack.Formatters.NullableFormatter(); + } + + if (t == typeof(Capability)) + { + return new CapabilityFormatter(); + } + + if (t == typeof(MessageExtras)) + { + return new MessageExtrasFormatter(); + } + + if (t == typeof(ChannelParams)) + { + return new ChannelParamsFormatter(); + } + + if (t == typeof(JObject)) + { + return new JObjectMessagePackSerializer(); + } + + return null; + } + } + } + +#pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs new file mode 100644 index 000000000..71e8b0204 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/CapabilityMessagePackSerializer.cs @@ -0,0 +1,36 @@ +using MessagePack; +using MessagePack.Formatters; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ +#pragma warning disable SA1600 // Elements should be documented +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public class CapabilityFormatter : IMessagePackFormatter + { + /// + public void Serialize(ref MessagePackWriter writer, Capability value, MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + writer.Write(value.ToJson()); + } + + /// + public Capability Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return new Capability(); + } + + var json = reader.ReadString(); + return new Capability(json); + } + } +#pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/ChannelParamsFormatter.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/ChannelParamsFormatter.cs new file mode 100644 index 000000000..03a73efb7 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/ChannelParamsFormatter.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using MessagePack; +using MessagePack.Formatters; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ + /// + /// Custom formatter for ChannelParams that serializes it as a dictionary. + /// + public class ChannelParamsFormatter : IMessagePackFormatter + { + /// + public void Serialize(ref MessagePackWriter writer, ChannelParams value, MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + writer.WriteMapHeader(value.Count); + foreach (var kvp in value) + { + writer.Write(kvp.Key); + writer.Write(kvp.Value); + } + } + + /// + public ChannelParams Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + var count = reader.ReadMapHeader(); + var result = new ChannelParams(); + + for (int i = 0; i < count; i++) + { + var key = reader.ReadString(); + var value = reader.ReadString(); + result[key] = value; + } + + return result; + } + } +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs new file mode 100644 index 000000000..03a9824b3 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/DateTimeOffsetMessagePackSerializer.cs @@ -0,0 +1,52 @@ +using System; +using MessagePack; +using MessagePack.Formatters; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ +#pragma warning disable SA1600 // Elements should be documented +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public class DateTimeOffsetFormatter : IMessagePackFormatter + { + /// + public void Serialize(ref MessagePackWriter writer, DateTimeOffset value, MessagePackSerializerOptions options) + { + writer.Write(value.ToUnixTimeInMilliseconds()); + } + + /// + public DateTimeOffset Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + var nextType = reader.NextMessagePackType; + + // Handle integer types (Int64, Int32, etc.) + if (nextType == MessagePackType.Integer) + { + var milliseconds = reader.ReadInt64(); + return milliseconds.FromUnixTimeInMilliseconds(); + } + + // Handle float types (Single, Double) + if (nextType == MessagePackType.Float) + { + var milliseconds = reader.ReadDouble(); + return ((long)milliseconds).FromUnixTimeInMilliseconds(); + } + + // Handle string type (parse DateTimeOffset string representation) + if (nextType == MessagePackType.String) + { + var value = reader.ReadString(); + if (DateTimeOffset.TryParse(value, out var result)) + { + return result; + } + } + + // Return MinValue if unable to parse + return DateTimeOffset.MinValue; + } + } +#pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/JObjectMessagePackSerializer.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/JObjectMessagePackSerializer.cs new file mode 100644 index 000000000..448c881d8 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/JObjectMessagePackSerializer.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Text; +using MessagePack; +using MessagePack.Formatters; +using Newtonsoft.Json.Linq; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ + internal class JObjectMessagePackSerializer : IMessagePackFormatter + { + void IMessagePackFormatter.Serialize(ref MessagePackWriter writer, JObject value, MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + var bytes = MessagePackSerializer.ConvertFromJson(value.ToJson()); + writer.WriteRaw(bytes); + } + + JObject IMessagePackFormatter.Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + // Check if there's any data left to read from the current position + var remainingSequence = reader.Sequence.Slice(reader.Position); + if (remainingSequence.Length == 0) + { + return null; + } + + if (reader.TryReadNil()) + { + return null; + } + + var bytes = reader.ReadRaw(); + if (bytes.Length == 0) + { + return null; + } + + var jsonString = MessagePackSerializer.ConvertToJson(bytes); + if (jsonString.IsEmpty()) + { + return null; + } + + return JObject.Parse(jsonString); + } + } +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/MessageExtrasMessagePackSerializer.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/MessageExtrasMessagePackSerializer.cs new file mode 100644 index 000000000..fccc6c5e3 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/MessageExtrasMessagePackSerializer.cs @@ -0,0 +1,59 @@ +using IO.Ably.Types; +using MessagePack; +using MessagePack.Formatters; +using Newtonsoft.Json.Linq; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ +#pragma warning disable SA1600 // Elements should be documented +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public class MessageExtrasFormatter : IMessagePackFormatter + { + /// + public void Serialize(ref MessagePackWriter writer, MessageExtras value, MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + var jToken = value.ToJson(); + if (jToken == null) + { + writer.WriteNil(); + } + else + { + var bytes = MessagePackSerializer.ConvertFromJson(jToken.ToString()); + writer.WriteRaw(bytes); + } + } + + /// + public MessageExtras Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + var bytes = reader.ReadRaw(); + if (bytes.Length == 0) + { + return null; + } + + var jsonString = MessagePackSerializer.ConvertToJson(bytes); + if (jsonString.IsEmpty()) + { + return null; + } + + var jToken = JToken.Parse(jsonString); + return MessageExtras.From(jToken); + } + } +#pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/src/IO.Ably.Shared/MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs new file mode 100644 index 000000000..96bd5b4e5 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/CustomSerialisers/TimespanMessagePackSerializer.cs @@ -0,0 +1,52 @@ +using System; +using MessagePack; +using MessagePack.Formatters; + +namespace IO.Ably.MsgPack.CustomSerialisers +{ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable SA1600 // Elements should be documented + public class TimespanFormatter : IMessagePackFormatter + { + /// + public void Serialize(ref MessagePackWriter writer, TimeSpan value, MessagePackSerializerOptions options) + { + writer.Write((long)value.TotalMilliseconds); + } + + /// + public TimeSpan Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + var nextType = reader.NextMessagePackType; + + // Handle integer types (Int64, Int32, etc.) + if (nextType == MessagePackType.Integer) + { + var milliseconds = reader.ReadInt64(); + return TimeSpan.FromMilliseconds(milliseconds); + } + + // Handle float types (Single, Double) + if (nextType == MessagePackType.Float) + { + var milliseconds = reader.ReadDouble(); + return TimeSpan.FromMilliseconds(milliseconds); + } + + // Handle string type (parse TimeSpan string representation) + if (nextType == MessagePackType.String) + { + var value = reader.ReadString(); + if (TimeSpan.TryParse(value, out var result)) + { + return result; + } + } + + // Return null TimeSpan if unable to parse + return TimeSpan.MinValue; + } + } +#pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/src/IO.Ably.Shared/MsgPack/MsgPackHelper.cs b/src/IO.Ably.Shared/MsgPack/MsgPackHelper.cs new file mode 100644 index 000000000..198609133 --- /dev/null +++ b/src/IO.Ably.Shared/MsgPack/MsgPackHelper.cs @@ -0,0 +1,99 @@ +using System; +using System.Text; +using IO.Ably.CustomSerialisers; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using MessagePack; +using MessagePack.Resolvers; +using IO.Ably.MsgPack.CustomSerialisers; + +namespace IO.Ably +{ + internal static class MsgPackHelper + { + private static readonly MessagePackSerializerOptions Options = + MessagePackSerializerOptions.Standard + .WithResolver(CompositeResolver.Create( + AblyResolver.Instance, + AblyGeneratedResolver.Instance, + StandardResolver.Instance)); + + public static byte[] Serialise(object obj) + { + if (obj == null) + { + return null; + } + + if (obj is JToken value) + { + return MessagePackSerializer.ConvertFromJson(value.ToString()); + } + + return MessagePackSerializer.Serialize(obj.GetType(), obj, Options); + } + + public static object Deserialise(byte[] byteArray, Type objectType) + { + if (byteArray == null || byteArray.Length == 0) + { + return null; + } + + // Checks if given type is subset of JToken + if (typeof(JToken).IsAssignableFrom(objectType)) + { + return JToken.Parse(ToJsonString(byteArray)); + } + + return MessagePackSerializer.Deserialize(objectType, byteArray, Options); + } + + public static T Deserialise(byte[] byteArray) + { + if (byteArray == null || byteArray.Length == 0) + { + return default(T); + } + + return MessagePackSerializer.Deserialize(byteArray, Options); + } + + // This uses MessagePack's built-in JSON conversion which handles all MessagePack types + public static string ToJsonString(byte[] byteArray) + { + if (byteArray == null || byteArray.Length == 0) + { + return null; + } + + return MessagePackSerializer.ConvertToJson(byteArray, Options); + } + + public static string DecodeMsgPackObject(byte[] byteArray) + { + if (byteArray == null || byteArray.Length == 0) + { + return string.Empty; + } + + try + { + // Convert MessagePack binary data to JSON string for pretty printing + return JToken.Parse(ToJsonString(byteArray)).ToString(Formatting.Indented); + } + catch (Exception) + { + // Last resort: return hex representation for debugging + var sb = new StringBuilder(byteArray.Length * 2); + sb.Append("0x"); + foreach (byte b in byteArray) + { + sb.AppendFormat("{0:x2}", b); + } + + return sb.ToString(); + } + } + } +} diff --git a/src/IO.Ably.Shared/Protocol.cs b/src/IO.Ably.Shared/Protocol.cs index 9e95a3d2a..0c7dd0219 100644 --- a/src/IO.Ably.Shared/Protocol.cs +++ b/src/IO.Ably.Shared/Protocol.cs @@ -5,16 +5,30 @@ namespace IO.Ably /// public enum Protocol { -#if MSGPACK /// - /// Msg packg binary protocol. + /// MessagePack binary protocol (default for better performance). /// MsgPack = 0, -#endif /// - /// Json text protocol. + /// JSON text protocol. /// Json = 1 } + + /// + /// Extension methods for Protocol enum. + /// + public static class ProtocolExtensions + { + /// + /// Determines whether the specified protocol is binary (MsgPack). + /// + /// The protocol to check. + /// true if the protocol is MsgPack; otherwise, false. + public static bool IsBinary(this Protocol protocol) + { + return protocol == Protocol.MsgPack; + } + } } diff --git a/src/IO.Ably.Shared/Push/DeviceDetails.cs b/src/IO.Ably.Shared/Push/DeviceDetails.cs index b3cd7223b..27836924b 100644 --- a/src/IO.Ably.Shared/Push/DeviceDetails.cs +++ b/src/IO.Ably.Shared/Push/DeviceDetails.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using MessagePack; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace IO.Ably.Push @@ -6,71 +7,83 @@ namespace IO.Ably.Push /// /// Class representing a Device registered for Ably push notifications. /// + [MessagePackObject(keyAsPropertyName: true)] public class DeviceDetails { /// /// Device Id. /// + [Key("id")] [JsonProperty("id")] public string Id { get; set; } /// /// Device platform. One of 'android', 'ios' or 'browser'). /// + [Key("platform")] [JsonProperty("platform")] public string Platform { get; set; } /// /// Device form factor. One of 'phone', 'tablet', 'desktop', 'tv', 'watch', 'car' or 'embedded'. /// + [Key("formFactor")] [JsonProperty("formFactor")] public string FormFactor { get; set; } /// /// Device ClientId which is associated with the push registration. /// + [Key("clientId")] [JsonProperty("clientId")] public string ClientId { get; set; } /// /// Device Metadata. It's a flexible key value pair. Usually used to tag devices. /// + [Key("metadata")] [JsonProperty("metadata")] public JObject Metadata { get; set; } /// /// Push registration data. /// + [Key("push")] [JsonProperty("push")] public PushData Push { get; set; } = new PushData(); /// /// Random string which is automatically generated when a new LocalDevice is created and can be used to authenticate PushAdmin Rest requests. /// + [Key("deviceSecret")] [JsonProperty("deviceSecret")] public string DeviceSecret { get; set; } /// /// Class describing Push data. /// + [MessagePackObject(keyAsPropertyName: true)] public class PushData { /// /// Push Recipient. Currently supporter recipients are Apple (apns), Google (fcm) and Browser (web). /// For more information - https://ably.com/docs/rest-api#post-device-registration. /// + [Key("recipient")] [JsonProperty("recipient")] public JObject Recipient { get; set; } /// /// State of the push integration. /// + [Key("state")] [JsonProperty("state")] public string State { get; set; } /// /// Error registering device as a PushTarget. /// + [Key("errorReason")] [JsonProperty("errorReason")] public ErrorInfo ErrorReason { get; set; } } diff --git a/src/IO.Ably.Shared/Push/LocalDevice.cs b/src/IO.Ably.Shared/Push/LocalDevice.cs index 0986f5df6..d8c66aa41 100644 --- a/src/IO.Ably.Shared/Push/LocalDevice.cs +++ b/src/IO.Ably.Shared/Push/LocalDevice.cs @@ -1,5 +1,6 @@ using System; using IO.Ably.Encryption; +using MessagePack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -8,6 +9,7 @@ namespace IO.Ably.Push /// /// LocalDevice represents the current state of the device in respect of it being a target for push notifications. /// + [MessagePackObject(keyAsPropertyName: true)] public class LocalDevice : DeviceDetails { private const string JsonTokenTypeParameterName = "transportType"; @@ -21,17 +23,22 @@ public class LocalDevice : DeviceDetails /// It can be used to authenticate Push Admin requests. /// [JsonIgnore] + [IgnoreMember] public string DeviceIdentityToken { get; set; } + [IgnoreMember] internal Action ClientIdUpdated { get; set; } = (newClientId) => { }; /// /// Checks if the device is registered to receive push notifications. /// + [IgnoreMember] public bool IsRegistered => DeviceIdentityToken.IsNotEmpty(); + [IgnoreMember] internal bool IsCreated => Id.IsNotEmpty() && DeviceSecret.IsNotEmpty(); + [IgnoreMember] internal RegistrationToken RegistrationToken { get => GetRegistrationToken(Push?.Recipient); diff --git a/src/IO.Ably.Shared/Push/PushChannelSubscription.cs b/src/IO.Ably.Shared/Push/PushChannelSubscription.cs index 454475675..ab21c2d0d 100644 --- a/src/IO.Ably.Shared/Push/PushChannelSubscription.cs +++ b/src/IO.Ably.Shared/Push/PushChannelSubscription.cs @@ -1,27 +1,32 @@ -using Newtonsoft.Json; +using MessagePack; +using Newtonsoft.Json; namespace IO.Ably.Push { /// /// Represents a push channel subscription. /// + [MessagePackObject(keyAsPropertyName: true)] public class PushChannelSubscription { /// /// Name of the channel. /// + [Key("channel")] [JsonProperty("channel")] public string Channel { get; set; } /// /// Device id attached to the subscription. /// + [Key("deviceId")] [JsonProperty("deviceId")] public string DeviceId { get; set; } /// /// Client id attached to the channel. /// + [Key("clientId")] [JsonProperty("clientId")] public string ClientId { get; set; } diff --git a/src/IO.Ably.Shared/Rest/ChannelDetails.cs b/src/IO.Ably.Shared/Rest/ChannelDetails.cs index 95e02f0e9..758037551 100644 --- a/src/IO.Ably.Shared/Rest/ChannelDetails.cs +++ b/src/IO.Ably.Shared/Rest/ChannelDetails.cs @@ -1,36 +1,43 @@ -using Newtonsoft.Json; +using MessagePack; +using Newtonsoft.Json; namespace IO.Ably.Rest { #pragma warning disable SA1307 #pragma warning disable SA1600 + [MessagePackObject(keyAsPropertyName: true)] public class ChannelDetails { /// /// The required name of the channel including any qualifier, if any. /// + [Key("channelId")] [JsonProperty("channelId")] public string ChannelId { get; set; } /// /// The status and occupancy stats for the channel. /// + [Key("status")] [JsonProperty("status")] public ChannelStatus Status { get; set; } } + [MessagePackObject(keyAsPropertyName: true)] public class ChannelStatus { /// /// Indicates whether the channel that is the subject of the event is active. /// + [Key("isActive")] [JsonProperty("isActive")] public bool IsActive { get; set; } /// /// Metadata relating to the occupants of the channel. /// + [Key("occupancy")] [JsonProperty("occupancy")] public ChannelOccupancy Occupancy { get; set; } } @@ -38,47 +45,56 @@ public class ChannelStatus /// /// Metadata relating to the occupants of the channel. /// + [MessagePackObject(keyAsPropertyName: true)] public class ChannelOccupancy { + [Key("metrics")] [JsonProperty("metrics")] public ChannelMetrics Metrics { get; set; } } + [MessagePackObject(keyAsPropertyName: true)] public class ChannelMetrics { /// /// The number of connections. /// + [Key("connections")] [JsonProperty("connections")] public int Connections { get; set; } /// /// The number of connections attached to the channel that are authorised to publish. /// + [Key("publishers")] [JsonProperty("publishers")] public int Publishers { get; set; } /// /// The number of connections attached that are authorised to subscribe to messages. /// + [Key("subscribers")] [JsonProperty("subscribers")] public int Subscribers { get; set; } /// /// The number of connections that are authorised to enter members into the presence channel. /// + [Key("presenceConnections")] [JsonProperty("presenceConnections")] public int PresenceConnections { get; set; } /// /// The number of members currently entered into the presence channel. /// + [Key("presenceMembers")] [JsonProperty("presenceMembers")] public int PresenceMembers { get; set; } /// /// The number of connections that are authorised to subscribe to presence messages. /// + [Key("presenceSubscribers")] [JsonProperty("presenceSubscribers")] public int PresenceSubscribers { get; set; } } diff --git a/src/IO.Ably.Shared/Statistics.cs b/src/IO.Ably.Shared/Statistics.cs index 642fe0fde..ecb7ba32e 100644 --- a/src/IO.Ably.Shared/Statistics.cs +++ b/src/IO.Ably.Shared/Statistics.cs @@ -1,5 +1,6 @@ using System; using System.Globalization; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably @@ -11,69 +12,82 @@ namespace IO.Ably /// This class defines the Stats type and its subtypes, giving a structured /// representation of service usage for a specific scope and time interval. /// + [MessagePackObject(keyAsPropertyName: true)] public class Stats { /// /// Aggregates inbound and outbound messages. /// + [Key("all")] public MessageTypes All { get; set; } /// /// All inbound messages. /// + [Key("inbound")] public InboundMessageTraffic Inbound { get; set; } /// /// All outbound messages. /// + [Key("outbound")] public OutboundMessageTraffic Outbound { get; set; } /// /// Messages persisted for later retrieval via the history API. /// + [Key("persisted")] public MessageTypes Persisted { get; set; } /// /// Breakdown of connection stats data for different (TLS vs non-TLS) connection types. /// + [Key("connections")] public ConnectionTypes Connections { get; set; } /// /// Breakdown of channels stats. /// + [Key("channels")] public ResourceCount Channels { get; set; } /// /// Breakdown of API requests received via the REST API. /// + [Key("apiRequests")] public RequestCount ApiRequests { get; set; } /// /// Breakdown of Token requests received via the REST API. /// + [Key("tokenRequests")] public RequestCount TokenRequests { get; set; } /// /// The interval that this statistic applies to. /// + [Key("intervalId")] [JsonProperty("intervalId")] public string IntervalId { get; set; } /// /// The granularity of the interval for the stat such as :day, :hour, :minute, see . /// + [Key("intervalGranularity")] [JsonProperty("intervalGranularity")] public StatsIntervalGranularity IntervalGranularity { get; set; } /// /// A DateTimeOffset representing the start of the interval. /// + [Key("intervalTime")] [JsonProperty("intervalTime")] public DateTimeOffset IntervalTime { get; set; } /// /// IntervalId converted to a DateTimeOffset. /// + [IgnoreMember] public DateTimeOffset Interval => DateTimeOffset.ParseExact(IntervalId, "yyyy-MM-dd:HH:mm", CultureInfo.InvariantCulture); /// @@ -96,21 +110,25 @@ public Stats() /// A breakdown of summary stats data for different (tls vs non-tls) /// connection types. /// + [MessagePackObject(keyAsPropertyName: true)] public class ConnectionTypes { /// /// All connection count (includes both TLS & non-TLS connections). /// + [Key("all")] public ResourceCount All { get; set; } /// /// Non-TLS connection count (unencrypted). /// + [Key("plain")] public ResourceCount Plain { get; set; } /// /// TLS connection count. /// + [Key("tls")] public ResourceCount Tls { get; set; } /// @@ -127,16 +145,19 @@ public ConnectionTypes() /// /// MessageCount contains aggregate counts for messages and data transferred. /// + [MessagePackObject(keyAsPropertyName: true)] public class MessageCount { /// /// Count of all message. /// + [Key("count")] public long Count { get; set; } /// /// Total data transferred for all messages in bytes. /// + [Key("data")] public long Data { get; set; } } @@ -144,21 +165,25 @@ public class MessageCount /// A breakdown of summary stats data for different (message vs presence) /// message types. /// + [MessagePackObject(keyAsPropertyName: true)] public class MessageTypes { /// /// All messages count (includes both presence & messages). /// + [Key("all")] public MessageCount All { get; set; } /// /// Count of channel messages. /// + [Key("messages")] public MessageCount Messages { get; set; } /// /// Count of presence messages. /// + [Key("presence")] public MessageCount Presence { get; set; } /// @@ -175,21 +200,25 @@ public MessageTypes() /// /// A breakdown of summary stats data for traffic over various transport types. /// + [MessagePackObject(keyAsPropertyName: true)] public class InboundMessageTraffic { /// /// All messages count (includes realtime, rest and webhook messages). /// + [Key("all")] public MessageTypes All { get; set; } /// /// Count of messages transferred over a realtime transport such as WebSockets. /// + [Key("realtime")] public MessageTypes Realtime { get; set; } /// /// Count of messages transferred using REST. /// + [Key("rest")] public MessageTypes Rest { get; set; } /// @@ -206,26 +235,31 @@ public InboundMessageTraffic() /// /// A breakdown of summary stats data for traffic over various transport types. /// + [MessagePackObject(keyAsPropertyName: true)] public class OutboundMessageTraffic { /// /// All messages count (includes realtime, rest and webhook messages). /// + [Key("all")] public MessageTypes All { get; set; } /// /// Count of messages transferred over a realtime transport such as WebSockets. /// + [Key("realtime")] public MessageTypes Realtime { get; set; } /// /// Count of messages transferred using REST. /// + [Key("rest")] public MessageTypes Rest { get; set; } /// /// Count of messages delivered using WebHooks. /// + [Key("webhook")] public MessageTypes Webhook { get; set; } /// @@ -243,56 +277,66 @@ public OutboundMessageTraffic() /// /// RequestCount contains aggregate counts for requests made. /// + [MessagePackObject(keyAsPropertyName: true)] public class RequestCount { /// /// Requests succeeded. /// + [Key("succeeded")] public long Succeeded { get; set; } /// /// Requests failed. /// + [Key("failed")] public long Failed { get; set; } /// /// Requests refused typically as a result of permissions or a limit being exceeded. /// + [Key("refused")] public long Refused { get; set; } } /// /// Aggregate data for usage of a resource in a specific scope. /// + [MessagePackObject(keyAsPropertyName: true)] public class ResourceCount { /// /// Total resources of this type opened. /// + [Key("opened")] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double Opened { get; set; } /// /// Peak resources of this type used for this period. /// + [Key("peak")] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double Peak { get; set; } /// /// Average resources of this type used for this period. /// + [Key("mean")] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double Mean { get; set; } /// /// Minimum total resources of this type used for this period. /// + [Key("min")] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double Min { get; set; } /// /// Resource requests refused within this period. /// + [Key("refused")] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double Refused { get; set; } } diff --git a/src/IO.Ably.Shared/TokenDetails.cs b/src/IO.Ably.Shared/TokenDetails.cs index 4b774def0..8c652720e 100644 --- a/src/IO.Ably.Shared/TokenDetails.cs +++ b/src/IO.Ably.Shared/TokenDetails.cs @@ -1,4 +1,5 @@ using System; +using MessagePack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -7,41 +8,48 @@ namespace IO.Ably /// /// A class providing details of a token and its associated metadata. /// + [MessagePackObject(keyAsPropertyName: true)] public sealed class TokenDetails { /// /// The allowed capabilities for this token. . /// + [Key("capability")] [JsonProperty("capability")] public Capability Capability { get; set; } /// /// The clientId associated with the token. /// + [Key("clientId")] [JsonProperty("clientId", NullValueHandling = NullValueHandling.Ignore)] public string ClientId { get; set; } /// /// Absolute token expiry date in UTC. /// + [Key("expires")] [JsonProperty("expires")] public DateTimeOffset Expires { get; set; } /// /// Date and time when the token was issued in UTC. /// + [Key("issued")] [JsonProperty("issued")] public DateTimeOffset Issued { get; set; } /// /// The token itself. /// + [Key("token")] [JsonProperty("token")] public string Token { get; set; } /// /// API key name used to create this token. /// + [Key("keyName")] [JsonProperty("keyName")] public string KeyName { get; set; } @@ -62,6 +70,7 @@ public TokenDetails(string token) Token = token; } + [IgnoreMember] internal bool CanBeUsedToCheckExpiry => Expires != DateTimeOffset.MinValue; /// diff --git a/src/IO.Ably.Shared/TokenRequest.cs b/src/IO.Ably.Shared/TokenRequest.cs index f1c034369..6a66d2e75 100644 --- a/src/IO.Ably.Shared/TokenRequest.cs +++ b/src/IO.Ably.Shared/TokenRequest.cs @@ -1,6 +1,7 @@ using System; using System.Globalization; using IO.Ably.Encryption; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably @@ -8,10 +9,13 @@ namespace IO.Ably /// /// A class providing parameters of a token request. /// + [MessagePackObject(keyAsPropertyName: true)] public class TokenRequest { + [IgnoreMember] private readonly Func _now; + [IgnoreMember] private DateTimeOffset? _timestamp; /// @@ -31,6 +35,7 @@ internal TokenRequest(Func nowFunc) /// /// The Id against which the request is made. /// + [Key("keyName")] [JsonProperty("keyName")] public string KeyName { get; set; } @@ -40,6 +45,7 @@ internal TokenRequest(Func nowFunc) /// than or equal to this value depending on application settings /// and the attributes of the issuing key. /// + [Key("ttl")] [JsonProperty("ttl")] public TimeSpan? Ttl { get; set; } @@ -48,12 +54,14 @@ internal TokenRequest(Func nowFunc) /// the capability of the returned token will be the intersection of /// this capability with the capability of the issuing key. /// + [Key("capability")] [JsonProperty("capability", NullValueHandling = NullValueHandling.Ignore)] public Capability Capability { get; set; } /// /// ClientId to associate with the current token. The generated token may be to authenticate as this tokenId. /// + [Key("clientId")] [JsonProperty("clientId", NullValueHandling = NullValueHandling.Ignore)] public string ClientId { get; set; } @@ -62,6 +70,7 @@ internal TokenRequest(Func nowFunc) /// Timestamps, in conjunction with the nonce, are used to prevent /// token requests from being replayed. /// + [Key("timestamp")] [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { @@ -82,6 +91,7 @@ public DateTimeOffset? Timestamp /// same nonce will be rejected. /// /// + [Key("nonce")] [JsonProperty("nonce")] public string Nonce { get; set; } @@ -89,6 +99,7 @@ public DateTimeOffset? Timestamp /// The Message Authentication Code for this request. See the Ably /// Authentication documentation for more details. /// + [Key("mac")] [JsonProperty("mac")] public string Mac { get; set; } diff --git a/src/IO.Ably.Shared/Transport/MsWebSocketTransport.cs b/src/IO.Ably.Shared/Transport/MsWebSocketTransport.cs index 26a09cd88..48f19e572 100644 --- a/src/IO.Ably.Shared/Transport/MsWebSocketTransport.cs +++ b/src/IO.Ably.Shared/Transport/MsWebSocketTransport.cs @@ -169,10 +169,9 @@ private void HandleMessageReceived(RealtimeTransportData data) { try { -#if MSGPACK - var message = MsgPackHelper.DeserialiseMsgPackObject(data.Data).ToString(); - Logger.Debug("Websocket data message received. Raw: " + message); -#endif + // Always available - no conditional compilation + var message = MsgPackHelper.DecodeMsgPackObject(data.Data); + Logger.Debug("Websocket data message received. MsgPack Decoded: " + message); } catch (Exception) { diff --git a/src/IO.Ably.Shared/Types/AuthDetails.cs b/src/IO.Ably.Shared/Types/AuthDetails.cs index 1b7498bdc..306f4588a 100644 --- a/src/IO.Ably.Shared/Types/AuthDetails.cs +++ b/src/IO.Ably.Shared/Types/AuthDetails.cs @@ -1,15 +1,18 @@ -using Newtonsoft.Json; +using MessagePack; +using Newtonsoft.Json; namespace IO.Ably.Types { /// /// AuthDetails is a type used with an AUTH protocol messages to send authentication details. /// + [MessagePackObject(keyAsPropertyName: true)] public class AuthDetails { /// /// Gets or sets the accessToken. /// + [Key("accessToken")] [JsonProperty("accessToken")] public string AccessToken { get; set; } } diff --git a/src/IO.Ably.Shared/Types/ChannelParams.cs b/src/IO.Ably.Shared/Types/ChannelParams.cs index 90723889f..ab0283257 100644 --- a/src/IO.Ably.Shared/Types/ChannelParams.cs +++ b/src/IO.Ably.Shared/Types/ChannelParams.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using MessagePack; namespace IO.Ably { diff --git a/src/IO.Ably.Shared/Types/ConnectionDetails.cs b/src/IO.Ably.Shared/Types/ConnectionDetails.cs index 095533fe3..6ba855bb6 100644 --- a/src/IO.Ably.Shared/Types/ConnectionDetails.cs +++ b/src/IO.Ably.Shared/Types/ConnectionDetails.cs @@ -1,4 +1,5 @@ using System; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably @@ -6,47 +7,55 @@ namespace IO.Ably /// /// provides details on the constraints or defaults for the connection such as max message size, client ID or connection state TTL. /// + [MessagePackObject(keyAsPropertyName: true)] public class ConnectionDetails { /// /// Client id associated with the current connection. /// + [Key("clientId")] [JsonProperty("clientId")] public string ClientId { get; set; } /// /// Connection key. /// + [Key("connectionKey")] [JsonProperty("connectionKey")] public string ConnectionKey { get; set; } /// /// Optional Connection state time to live. /// + [Key("connectionStateTtl")] [JsonProperty("connectionStateTtl")] public TimeSpan? ConnectionStateTtl { get; set; } /// /// Max frame size. /// + [Key("maxFrameSize")] [JsonProperty("maxFrameSize")] public long MaxFrameSize { get; set; } /// /// Max inbound rate. /// + [Key("maxInboundRate")] [JsonProperty("maxInboundRate")] public long MaxInboundRate { get; set; } /// /// Max message size. /// + [Key("maxMessageSize")] [JsonProperty("maxMessageSize")] public long MaxMessageSize { get; set; } /// /// Server id associated with the current connection. /// + [Key("serverId")] [JsonProperty("serverId")] public string ServerId { get; set; } } diff --git a/src/IO.Ably.Shared/Types/ErrorInfo.cs b/src/IO.Ably.Shared/Types/ErrorInfo.cs index 03dfa9b59..e6c8ea82c 100644 --- a/src/IO.Ably.Shared/Types/ErrorInfo.cs +++ b/src/IO.Ably.Shared/Types/ErrorInfo.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.Net; using System.Text; +using MessagePack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -10,6 +11,7 @@ namespace IO.Ably /// /// An exception type encapsulating error information containing an Ably specific error code and generic status code. /// + [MessagePackObject(keyAsPropertyName: true)] public class ErrorInfo { internal static readonly ErrorInfo ReasonClosed = new ErrorInfo("Connection closed by client", ErrorCodes.NoError); @@ -31,54 +33,63 @@ public class ErrorInfo /// /// Ably error code (see https://github.com/ably/ably-common/blob/main/protocol/errors.json). /// + [Key("code")] [JsonProperty("code")] public int Code { get; set; } /// /// The http status code corresponding to this error. /// + [Key("statusCode")] [JsonProperty("statusCode")] public HttpStatusCode? StatusCode { get; set; } /// /// Additional reason information, where available. /// + [Key("message")] [JsonProperty("message")] public string Message { get; set; } /// /// Link to specification detail for this error code, where available. Spec TI4. /// + [Key("href")] [JsonProperty("href")] public string Href { get; set; } /// /// Additional cause information, where available. /// + [Key("cause")] [JsonProperty("cause")] public ErrorInfo Cause { get; set; } /// /// Is this Error as result of a 401 Unauthorized HTTP response. /// + [IgnoreMember] public bool IsUnAuthorizedError => StatusCode.HasValue && StatusCode.Value == HttpStatusCode.Unauthorized; /// /// Is this Error as result of a 403 Forbidden HTTP response. /// + [IgnoreMember] public bool IsForbiddenError => StatusCode.HasValue && StatusCode.Value == HttpStatusCode.Forbidden; /// /// Is the error Code a token error code. /// + [IgnoreMember] public bool IsTokenError => Code >= Defaults.TokenErrorCodesRangeStart && Code <= Defaults.TokenErrorCodesRangeEnd; /// /// Get or Sets the InnerException. /// + [IgnoreMember] public Exception InnerException { get; set; } /// @@ -179,23 +190,30 @@ internal static ErrorInfo Parse(AblyResponse response) int errorCode = response.StatusCode == HttpStatusCode.Forbidden ? 40300 : ErrorCodes.InternalError; string reason = string.Empty; - if (response.Type == ResponseType.Json) + string errorResponse; + if (response.Type == ResponseType.Binary) { - try - { - var json = JObject.Parse(response.TextResponse); - if (json["error"] != null) - { - reason = (string)json["error"]["message"]; - errorCode = (int)json["error"]["code"]; - } - } - catch (Exception ex) + errorResponse = MsgPackHelper.ToJsonString(response.Body); + } + else + { + errorResponse = response.TextResponse; + } + + try + { + var json = JObject.Parse(errorResponse); + if (json["error"] != null) { - // If there is no json or there is something wrong we don't want to throw from here. - Debug.WriteLine(ex.Message); + reason = (string)json["error"]["message"]; + errorCode = (int)json["error"]["code"]; } } + catch (Exception ex) + { + // If there is no json or there is something wrong we don't want to throw from here. + Debug.WriteLine(ex.Message); + } return new ErrorInfo(reason.IsEmpty() ? "Unknown error" : reason, errorCode, response.StatusCode); } diff --git a/src/IO.Ably.Shared/Types/Message.cs b/src/IO.Ably.Shared/Types/Message.cs index 894c6b133..403d9f406 100644 --- a/src/IO.Ably.Shared/Types/Message.cs +++ b/src/IO.Ably.Shared/Types/Message.cs @@ -2,14 +2,16 @@ using System.Collections.Generic; using System.Diagnostics; using IO.Ably.MessageEncoders; -using IO.Ably.Shared.CustomSerialisers; +using IO.Ably.CustomSerialisers; using IO.Ably.Types; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably { /// A class representing an individual message to be sent or received via the Ably realtime service. [DebuggerDisplay("{ToString()}")] + [MessagePackObject(keyAsPropertyName: true)] public class Message : IMessage { private static readonly Message DefaultInstance = new Message(); @@ -42,30 +44,37 @@ public Message(string name = null, object data = null, string clientId = null, M } /// A globally unique message id. + [Key("id")] [JsonProperty("id")] public string Id { get; set; } /// The id of the publisher of this message. + [Key("clientId")] [JsonProperty("clientId")] public string ClientId { get; set; } /// The connection id of the publisher of the message. + [Key("connectionId")] [JsonProperty("connectionId")] public string ConnectionId { get; set; } /// The connection key of the publisher of the message. Used for impersonation. + [Key("connectionKey")] [JsonProperty("connectionKey")] public string ConnectionKey { get; set; } /// The event name, if available. + [Key("name")] [JsonProperty("name")] public string Name { get; set; } /// Timestamp when the message was received by the Ably real-time service. + [Key("timestamp")] [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } /// The message payload. Supported data types are objects, byte[] and strings. + [Key("data")] [JsonProperty("data")] [JsonConverter(typeof(MessageDataConverter))] public object Data { get; set; } @@ -73,6 +82,7 @@ public Message(string name = null, object data = null, string clientId = null, M /// /// Extra properties associated with the message. /// + [Key("extras")] [JsonProperty("extras")] public MessageExtras Extras { get; set; } @@ -81,6 +91,7 @@ public Message(string name = null, object data = null, string clientId = null, M /// library. /// Therefore, the `encoding` attribute should always be nil unless an Ably library decoding error has occurred. /// + [Key("encoding")] [JsonProperty("encoding")] public string Encoding { get; set; } @@ -99,6 +110,7 @@ public override string ToString() /// /// Checks if this is an empty message. /// + [IgnoreMember] [JsonIgnore] public bool IsEmpty => Equals(this, DefaultInstance); diff --git a/src/IO.Ably.Shared/Types/PresenceMessage.cs b/src/IO.Ably.Shared/Types/PresenceMessage.cs index 10f1ba86a..1a55bce4e 100644 --- a/src/IO.Ably.Shared/Types/PresenceMessage.cs +++ b/src/IO.Ably.Shared/Types/PresenceMessage.cs @@ -1,4 +1,5 @@ using System; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably @@ -38,6 +39,7 @@ public enum PresenceAction : byte /// A class representing an individual presence update to be sent or received /// via the Ably Realtime service. /// + [MessagePackObject(keyAsPropertyName: true)] public class PresenceMessage : IMessage { /// @@ -75,52 +77,61 @@ public PresenceMessage(PresenceAction action, string clientId, object data, stri /// /// Ably message id. /// + [Key("id")] [JsonProperty("id")] public string Id { get; set; } /// /// Presence action associated with the presence message. /// + [Key("action")] [JsonProperty("action")] public PresenceAction Action { get; set; } /// /// Id of the client associate. /// + [Key("clientId")] [JsonProperty("clientId")] public string ClientId { get; set; } /// /// Id of the current connection. /// + [Key("connectionId")] [JsonProperty("connectionId")] public string ConnectionId { get; set; } /// The connection key of the publisher of the message. Used for impersonation. + [Key("connectionKey")] [JsonProperty("connectionKey")] public string ConnectionKey { get; set; } /// /// Custom data object associated with the message. /// + [Key("data")] [JsonProperty("data")] public object Data { get; set; } /// /// Encoding for the message. /// + [Key("encoding")] [JsonProperty("encoding")] public string Encoding { get; set; } /// /// Server timestamp for the message. /// + [Key("timestamp")] [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } /// /// Member key which is a combination of ClientId:ConnectionId. /// + [IgnoreMember] [JsonIgnore] public string MemberKey => $"{ClientId}:{ConnectionId}"; diff --git a/src/IO.Ably.Shared/Types/ProtocolMessage.cs b/src/IO.Ably.Shared/Types/ProtocolMessage.cs index 0083046d2..616d7ab1d 100644 --- a/src/IO.Ably.Shared/Types/ProtocolMessage.cs +++ b/src/IO.Ably.Shared/Types/ProtocolMessage.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Runtime.Serialization; using System.Text; +using MessagePack; using Newtonsoft.Json; namespace IO.Ably.Types @@ -15,6 +16,7 @@ namespace IO.Ably.Types /// See the Ably client library developer documentation for further /// details on the members of a ProtocolMessage. /// + [MessagePackObject(keyAsPropertyName: true)] public class ProtocolMessage { /// @@ -92,6 +94,7 @@ public static bool HasFlag(int? value, Flag flag) /// ATTACHED message. /// For more information https://ably.com/docs/realtime/channels/channel-parameters/overview. /// + [Key("params")] [JsonProperty("params")] public ChannelParams Params { get; set; } @@ -119,87 +122,102 @@ internal ProtocolMessage(MessageAction action, string channel) /// /// Current message action. /// + [Key("action")] [JsonProperty("action")] public MessageAction Action { get; set; } /// /// for the current message. /// + [Key("auth")] [JsonProperty("auth")] public AuthDetails Auth { get; set; } /// /// Current message flags. /// + [Key("flags")] [JsonProperty("flags")] public int? Flags { get; set; } /// /// Count. /// + [Key("count")] [JsonProperty("count")] public int? Count { get; set; } /// /// Error associated with the message. /// + [Key("error")] [JsonProperty("error")] public ErrorInfo Error { get; set; } /// /// Ably generated message id. /// + [Key("id")] [JsonProperty("id")] public string Id { get; set; } /// /// Optional channel for which the message belongs to. /// + [Key("channel")] [JsonProperty("channel")] public string Channel { get; set; } /// /// Current channel serial. /// + [Key("channelSerial")] [JsonProperty("channelSerial")] public string ChannelSerial { get; set; } /// /// Current connectionId. /// + [Key("connectionId")] [JsonProperty("connectionId")] public string ConnectionId { get; set; } /// /// Current message serial. /// + [Key("msgSerial")] [JsonProperty("msgSerial")] public long MsgSerial { get; set; } /// /// Timestamp of the message. /// + [Key("timestamp")] [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } /// /// List of messages contained in this protocol message. /// + [Key("messages")] [JsonProperty("messages")] public Message[] Messages { get; set; } /// /// List of presence messages contained in this protocol message. /// + [Key("presence")] [JsonProperty("presence")] public PresenceMessage[] Presence { get; set; } /// /// Connection details received. . /// + [Key("connectionDetails")] [JsonProperty("connectionDetails")] public ConnectionDetails ConnectionDetails { get; set; } + [IgnoreMember] [JsonIgnore] internal bool AckRequired => Action == MessageAction.Message || Action == MessageAction.Presence; diff --git a/src/IO.Ably.Tests.DotNET/IO.Ably.Tests.DotNET.csproj b/src/IO.Ably.Tests.DotNET/IO.Ably.Tests.DotNET.csproj index eff508212..a75afba9c 100644 --- a/src/IO.Ably.Tests.DotNET/IO.Ably.Tests.DotNET.csproj +++ b/src/IO.Ably.Tests.DotNET/IO.Ably.Tests.DotNET.csproj @@ -14,6 +14,7 @@ + @@ -24,8 +25,8 @@ + - diff --git a/src/IO.Ably.Tests.NETFramework/IO.Ably.Tests.NETFramework.csproj b/src/IO.Ably.Tests.NETFramework/IO.Ably.Tests.NETFramework.csproj index 1c7f16f63..bdf81fd16 100644 --- a/src/IO.Ably.Tests.NETFramework/IO.Ably.Tests.NETFramework.csproj +++ b/src/IO.Ably.Tests.NETFramework/IO.Ably.Tests.NETFramework.csproj @@ -66,6 +66,11 @@ messages-encoding.json + + + msgpack_test_fixtures.json + + test-app-setup.json @@ -113,6 +118,9 @@ 6.2.0 + + 3.1.4 + 13.0.1 diff --git a/src/IO.Ably.Tests.Shared/AuthTests/AuthSandboxSpecs.cs b/src/IO.Ably.Tests.Shared/AuthTests/AuthSandboxSpecs.cs index d4e9219f5..795ff8c0d 100644 --- a/src/IO.Ably.Tests.Shared/AuthTests/AuthSandboxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/AuthTests/AuthSandboxSpecs.cs @@ -598,7 +598,7 @@ public async Task WithTokenId_WhenTryingToPublishToUnspecifiedChannel_ThrowsAbly var token = ably.Auth.RequestTokenAsync(CreateTokenParams(capability)).Result; - var tokenAbly = new AblyRest(new ClientOptions { Token = token.Token, Environment = "sandbox" }); + var tokenAbly = new AblyRest(new ClientOptions { Token = token.Token, Environment = "sandbox", UseBinaryProtocol = protocol.IsBinary() }); var error = await @@ -655,7 +655,7 @@ public async Task TokenAuthWithoutClientId_ShouldNotSetClientIdOnMessagesAndTheC { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); tokenClient.AblyAuth.ClientId.Should().BeNullOrEmpty(); @@ -678,7 +678,7 @@ public async Task TokenAuthWithoutClientIdAndAMessageWithExplicitId_ShouldThrow( { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); await Assert.ThrowsAsync( @@ -698,7 +698,7 @@ public async Task TokenAuthWithWildcardClientId_ShouldPublishMessageSuccessfully { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -723,7 +723,7 @@ public async Task { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -747,7 +747,7 @@ public async Task TokenAuthUrlWhenPlainTextTokenIsReturn_ShouldBeAblyToPublishWi { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = authUrlClient.Channels["pesisted:test"]; @@ -771,7 +771,7 @@ public async Task TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToPublishWithNew { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20) }); @@ -794,12 +794,12 @@ public async Task TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToConnect(Protoc var authUrl = "http://echo.ably.io/?type=json&body=" + Uri.EscapeDataString(tokenJson); var client = new AblyRealtime(new ClientOptions - { - AuthUrl = new Uri(authUrl), - Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, - HttpRequestTimeout = new TimeSpan(0, 0, 20) - }); + { + AuthUrl = new Uri(authUrl), + Environment = settings.Environment, + UseBinaryProtocol = protocol.IsBinary(), + HttpRequestTimeout = new TimeSpan(0, 0, 20) + }); await client.WaitForState(); client.Connection.State.Should().Be(ConnectionState.Connected); @@ -816,12 +816,12 @@ public async Task TokenAuthUrlWithIncorrectJsonTokenReturned_ShouldNotBeAbleToCo var authUrl = "http://echo.ably.io/?type=json&body=" + Uri.EscapeDataString(incorrectJson); var client = new AblyRealtime(new ClientOptions - { - AuthUrl = new Uri(authUrl), - Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, - HttpRequestTimeout = new TimeSpan(0, 0, 20) - }); + { + AuthUrl = new Uri(authUrl), + Environment = settings.Environment, + UseBinaryProtocol = protocol.IsBinary(), + HttpRequestTimeout = new TimeSpan(0, 0, 20) + }); var tsc = new TaskCompletionAwaiter(); ErrorInfo err = null; @@ -848,7 +848,7 @@ public async Task TokenAuthCallbackWithTokenDetailsReturned_ShouldBeAbleToPublis { options.AuthCallback = tokenParams => tokenClient.Auth.RequestTokenAsync(new TokenParams { ClientId = "*" }).Convert(); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"]; @@ -871,7 +871,7 @@ public async Task TokenAuthCallbackWithTokenRequestReturned_ShouldBeAbleToGetATo { options.AuthCallback = async tokenParams => await tokenClient.Auth.CreateTokenRequestAsync(new TokenParams { ClientId = "*" }); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"]; diff --git a/src/IO.Ably.Tests.Shared/CustomSerializers/JsonSerializationTests.cs b/src/IO.Ably.Tests.Shared/CustomSerializers/JsonSerializationTests.cs new file mode 100644 index 000000000..563d2b9f3 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/CustomSerializers/JsonSerializationTests.cs @@ -0,0 +1,36 @@ +using FluentAssertions; +using Xunit; + +namespace IO.Ably.Tests.Shared.CustomSerializers +{ + public class JsonSerializationTests + { + [Fact] + public void CanDeserialiseTokenResponse() + { + var value = @"{ + ""access_token"": { + ""token"": ""_SYo4Q.D3WmHhU"", + ""keyName"": ""_SYo4Q.j8mhAQ"", + ""issued"": 1449163326485, + ""expires"": 1449163326485, + ""capability"": { + ""*"": [ + ""*"" + ] + }, + ""clientId"": ""123"" + } + }"; + + var response = JsonHelper.Deserialize(value); + + response.AccessToken.Should().NotBeNull(); + response.AccessToken.Capability.ToJson().Should().Be("{\"*\":[\"*\"]}"); + response.AccessToken.ClientId.Should().Be("123"); + response.AccessToken.Token.Should().Be("_SYo4Q.D3WmHhU"); + response.AccessToken.Issued.Should().Be(((long)1449163326485).FromUnixTimeInMilliseconds()); + response.AccessToken.Expires.Should().Be(((long)1449163326485).FromUnixTimeInMilliseconds()); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/DefaultTests.cs b/src/IO.Ably.Tests.Shared/DefaultTests.cs index 00c571f90..1985df92b 100644 --- a/src/IO.Ably.Tests.Shared/DefaultTests.cs +++ b/src/IO.Ably.Tests.Shared/DefaultTests.cs @@ -36,11 +36,5 @@ public void Defaults_WithEnvironment_ReturnsEnvironmentFallbackHosts() var fallbackHosts = Defaults.GetEnvironmentFallbackHosts("sandbox"); Assert.Equal(expectedFallBackHosts, fallbackHosts); } - - [Fact] - public void Defaults_ProtocolIsJson() - { - Defaults.Protocol.Should().Be(Protocol.Json); - } } } diff --git a/src/IO.Ably.Tests.Shared/IO.Ably.Tests.Shared.projitems b/src/IO.Ably.Tests.Shared/IO.Ably.Tests.Shared.projitems index 2eace096f..3ec751ebc 100644 --- a/src/IO.Ably.Tests.Shared/IO.Ably.Tests.Shared.projitems +++ b/src/IO.Ably.Tests.Shared/IO.Ably.Tests.Shared.projitems @@ -23,6 +23,7 @@ + @@ -72,8 +73,15 @@ - - + + + + + + + + + @@ -157,4 +165,7 @@ + + + \ No newline at end of file diff --git a/src/IO.Ably.Tests.Shared/Infrastructure/AblyRealtimeSpecs.cs b/src/IO.Ably.Tests.Shared/Infrastructure/AblyRealtimeSpecs.cs index 916bc7a47..7732084e1 100644 --- a/src/IO.Ably.Tests.Shared/Infrastructure/AblyRealtimeSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Infrastructure/AblyRealtimeSpecs.cs @@ -161,7 +161,7 @@ protected Task GetTestChannel(IRealtimeClient client = null, C { if (client == null) { - return GetConnectedClient().MapAsync(x => x.Channels.Get(TestChannelName, channelOptions)); + return GetConnectedClient(opts => { opts.UseBinaryProtocol = false; }).MapAsync(x => x.Channels.Get(TestChannelName, channelOptions)); } return Task.FromResult(client.Channels.Get(TestChannelName, channelOptions)); diff --git a/src/IO.Ably.Tests.Shared/Infrastructure/AblySandboxFixture.cs b/src/IO.Ably.Tests.Shared/Infrastructure/AblySandboxFixture.cs index 29076cbb9..b1ed8cf77 100644 --- a/src/IO.Ably.Tests.Shared/Infrastructure/AblySandboxFixture.cs +++ b/src/IO.Ably.Tests.Shared/Infrastructure/AblySandboxFixture.cs @@ -13,6 +13,8 @@ public class AblySandboxFixture private static readonly Dictionary Settings = new Dictionary(); + private static Protocol sandboxJsonProtocol = Protocol.Json; + public static async Task GetSettings(string environment = null) { environment = environment ?? "sandbox"; @@ -47,11 +49,11 @@ private static async Task Initialise(string environment ((string)cipher["iv"]).FromBase64()); AblyHttpClient client = settings.GetHttpClient(environment); - AblyRequest request = new AblyRequest("/apps", HttpMethod.Post); + AblyRequest request = new AblyRequest("/apps", HttpMethod.Post, sandboxJsonProtocol); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); request.RequestBody = testAppSpec["post_apps"].ToString().GetBytes(); - request.Protocol = Protocol.Json; + request.Protocol = sandboxJsonProtocol; var response = await RetryExecute(() => client.Execute(request)); @@ -114,8 +116,8 @@ private static async Task SetupSampleStats(TestEnvironmentSettings settings) AblyRest ablyRest = new AblyRest(settings.FirstValidKey); AblyHttpClient client = settings.GetHttpClient(); - var request = new AblyRequest("/stats", HttpMethod.Post); - request.Protocol = Protocol.Json; + var request = new AblyRequest("/stats", HttpMethod.Post, sandboxJsonProtocol); + request.Protocol = sandboxJsonProtocol; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); await ablyRest.AblyAuth.AddAuthHeader(request); diff --git a/src/IO.Ably.Tests.Shared/Infrastructure/InteroperabilityMessagePayloadDataAttribute.cs b/src/IO.Ably.Tests.Shared/Infrastructure/InteroperabilityMessagePayloadDataAttribute.cs index a5ee81166..6312187e4 100644 --- a/src/IO.Ably.Tests.Shared/Infrastructure/InteroperabilityMessagePayloadDataAttribute.cs +++ b/src/IO.Ably.Tests.Shared/Infrastructure/InteroperabilityMessagePayloadDataAttribute.cs @@ -15,7 +15,7 @@ public override IEnumerable GetData(MethodInfo testMethod) { var message = (JObject)jToken; yield return new object[] { Protocol.Json, message }; - yield return new object[] { Defaults.Protocol, message }; + yield return new object[] { Protocol.MsgPack, message }; } } } diff --git a/src/IO.Ably.Tests.Shared/Infrastructure/ProtocolDataAttribute.cs b/src/IO.Ably.Tests.Shared/Infrastructure/ProtocolDataAttribute.cs index bedff81be..62ed006d3 100644 --- a/src/IO.Ably.Tests.Shared/Infrastructure/ProtocolDataAttribute.cs +++ b/src/IO.Ably.Tests.Shared/Infrastructure/ProtocolDataAttribute.cs @@ -20,18 +20,15 @@ public ProtocolDataAttribute(params object[] data) /// public override IEnumerable GetData(MethodInfo testMethod) { + // Return Protocol.Json with relevant data var d = new List { Protocol.Json }; d.AddRange(_data); yield return d.ToArray(); - if (Defaults.MsgPackEnabled) -#pragma warning disable 162 - { - d = new List { Defaults.Protocol }; - d.AddRange(_data); - yield return d.ToArray(); - } -#pragma warning restore 162 + // Return Protocol.MsgPack with relevant data + d = new List { Protocol.MsgPack }; + d.AddRange(_data); + yield return d.ToArray(); } } } diff --git a/src/IO.Ably.Tests.Shared/Infrastructure/TestTransportFactory.cs b/src/IO.Ably.Tests.Shared/Infrastructure/TestTransportFactory.cs index 30c153552..66309480f 100644 --- a/src/IO.Ably.Tests.Shared/Infrastructure/TestTransportFactory.cs +++ b/src/IO.Ably.Tests.Shared/Infrastructure/TestTransportFactory.cs @@ -31,7 +31,7 @@ public ITransport CreateTransport(TransportParams parameters) { var factory = IoC.TransportFactory; var transport - = new TestTransportWrapper(factory.CreateTransport(parameters), parameters.UseBinaryProtocol ? Defaults.Protocol : Protocol.Json); + = new TestTransportWrapper(factory.CreateTransport(parameters), parameters.UseBinaryProtocol ? Protocol.MsgPack : Protocol.Json); transport.BeforeDataProcessed = BeforeDataProcessed; OnTransportCreated(transport); diff --git a/src/IO.Ably.Tests.Shared/MessageEncodes/Base64EncoderTests.cs b/src/IO.Ably.Tests.Shared/MessageEncodes/Base64EncoderTests.cs index 583f18eb5..47589b6e7 100644 --- a/src/IO.Ably.Tests.Shared/MessageEncodes/Base64EncoderTests.cs +++ b/src/IO.Ably.Tests.Shared/MessageEncodes/Base64EncoderTests.cs @@ -55,28 +55,7 @@ public void WithMessageAnotherEncoding_LeavesDataAndEncodingIntact() } } - public class EncodeWithBinaryProtocol : Base64EncoderTests - { - [Fact] - public void WithBinaryData_LeavesDataAndEncodingIntact() - { - if (!Defaults.MsgPackEnabled) - { - return; - } - -#pragma warning disable 162 - IPayload payload = new Message { Data = _binaryData }; - - payload = _encoder.Encode(payload, new DecodingContext()).Value; - - payload.Data.Should().Be(_binaryData); - payload.Encoding.Should().BeNull(); -#pragma warning restore 162 - } - } - - public class EncodeWithTextProtocol : Base64EncoderTests + public class Encode : Base64EncoderTests { [Fact] public void WithBinaryPayloadWithoutPriorEncoding_ConvertsDataToBase64StringAndSetsEncoding() diff --git a/src/IO.Ably.Tests.Shared/MessageEncodes/MessageDecodingAcceptanceTests.cs b/src/IO.Ably.Tests.Shared/MessageEncodes/MessageDecodingAcceptanceTests.cs index eb692cf64..66057478b 100644 --- a/src/IO.Ably.Tests.Shared/MessageEncodes/MessageDecodingAcceptanceTests.cs +++ b/src/IO.Ably.Tests.Shared/MessageEncodes/MessageDecodingAcceptanceTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Security.Cryptography; using FluentAssertions; using IO.Ably.Encryption; @@ -39,7 +40,7 @@ public void WithBase64EncodingBeforeOtherEncodings_SavesDecodedDataToTheContext( public void WhenBase64IsNotTheFirstEncoding_ShouldSaveTheOriginalPayloadInContext() { var message = new Message { Data = new { Text = "Hello" } }; - MessageHandler.EncodePayload(message, new DecodingContext()); + new MessageHandler(DefaultLogger.LoggerInstance, Protocol.Json).EncodePayloads(new DecodingContext(), new List { message }); var payloadData = message.Data as string; var payloadEncoding = message.Encoding; diff --git a/src/IO.Ably.Tests.Shared/MessageEncodes/MessageEncodersAcceptanceTests.cs b/src/IO.Ably.Tests.Shared/MessageEncodes/MessageEncodersAcceptanceTests.cs index 03470432e..fe4da6c07 100644 --- a/src/IO.Ably.Tests.Shared/MessageEncodes/MessageEncodersAcceptanceTests.cs +++ b/src/IO.Ably.Tests.Shared/MessageEncodes/MessageEncodersAcceptanceTests.cs @@ -4,12 +4,11 @@ using System.Threading.Tasks; using FluentAssertions; using IO.Ably.Encryption; +using IO.Ably.MessageEncoders; using IO.Ably.Tests; using Xunit; using Xunit.Abstractions; -#pragma warning disable 162 - namespace IO.Ably.AcceptanceTests { public class MessageEncodersAcceptanceTests : AblySpecs @@ -80,6 +79,33 @@ public async Task PublishSupportedMessages(Message message, string encoding) } } + [Fact] + public void WithTextProtocolAllEncoderAvailable() + { + // All encoders + var allEncoders = MessageHandler.AllEncoders; + allEncoders.Should().HaveCount(5); + // Encoders available for given MessageHandler + var messageHandler = new MessageHandler(DefaultLogger.LoggerInstance, Protocol.Json); + messageHandler.Encoders.Should().HaveCount(5); + // Available encoders are same as all encoders + Assert.Equal(messageHandler.Encoders, MessageHandler.AllEncoders); + } + + [Fact] + public void WithBinaryProtocolAllEncodersExceptBase64Encoder() + { + // All encoders + var allEncoders = MessageHandler.AllEncoders; + allEncoders.Should().HaveCount(5); + // Encoders available for given MessageHandler + var messageHandler = new MessageHandler(DefaultLogger.LoggerInstance, Protocol.MsgPack); + messageHandler.Encoders.Should().HaveCount(4); + + messageHandler.Encoders.Should().BeSubsetOf(allEncoders); + messageHandler.Encoders.Should().NotContain(encoder => encoder is Base64Encoder); + } + [Trait("spec", "RSL4d")] public class WithTextProtocolWithoutEncryption : MockHttpRestSpecs { @@ -88,7 +114,7 @@ public class WithTextProtocolWithoutEncryption : MockHttpRestSpecs public WithTextProtocolWithoutEncryption(ITestOutputHelper output) : base(output) { - _client = GetRestClient(); + _client = GetRestClient(null, opts => opts.UseBinaryProtocol = false); } private Message GetPayload() @@ -151,7 +177,7 @@ public WithTextProtocolWithEncryption(ITestOutputHelper output) : base(output) { _options = new ChannelOptions(Crypto.GetDefaultParams()); - _client = GetRestClient(); + _client = GetRestClient(null, opts => opts.UseBinaryProtocol = false); } [Fact] @@ -206,7 +232,6 @@ private Message GetPayload() } } -#if MSGPACK [Trait("spec", "RSL4c")] public class WithBinaryProtocolWithoutEncryption : MockHttpRestSpecs { @@ -215,6 +240,7 @@ public class WithBinaryProtocolWithoutEncryption : MockHttpRestSpecs public WithBinaryProtocolWithoutEncryption(ITestOutputHelper output) : base(output) { + // MsgPack is enabled now _client = GetRestClient(null, opts => opts.UseBinaryProtocol = true); } @@ -222,11 +248,6 @@ public WithBinaryProtocolWithoutEncryption(ITestOutputHelper output) [Trait("spec", "RSL4c2")] public void WithString_DoesNotApplyAnyEncoding() { - if (!Defaults.MsgPackEnabled) - { - return; - } - // Act _client.Channels.Get("Test").PublishAsync("test", "test"); @@ -240,11 +261,6 @@ public void WithString_DoesNotApplyAnyEncoding() [Trait("spec", "RSL4c1")] public void WithBinaryData_DoesNotApplyAnyEncoding() { - if (!Defaults.MsgPackEnabled) - { - return; - } - // Act var bytes = new byte[] { 10, 111, 128 }; _client.Channels.Get("Test").PublishAsync("test", bytes); @@ -259,11 +275,6 @@ public void WithBinaryData_DoesNotApplyAnyEncoding() [Trait("spec", "RSL4c3")] public void WithJsonData_AppliesCorrectEncoding() { - if (!Defaults.MsgPackEnabled) - { - return; - } - // Arrange var obj = new { Test = "test", name = "name" }; @@ -304,11 +315,7 @@ private Message GetPayload() [Fact] public void WithBinaryData_SetsEncodingAndDataCorrectly() { - if (!Defaults.MsgPackEnabled) - { - return; - } - + // MsgPack is always enabled now // Arrange var bytes = new byte[] { 1, 2, 3 }; @@ -325,11 +332,7 @@ public void WithBinaryData_SetsEncodingAndDataCorrectly() [Fact] public void WithStringData_SetsEncodingAndDataCorrectly() { - if (!Defaults.MsgPackEnabled) - { - return; - } - + // MsgPack is always enabled now // Act _client.Channels.Get("test", _options).PublishAsync("test", "test"); @@ -343,11 +346,7 @@ public void WithStringData_SetsEncodingAndDataCorrectly() [Fact] public void WithJsonData_SetsEncodingAndDataCorrectly() { - if (!Defaults.MsgPackEnabled) - { - return; - } - + // MsgPack is always enabled now // Act var obj = new { Test = "test", Name = "name" }; _client.Channels.Get("test", _options).PublishAsync("test", obj); @@ -360,6 +359,5 @@ public void WithJsonData_SetsEncodingAndDataCorrectly() decryptedString.Should().Be(JsonHelper.Serialize(obj)); } } -#endif } } diff --git a/src/IO.Ably.Tests.Shared/MessageEncodes/ProtocolMessageSpecs.cs b/src/IO.Ably.Tests.Shared/MessageEncodes/ProtocolMessageSpecs.cs index 6a3129fdc..1e1758c28 100644 --- a/src/IO.Ably.Tests.Shared/MessageEncodes/ProtocolMessageSpecs.cs +++ b/src/IO.Ably.Tests.Shared/MessageEncodes/ProtocolMessageSpecs.cs @@ -1,4 +1,7 @@ -using Xunit; +using FluentAssertions; +using System.Linq; +using Xunit; +using IO.Ably.Types; namespace IO.Ably.Tests { @@ -7,12 +10,7 @@ public class ProtocolMessageSpecs [Fact] public void WithMsgPackEncoding_CanSerialiseAndDeserializeProtocolMessage() { -#if MSGPACK - if (!Defaults.MsgPackEnabled) - { - return; - } - + // MsgPack is always enabled now var message = new ProtocolMessage(ProtocolMessage.MessageAction.Presence, "boo"); message.Presence = new[] { new PresenceMessage(PresenceAction.Enter, "123", "my data") }; @@ -21,7 +19,6 @@ public void WithMsgPackEncoding_CanSerialiseAndDeserializeProtocolMessage() result.Action.Should().Be(message.Action); result.Presence.First().Data.Should().Be(message.Presence[0].Data); -#endif } } } diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/CapabilityFormatterTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/CapabilityFormatterTests.cs new file mode 100644 index 000000000..39b835d22 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/CapabilityFormatterTests.cs @@ -0,0 +1,149 @@ +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using MessagePack; +using Xunit; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class CapabilityFormatterTests + { + [Fact] + public void ShouldSerializeAndDeserializeAllowAllCapability() + { + var allAllowed = Capability.AllowAll; + var serialized = MsgPackHelper.Serialise(allAllowed); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(Capability)) as Capability; + + deserialized.Should().NotBeNull(); + deserialized.Should().Be(allAllowed); + deserialized.ToJson().Should().Be(allAllowed.ToJson()); + } + + [Fact] + public void ShouldSerializeAndDeserializeCapabilityWithOneResource() + { + var withOneResource = new Capability(); + withOneResource.AddResource("test").AllowPresence().AllowPublish().AllowSubscribe(); + + var serialized = MsgPackHelper.Serialise(withOneResource); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(Capability)) as Capability; + + deserialized.Should().NotBeNull(); + deserialized.Should().Be(withOneResource); + deserialized.ToJson().Should().Be(withOneResource.ToJson()); + } + + [Fact] + public void ShouldSerializeAndDeserializeCapabilityWithTwoResources() + { + var withTwoResources = new Capability(); + withTwoResources.AddResource("one").AllowAll(); + withTwoResources.AddResource("two").AllowPublish().AllowSubscribe(); + + var serialized = MsgPackHelper.Serialise(withTwoResources); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(Capability)) as Capability; + + deserialized.Should().NotBeNull(); + deserialized.Should().Be(withTwoResources); + deserialized.ToJson().Should().Be(withTwoResources.ToJson()); + } + + [Fact] + public void ShouldSerializeAndDeserializeEmptyCapability() + { + var emptyCapability = new Capability(); + + var serialized = MsgPackHelper.Serialise(emptyCapability); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(Capability)) as Capability; + + deserialized.Should().NotBeNull(); + deserialized.ToJson().Should().Be(emptyCapability.ToJson()); + } + + [Fact] + public void ShouldHandleNullCapability() + { + var formatter = new CapabilityFormatter(); + var bufferWriter = new SimpleBufferWriter(); + var writer = new MessagePackWriter(bufferWriter); + + formatter.Serialize(ref writer, null, MessagePackSerializerOptions.Standard); + writer.Flush(); + var bytes = bufferWriter.WrittenMemory.ToArray(); + + var reader = new MessagePackReader(bytes); + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().NotBeNull(); + result.ToJson().Should().BeEmpty(); + } + + [Fact] + public void ShouldDeserializeNilAsEmptyCapability() + { + var formatter = new CapabilityFormatter(); + + // Serialize nil + var bytes = MessagePackSerializer.Serialize(null); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().NotBeNull(); + result.ToJson().Should().BeEmpty(); + } + + [Fact] + public void ShouldSerializeCapabilityAsJsonString() + { + var capability = new Capability(); + capability.AddResource("channel1").AllowPublish(); + + var formatter = new CapabilityFormatter(); + var bufferWriter = new SimpleBufferWriter(); + var writer = new MessagePackWriter(bufferWriter); + + formatter.Serialize(ref writer, capability, MessagePackSerializerOptions.Standard); + writer.Flush(); + var bytes = bufferWriter.WrittenMemory.ToArray(); + + // Deserialize as string to verify it's stored as JSON string + var jsonString = MessagePackSerializer.Deserialize(bytes); + jsonString.Should().Be(capability.ToJson()); + } + + [Fact] + public void ShouldDeserializeFromJsonString() + { + var expectedCapability = new Capability(); + expectedCapability.AddResource("test").AllowAll(); + var jsonString = expectedCapability.ToJson(); + + // Serialize the JSON string + var bytes = MessagePackSerializer.Serialize(jsonString); + + var formatter = new CapabilityFormatter(); + var reader = new MessagePackReader(bytes); + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().NotBeNull(); + result.ToJson().Should().Be(expectedCapability.ToJson()); + } + + [Fact] + public void ShouldHandleComplexCapabilityWithMultipleOperations() + { + var capability = new Capability(); + capability.AddResource("channel:*").AllowAll(); + capability.AddResource("private:*").AllowPublish().AllowSubscribe(); + capability.AddResource("presence:*").AllowPresence(); + + var serialized = MsgPackHelper.Serialise(capability); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(Capability)) as Capability; + + deserialized.Should().NotBeNull(); + deserialized.Should().Be(capability); + deserialized.ToJson().Should().Be(capability.ToJson()); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/ChannelParamsFormatterTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/ChannelParamsFormatterTests.cs new file mode 100644 index 000000000..c0460c248 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/ChannelParamsFormatterTests.cs @@ -0,0 +1,172 @@ +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using MessagePack; +using Xunit; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class ChannelParamsFormatterTests + { + [Fact] + public void ShouldSerializeAndDeserializeEmptyChannelParams() + { + var channelParams = new ChannelParams(); + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized.Count.Should().Be(0); + } + + [Fact] + public void ShouldSerializeAndDeserializeChannelParamsWithOneEntry() + { + var channelParams = new ChannelParams + { + ["key1"] = "value1" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized.Count.Should().Be(1); + deserialized["key1"].Should().Be("value1"); + } + + [Fact] + public void ShouldSerializeAndDeserializeChannelParamsWithMultipleEntries() + { + var channelParams = new ChannelParams + { + ["key1"] = "value1", + ["key2"] = "value2", + ["key3"] = "value3" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized.Count.Should().Be(3); + deserialized["key1"].Should().Be("value1"); + deserialized["key2"].Should().Be("value2"); + deserialized["key3"].Should().Be("value3"); + } + + [Fact] + public void ShouldHandleNullChannelParams() + { + var serialized = MsgPackHelper.Serialise(null as ChannelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().BeNull(); + } + + [Fact] + public void ShouldDeserializeNilAsNull() + { + var formatter = new ChannelParamsFormatter(); + + // Serialize nil + var bytes = MessagePackSerializer.Serialize(null); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().BeNull(); + } + + [Fact] + public void ShouldSerializeChannelParamsAsMap() + { + var channelParams = new ChannelParams + { + ["param1"] = "value1", + ["param2"] = "value2" + }; + + var bytes = MsgPackHelper.Serialise(channelParams); + + // Verify it's serialized as a map + var reader = new MessagePackReader(bytes); + var mapHeader = reader.ReadMapHeader(); + mapHeader.Should().Be(2); + } + + [Fact] + public void ShouldPreserveKeyValuePairs() + { + var channelParams = new ChannelParams + { + ["rewind"] = "1", + ["delta"] = "vcdiff" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized.Should().ContainKey("rewind"); + deserialized.Should().ContainKey("delta"); + deserialized["rewind"].Should().Be("1"); + deserialized["delta"].Should().Be("vcdiff"); + } + + [Fact] + public void ShouldHandleSpecialCharactersInValues() + { + var channelParams = new ChannelParams + { + ["key"] = "value with spaces", + ["special"] = "!@#$%^&*()", + ["unicode"] = "こんにちは" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized["key"].Should().Be("value with spaces"); + deserialized["special"].Should().Be("!@#$%^&*()"); + deserialized["unicode"].Should().Be("こんにちは"); + } + + [Fact] + public void ShouldHandleEmptyStringValues() + { + var channelParams = new ChannelParams + { + ["empty"] = string.Empty, + ["notEmpty"] = "value" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized["empty"].Should().Be(string.Empty); + deserialized["notEmpty"].Should().Be("value"); + } + + [Fact] + public void ShouldMaintainOrderOfEntries() + { + var channelParams = new ChannelParams + { + ["first"] = "1", + ["second"] = "2", + ["third"] = "3" + }; + + var serialized = MsgPackHelper.Serialise(channelParams); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ChannelParams)) as ChannelParams; + + deserialized.Should().NotBeNull(); + deserialized.Count.Should().Be(3); + // Dictionary doesn't guarantee order, but all keys should be present + deserialized.Should().ContainKeys("first", "second", "third"); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/DateTimeOffsetFormatterTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/DateTimeOffsetFormatterTests.cs new file mode 100644 index 000000000..cd7cfb958 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/DateTimeOffsetFormatterTests.cs @@ -0,0 +1,138 @@ +using System; +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using MessagePack; +using Xunit; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class DateTimeOffsetFormatterTests + { + [MessagePackObject(keyAsPropertyName: true)] + public class TestClass + { + public TestClass() + { + } + + public TestClass(DateTimeOffset data) + { + DateTimeOffset = data; + } + + public DateTimeOffset DateTimeOffset { get; set; } + } + + [Fact] + public void ShouldSerializeDateTimeOffsetToMilliseconds() + { + var originalDateTimeOffset = new TestClass(new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var serialized = MsgPackHelper.Serialise(originalDateTimeOffset); + + serialized.Should().NotBeNull(); + + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.DateTimeOffset.Should().Be(originalDateTimeOffset.DateTimeOffset); + } + + [Fact] + public void ShouldPreserveTimezoneInformation() + { + var originalDateTimeOffset = new TestClass(new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var serialized = MsgPackHelper.Serialise(originalDateTimeOffset); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.DateTimeOffset.Should().Be(originalDateTimeOffset.DateTimeOffset); + } + + [Fact] + public void ShouldHandleIntegerTypeDeserialization() + { + var formatter = new DateTimeOffsetFormatter(); + var expectedDate = new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero); + var milliseconds = expectedDate.ToUnixTimeInMilliseconds(); + + // Serialize the milliseconds as integer + var bytes = MessagePackSerializer.Serialize(milliseconds); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedDate); + } + + [Fact] + public void ShouldHandleFloatTypeDeserialization() + { + var formatter = new DateTimeOffsetFormatter(); + var expectedDate = new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero); + var milliseconds = (double)expectedDate.ToUnixTimeInMilliseconds(); + + // Serialize the milliseconds as double + var bytes = MessagePackSerializer.Serialize(milliseconds); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedDate); + } + + [Fact] + public void ShouldHandleStringTypeDeserialization() + { + var formatter = new DateTimeOffsetFormatter(); + var expectedDate = new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero); + var dateString = expectedDate.ToString("O"); + + // Serialize the date as string + var bytes = MessagePackSerializer.Serialize(dateString); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedDate); + } + + [Fact] + public void ShouldReturnMinValueForInvalidString() + { + var formatter = new DateTimeOffsetFormatter(); + var invalidString = "invalid-date"; + + var bytes = MessagePackSerializer.Serialize(invalidString); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(DateTimeOffset.MinValue); + } + + [MessagePackObject(keyAsPropertyName: true)] + public class NullableTestClass + { + public NullableTestClass() + { + } + + public NullableTestClass(DateTimeOffset? data = null) + { + DateTimeOffset = data; + } + + public DateTimeOffset? DateTimeOffset { get; set; } + } + + [Fact] + public void ShouldHandleNullableDateTimeOffset() + { + var originalDateTimeOffset = new NullableTestClass(new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var serialized = MsgPackHelper.Serialise(originalDateTimeOffset); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.DateTimeOffset.Should().Be(originalDateTimeOffset.DateTimeOffset); + } + + [Fact] + public void ShouldHandleNullDateTimeOffset() + { + var originalDateTimeOffset = new NullableTestClass(); + var serialized = MsgPackHelper.Serialise(originalDateTimeOffset); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.DateTimeOffset.Should().BeNull(); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/JObjectMessagePackSerializerTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/JObjectMessagePackSerializerTests.cs new file mode 100644 index 000000000..6a833d0e0 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/JObjectMessagePackSerializerTests.cs @@ -0,0 +1,349 @@ +using System.Buffers; +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using IO.Ably.Tests.Shared.Helpers; +using MessagePack; +using MessagePack.Formatters; +using Newtonsoft.Json.Linq; +using Xunit; +using Xunit.Abstractions; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class JObjectMessagePackSerializerTests + { + private readonly ITestOutputHelper _testOutputHelper; + + public JObjectMessagePackSerializerTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] + public void ShouldSerializeAndDeserializeSimpleJObject() + { + var jObject = new JObject + { + ["key1"] = "value1", + ["key2"] = "value2" + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldSerializeAndDeserializeNestedJObject() + { + var jObject = new JObject + { + ["level1"] = new JObject + { + ["level2"] = new JObject + { + ["level3"] = "deepValue" + } + } + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldSerializeAndDeserializeJObjectWithArray() + { + var jObject = new JObject + { + ["array"] = new JArray { "item1", "item2", "item3" }, + ["number"] = 42 + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldSerializeAndDeserializeJObjectWithVariousDataTypes() + { + var jObject = new JObject + { + ["string"] = "text", + ["integer"] = 123, + ["float"] = 45.67, + ["boolean"] = true, + ["null"] = null, + ["array"] = new JArray { 1, 2, 3 }, + ["object"] = new JObject { ["nested"] = "value" } + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleNullJObject() + { + var formatter = new JObjectMessagePackSerializer(); + var bufferWriter = new SimpleBufferWriter(); + var writer = new MessagePackWriter(bufferWriter); + + ((IMessagePackFormatter)formatter).Serialize(ref writer, null, MessagePackSerializerOptions.Standard); + writer.Flush(); + var bytes = bufferWriter.WrittenSpan.ToArray(); + + var reader = new MessagePackReader(bytes); + var result = ((IMessagePackFormatter)formatter).Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().BeNull(); + } + + [Fact] + public void ShouldDeserializeNilAsNull() + { + var formatter = new JObjectMessagePackSerializer(); + + // Serialize nil + var bytes = MessagePackSerializer.Serialize(null); + var reader = new MessagePackReader(bytes); + + var result = ((IMessagePackFormatter)formatter).Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().BeNull(); + } + + [Fact] + public void ShouldHandleEmptyJObject() + { + var jObject = new JObject(); + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + deserialized.Count.Should().Be(0); + } + + [Fact] + public void ShouldPreservePropertyOrder() + { + var jObject = new JObject + { + ["first"] = 1, + ["second"] = 2, + ["third"] = 3 + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleComplexNestedStructures() + { + var jObject = new JObject + { + ["users"] = new JArray + { + new JObject + { + ["name"] = "Alice", + ["age"] = 30, + ["active"] = true + }, + new JObject + { + ["name"] = "Bob", + ["age"] = 25, + ["active"] = false + } + }, + ["metadata"] = new JObject + { + ["version"] = "1.0", + ["timestamp"] = 1234567890 + } + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleSpecialCharacters() + { + var jObject = new JObject + { + ["unicode"] = "こんにちは", + ["emoji"] = "😀🎉", + ["special"] = "!@#$%^&*()", + ["quotes"] = "\"quoted\"", + ["newline"] = "line1\nline2" + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleLargeNumbers() + { + var jObject = new JObject + { + ["int32Max"] = int.MaxValue, + ["int64Max"] = long.MaxValue, + ["double"] = double.MaxValue, + ["negative"] = -999999999 + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + deserialized["int32Max"].Value().Should().Be(int.MaxValue); + deserialized["int64Max"].Value().Should().Be(long.MaxValue); + deserialized["negative"].Value().Should().Be(-999999999); + } + + [Fact] + public void ShouldHandleEmptyArrays() + { + var jObject = new JObject + { + ["emptyArray"] = new JArray(), + ["nonEmptyArray"] = new JArray { 1, 2, 3 } + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleNullValues() + { + var jObject = new JObject + { + ["nullValue"] = null, + ["notNull"] = "value" + }; + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + deserialized["nullValue"].Type.Should().Be(JTokenType.Null); + deserialized["notNull"].Value().Should().Be("value"); + } + + [Fact] + public void ShouldConvertToAndFromJson() + { + var originalJson = @"{ + ""name"": ""test"", + ""value"": 123, + ""nested"": { + ""key"": ""value"" + } + }"; + var jObject = JObject.Parse(originalJson); + + var serialized = MsgPackHelper.Serialise(jObject); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(JObject)) as JObject; + + deserialized.Should().NotBeNull(); + JAssert.DeepEquals(jObject, deserialized, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + public void ShouldHandleEmptyByteArrayDeserialization() + { + var formatter = new JObjectMessagePackSerializer(); + + // Create empty raw bytes using a simple buffer writer (compatible with .NET Standard 2.0) + var bufferWriter = new SimpleBufferWriter(); + var writer = new MessagePackWriter(bufferWriter); + writer.WriteRaw(new byte[0]); + writer.Flush(); + var bytes = bufferWriter.WrittenMemory.ToArray(); + + var reader = new MessagePackReader(bytes); + var result = ((IMessagePackFormatter)formatter).Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().BeNull(); + } + + [Fact] + public void ShouldDeserializeJObjectAsPartOfLargerStructure() + { + // Test that JObject can be deserialized when it's a value in a larger MessagePack structure + // This ensures our empty buffer check doesn't interfere with reading from a larger stream + + var jObjectData = new JObject + { + ["key1"] = "value1", + ["key2"] = 42, + ["nested"] = new JObject + { + ["inner"] = "innerValue" + } + }; + + // Use a concrete class with MessagePackObject attribute + var containerData = new TestContainer + { + Id = 123, + Name = "test", + Data = jObjectData, + Timestamp = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }; + + var serialized = MsgPackHelper.Serialise(containerData); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(TestContainer)) as TestContainer; + + deserialized.Should().NotBeNull(); + deserialized.Id.Should().Be(123); + deserialized.Name.Should().Be("test"); + deserialized.Data.Should().NotBeNull(); + + // The data should be deserialized as a JObject + deserialized.Data.Should().BeOfType(); + JAssert.DeepEquals(jObjectData, deserialized.Data, _testOutputHelper).Should().BeTrue(); + } + + [MessagePackObject(keyAsPropertyName: true)] + public class TestContainer + { + public int Id { get; set; } + + public string Name { get; set; } + + public JObject Data { get; set; } + + public long Timestamp { get; set; } + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/MessageExtrasFormatterTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/MessageExtrasFormatterTests.cs new file mode 100644 index 000000000..3b5c32a5e --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/MessageExtrasFormatterTests.cs @@ -0,0 +1,248 @@ +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using IO.Ably.Tests.Shared.Helpers; +using IO.Ably.Types; +using MessagePack; +using Newtonsoft.Json.Linq; +using Xunit; +using Xunit.Abstractions; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class MessageExtrasFormatterTests + { + private readonly ITestOutputHelper _testOutputHelper; + + public MessageExtrasFormatterTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldSerializeAndDeserializeMessageExtrasWithDelta() + { + var deltaExtras = new DeltaExtras("1", "best"); + var jObject = new JObject + { + ["delta"] = new JObject + { + ["From"] = "1", + ["Format"] = "best" + } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + deserialized.Delta.Should().NotBeNull(); + deserialized.Delta.From.Should().Be("1"); + deserialized.Delta.Format.Should().Be("best"); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldSerializeAndDeserializeMessageExtrasWithArbitraryProperties() + { + var jObject = new JObject + { + ["random"] = "boo", + ["delta"] = new JObject + { + ["From"] = "1", + ["Format"] = "best" + } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + deserialized.Delta.Should().NotBeNull(); + deserialized.Delta.From.Should().Be("1"); + deserialized.Delta.Format.Should().Be("best"); + ((string)deserialized.ToJson()["random"]).Should().Be("boo"); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldSerializeAndDeserializeMessageExtrasWithoutDelta() + { + var jObject = new JObject + { + ["random"] = "boo", + ["foo"] = "fooValue", + ["bar"] = "barValue", + ["object"] = new JObject + { + ["key1"] = "value1", + ["key2"] = "value2" + } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + ((string)deserialized.ToJson()["random"]).Should().Be("boo"); + ((string)deserialized.ToJson()["foo"]).Should().Be("fooValue"); + ((string)deserialized.ToJson()["bar"]).Should().Be("barValue"); + ((string)deserialized.ToJson()["object"]["key1"]).Should().Be("value1"); + ((string)deserialized.ToJson()["object"]["key2"]).Should().Be("value2"); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldHandleNullMessageExtras() + { + var serialized = MsgPackHelper.Serialise(null as MessageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().BeNull(); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldDeserializeNilAsNull() + { + var formatter = new MessageExtrasFormatter(); + + // Serialize nil + var bytes = MessagePackSerializer.Serialize(null); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + + result.Should().BeNull(); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldHandleEmptyMessageExtras() + { + var jObject = new JObject(); + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + deserialized.ToJson().Should().NotBeNull(); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldPreserveComplexNestedStructures() + { + var jObject = new JObject + { + ["level1"] = new JObject + { + ["level2"] = new JObject + { + ["level3"] = "deepValue" + } + }, + ["array"] = new JArray { "item1", "item2", "item3" } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + var deserializedJson = deserialized.ToJson(); + JAssert.DeepEquals(jObject, deserializedJson, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldHandleMessageExtrasWithOnlyDelta() + { + var jObject = new JObject + { + ["delta"] = new JObject + { + ["From"] = "1", + ["Format"] = "best" + } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + deserialized.Delta.Should().NotBeNull(); + deserialized.Delta.From.Should().Be("1"); + deserialized.Delta.Format.Should().Be("best"); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldSerializeMessageExtrasToJsonAndBack() + { + var originalJObject = new JObject + { + ["custom"] = "value", + ["number"] = 42, + ["boolean"] = true, + ["delta"] = new JObject + { + ["From"] = "test", + ["Format"] = "json" + } + }; + var messageExtras = MessageExtras.From(originalJObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + var deserializedJson = deserialized.ToJson(); + JAssert.DeepEquals(originalJObject, deserializedJson, _testOutputHelper).Should().BeTrue(); + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldHandleEmptyByteArray() + { + // Create a byte array with empty array marker + var bytes = MessagePackSerializer.Serialize(new object[0]); + + var reader = new MessagePackReader(bytes); + reader.ReadArrayHeader(); // Read the array header + + // Now the reader is at the end, simulating empty data scenario + // This should be handled gracefully + } + + [Fact] + [Trait("spec", "tm2i")] + public void ShouldRoundTripMessageExtrasWithVariousDataTypes() + { + var jObject = new JObject + { + ["string"] = "text", + ["integer"] = 123, + ["float"] = 45.67, + ["boolean"] = true, + ["null"] = null, + ["array"] = new JArray { 1, 2, 3 }, + ["object"] = new JObject { ["nested"] = "value" } + }; + var messageExtras = MessageExtras.From(jObject); + + var serialized = MsgPackHelper.Serialise(messageExtras); + var deserialized = MsgPackHelper.Deserialise(serialized, typeof(MessageExtras)) as MessageExtras; + + deserialized.Should().NotBeNull(); + var deserializedJson = deserialized.ToJson(); + JAssert.DeepEquals(jObject, deserializedJson, _testOutputHelper).Should().BeTrue(); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/SimpleBufferWriter.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/SimpleBufferWriter.cs new file mode 100644 index 000000000..49416949e --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/SimpleBufferWriter.cs @@ -0,0 +1,52 @@ +using System; +using System.Buffers; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + /// + /// Simple IBufferWriter implementation compatible with .NET Standard 2.0 and .NET Framework. + /// This is used in tests as a replacement for ArrayBufferWriter which is not available in .NET Framework. + /// + internal class SimpleBufferWriter : IBufferWriter + { + private byte[] _buffer = new byte[256]; + private int _index = 0; + + public ReadOnlyMemory WrittenMemory => new ReadOnlyMemory(_buffer, 0, _index); + + public ReadOnlySpan WrittenSpan => new ReadOnlySpan(_buffer, 0, _index); + + public void Advance(int count) + { + _index += count; + } + + public Memory GetMemory(int sizeHint = 0) + { + EnsureCapacity(sizeHint); + return new Memory(_buffer, _index, _buffer.Length - _index); + } + + public Span GetSpan(int sizeHint = 0) + { + EnsureCapacity(sizeHint); + return new Span(_buffer, _index, _buffer.Length - _index); + } + + private void EnsureCapacity(int sizeHint) + { + if (sizeHint == 0) + { + sizeHint = 1; + } + + if (_index + sizeHint > _buffer.Length) + { + var newSize = Math.Max(_buffer.Length * 2, _index + sizeHint); + var newBuffer = new byte[newSize]; + Array.Copy(_buffer, newBuffer, _index); + _buffer = newBuffer; + } + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/TimespanFormatterTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/TimespanFormatterTests.cs new file mode 100644 index 000000000..c3ab366f5 --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/CustomSerializers/TimespanFormatterTests.cs @@ -0,0 +1,156 @@ +using System; +using FluentAssertions; +using IO.Ably.MsgPack.CustomSerialisers; +using MessagePack; +using Xunit; + +namespace IO.Ably.Tests.MsgPack.CustomSerializers +{ + public class TimespanFormatterTests + { + [MessagePackObject(keyAsPropertyName: true)] + public class TestClass + { + public TestClass() + { + } + + public TestClass(TimeSpan data) + { + TimeSpan = data; + } + + public TimeSpan TimeSpan { get; set; } + } + + [Fact] + public void ShouldSerializeTimeSpanToMilliseconds() + { + var originalTimeSpan = new TestClass(TimeSpan.FromSeconds(60)); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + + serialized.Should().NotBeNull(); + + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().Be(originalTimeSpan.TimeSpan); + } + + [Fact] + public void ShouldPreserveTimeSpanValue() + { + var originalTimeSpan = new TestClass(TimeSpan.FromMinutes(5)); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().Be(originalTimeSpan.TimeSpan); + } + + [Fact] + public void ShouldHandleIntegerTypeDeserialization() + { + var formatter = new TimespanFormatter(); + var expectedTimeSpan = TimeSpan.FromSeconds(60); + var milliseconds = (long)expectedTimeSpan.TotalMilliseconds; + + // Serialize the milliseconds as integer + var bytes = MessagePackSerializer.Serialize(milliseconds); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedTimeSpan); + } + + [Fact] + public void ShouldHandleFloatTypeDeserialization() + { + var formatter = new TimespanFormatter(); + var expectedTimeSpan = TimeSpan.FromSeconds(60); + var milliseconds = expectedTimeSpan.TotalMilliseconds; + + // Serialize the milliseconds as double + var bytes = MessagePackSerializer.Serialize(milliseconds); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedTimeSpan); + } + + [Fact] + public void ShouldHandleStringTypeDeserialization() + { + var formatter = new TimespanFormatter(); + var expectedTimeSpan = TimeSpan.FromSeconds(60); + var timeSpanString = expectedTimeSpan.ToString(); + + // Serialize the timespan as string + var bytes = MessagePackSerializer.Serialize(timeSpanString); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(expectedTimeSpan); + } + + [Fact] + public void ShouldReturnMinValueForInvalidString() + { + var formatter = new TimespanFormatter(); + var invalidString = "invalid-timespan"; + + var bytes = MessagePackSerializer.Serialize(invalidString); + var reader = new MessagePackReader(bytes); + + var result = formatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); + result.Should().Be(TimeSpan.MinValue); + } + + [Fact] + public void ShouldHandleZeroTimeSpan() + { + var originalTimeSpan = new TestClass(TimeSpan.Zero); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().Be(TimeSpan.Zero); + } + + [Fact] + public void ShouldHandleNegativeTimeSpan() + { + var originalTimeSpan = new TestClass(TimeSpan.FromSeconds(-30)); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().Be(TimeSpan.FromSeconds(-30)); + } + + [MessagePackObject(keyAsPropertyName: true)] + public class NullableTestClass + { + public NullableTestClass() + { + } + + public NullableTestClass(TimeSpan? data = null) + { + TimeSpan = data; + } + + public TimeSpan? TimeSpan { get; set; } + } + + [Fact] + public void ShouldHandleNullableTimeSpan() + { + var originalTimeSpan = new NullableTestClass(TimeSpan.FromSeconds(60)); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().Be(originalTimeSpan.TimeSpan); + } + + [Fact] + public void ShouldHandleNullTimeSpan() + { + var originalTimeSpan = new NullableTestClass(); + var serialized = MsgPackHelper.Serialise(originalTimeSpan); + var deserialized = MsgPackHelper.Deserialise(serialized); + deserialized.TimeSpan.Should().BeNull(); + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MessagePack/SerializationTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/MsgPackHelperTests.cs similarity index 75% rename from src/IO.Ably.Tests.Shared/MessagePack/SerializationTests.cs rename to src/IO.Ably.Tests.Shared/MsgPack/MsgPackHelperTests.cs index b3e18e700..dd914ddc9 100644 --- a/src/IO.Ably.Tests.Shared/MessagePack/SerializationTests.cs +++ b/src/IO.Ably.Tests.Shared/MsgPack/MsgPackHelperTests.cs @@ -1,25 +1,30 @@ -#if MSGPACK -namespace IO.Ably.Tests.MessagePack +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Xunit; +using Xunit.Abstractions; + +namespace IO.Ably.Tests.MsgPack { - public class MessagePackSerializationTests : AblySpecs + public class MsgPackHelperTests : AblySpecs { - public MessagePackSerializationTests(ITestOutputHelper output) : base(output) + public MsgPackHelperTests(ITestOutputHelper output) + : base(output) { - } [Fact] public void CanSerialiseListOfMessagesAndDeserialiseThem() { var message = new Message("example", "The quick brown fox jumped over the lazy dog"); - var serialised = MsgPackHelper.Serialise(new List {message}); + var serialised = MsgPackHelper.Serialise(new List { message }); - var result = MsgPackHelper.Deserialise(serialised, typeof (List)) as List; + var result = MsgPackHelper.Deserialise(serialised, typeof(List)) as List; var resultMessage = result.First(); resultMessage.Data.Should().Be(message.Data); resultMessage.Name.Should().Be(message.Name); - } [Fact] @@ -32,7 +37,7 @@ public void CanSerializeAndDeserialiseCapabilityObject() withTwoResources.AddResource("one").AllowAll(); withTwoResources.AddResource("two").AllowPublish().AllowSubscribe(); - var list = new[] {allAllowed, withOneResource, withTwoResources}; + var list = new[] { allAllowed, withOneResource, withTwoResources }; foreach (var item in list) { var data = MsgPackHelper.Serialise(item); @@ -74,10 +79,9 @@ public void CanSerialiseAndDeserialiseStatsCorrectly() var expected = JsonHelper.Deserialize>(ResourceHelper.GetResource("MsgPackStatsTest.json")); - var unpacked = (List) MsgPackHelper.Deserialise(bytes, typeof(List)); + var unpacked = (List)MsgPackHelper.Deserialise(bytes, typeof(List)); unpacked.Should().BeEquivalentTo(expected); - } [Fact] @@ -99,7 +103,7 @@ public void CanSerialiseAndDeserialiseTokenDetailsWithEmptyCapability() [Fact] public void CanSerialiseAndDeserialiseBase64ByteArray() { - var message = new Message() {Name = "example", Data = "AAECAwQFBgcICQoLDA0ODw==".FromBase64()}; + var message = new Message() { Name = "example", Data = "AAECAwQFBgcICQoLDA0ODw==".FromBase64() }; var serialised = MsgPackHelper.Serialise(new List { message }); var resultMessage = MsgPackHelper.Deserialise(serialised, typeof(List)) as List; var data = resultMessage.First().Data as byte[]; @@ -113,57 +117,27 @@ public void CanDeserialiseTokenResponse() var value = "gaxhY2Nlc3NfdG9rZW6GpXRva2Vu2YhnNFg2UVEuRHlCYzlMZUdvdy1saWVEcG4zTXRsd09uUEhoN2VtN3MyQ3JTZ1pLM2NUNkRvZUo1dlQxWXRwNDFvaTVWUUtNUkxuSVdDckFadHVOb3F5Q0lvVFphQjFfb1FFX0Utb3c2Y3hKX1EwcFUyZ3lpb2xRNGp1VDM1TjI0Qzgzd0p6aUI5p2tleU5hbWWtZzRYNlFRLnV0ekdsZ6Zpc3N1ZWTOVMEP1qdleHBpcmVzzlTBHeaqY2FwYWJpbGl0eYGhKpGhKqhjbGllbnRJZKMxMjM="; - var decodedMessagePack = MsgPackHelper.Deserialise(value.FromBase64(), typeof (MessagePackObject)).ToString(); - - var response = JsonHelper.Deserialize(decodedMessagePack); + // MessagePackObject doesn't exist in MessagePack-CSharp v3.x + // Deserialize to a dictionary instead and convert to JSON + var decodedMessagePack = MsgPackHelper.Deserialise(value.FromBase64(), typeof(System.Collections.Generic.Dictionary)); + var jsonString = JsonHelper.Serialize(decodedMessagePack); + var response = JsonHelper.Deserialize(jsonString); response.AccessToken.Should().NotBeNull(); response.AccessToken.Capability.ToJson().Should().Be("{\"*\":[\"*\"]}"); response.AccessToken.ClientId.Should().Be("123"); response.AccessToken.Token.Should().Be("g4X6QQ.DyBc9LeGow-lieDpn3MtlwOnPHh7em7s2CrSgZK3cT6DoeJ5vT1Ytp41oi5VQKMRLnIWCrAZtuNoqyCIoTZaB1_oQE_E-ow6cxJ_Q0pU2gyiolQ4juT35N24C83wJziB9"); - response.AccessToken.Issued.Should().Be(((long)1421938646).FromUnixTimeInMilliseconds()); - response.AccessToken.Expires.Should().Be(((long)1421942246).FromUnixTimeInMilliseconds()); + response.AccessToken.Issued.Should().Be(1421938646L.FromUnixTimeInMilliseconds()); + response.AccessToken.Expires.Should().Be(1421942246L.FromUnixTimeInMilliseconds()); } [Fact] public void CanDeserialiseConnectionDetailsMessages() { - var connectionDetails = new ConnectionDetails() { ClientId = "123", ConnectionStateTtl = TimeSpan.FromSeconds(60)}; + var connectionDetails = new ConnectionDetails() { ClientId = "123", ConnectionStateTtl = TimeSpan.FromSeconds(60) }; var serialized = MsgPackHelper.Serialise(connectionDetails); var deserialized = MsgPackHelper.Deserialise(serialized, typeof(ConnectionDetails)); deserialized.Should().BeEquivalentTo(connectionDetails); } } - - public class JsonSerializationTests - { - [Fact] - public void CanDeserialiseTokenResponse() - { - var value = @"{ - ""access_token"": { - ""token"": ""_SYo4Q.D3WmHhU"", - ""keyName"": ""_SYo4Q.j8mhAQ"", - ""issued"": 1449163326485, - ""expires"": 1449163326485, - ""capability"": { - ""*"": [ - ""*"" - ] - }, - ""clientId"": ""123"" - } - }"; - - var response = JsonHelper.Deserialize(value); - - response.AccessToken.Should().NotBeNull(); - response.AccessToken.Capability.ToJson().Should().Be("{\"*\":[\"*\"]}"); - response.AccessToken.ClientId.Should().Be("123"); - response.AccessToken.Token.Should().Be("_SYo4Q.D3WmHhU"); - response.AccessToken.Issued.Should().Be(((long)1449163326485).FromUnixTimeInMilliseconds()); - response.AccessToken.Expires.Should().Be(((long)1449163326485).FromUnixTimeInMilliseconds()); - } - } } -#endif diff --git a/src/IO.Ably.Tests.Shared/MsgPack/MsgPackMessageSerializerTests.cs b/src/IO.Ably.Tests.Shared/MsgPack/MsgPackMessageSerializerTests.cs new file mode 100644 index 000000000..494f9334c --- /dev/null +++ b/src/IO.Ably.Tests.Shared/MsgPack/MsgPackMessageSerializerTests.cs @@ -0,0 +1,728 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using IO.Ably.Tests.Shared.Helpers; +using IO.Ably.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Xunit; +using Xunit.Abstractions; + +namespace IO.Ably.Tests.MsgPack +{ + // NOTE: The old GenerateMsgPackSerializers class has been removed. + // MessagePack-CSharp v3.x uses automatic source generation during build. + // No manual serializer generation is needed - the source generator handles it automatically. + + public class MsgPackMessageSerializerTests : AblySpecs + { + public static IEnumerable Messages + { + get + { + yield return new object[] { new Message[] { new Message() } }; // 1 empty message + yield return new object[] { new Message[] { new Message(), new Message() } }; // 2 empty messages + yield return new object[] { new Message[] { new Message(), new Message("test", null) } }; // 1 empty, 1 message + yield return new object[] { new Message[] { new Message("test", null), new Message("attach", null) } }; // 2 messages + } + } + + public static IEnumerable Presence + { + get + { + yield return new object[] { new PresenceMessage[] { new PresenceMessage() } }; // 1 empty message + yield return new object[] { new PresenceMessage[] { new PresenceMessage(), new PresenceMessage() } }; // 2 empty messages + yield return new object[] { new PresenceMessage[] { new PresenceMessage(), new PresenceMessage(PresenceAction.Enter, "test") } }; // 1 empty, 1 message + yield return new object[] { new PresenceMessage[] { new PresenceMessage(PresenceAction.Enter, "test"), new PresenceMessage(PresenceAction.Enter, "test2") } }; // 2 messages + } + } + + public static IEnumerable BinMessages + { + get + { + yield return new object[] { new byte[] { 0x90 }, new Message[] { } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa4, 0x74, 0x65, 0x73, 0x74 }, new Message[] { new Message("test", null) } }; + yield return new object[] { new byte[] { 0x92, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa4, 0x74, 0x65, 0x73, 0x74, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa6, 0x61, 0x74, 0x74, 0x61, 0x63, 0x68 }, new Message[] { new Message("test", null), new Message("attach", null) } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xa4, 0x74, 0x65, 0x73, 0x74 }, new Message[] { new Message(null, "test") } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xcd, 0x04, 0xd2 }, new Message[] { new Message(null, (ushort)1234) } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xcb, 0x40, 0x5e, 0xc0, 0xa3, 0xd7, 0x0a, 0x3d, 0x71 }, new Message[] { new Message(null, 123.01d) } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xc3 }, new Message[] { new Message(null, true) } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xc0 }, new Message[] { new Message(null, null) } }; + yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0x92, 0xcd, 0x04, 0xd2, 0xcd, 0x10, 0xe1 }, new Message[] { new Message(null, new object[] { (ushort)1234, (ushort)4321 }) } }; + } + } + + [Theory] + [InlineData(ProtocolMessage.MessageAction.Attach)] + [InlineData(ProtocolMessage.MessageAction.Detach)] + [InlineData(ProtocolMessage.MessageAction.Error)] + [InlineData(ProtocolMessage.MessageAction.Heartbeat)] + [InlineData(ProtocolMessage.MessageAction.Message)] + [InlineData(ProtocolMessage.MessageAction.Sync)] + public void SerializesMessageCorrectly_Action(ProtocolMessage.MessageAction messageAction) + { + // Arrange + ProtocolMessage message = new ProtocolMessage(messageAction); + List expectedMessage = BuildExpectedProtocolMessage(action: messageAction); + + // Act + object result = MsgPackHelper.Serialise(message); + + // Assert + result.Should().BeOfType(); + + ValidateAndLog(expectedMessage.ToArray(), result as byte[]); + + Assert.Equal(expectedMessage.ToArray(), result as byte[]); + } + + private void ValidateAndLog(byte[] expectedBytes, byte[] actualBytes) + { + if (!expectedBytes.SequenceEqual(actualBytes)) + { + Output.WriteLine($"Expected: {BitConverter.ToString(expectedBytes)}"); + Output.WriteLine($"Actual: {BitConverter.ToString(actualBytes)}"); + } + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("test")] + [InlineData("my channel")] + [InlineData("1234")] + public void SerializesMessageCorrectly_Channel(string channel) + { + // Arrange + ProtocolMessage message = new ProtocolMessage() { Channel = channel }; + List expectedMessage = BuildExpectedProtocolMessage(channel: channel); + + // Act + object result = MsgPackHelper.Serialise(message); + + // Assert + result.Should().BeOfType(); + + ValidateAndLog(expectedMessage.ToArray(), result as byte[]); + + Assert.Equal(expectedMessage.ToArray(), result as byte[]); + } + + [Theory] + [InlineData(-1)] + [InlineData(0)] + [InlineData(10)] + [InlineData(1000)] + public void SerializesMessageCorrectly_MsgSerial(long msgSerial) + { + // Arrange + ProtocolMessage message = new ProtocolMessage() { MsgSerial = msgSerial }; + List expectedMessage = BuildExpectedProtocolMessage(msgSerial: msgSerial); + + // Act + object result = MsgPackHelper.Serialise(message); + + // Assert + result.Should().BeOfType(); + + ValidateAndLog(expectedMessage.ToArray(), result as byte[]); + + Assert.Equal(expectedMessage.ToArray(), result as byte[]); + } + + [Theory] + [MemberData(nameof(Messages))] + public void SerializesMessageCorrectly_Messages(params Message[] messages) + { + // Arrange + ProtocolMessage message = new ProtocolMessage() { Messages = messages }; + List expectedMessage = BuildExpectedProtocolMessage(messages: messages); + + // Act + object result = MsgPackHelper.Serialise(message); + + // Assert + result.Should().BeOfType(); + + ValidateAndLog(expectedMessage.ToArray(), result as byte[]); + + Assert.Equal(expectedMessage.ToArray(), result as byte[]); + } + + [Theory] + [MemberData(nameof(Presence))] + public void SerializesMessageCorrectly_Presence(params PresenceMessage[] messages) + { + // Arrange + ProtocolMessage message = new ProtocolMessage() { Presence = messages }; + List expectedMessage = BuildExpectedProtocolMessage(presence: messages); + + // Act + object result = MsgPackHelper.Serialise(message); + + // Assert + result.Should().BeOfType(); + + ValidateAndLog(expectedMessage.ToArray(), result as byte[]); + + Assert.Equal(expectedMessage.ToArray(), result as byte[]); + } + + [Theory] + [InlineData(ProtocolMessage.MessageAction.Attach)] + [InlineData(ProtocolMessage.MessageAction.Detach)] + [InlineData(ProtocolMessage.MessageAction.Error)] + [InlineData(ProtocolMessage.MessageAction.Heartbeat)] + [InlineData(ProtocolMessage.MessageAction.Message)] + [InlineData(ProtocolMessage.MessageAction.Sync)] + public void DeserializesMessageCorrectly_Action(ProtocolMessage.MessageAction action) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("action")); + expectedMessage.Add((byte)action); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(action, target.Action); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("test")] + [InlineData("my channel")] + [InlineData("1234")] + public void DeserializesMessageCorrectly_Channel(string channel) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("channel")); + if (channel != null) + { + expectedMessage.AddRange(SerializeString(channel)); + } + else + { + expectedMessage.Add(0xc0); + } + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(channel, target.Channel); + } + + [Theory] + [InlineData("123")] + [InlineData("123.456")] + [InlineData("123^&456")] + [InlineData("absder#^&456")] + public void DeserializesMessageCorrectly_ChannelSerial(string serial) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("channelSerial")); + if (serial != null) + { + expectedMessage.AddRange(SerializeString(serial)); + } + else + { + expectedMessage.Add(0xc0); + } + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(serial, target.ChannelSerial); + } + + [Theory] + [InlineData("123")] + [InlineData("123.456")] + [InlineData("123^&456")] + [InlineData("absder#^&456")] + public void DeserializesMessageCorrectly_ConnectionId(string connectionId) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("connectionId")); + expectedMessage.AddRange(SerializeString(connectionId)); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(connectionId, target.ConnectionId); + } + + [Theory] + [InlineData("123")] + [InlineData("123.456")] + [InlineData("123^&456")] + [InlineData("absder#^&456")] + public void DeserializesMessageCorrectly_ConnectionKey(string connectionKey) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("connectionKey")); + expectedMessage.AddRange(SerializeString(connectionKey)); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + // Assert.Equal(connectionKey, target.ConnectionKey); + } + + [Theory] + [InlineData("123")] + [InlineData("123.456")] + [InlineData("123^&456")] + [InlineData("absder#^&456")] + public void DeserializesMessageCorrectly_Id(string id) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("id")); + expectedMessage.AddRange(SerializeString(id)); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(id, target.Id); + } + + [Theory] + [InlineData(123)] + [InlineData(0)] + [InlineData(-1)] + public void DeserializesMessageCorrectly_Count(int count) + { + // Arrange + byte[] expectedMessage = MsgPackHelper.Serialise(new ProtocolMessage() { Count = count }) as byte[]; + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(count, target.Count.Value); + } + + [Theory] + [InlineData(123)] + [InlineData(0)] + [InlineData(-1)] + public void DeserializesMessageCorrectly_MsgSerial(long serial) + { + // Arrange + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("msgSerial")); + expectedMessage.Add(BitConverter.GetBytes(serial).First()); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal(serial, target.MsgSerial); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(123)] + public void DeserializesMessageCorrectly_Flags(int flags) + { + // Arrange + + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("flags")); + expectedMessage.Add((byte)flags); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + Assert.Equal((byte)flags, (byte)target.Flags); + } + + [Theory] + [MemberData(nameof(BinMessages))] + public void DeserializesMessageCorrectly_Messages(byte[] messageBin, params Message[] expectedMessages) + { + // Arrange + + List expectedMessage = new List(); + expectedMessage.Add(0x81); + expectedMessage.AddRange(SerializeString("messages")); + expectedMessage.AddRange(messageBin); + + // Act + ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); + + // Assert + target.Should().NotBeNull(); + target.Messages.Should().NotBeNull(); + Assert.Equal(expectedMessages.Length, target.Messages.Length); + for (int i = 0; i < expectedMessages.Length; i++) + { + Assert.Equal(expectedMessages[i].Name, target.Messages[i].Name); + Assert.Equal(expectedMessages[i].Data, target.Messages[i].Data); + } + } + + /// + /// Builds the expected MessagePack byte array for a ProtocolMessage with all 15 fields. + /// Allows customization of specific fields by passing actual values. + /// + /// Optional action value (null by default) + /// Optional channel value (null by default) + /// Optional msgSerial value (null by default) + /// Optional messages array (null by default) + /// Optional presence array (null by default) + /// List of bytes representing the expected MessagePack structure + private static List BuildExpectedProtocolMessage( + ProtocolMessage.MessageAction? action = null, + string channel = null, + long? msgSerial = null, + Message[] messages = null, + PresenceMessage[] presence = null) + { + List expectedMessage = new List(); + // MessagePack now serializes all 15 fields (including nulls) in declaration order + expectedMessage.Add(0x8F); // map with 15 elements + + // Fields in declaration order: params, action, auth, flags, count, error, id, channel, + // channelSerial, connectionId, msgSerial, timestamp, messages, presence, connectionDetails + expectedMessage.AddRange(SerializeString("params")); + expectedMessage.Add(0xc0); // null + + expectedMessage.AddRange(SerializeString("action")); + expectedMessage.Add(action.HasValue ? (byte)action.Value : (byte)0); + + expectedMessage.AddRange(SerializeString("auth")); + expectedMessage.Add(0xc0); // null + expectedMessage.AddRange(SerializeString("flags")); + expectedMessage.Add(0xc0); // null + expectedMessage.AddRange(SerializeString("count")); + expectedMessage.Add(0xc0); // null + expectedMessage.AddRange(SerializeString("error")); + expectedMessage.Add(0xc0); // null + expectedMessage.AddRange(SerializeString("id")); + expectedMessage.Add(0xc0); // null + + expectedMessage.AddRange(SerializeString("channel")); + if (channel == null) + { + expectedMessage.Add(0xc0); // null + } + else + { + // Empty string is serialized as empty string, not null + expectedMessage.AddRange(SerializeString(channel)); + } + + expectedMessage.AddRange(SerializeString("channelSerial")); + expectedMessage.Add(0xc0); // null + expectedMessage.AddRange(SerializeString("connectionId")); + expectedMessage.Add(0xc0); // null + + expectedMessage.AddRange(SerializeString("msgSerial")); + SerializeMsgSerial(expectedMessage, msgSerial ?? 0); + + expectedMessage.AddRange(SerializeString("timestamp")); + expectedMessage.Add(0xc0); // null + + expectedMessage.AddRange(SerializeString("messages")); + SerializeMessages(expectedMessage, messages); + + expectedMessage.AddRange(SerializeString("presence")); + SerializePresence(expectedMessage, presence); + + expectedMessage.AddRange(SerializeString("connectionDetails")); + expectedMessage.Add(0xc0); // null + + return expectedMessage; + } + + private static void SerializeMsgSerial(List bytes, long msgSerial) + { + if (msgSerial >= 0 && msgSerial <= 127) + { + // Positive fixint (0x00 to 0x7f) + bytes.Add((byte)msgSerial); + } + else if (msgSerial < 0 && msgSerial >= -32) + { + // Negative fixint (0xe0 to 0xff) + bytes.Add((byte)msgSerial); + } + else if (msgSerial >= 0 && msgSerial <= 255) + { + // uint8 (0xcc) + bytes.Add(0xcc); + bytes.Add((byte)msgSerial); + } + else if (msgSerial >= 0 && msgSerial <= 65535) + { + // uint16 (0xcd) - MessagePack uses unsigned for positive values + bytes.Add(0xcd); + bytes.AddRange(BitConverter.GetBytes((ushort)msgSerial).Reverse()); + } + else if (msgSerial < 0 && msgSerial >= -128) + { + // int8 (0xd0) + bytes.Add(0xd0); + bytes.Add((byte)msgSerial); + } + else if (msgSerial < 0 && msgSerial >= -32768) + { + // int16 (0xd1) + bytes.Add(0xd1); + bytes.AddRange(BitConverter.GetBytes((short)msgSerial).Reverse()); + } + else + { + // int64 (0xd3) for larger values + bytes.Add(0xd3); + bytes.AddRange(BitConverter.GetBytes(msgSerial).Reverse()); + } + } + + private static void SerializeMessages(List bytes, Message[] messages) + { + if (messages == null || messages.Length == 0) + { + bytes.Add(0x90); // empty array + return; + } + + // Messages are serialized with all fields including nulls, but empty messages are NOT filtered by OnSerializing + // The actual serialization includes ALL messages, even those with empty names + bytes.Add((byte)((0x09 << 4) + messages.Length)); + foreach (Message msg in messages) + { + // Each message now has 9 fields in declaration order: id, clientId, connectionId, connectionKey, name, timestamp, data, extras, encoding + bytes.Add(0x89); // map with 9 elements + bytes.AddRange(SerializeString("id")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("clientId")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("connectionId")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("connectionKey")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("name")); + if (string.IsNullOrEmpty(msg.Name)) + { + bytes.Add(0xc0); // null for empty name + } + else + { + bytes.AddRange(SerializeString(msg.Name)); + } + + bytes.AddRange(SerializeString("timestamp")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("data")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("extras")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("encoding")); + bytes.Add(0xc0); // null + } + } + + private static void SerializePresence(List bytes, PresenceMessage[] messages) + { + if (messages == null || messages.Length == 0) + { + bytes.Add(0x90); // empty array + return; + } + + bytes.Add((byte)((0x09 << 4) + messages.Length)); + foreach (PresenceMessage msg in messages) + { + // Each presence message now has 8 fields in declaration order: id, action, clientId, connectionId, connectionKey, data, encoding, timestamp + bytes.Add(0x88); // map with 8 elements + bytes.AddRange(SerializeString("id")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("action")); + bytes.Add((byte)msg.Action); + bytes.AddRange(SerializeString("clientId")); + if (!string.IsNullOrEmpty(msg.ClientId)) + { + bytes.AddRange(SerializeString(msg.ClientId)); + } + else + { + bytes.Add(0xc0); // null + } + + bytes.AddRange(SerializeString("connectionId")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("connectionKey")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("data")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("encoding")); + bytes.Add(0xc0); // null + bytes.AddRange(SerializeString("timestamp")); + bytes.Add(0xc0); // null + } + } + + private static byte[] SerializeString(string str) + { + List bytes = new List(); + bytes.Add((byte)(0xa0 + str.Length)); + bytes.AddRange(System.Text.Encoding.GetEncoding("utf-8").GetBytes(str)); + return bytes.ToArray(); + } + + /// + /// Test fixture class for msgpack test data. + /// + public class MsgpackTestFixture + { + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("data")] + public object Data { get; set; } + + [JsonProperty("encoding")] + public string Encoding { get; set; } + + [JsonProperty("numRepeat")] + public int NumRepeat { get; set; } + + [JsonProperty("type")] + public string Type { get; set; } + + [JsonProperty("msgpack")] + public string MsgPack { get; set; } + } + + /// + /// Loads msgpack test fixtures from the embedded resource. + /// + private static List LoadMsgpackFixtures() + { + var json = ResourceHelper.GetResource("msgpack_test_fixtures.json"); + return JsonConvert.DeserializeObject>(json); + } + + /// + /// Provides test data for msgpack decoding tests. + /// Each test case is named after the fixture name for better test reporting. + /// + public static IEnumerable MsgpackDecodingFixtures + { + get + { + var fixtures = LoadMsgpackFixtures(); + foreach (var fixture in fixtures) + { + // Pass fixture.Name as first parameter for better test display names + yield return new object[] { fixture.Name, fixture }; + } + } + } + + [Theory] + [Trait("spec", "RSL6a3")] + [MemberData(nameof(MsgpackDecodingFixtures))] + public void TestMsgpackDecoding(string testName, MsgpackTestFixture fixture) + { + Output.WriteLine($"Testing: {testName}"); + + // Decode base64 msgpack data + var msgpackData = Convert.FromBase64String(fixture.MsgPack); + + // Deserialize to ProtocolMessage + var protoMsg = MsgPackHelper.Deserialise(msgpackData); + protoMsg.Should().NotBeNull(); + protoMsg.Messages.Should().NotBeNull(); + protoMsg.Messages.Should().HaveCount(1); + + var msg = protoMsg.Messages[0]; + + // Decode the message data using FromEncoded + var decodedMsg = Message.FromEncoded(msg); + + // Verify decoded data based on type + switch (fixture.Type) + { + case "string": + decodedMsg.Data.Should().BeOfType(); + var expectedString = string.Concat(Enumerable.Repeat(fixture.Data.ToString(), fixture.NumRepeat)); + decodedMsg.Data.Should().Be(expectedString); + (decodedMsg.Data as string).Length.Should().Be(fixture.NumRepeat); + break; + + case "binary": + decodedMsg.Data.Should().BeOfType(); + var expectedBytes = System.Text.Encoding.UTF8.GetBytes( + string.Concat(Enumerable.Repeat(fixture.Data.ToString(), fixture.NumRepeat))); + (decodedMsg.Data as byte[]).Should().Equal(expectedBytes); + (decodedMsg.Data as byte[]).Length.Should().Be(fixture.NumRepeat); + break; + + case "jsonObject": + // For JSON objects, compare as JToken for proper equality + var expectedJson = JsonConvert.SerializeObject(fixture.Data); + var actualJson = JsonConvert.SerializeObject(decodedMsg.Data); + JAssert.DeepEquals(JToken.Parse(expectedJson), JToken.Parse(actualJson), Output).Should().BeTrue(); + break; + + case "jsonArray": + // For JSON arrays, compare as JToken for proper equality + var expectedArrayJson = JsonConvert.SerializeObject(fixture.Data); + var actualArrayJson = JsonConvert.SerializeObject(decodedMsg.Data); + JAssert.DeepEquals(JToken.Parse(expectedArrayJson), JToken.Parse(actualArrayJson), Output).Should().BeTrue(); + break; + + default: + throw new InvalidOperationException($"Unknown fixture type: {fixture.Type}"); + } + + // TODO: Re-encode the message and verify it matches the original + // Create a new message with the decoded data and encode it + // Similar to `TestMsgpackDecoding` test in `proto_message_decoding_test.go` + // This will need omitting keys for null values, current serializer omits keys with nulls. + } + + public MsgPackMessageSerializerTests(ITestOutputHelper output) + : base(output) + { + } + } +} diff --git a/src/IO.Ably.Tests.Shared/MsgPackMessageSerializerTests.cs b/src/IO.Ably.Tests.Shared/MsgPackMessageSerializerTests.cs deleted file mode 100644 index e41243fb3..000000000 --- a/src/IO.Ably.Tests.Shared/MsgPackMessageSerializerTests.cs +++ /dev/null @@ -1,474 +0,0 @@ -#if MSGPACK -using FluentAssertions; - -namespace IO.Ably.Tests -{ - public class GenerateMsgPackSerializers - { - [Fact(Skip="true")] - public void Generate() - { - var applicationLibraryAssembly = typeof(ProtocolMessage).Assembly; - SerializerGenerator.GenerateCode( - new SerializerCodeGenerationConfiguration - { - Namespace = "IO.Ably.CustomSerialisers", - OutputDirectory = "../../../IO.Ably/CustomSerialisers/GeneratedSerializers", - EnumSerializationMethod = EnumSerializationMethod.ByName, // You can tweak it to use ByUnderlyingValue as you like. - IsRecursive = true, // Set dependent serializers are also generated. - PreferReflectionBasedSerializer = false, // Set true if you want to use reflection based collection serializer, false if you want to get generated collection serializers. - SerializationMethod = SerializationMethod.Map // You tweak it to generate 'map' based serializers. - }, - applicationLibraryAssembly.GetTypes().Where(type => - type == typeof(TokenRequest) - //type == typeof(Message) || type == typeof(ProtocolMessage) || type == typeof(PresenceMessage) || - //type == typeof(PaginatedResult) || type == typeof(TokenDetails) || type == typeof(Stats) - ///* ...you can filter types to be serialized by their namespace, custom attributes, etc... */ - ) - ); - } - } - - public class MsgPackMessageSerializerTests : AblySpecs - { - public static IEnumerable Messages - { - get - { - yield return new object[] { new Message[] { new Message() } }; // 1 empty message - yield return new object[] { new Message[] { new Message(), new Message() } }; // 2 empty messages - yield return new object[] { new Message[] { new Message(), new Message("test", null) } }; // 1 empty, 1 message - yield return new object[] { new Message[] { new Message("test", null), new Message("attach", null) } }; // 2 messages - } - } - - public static IEnumerable Presence - { - get - { - yield return new object[] { new PresenceMessage[] { new PresenceMessage() } }; // 1 empty message - yield return new object[] { new PresenceMessage[] { new PresenceMessage(), new PresenceMessage() } }; // 2 empty messages - yield return new object[] { new PresenceMessage[] { new PresenceMessage(), new PresenceMessage(PresenceAction.Enter, "test") } }; // 1 empty, 1 message - yield return new object[] { new PresenceMessage[] { new PresenceMessage(PresenceAction.Enter, "test"), new PresenceMessage(PresenceAction.Enter, "test2") } }; // 2 messages - } - } - - public static IEnumerable BinMessages - { - get - { - yield return new object[] { new byte[] { 0x90 }, new Message[] { } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa4, 0x74, 0x65, 0x73, 0x74 }, new Message[] { new Message("test", null) } }; - yield return new object[] { new byte[] { 0x92, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa4, 0x74, 0x65, 0x73, 0x74, 0x81, 0xa4, 0x6e, 0x61, 0x6d, 0x65, 0xa6, 0x61, 0x74, 0x74, 0x61, 0x63, 0x68 }, new Message[] { new Message("test", null), new Message("attach", null) } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xa4, 0x74, 0x65, 0x73, 0x74 }, new Message[] { new Message(null, "test") } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xcd, 0x04, 0xd2 }, new Message[] { new Message(null, (ushort)1234) } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xcb, 0x40, 0x5e, 0xc0, 0xa3, 0xd7, 0x0a, 0x3d, 0x71 }, new Message[] { new Message(null, 123.01d) } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xc3 }, new Message[] { new Message(null, true) } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xc0 }, new Message[] { new Message(null, null) } }; - yield return new object[] { new byte[] { 0x91, 0x81, 0xa4, 0x64, 0x61, 0x74, 0x61, 0x92, 0xcd, 0x04, 0xd2, 0xcd, 0x10, 0xe1 }, new Message[] { new Message(null, new object[] { (ushort)1234, (ushort)4321 }) } }; - } - } - - [Theory] - [InlineData(ProtocolMessage.MessageAction.Attach)] - [InlineData(ProtocolMessage.MessageAction.Detach)] - [InlineData(ProtocolMessage.MessageAction.Error)] - [InlineData(ProtocolMessage.MessageAction.Heartbeat)] - [InlineData(ProtocolMessage.MessageAction.Message)] - [InlineData(ProtocolMessage.MessageAction.Sync)] - public void SerializesMessageCorrectly_Action(ProtocolMessage.MessageAction messageAction) - { - // Arrange - ProtocolMessage message = new ProtocolMessage(messageAction); - List expectedMessage = new List(); - expectedMessage.Add(0x82); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add((byte)messageAction); - expectedMessage.AddRange(SerializeString("msgSerial")); - expectedMessage.Add(0); - - // Act - object result = MsgPackHelper.Serialise(message); - - // Assert - result.Should().BeOfType(); - Assert.Equal(expectedMessage.ToArray(), result as byte[]); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("test")] - [InlineData("my channel")] - [InlineData("1234")] - public void SerializesMessageCorrectly_Channel(string channel) - { - // Arrange - ProtocolMessage message = new ProtocolMessage() { Channel = channel }; - List expectedMessage = new List(); - expectedMessage.Add(0x82); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add(0); - if (!string.IsNullOrEmpty(channel)) - { - expectedMessage[0]++; - expectedMessage.AddRange(SerializeString("channel")); - expectedMessage.AddRange(SerializeString(channel)); - } - expectedMessage.AddRange(SerializeString("msgSerial")); - expectedMessage.Add(0); - - // Act - object result = MsgPackHelper.Serialise(message); - - // Assert - result.Should().BeOfType(); - Assert.Equal(expectedMessage.ToArray(), result as byte[]); - } - - [Theory] - [InlineData(-1)] - [InlineData(0)] - [InlineData(10)] - [InlineData(1000)] - public void SerializesMessageCorrectly_MsgSerial(long msgSerial) - { - // Arrange - ProtocolMessage message = new ProtocolMessage() { MsgSerial = msgSerial }; - List expectedMessage = new List(); - expectedMessage.Add(0x82); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add(0); - expectedMessage.AddRange(SerializeString("msgSerial")); - if (Math.Abs(msgSerial) < 255) - { - expectedMessage.Add(BitConverter.GetBytes(msgSerial).First()); - } - else - { - expectedMessage.Add(0xd1); - expectedMessage.AddRange(BitConverter.GetBytes(msgSerial).TakeWhile(c => c > 0).Reverse()); - } - - // Act - object result = MsgPackHelper.Serialise(message); - - // Assert - result.Should().BeOfType(); - Assert.Equal(expectedMessage.ToArray(), result as byte[]); - } - - [Theory] - [MemberData(nameof(Messages))] - public void SerializesMessageCorrectly_Messages(params Message[] messages) - { - // Arrange - - ProtocolMessage message = new ProtocolMessage() { Messages = messages }; - List expectedMessage = new List(); - expectedMessage.Add(0x82); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add(0); - expectedMessage.AddRange(SerializeString("msgSerial")); - expectedMessage.Add(0); - var validMessages = messages.Where(c => !string.IsNullOrEmpty(c.Name)); - if (validMessages.Any()) - { - expectedMessage[0]++; - expectedMessage.AddRange(SerializeString("messages")); - expectedMessage.Add((byte)((0x09 << 4) + validMessages.Count())); - foreach (Message msg in validMessages) - { - expectedMessage.Add((0x08 << 4) + 1); - expectedMessage.AddRange(SerializeString("name")); - expectedMessage.AddRange(SerializeString(msg.Name)); - } - } - - // Act - object result = MsgPackHelper.Serialise(message); - - // Assert - result.Should().BeOfType(); - Assert.Equal(expectedMessage.ToArray(), result as byte[]); - } - - [Theory] - [MemberData(nameof(Presence))] - public void SerializesMessageCorrectly_Presence(params PresenceMessage[] messages) - { - // Arrange - ProtocolMessage message = new ProtocolMessage() { Presence = messages }; - List expectedMessage = new List(); - expectedMessage.Add(0x82); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add(0); - expectedMessage.AddRange(SerializeString("msgSerial")); - expectedMessage.Add(0); - if (messages.Length > 0) - { - expectedMessage[0]++; - expectedMessage.AddRange(SerializeString("presence")); - expectedMessage.Add((byte)((0x09 << 4) + messages.Length)); - foreach (PresenceMessage msg in messages) - { - expectedMessage.Add((0x08 << 4) + 1); - expectedMessage[expectedMessage.Count - 1] += (byte)(string.IsNullOrEmpty(msg.ClientId) ? 0 : 1); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add((byte)msg.Action); - if (!string.IsNullOrEmpty(msg.ClientId)) - { - expectedMessage.AddRange(SerializeString("clientId")); - expectedMessage.AddRange(SerializeString(msg.ClientId)); - } - } - } - - // Act - object result = MsgPackHelper.Serialise(message); - - // Assert - result.Should().BeOfType(); - Assert.Equal(expectedMessage.ToArray(), result as byte[]); - } - - [Theory] - [InlineData(ProtocolMessage.MessageAction.Attach)] - [InlineData(ProtocolMessage.MessageAction.Detach)] - [InlineData(ProtocolMessage.MessageAction.Error)] - [InlineData(ProtocolMessage.MessageAction.Heartbeat)] - [InlineData(ProtocolMessage.MessageAction.Message)] - [InlineData(ProtocolMessage.MessageAction.Sync)] - public void DeserializesMessageCorrectly_Action(ProtocolMessage.MessageAction action) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("action")); - expectedMessage.Add((byte)action); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(action, target.Action); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("test")] - [InlineData("my channel")] - [InlineData("1234")] - public void DeserializesMessageCorrectly_Channel(string channel) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("channel")); - if (channel != null) - { - expectedMessage.AddRange(SerializeString(channel)); - } - else - { - expectedMessage.Add(0xc0); - } - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(channel, target.Channel); - } - - [Theory] - [InlineData("123")] - [InlineData("123.456")] - [InlineData("123^&456")] - [InlineData("absder#^&456")] - public void DeserializesMessageCorrectly_ChannelSerial(string serial) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("channelSerial")); - if (serial != null) - { - expectedMessage.AddRange(SerializeString(serial)); - } - else - { - expectedMessage.Add(0xc0); - } - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(serial, target.ChannelSerial); - } - - [Theory] - [InlineData("123")] - [InlineData("123.456")] - [InlineData("123^&456")] - [InlineData("absder#^&456")] - public void DeserializesMessageCorrectly_ConnectionId(string connectionId) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("connectionId")); - expectedMessage.AddRange(SerializeString(connectionId)); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(connectionId, target.ConnectionId); - } - - [Theory] - [InlineData("123")] - [InlineData("123.456")] - [InlineData("123^&456")] - [InlineData("absder#^&456")] - public void DeserializesMessageCorrectly_ConnectionKey(string connectionKey) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("connectionKey")); - expectedMessage.AddRange(SerializeString(connectionKey)); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(connectionKey, target.ConnectionKey); - } - - [Theory] - [InlineData("123")] - [InlineData("123.456")] - [InlineData("123^&456")] - [InlineData("absder#^&456")] - public void DeserializesMessageCorrectly_Id(string id) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("id")); - expectedMessage.AddRange(SerializeString(id)); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(id, target.Id); - } - - [Theory] - [InlineData(123)] - [InlineData(0)] - [InlineData(-1)] - public void DeserializesMessageCorrectly_Count(int count) - { - // Arrange - byte[] expectedMessage = MsgPackHelper.Serialise(new ProtocolMessage() {Count = count}) as byte[]; - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(count, target.Count.Value); - } - - [Theory] - [InlineData(123)] - [InlineData(0)] - [InlineData(-1)] - public void DeserializesMessageCorrectly_MsgSerial(long serial) - { - // Arrange - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("msgSerial")); - expectedMessage.Add(BitConverter.GetBytes(serial).First()); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal(serial, target.MsgSerial); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(123)] - public void DeserializesMessageCorrectly_Flags(int flags) - { - // Arrange - - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("flags")); - expectedMessage.Add((byte)flags); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - Assert.Equal((byte)flags, (byte)target.Flags); - } - - [Theory] - [MemberData(nameof(BinMessages))] - public void DeserializesMessageCorrectly_Messages(byte[] messageBin, params Message[] expectedMessages) - { - // Arrange - - List expectedMessage = new List(); - expectedMessage.Add(0x81); - expectedMessage.AddRange(SerializeString("messages")); - expectedMessage.AddRange(messageBin); - - // Act - ProtocolMessage target = MsgPackHelper.Deserialise(expectedMessage.ToArray()); - - // Assert - target.Should().NotBeNull(); - target.Messages.Should().NotBeNull(); - Assert.Equal(expectedMessages.Length, target.Messages.Length); - for (int i = 0; i < expectedMessages.Length; i++) - { - Assert.Equal(expectedMessages[i].Name, target.Messages[i].Name); - Assert.Equal(expectedMessages[i].Data, target.Messages[i].Data); - } - } - - private static byte[] SerializeString(string str) - { - List bytes = new List(); - bytes.Add((byte)(0xa0 + str.Length)); - bytes.AddRange(System.Text.Encoding.GetEncoding("utf-8").GetBytes(str)); - return bytes.ToArray(); - } - - public MsgPackMessageSerializerTests(ITestOutputHelper output) : base(output) - { - } - } -} -#endif diff --git a/src/IO.Ably.Tests.Shared/Push/LocalDeviceTests.cs b/src/IO.Ably.Tests.Shared/Push/LocalDeviceTests.cs index eecb7af3f..0ca9f6cda 100644 --- a/src/IO.Ably.Tests.Shared/Push/LocalDeviceTests.cs +++ b/src/IO.Ably.Tests.Shared/Push/LocalDeviceTests.cs @@ -184,6 +184,7 @@ public async Task WithoutClientId_WhenAuthorizedWithTokenParamsWithClientId_Shou _ = await ably.Auth.AuthorizeAsync(new TokenParams { ClientId = newClientId }); + await new ConditionalAwaiter(() => localDevice.ClientId != null); localDevice.ClientId.Should().Be(newClientId); mobileDevice.GetPreference(PersistKeys.Device.ClientId, PersistKeys.Device.SharedName).Should().Be(newClientId); } diff --git a/src/IO.Ably.Tests.Shared/Push/PushAdminTests.cs b/src/IO.Ably.Tests.Shared/Push/PushAdminTests.cs index 41f8f73c4..38b9bbe21 100644 --- a/src/IO.Ably.Tests.Shared/Push/PushAdminTests.cs +++ b/src/IO.Ably.Tests.Shared/Push/PushAdminTests.cs @@ -16,12 +16,13 @@ public static class PushAdminTests { public class GeneralTests : MockHttpRestSpecs { - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSH6")] [Trait("spec", "RSH6a")] - public void WhenLocalDeviceHasDeviceIdentityToken_ShouldAddHeaderToRequestWithCorrectValue() + public void WhenLocalDeviceHasDeviceIdentityToken_ShouldAddHeaderToRequestWithCorrectValue(Protocol protocol) { - var request = new AblyRequest("/", HttpMethod.Get); + var request = new AblyRequest("/", HttpMethod.Get, protocol); var localDevice = new LocalDevice() { DeviceIdentityToken = "test" }; _ = GetRestClient(); @@ -30,12 +31,13 @@ public void WhenLocalDeviceHasDeviceIdentityToken_ShouldAddHeaderToRequestWithCo request.Headers.Should().ContainKey(Defaults.DeviceIdentityTokenHeader).WhoseValue.Should().Be("test"); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSH6")] [Trait("spec", "RSH6b")] - public void WhenLocalDeviceHasDeviceSecret_ShouldAddHeaderToRequestWithCorrectValue() + public void WhenLocalDeviceHasDeviceSecret_ShouldAddHeaderToRequestWithCorrectValue(Protocol protocol) { - var request = new AblyRequest("/", HttpMethod.Get); + var request = new AblyRequest("/", HttpMethod.Get, protocol); var localDevice = new LocalDevice() { DeviceSecret = "test" }; _ = GetRestClient(); @@ -44,11 +46,12 @@ public void WhenLocalDeviceHasDeviceSecret_ShouldAddHeaderToRequestWithCorrectVa request.Headers.Should().ContainKey(Defaults.DeviceSecretHeader).WhoseValue.Should().Be("test"); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSH6")] - public void WhenLocalDeviceHasBothDeviceIdentityTokenAndSecret_ShouldOnlyAddIdentityTokenHeader() + public void WhenLocalDeviceHasBothDeviceIdentityTokenAndSecret_ShouldOnlyAddIdentityTokenHeader(Protocol protocol) { - var request = new AblyRequest("/", HttpMethod.Get); + var request = new AblyRequest("/", HttpMethod.Get, protocol); var localDevice = new LocalDevice() { DeviceIdentityToken = "test", DeviceSecret = "secret" }; _ = GetRestClient(); @@ -58,11 +61,12 @@ public void WhenLocalDeviceHasBothDeviceIdentityTokenAndSecret_ShouldOnlyAddIden request.Headers.Should().NotContainKey(Defaults.DeviceSecretHeader); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSH6")] - public void WhenLocalDevice_DoesNOT_HaveEitherDeviceIdentityTokenAndSecret_ShouldNotAddAnyHeaders() + public void WhenLocalDevice_DoesNOT_HaveEitherDeviceIdentityTokenAndSecret_ShouldNotAddAnyHeaders(Protocol protocol) { - var request = new AblyRequest("/", HttpMethod.Get); + var request = new AblyRequest("/", HttpMethod.Get, protocol); var localDevice = new LocalDevice(); _ = GetRestClient(); diff --git a/src/IO.Ably.Tests.Shared/Realtime/ChannelSandboxSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ChannelSandboxSpecs.cs index 5aa8c564b..02f89d809 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ChannelSandboxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ChannelSandboxSpecs.cs @@ -11,6 +11,7 @@ using IO.Ably.Realtime; using IO.Ably.Tests.Extensions; using IO.Ably.Tests.Infrastructure; +using IO.Ably.Tests.Shared.Helpers; using IO.Ably.Types; using Newtonsoft.Json.Linq; using Xunit; @@ -868,14 +869,11 @@ public static IEnumerable FixtureData { get { - if (Defaults.MsgPackEnabled) -#pragma warning disable 162 - { - yield return new object[] { Defaults.Protocol, GetAes128FixtureData() }; - yield return new object[] { Defaults.Protocol, GetAes256FixtureData() }; - } -#pragma warning restore 162 + // Fixture data for MsgPack + yield return new object[] { Protocol.MsgPack, GetAes128FixtureData() }; + yield return new object[] { Protocol.MsgPack, GetAes256FixtureData() }; + // Fixture data for Json yield return new object[] { Protocol.Json, GetAes128FixtureData() }; yield return new object[] { Protocol.Json, GetAes256FixtureData() }; } @@ -913,7 +911,7 @@ public async Task ShouldPublishAndReceiveFixtureData(Protocol protocol, JObject } else if (encoding == "json") { - JToken.DeepEquals((JToken)lastMessage.Data, (JToken)decodedData).Should().BeTrue("Item number {0} data does not match decoded data", count); + JAssert.DeepEquals((JToken)lastMessage.Data, (JToken)decodedData, Output).Should().BeTrue("Item number {0} data does not match decoded data", count); } else { @@ -928,13 +926,13 @@ public async Task ShouldPublishAndReceiveFixtureData(Protocol protocol, JObject } [Theory] - [InlineData(ChannelState.Detached)] - [InlineData(ChannelState.Failed)] - [InlineData(ChannelState.Suspended)] + [ProtocolData(ChannelState.Detached)] + [ProtocolData(ChannelState.Failed)] + [ProtocolData(ChannelState.Suspended)] [Trait("spec", "RTL11")] - public async Task WhenChannelEntersDetachedFailedSuspendedState_ShouldDeleteQueuedPresenceMessageAndCallbackShouldIndicateError(ChannelState state) + public async Task WhenChannelEntersDetachedFailedSuspendedState_ShouldDeleteQueuedPresenceMessageAndCallbackShouldIndicateError(Protocol protocol, ChannelState state) { - var client = await GetRealtimeClient(Defaults.Protocol, (options, settings) => + var client = await GetRealtimeClient(protocol, (options, settings) => { // A bogus AuthUrl will cause connection to become disconnected options.AuthUrl = new Uri("http://235424c24.fake:49999"); @@ -969,13 +967,13 @@ public async Task WhenChannelEntersDetachedFailedSuspendedState_ShouldDeleteQueu } [Theory] - [InlineData(ChannelState.Detached)] - [InlineData(ChannelState.Failed)] - [InlineData(ChannelState.Suspended)] + [ProtocolData(ChannelState.Detached)] + [ProtocolData(ChannelState.Failed)] + [ProtocolData(ChannelState.Suspended)] [Trait("spec", "RTL11a")] - public async Task WhenChannelEntersDetachedFailedSuspendedState_MessagesAwaitingAckOrNackShouldNotBeAffected(ChannelState state) + public async Task WhenChannelEntersDetachedFailedSuspendedState_MessagesAwaitingAckOrNackShouldNotBeAffected(Protocol protocol, ChannelState state) { - var client = await GetRealtimeClient(Defaults.Protocol); + var client = await GetRealtimeClient(protocol); var channel = client.Channels.Get("test".AddRandomSuffix()); var tsc = new TaskCompletionAwaiter(5000); diff --git a/src/IO.Ably.Tests.Shared/Realtime/ChannelSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ChannelSpecs.cs index 863ba6628..f8669a4cd 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ChannelSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ChannelSpecs.cs @@ -942,7 +942,7 @@ public async Task WithNameAndData_ShouldSendASingleProtocolMessageWithASingleEnc [Trait("spec", "RTL6i2")] public async Task WithListOfMessages_ShouldPublishASingleProtocolMessageToTransport() { - var (client, channel) = await GetClientAndChannel(); + var (client, channel) = await GetClientAndChannel(opts => { opts.UseBinaryProtocol = false; }); SetState(channel, ChannelState.Attached); var list = new List @@ -963,7 +963,7 @@ public async Task WithListOfMessages_ShouldPublishASingleProtocolMessageToTransp [Trait("spec", "RTL6i3")] public async Task WithMessageWithOutData_ShouldSendOnlyData() { - var (client, channel) = await GetClientAndChannel(); + var (client, channel) = await GetClientAndChannel(opts => { opts.UseBinaryProtocol = false; }); SetState(channel, ChannelState.Attached); channel.Publish(null, "data"); @@ -976,7 +976,7 @@ public async Task WithMessageWithOutData_ShouldSendOnlyData() [Trait("spec", "RTL6i3")] public async Task WithMessageWithOutName_ShouldSendOnlyData() { - var (client, channel) = await GetClientAndChannel(); + var (client, channel) = await GetClientAndChannel(opts => { opts.UseBinaryProtocol = false; }); SetState(channel, ChannelState.Attached); channel.Publish("name", null); @@ -991,7 +991,7 @@ public class ConnectionStateConditions : PublishSpecs [Trait("spec", "RTL6c1")] public async Task WhenConnectionIsConnected_ShouldSendMessagesDirectly() { - var (client, channel) = await GetClientAndChannel(); + var (client, channel) = await GetClientAndChannel(opts => { opts.UseBinaryProtocol = false; }); SetState(channel, ChannelState.Attached); @@ -1280,7 +1280,14 @@ public async Task WithAMessageThatFailDecryption_ShouldDeliverMessageAndNotPutAn }; var message = new Message("name", "encrypted with otherChannelOptions"); - MessageHandler.EncodePayloads(otherChannelOptions.ToDecodingContext(), new[] { message }); + + Protocol protocol = Protocol.Json; + if (client.Options.UseBinaryProtocol) + { + protocol = Protocol.MsgPack; + } + + new MessageHandler(DefaultLogger.LoggerInstance, protocol).EncodePayloads(otherChannelOptions.ToDecodingContext(), new[] { message }); client.FakeMessageReceived(message, encryptedChannel.Name); @@ -1303,7 +1310,14 @@ public async Task channel.Subscribe(msg => { receivedMessage = msg; }); var message = new Message("name", "encrypted with otherChannelOptions") { Encoding = "json" }; - MessageHandler.EncodePayloads(otherChannelOptions.ToDecodingContext(), new[] { message }); + + Protocol protocol = Protocol.Json; + if (client.Options.UseBinaryProtocol) + { + protocol = Protocol.MsgPack; + } + + new MessageHandler(DefaultLogger.LoggerInstance, protocol).EncodePayloads(otherChannelOptions.ToDecodingContext(), new[] { message }); var testSink = new TestLoggerSink(); using (DefaultLogger.SetTempDestination(testSink)) diff --git a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandBoxSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandBoxSpecs.cs index e7e303bca..1fece67f2 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandBoxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandBoxSpecs.cs @@ -829,7 +829,7 @@ public async Task WithAuthUrlShouldGetTokenFromUrl(Protocol protocol) { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); await WaitForState(authUrlClient, waitSpan: TimeSpan.FromSeconds(5)); @@ -1129,34 +1129,29 @@ public async Task WithShortLivedToken_ShouldRenewTokenMoreThanOnce(Protocol prot opts.AutoConnect = false; }); - var stateChanges = new List(); + var stateChanges = new List(); client.Connection.On((args) => { - stateChanges.Add(args.Current); + stateChanges.Add(args); }); - await client.Auth.AuthorizeAsync(new TokenParams { Ttl = TimeSpan.FromSeconds(5) }); + await client.Auth.AuthorizeAsync(new TokenParams { Ttl = TimeSpan.FromSeconds(1) }); var channel = client.Channels.Get("shortToken_test" + protocol); await channel.AttachAsync(); - int count = 0; - while (true) + await new ConditionalAwaiter(() => stateChanges.Count(ev => ev.Current == ConnectionState.Connected) >= 3); + var disconnectedStates = stateChanges.FindAll(ev => ev.Current == ConnectionState.Disconnected); + disconnectedStates.Count.Should().BeGreaterThanOrEqualTo(2); + foreach (var state in disconnectedStates) { - Interlocked.Increment(ref count); - channel.Publish("test", "test"); - await Task.Delay(2000); - if (count == 10) - { - break; - } + state.Current.Should().Be(ConnectionState.Disconnected); + state.Reason.Should().NotBeNull(); + state.Reason.Code.Should().Be(ErrorCodes.TokenExpired); } - stateChanges.Count(x => x == ConnectionState.Connected).Should().BeGreaterThan(2); - - await client.WaitForState(); - client.Connection.State.Should().Be(ConnectionState.Connected); + await client.WaitForState(ConnectionState.Connected); } [Theory] diff --git a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandboxOperatingSystemEventsForNetworkSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandboxOperatingSystemEventsForNetworkSpecs.cs index 7dd28ac50..e9506a41c 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandboxOperatingSystemEventsForNetworkSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSandboxOperatingSystemEventsForNetworkSpecs.cs @@ -17,10 +17,8 @@ namespace IO.Ably.Tests.Realtime public class ConnectionSandboxOperatingSystemEventsForNetworkSpecs : SandboxSpecs { [Theory] -#if MSGPACK [InlineData(Protocol.MsgPack, ConnectionState.Connected)] [InlineData(Protocol.MsgPack, ConnectionState.Connecting)] -#endif [InlineData(Protocol.Json, ConnectionState.Connecting)] [InlineData(Protocol.Json, ConnectionState.Connected)] [Trait("spec", "RTN20a")] diff --git a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionFallbackSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionFallbackSpecs.cs index ad312a2ef..167f23e7b 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionFallbackSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionFallbackSpecs.cs @@ -115,7 +115,7 @@ public async Task WithFallbackHost_ShouldMakeRestRequestsOnSameHost() { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("[12345678]") }; var handler = new FakeHttpMessageHandler(response); - var client = GetClientWithFakeTransportAndMessageHandler(messageHandler: handler); + var client = GetClientWithFakeTransportAndMessageHandler(opts => { opts.UseBinaryProtocol = false; }, messageHandler: handler); client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Connected) { @@ -223,7 +223,7 @@ public async Task WhenRealtimeGoesFromFallbackHostToDefault_RestRequestShouldBeO { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("[12345678]") }; var handler = new FakeHttpMessageHandler(response); - var client = GetClientWithFakeTransportAndMessageHandler(null, handler); + var client = GetClientWithFakeTransportAndMessageHandler(opts => { opts.UseBinaryProtocol = false; }, messageHandler: handler); await client.ConnectClient(); // On the default host await client.DisconnectWithRetryableError(); diff --git a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionParameterSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionParameterSpecs.cs index 740708b2a..40a575418 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionParameterSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/ConnectionSpecs/ConnectionParameterSpecs.cs @@ -24,18 +24,11 @@ public async Task ShouldUseDefaultRealtimeHost() [InlineData(true, "msgpack")] [InlineData(false, "json")] [Trait("spec", "RTN2a")] - public void WithUseBinaryEncoding_ShouldSetTransportFormatProperty(bool useBinary, string format) + public async void WithUseBinaryEncoding_ShouldSetTransportFormatProperty(bool useBinary, string format) { - if (!Defaults.MsgPackEnabled) - { - return; - } - -#pragma warning disable 162 - _ = GetClientWithFakeTransport(opts => opts.UseBinaryProtocol = useBinary); + _ = await GetConnectedClient(opts => opts.UseBinaryProtocol = useBinary); LastCreatedTransport.Parameters.UseBinaryProtocol.Should().Be(useBinary); LastCreatedTransport.Parameters.GetParams().Should().ContainKey("format").WhoseValue.Should().Be(format); -#pragma warning restore 162 } [Theory] diff --git a/src/IO.Ably.Tests.Shared/Realtime/RealtimeSpecs.cs b/src/IO.Ably.Tests.Shared/Realtime/RealtimeSpecs.cs index 83056066e..1efdc9839 100644 --- a/src/IO.Ably.Tests.Shared/Realtime/RealtimeSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Realtime/RealtimeSpecs.cs @@ -101,11 +101,15 @@ public void When_HostNotSetInOptions_UseBinaryProtocol_TrueByDefault() // Act if (Defaults.MsgPackEnabled) -#pragma warning disable 162 { options.UseBinaryProtocol.Should().BeTrue(); } -#pragma warning restore 162 + else + { +#pragma warning disable CS0162 // Unreachable code detected + options.UseBinaryProtocol.Should().BeFalse(); +#pragma warning restore CS0162 // Unreachable code detected + } } [Fact] diff --git a/src/IO.Ably.Tests.Shared/Rest/AblyHttpClientSpecs.cs b/src/IO.Ably.Tests.Shared/Rest/AblyHttpClientSpecs.cs index 3429ae70c..b983cbf3a 100644 --- a/src/IO.Ably.Tests.Shared/Rest/AblyHttpClientSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Rest/AblyHttpClientSpecs.cs @@ -10,53 +10,57 @@ namespace IO.Ably.Tests { public class AblyHttpClientSpecs { - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7")] - public void WithSecureTrue_CreatesSecureRestUrlsWithDefaultHost() + public void WithSecureTrue_CreatesSecureRestUrlsWithDefaultHost(Protocol protocol) { var client = new AblyHttpClient(new AblyHttpOptions { IsSecure = true }); - var url = client.GetRequestUrl(new AblyRequest("/test", HttpMethod.Get)); + var url = client.GetRequestUrl(new AblyRequest("/test", HttpMethod.Get, protocol)); url.Scheme.Should().Be("https"); url.Host.Should().Be(Defaults.RestHost); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7")] - public void WithSecureFalse_CreatesNonSecureRestUrlsWithDefaultRestHost() + public void WithSecureFalse_CreatesNonSecureRestUrlsWithDefaultRestHost(Protocol protocol) { var client = new AblyHttpClient(new AblyHttpOptions { IsSecure = false }); - var url = client.GetRequestUrl(new AblyRequest("/test", HttpMethod.Get)); + var url = client.GetRequestUrl(new AblyRequest("/test", HttpMethod.Get, protocol)); url.Scheme.Should().Be("http"); url.Host.Should().Be(Defaults.RestHost); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7a")] [Trait("spec", "G4")] - public async Task WhenCallingUrl_AddsDefaultAblyLibraryVersionHeader() + public async Task WhenCallingUrl_AddsDefaultAblyLibraryVersionHeader(Protocol protocol) { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Success") }; var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions(), handler); - await client.Execute(new AblyRequest("/test", HttpMethod.Get)); + await client.Execute(new AblyRequest("/test", HttpMethod.Get, protocol)); var values = handler.LastRequest.Headers.GetValues("X-Ably-Version").ToArray(); values.Should().NotBeEmpty(); values.First().Should().Be(Defaults.ProtocolVersion); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7c")] - public async Task WhenCallingUrl_AddsRequestIdIfSetTrue() + public async Task WhenCallingUrl_AddsRequestIdIfSetTrue(Protocol protocol) { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Success") }; var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions { AddRequestIds = true }, handler); - var ablyRequest = new AblyRequest("/test", HttpMethod.Get); + var ablyRequest = new AblyRequest("/test", HttpMethod.Get, protocol); ablyRequest.AddHeaders(new Dictionary { { "request_id", "custom_request_id" } }); await client.Execute(ablyRequest); var values = handler.LastRequest.Headers.GetValues("request_id").ToArray(); @@ -64,14 +68,15 @@ public async Task WhenCallingUrl_AddsRequestIdIfSetTrue() values.First().Should().StartWith("custom_request_id"); } - [Fact] - public async Task WhenCallingUrlWithPostParamsAndEmptyBody_PassedTheParamsAsUrlEncodedValues() + [Theory] + [ProtocolData] + public async Task WhenCallingUrlWithPostParamsAndEmptyBody_PassedTheParamsAsUrlEncodedValues(Protocol protocol) { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Success") }; var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions(), handler); - var ablyRequest = new AblyRequest("/test", HttpMethod.Post) + var ablyRequest = new AblyRequest("/test", HttpMethod.Post, protocol) { PostParameters = new Dictionary { { "test", "test" }, { "best", "best" } }, }; @@ -82,15 +87,16 @@ public async Task WhenCallingUrlWithPostParamsAndEmptyBody_PassedTheParamsAsUrlE formContent.Should().NotBeNull("Content should be of type FormUrlEncodedContent"); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7d")] - public async Task WhenCallingUrl_AddsDefaultAblyAgentHeader() + public async Task WhenCallingUrl_AddsDefaultAblyAgentHeader(Protocol protocol) { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Success") }; var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions(), handler); - await client.Execute(new AblyRequest("/test", HttpMethod.Get)); + await client.Execute(new AblyRequest("/test", HttpMethod.Get, protocol)); string[] values = handler.LastRequest.Headers.GetValues("Ably-Agent").ToArray(); values.Should().HaveCount(1); string[] agentValues = values[0].Split(' '); @@ -113,9 +119,10 @@ public async Task WhenCallingUrl_AddsDefaultAblyAgentHeader() } } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC7d6")] - public async Task WhenCallingUrl_AddsCustomizedAblyAgentHeader() + public async Task WhenCallingUrl_AddsCustomizedAblyAgentHeader(Protocol protocol) { var response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Success") }; var handler = new FakeHttpMessageHandler(response); @@ -131,7 +138,7 @@ public async Task WhenCallingUrl_AddsCustomizedAblyAgentHeader() var client = new AblyHttpClient(ablyHttpOptions, handler); - await client.Execute(new AblyRequest("/test", HttpMethod.Get)); + await client.Execute(new AblyRequest("/test", HttpMethod.Get, protocol)); string[] values = handler.LastRequest.Headers.GetValues("Ably-Agent").ToArray(); values.Should().HaveCount(1); string[] agentValues = values[0].Split(' '); diff --git a/src/IO.Ably.Tests.Shared/Rest/ChannelSandboxSpecs.cs b/src/IO.Ably.Tests.Shared/Rest/ChannelSandboxSpecs.cs index 7688292e8..4d2a20236 100644 --- a/src/IO.Ably.Tests.Shared/Rest/ChannelSandboxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Rest/ChannelSandboxSpecs.cs @@ -11,6 +11,7 @@ using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; +using IO.Ably.Tests.Shared.Helpers; namespace IO.Ably.Tests.Rest { @@ -368,7 +369,7 @@ public async Task CanPublishAMessageAndRetrieveIt128(Protocol protocol) } else if (encoding == "json") { - JToken.DeepEquals((JToken)message.Data, (JToken)decodedData).Should().BeTrue("Item number {0} data does not match decoded data", count); + JAssert.DeepEquals((JToken)message.Data, (JToken)decodedData, Output).Should().BeTrue("Item number {0} data does not match decoded data", count); } else { @@ -408,7 +409,7 @@ public async Task CanPublishAMessageAndRetrieveIt256(Protocol protocol) } else if (encoding == "json") { - JToken.DeepEquals((JToken)message.Data, (JToken)decodedData).Should().BeTrue("Item number {0} data does not match decoded data", count); + JAssert.DeepEquals((JToken)message.Data, (JToken)decodedData, Output).Should().BeTrue("Item number {0} data does not match decoded data", count); } else { @@ -537,22 +538,14 @@ public async Task WithTestMessagePayloadsWhenDecoding_ShouldDecodeMessagesAsPerS { var channelName = "channel-name-" + new Random().Next(int.MaxValue); - var httpClient = (await AblySandboxFixture.GetSettings()).GetHttpClient(); - var rawMessage = new JObject { ["data"] = messageData["data"], ["encoding"] = messageData["encoding"], }; - var request = new AblyRequest($"/channels/{channelName}/messages", HttpMethod.Post) - { - RequestBody = rawMessage.ToJson().GetBytes(), - }; - var client1 = await GetRestClient(protocol); - await client1.AblyAuth.AddAuthHeader(request); - await httpClient.Execute(request); + client1.Request(HttpMethod.Post, $"/channels/{channelName}/messages", null, rawMessage); await Task.Delay(1000); @@ -581,7 +574,6 @@ public async Task WithTestMessagePayloadsWhenDecoding_ShouldEncodeMessagesAsPerS JObject messageData) { var channelName = "channel-name-" + new Random().Next(int.MaxValue); - var httpClient = (await AblySandboxFixture.GetSettings()).GetHttpClient(); var expectedType = (string)messageData["expectedType"]; var client1 = await GetRestClient(protocol); @@ -603,13 +595,10 @@ public async Task WithTestMessagePayloadsWhenDecoding_ShouldEncodeMessagesAsPerS await Task.Delay(1000); - var request = new AblyRequest($"/channels/{channelName}/messages", HttpMethod.Get); - await client1.AblyAuth.AddAuthHeader(request); - var response = await httpClient.Execute(request); + var response = await client1.Request(HttpMethod.Get, $"/channels/{channelName}/messages", null); // Assert - var historyData = JArray.Parse(response.TextResponse); - var responseData = (JObject)historyData.First; + var responseData = response.Items.First(); responseData.Should().NotBeNull(); if (expectedType == "binary") diff --git a/src/IO.Ably.Tests.Shared/Rest/PresenceSandboxSpecs.cs b/src/IO.Ably.Tests.Shared/Rest/PresenceSandboxSpecs.cs index 25442a068..f491c8bee 100644 --- a/src/IO.Ably.Tests.Shared/Rest/PresenceSandboxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Rest/PresenceSandboxSpecs.cs @@ -1,5 +1,7 @@ using System.Threading.Tasks; using FluentAssertions; +using IO.Ably.Tests.Shared.Helpers; +using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -37,10 +39,20 @@ public async Task WithCorrectCipherParams_DecryptsMessagesCorrectly(Protocol pro var channel = client.Channels.Get(TestEnvironmentSettings.PresenceChannelName, new ChannelOptions(settings.CipherParams)); var presence = await channel.Presence.GetAsync(); - foreach (var message in presence.Items) + presence.Items.Should().HaveCount(6); + + presence.Items[0].Data.Should().Be("true"); + + var exampleObject = new JObject { - message.Encoding.Should().BeNullOrEmpty(); - } + ["example"] = new JObject { ["json"] = "Object" } + }; + JAssert.DeepEquals(exampleObject, presence.Items[1].Data as JObject, Output).Should().BeTrue(); + JAssert.DeepEquals(exampleObject, presence.Items[2].Data as JObject, Output).Should().BeTrue(); + + presence.Items[3].Data.Should().Be("24"); + presence.Items[4].Data.Should().Be("{ \"test\": \"This is a JSONObject clientData payload\"}"); + presence.Items[5].Data.Should().Be("This is a string clientData payload"); } } } diff --git a/src/IO.Ably.Tests.Shared/Rest/RestSpecs.cs b/src/IO.Ably.Tests.Shared/Rest/RestSpecs.cs index 4e02013d9..61b330f75 100644 --- a/src/IO.Ably.Tests.Shared/Rest/RestSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Rest/RestSpecs.cs @@ -143,16 +143,8 @@ public void ShouldInitialiseAblyHttpClientWithCorrectTlsValue(bool tls) public void ShouldUseBinaryProtocolByDefault() { - if (!Defaults.MsgPackEnabled) - { - return; - } - -#pragma warning disable 162 var client = new AblyRest(ValidKey); client.Options.UseBinaryProtocol.Should().BeTrue(); - client.Protocol.Should().Be(Defaults.Protocol); -#pragma warning restore 162 } [Fact] @@ -394,15 +386,16 @@ public void HttpRequestTimeoutShouldComeFromClientOptions() client.HttpClient.Client.Timeout.Should().Be(httpRequestTimeout); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSC14a")] [Trait("spec", "RSA11")] - public async Task AddAuthHeader_WithBasicAuthentication_AddsCorrectAuthorizationHeader() + public async Task AddAuthHeader_WithBasicAuthentication_AddsCorrectAuthorizationHeader(Protocol protocol) { // Arrange var rest = new AblyRest(ValidKey); ApiKey key = ApiKey.Parse(ValidKey); - var request = new AblyRequest("/test", HttpMethod.Get); + var request = new AblyRequest("/test", HttpMethod.Get, protocol); var expectedValue = "Basic " + key.ToString().ToBase64(); // Act @@ -414,14 +407,15 @@ public async Task AddAuthHeader_WithBasicAuthentication_AddsCorrectAuthorization authHeader.Value.Should().Be(expectedValue); } - [Fact] + [Theory] + [ProtocolData] [Trait("spec", "RSA3b")] - public async Task AddAuthHeader_WithTokenAuthentication_AddsCorrectAuthorizationHeader() + public async Task AddAuthHeader_WithTokenAuthentication_AddsCorrectAuthorizationHeader(Protocol protocol) { // Arrange const string tokenValue = "TokenValue"; var rest = new AblyRest(opts => opts.Token = tokenValue); - var request = new AblyRequest("/test", HttpMethod.Get); + var request = new AblyRequest("/test", HttpMethod.Get, protocol); var expectedValue = "Bearer " + tokenValue.ToBase64(); // Act @@ -434,10 +428,10 @@ public async Task AddAuthHeader_WithTokenAuthentication_AddsCorrectAuthorization } [Theory] - [InlineData(true)] - [InlineData(false)] + [ProtocolData(true)] + [ProtocolData(false)] [Trait("spec", "RSA3a")] - public async Task TokenAuthCanBeUsedOverHttpAndHttps(bool tls) + public async Task TokenAuthCanBeUsedOverHttpAndHttps(Protocol protocol, bool tls) { // Arrange const string tokenValue = "TokenValue"; @@ -446,7 +440,7 @@ public async Task TokenAuthCanBeUsedOverHttpAndHttps(bool tls) opts.Token = tokenValue; opts.Tls = tls; }); - var request = new AblyRequest("/test", HttpMethod.Get); + var request = new AblyRequest("/test", HttpMethod.Get, protocol); // Act await rest.AblyAuth.AddAuthHeader(request); diff --git a/src/IO.Ably.Tests.Shared/Rest/SandboxSpecs.cs b/src/IO.Ably.Tests.Shared/Rest/SandboxSpecs.cs index fb0f419d4..5edc74c98 100644 --- a/src/IO.Ably.Tests.Shared/Rest/SandboxSpecs.cs +++ b/src/IO.Ably.Tests.Shared/Rest/SandboxSpecs.cs @@ -84,7 +84,7 @@ protected async Task GetRestClient(Protocol protocol, Action GetRealtimeClient( { var settings = await AblySandboxFixture.GetSettings(); var defaultOptions = settings.CreateDefaultOptions(); - defaultOptions.UseBinaryProtocol = protocol == Defaults.Protocol; + defaultOptions.UseBinaryProtocol = protocol.IsBinary(); defaultOptions.TransportFactory = new TestTransportFactory(); optionsAction?.Invoke(defaultOptions, settings); diff --git a/src/IO.Ably.Tests.Shared/RestProtocolTests.cs b/src/IO.Ably.Tests.Shared/RestProtocolTests.cs index 1109b04b4..9ccc8224c 100644 --- a/src/IO.Ably.Tests.Shared/RestProtocolTests.cs +++ b/src/IO.Ably.Tests.Shared/RestProtocolTests.cs @@ -5,37 +5,30 @@ namespace IO.Ably.Tests { public class RestProtocolTests { -#if MSGPACK [Fact] - public void WhenProtocolIsNotDefined_AndMsgPackEnabled_DefaultsToMsgPack() + public void WhenProtocolIsNotDefined_DefaultsToMsgPack() { - var rest = new AblyRest(new ClientOptions()); - rest.Protocol.Should().Be(Protocol.MsgPack); - Defaults.Protocol.Should().Be(Protocol.MsgPack); + var rest = new AblyRest(new ClientOptions("API_KEY")); + if (Defaults.MsgPackEnabled) + { + rest.Protocol.Should().Be(Protocol.MsgPack); + } + else + { +#pragma warning disable CS0162 // Unreachable code detected + rest.Protocol.Should().Be(Protocol.Json); +#pragma warning restore CS0162 // Unreachable code detected + } } - [Fact] - public void WhenProtocolIsMsgPack_ProtocolIsSetToMsgPack() - { - var rest = new AblyRest(new ClientOptions() { UseBinaryProtocol = true}); - rest.Protocol.Should().Be(Defaults.Protocol); - } -#else - [Fact] - public void WhenProtocolIsNotDefined_AndMsgPackDisabled_DefaultsToJson() - { - Defaults.Protocol.Should().Be(Protocol.Json); - var rest = new AblyRest(new ClientOptions { Key = "best.test:key" }); - rest.Protocol.Should().Be(Protocol.Json); - } - - [Fact] - public void WhenMsgPackIsDisabled_AndUseBinaryIsTrue_ProtocolIsSetToJson() + [Theory] + [InlineData(true, Protocol.MsgPack)] + [InlineData(false, Protocol.Json)] + public void WhenUseBinaryProtocolIsSet_ProtocolIsSetCorrectly(bool useBinaryProtocol, Protocol expectedProtocol) { - var rest = new AblyRest(new ClientOptions { UseBinaryProtocol = true, Key = "best.test:key" }); - rest.Protocol.Should().Be(Protocol.Json); + var rest = new AblyRest(new ClientOptions { UseBinaryProtocol = useBinaryProtocol, Key = "best.test:key" }); + rest.Protocol.Should().Be(expectedProtocol); } -#endif [Fact] public void WhenProtocolIsJson_RestProtocolIsSetToJson() diff --git a/src/IO.Ably.Xamarin.sln b/src/IO.Ably.Xamarin.sln index 30c44b4d4..78d84b9e2 100644 --- a/src/IO.Ably.Xamarin.sln +++ b/src/IO.Ably.Xamarin.sln @@ -31,8 +31,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Ably.iOS", "IO.Ably.iOS\ EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Tests.Shared", "IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.shproj", "{1609F12C-8216-4E7C-ADE0-240BFE160242}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.DeltaCodec", "..\lib\delta-codec\IO.Ably.DeltaCodec\IO.Ably.DeltaCodec.csproj", "{53CA3FD4-E11A-4368-A7A5-BCAB40D08BED}" @@ -867,7 +865,6 @@ Global {24B6FC97-9D3D-46AE-B5CB-47458354BEE1} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {8BB7B13C-E9F4-4D1B-BCCC-AF890A23ECE6} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {1609F12C-8216-4E7C-ADE0-240BFE160242} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {53CA3FD4-E11A-4368-A7A5-BCAB40D08BED} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {97ED15E5-6546-4437-BF4F-B929700CE922} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} @@ -891,6 +888,5 @@ Global IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{567feef7-41af-42f2-ad34-546a278355b1}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{8bb7b13c-e9f4-4d1b-bccc-af890a23ece6}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{97ed15e5-6546-4437-bf4f-b929700ce922}*SharedItemsImports = 5 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 EndGlobalSection EndGlobal diff --git a/src/IO.Ably.iOS/IO.Ably.iOS.csproj b/src/IO.Ably.iOS/IO.Ably.iOS.csproj index 1bfbaf99d..175a4178f 100644 --- a/src/IO.Ably.iOS/IO.Ably.iOS.csproj +++ b/src/IO.Ably.iOS/IO.Ably.iOS.csproj @@ -13,6 +13,8 @@ IO.Ably + true + obj/Generated true @@ -55,9 +57,16 @@ - + + + ..\packages\MessagePack.3.1.4\lib\netstandard2.0\MessagePack.dll + True + + + ..\packages\MessagePack.Annotations.3.1.4\lib\netstandard2.0\MessagePack.Annotations.dll + ..\packages\Microsoft.Bcl.Async.1.0.168\lib\portable-net45+win8+wpa81\Microsoft.Threading.Tasks.dll @@ -67,9 +76,6 @@ ..\packages\Microsoft.Bcl.Async.1.0.168\lib\portable-net45+win8+wpa81\Microsoft.Threading.Tasks.Extensions.dll True - - ..\packages\MsgPack.Cli.0.9.2\lib\Xamarin.iOS10\MsgPack.dll - ..\packages\Newtonsoft.Json.13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll True @@ -88,8 +94,8 @@ ..\packages\System.Threading.Channels.4.5.0\lib\netstandard2.0\System.Threading.Channels.dll True - - ..\packages\System.Threading.Tasks.Extensions.4.5.0\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll True @@ -107,6 +113,10 @@ + + + + {412deb5f-7936-4027-8bf8-977f23d465ed} @@ -114,7 +124,6 @@ - diff --git a/src/IO.Ably.iOS/packages.config b/src/IO.Ably.iOS/packages.config index ff1cf0904..e19946e5b 100644 --- a/src/IO.Ably.iOS/packages.config +++ b/src/IO.Ably.iOS/packages.config @@ -2,10 +2,12 @@ + + + - @@ -57,10 +59,10 @@ - + - \ No newline at end of file + diff --git a/src/IO.Ably.sln b/src/IO.Ably.sln index 05d848f0f..3b8f97414 100644 --- a/src/IO.Ably.sln +++ b/src/IO.Ably.sln @@ -36,8 +36,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.NETStandard20", "IO EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared", "IO.Ably.Shared\IO.Ably.Shared.shproj", "{3553E1B2-8F1F-4E83-9524-08E702C14FCF}" EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "IO.Ably.Shared.MsgPack", "IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.shproj", "{EEBF3249-3CA3-4078-A188-F8B916C3F4C2}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndroidSample", "..\examples\AndroidSample\AndroidSample.csproj", "{4F519937-3F75-49D7-A71E-79A6C798C5B8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IO.Ably.Tests.DotNET", "IO.Ably.Tests.DotNET\IO.Ably.Tests.DotNET.csproj", "{4805A9DA-3412-4BE8-8B95-5A0EFDA1AC01}" @@ -205,7 +203,6 @@ Global {8BB7B13C-E9F4-4D1B-BCCC-AF890A23ECE6} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {48EA337F-AE7B-4001-BD8C-DA1668FC6CBD} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {3553E1B2-8F1F-4E83-9524-08E702C14FCF} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} - {EEBF3249-3CA3-4078-A188-F8B916C3F4C2} = {8A0F718E-2168-4CC7-8F7B-A65508B52B0F} {4F519937-3F75-49D7-A71E-79A6C798C5B8} = {E02CFEF3-4CE4-49F6-A778-26503A1479D5} {4805A9DA-3412-4BE8-8B95-5A0EFDA1AC01} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} {1609F12C-8216-4E7C-ADE0-240BFE160242} = {C2F43DB7-AAA0-4687-9897-5D686EC91245} @@ -223,6 +220,5 @@ Global IO.Ably.Shared\IO.Ably.Shared.projitems*{48ea337f-ae7b-4001-bd8c-da1668fc6cbd}*SharedItemsImports = 5 IO.Ably.Tests.Shared\IO.Ably.Tests.Shared.projitems*{567feef7-41af-42f2-ad34-546a278355b1}*SharedItemsImports = 4 IO.Ably.Shared\IO.Ably.Shared.projitems*{8bb7b13c-e9f4-4d1b-bccc-af890a23ece6}*SharedItemsImports = 4 - IO.Ably.Shared.MsgPack\IO.Ably.Shared.MsgPack.projitems*{eebf3249-3ca3-4078-a188-f8b916c3f4c2}*SharedItemsImports = 13 EndGlobalSection EndGlobal diff --git a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilityResourceSerializer.cs b/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilityResourceSerializer.cs deleted file mode 100644 index ffca5716c..000000000 --- a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilityResourceSerializer.cs +++ /dev/null @@ -1,154 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_CapabilityResourceSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer> _serializer1; - - public IO_Ably_CapabilityResourceSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer>(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.CapabilityResource objectTree) { - packer.PackMapHeader(2); - this._serializer0.PackTo(packer, "AllowedOperations"); - this._serializer1.PackTo(packer, objectTree.AllowedOperations); - this._serializer0.PackTo(packer, "Name"); - this._serializer0.PackTo(packer, objectTree.Name); - } - - protected override IO.Ably.CapabilityResource UnpackFromCore(MsgPack.Unpacker unpacker) { - IO.Ably.CapabilityResource result = default(IO.Ably.CapabilityResource); - result = new IO.Ably.CapabilityResource(); - if (unpacker.IsArrayHeader) { - int unpacked = default(int); - int itemsCount = default(int); - itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - System.Collections.Generic.List nullable = default(System.Collections.Generic.List); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable = default(MsgPack.Unpacker); - disposable = unpacker.ReadSubtree(); - try { - nullable = this._serializer1.UnpackFrom(disposable); - } - finally { - if (((disposable == null) - == false)) { - disposable.Dispose(); - } - } - } - } - if (((nullable == null) - == false)) { - result.AllowedOperations = nullable; - } - unpacked = (unpacked + 1); - string nullable0 = default(string); - if ((unpacked < itemsCount)) { - nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.CapabilityResource), "System.String Name"); - } - if (((nullable0 == null) - == false)) { - result.Name = nullable0; - } - unpacked = (unpacked + 1); - } - else { - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) { - string key = default(string); - string nullable1 = default(string); - nullable1 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.CapabilityResource), "MemberName"); - if (((nullable1 == null) - == false)) { - key = nullable1; - } - else { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "Name")) { - string nullable3 = default(string); - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.CapabilityResource), "System.String Name"); - if (((nullable3 == null) - == false)) { - result.Name = nullable3; - } - } - else { - if ((key == "AllowedOperations")) { - System.Collections.Generic.List nullable2 = default(System.Collections.Generic.List); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable2 = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); - disposable0 = unpacker.ReadSubtree(); - try { - nullable2 = this._serializer1.UnpackFrom(disposable0); - } - finally { - if (((disposable0 == null) - == false)) { - disposable0.Dispose(); - } - } - } - if (((nullable2 == null) - == false)) { - result.AllowedOperations = nullable2; - } - } - else { - unpacker.Skip(); - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -} diff --git a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilitySerializer.cs b/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilitySerializer.cs deleted file mode 100644 index c5abf1b99..000000000 --- a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_CapabilitySerializer.cs +++ /dev/null @@ -1,133 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_CapabilitySerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer> _serializer1; - - public IO_Ably_CapabilitySerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer>(schema1); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Capability objectTree) { - packer.PackMapHeader(1); - this._serializer0.PackTo(packer, "Resources"); - this._serializer1.PackTo(packer, objectTree.Resources); - } - - protected override IO.Ably.Capability UnpackFromCore(MsgPack.Unpacker unpacker) { - IO.Ably.Capability result = default(IO.Ably.Capability); - result = new IO.Ably.Capability(); - if (unpacker.IsArrayHeader) { - int unpacked = default(int); - int itemsCount = default(int); - itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - System.Collections.Generic.List nullable = default(System.Collections.Generic.List); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable = default(MsgPack.Unpacker); - disposable = unpacker.ReadSubtree(); - try { - nullable = this._serializer1.UnpackFrom(disposable); - } - finally { - if (((disposable == null) - == false)) { - disposable.Dispose(); - } - } - } - } - if (((nullable == null) - == false)) { - result.Resources = nullable; - } - unpacked = (unpacked + 1); - } - else { - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) { - string key = default(string); - string nullable0 = default(string); - nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.Capability), "MemberName"); - if (((nullable0 == null) - == false)) { - key = nullable0; - } - else { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "Resources")) { - System.Collections.Generic.List nullable1 = default(System.Collections.Generic.List); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable1 = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); - disposable0 = unpacker.ReadSubtree(); - try { - nullable1 = this._serializer1.UnpackFrom(disposable0); - } - finally { - if (((disposable0 == null) - == false)) { - disposable0.Dispose(); - } - } - } - if (((nullable1 == null) - == false)) { - result.Resources = nullable1; - } - } - else { - unpacker.Skip(); - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -} diff --git a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_TokenRequestSerializer.cs b/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_TokenRequestSerializer.cs deleted file mode 100644 index 4f0d73e30..000000000 --- a/src/IO.Ably/CustomSerialisers/GeneratedSerializers/IO/Ably/CustomSerialisers/IO_Ably_TokenRequestSerializer.cs +++ /dev/null @@ -1,341 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace IO.Ably.CustomSerialisers { - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public class IO_Ably_TokenRequestSerializer : MsgPack.Serialization.MessagePackSerializer { - - private MsgPack.Serialization.MessagePackSerializer _serializer0; - - private MsgPack.Serialization.MessagePackSerializer _serializer1; - - private MsgPack.Serialization.MessagePackSerializer> _serializer2; - - private MsgPack.Serialization.MessagePackSerializer> _serializer3; - - public IO_Ably_TokenRequestSerializer(MsgPack.Serialization.SerializationContext context) : - base(context) { - MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); - schema0 = null; - this._serializer0 = context.GetSerializer(schema0); - MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); - schema1 = null; - this._serializer1 = context.GetSerializer(schema1); - MsgPack.Serialization.PolymorphismSchema schema2 = default(MsgPack.Serialization.PolymorphismSchema); - schema2 = null; - this._serializer2 = context.GetSerializer>(schema2); - MsgPack.Serialization.PolymorphismSchema schema3 = default(MsgPack.Serialization.PolymorphismSchema); - schema3 = null; - this._serializer3 = context.GetSerializer>(schema3); - } - - protected override void PackToCore(MsgPack.Packer packer, IO.Ably.TokenRequest objectTree) { - packer.PackMapHeader(7); - this._serializer0.PackTo(packer, "Capability"); - this._serializer1.PackTo(packer, objectTree.Capability); - this._serializer0.PackTo(packer, "ClientId"); - this._serializer0.PackTo(packer, objectTree.ClientId); - this._serializer0.PackTo(packer, "KeyName"); - this._serializer0.PackTo(packer, objectTree.KeyName); - this._serializer0.PackTo(packer, "Mac"); - this._serializer0.PackTo(packer, objectTree.Mac); - this._serializer0.PackTo(packer, "Nonce"); - this._serializer0.PackTo(packer, objectTree.Nonce); - this._serializer0.PackTo(packer, "Timestamp"); - this._serializer2.PackTo(packer, objectTree.Timestamp); - this._serializer0.PackTo(packer, "Ttl"); - this._serializer3.PackTo(packer, objectTree.Ttl); - } - - protected override IO.Ably.TokenRequest UnpackFromCore(MsgPack.Unpacker unpacker) { - IO.Ably.TokenRequest result = default(IO.Ably.TokenRequest); - result = new IO.Ably.TokenRequest(); - if (unpacker.IsArrayHeader) { - int unpacked = default(int); - int itemsCount = default(int); - itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - IO.Ably.Capability nullable = default(IO.Ably.Capability); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable = default(MsgPack.Unpacker); - disposable = unpacker.ReadSubtree(); - try { - nullable = this._serializer1.UnpackFrom(disposable); - } - finally { - if (((disposable == null) - == false)) { - disposable.Dispose(); - } - } - } - } - if (((nullable == null) - == false)) { - result.Capability = nullable; - } - unpacked = (unpacked + 1); - string nullable0 = default(string); - if ((unpacked < itemsCount)) { - nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String ClientId"); - } - if (((nullable0 == null) - == false)) { - result.ClientId = nullable0; - } - unpacked = (unpacked + 1); - string nullable1 = default(string); - if ((unpacked < itemsCount)) { - nullable1 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String KeyName"); - } - if (((nullable1 == null) - == false)) { - result.KeyName = nullable1; - } - unpacked = (unpacked + 1); - string nullable2 = default(string); - if ((unpacked < itemsCount)) { - nullable2 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String Mac"); - } - if (((nullable2 == null) - == false)) { - result.Mac = nullable2; - } - unpacked = (unpacked + 1); - string nullable3 = default(string); - if ((unpacked < itemsCount)) { - nullable3 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String Nonce"); - } - if (((nullable3 == null) - == false)) { - result.Nonce = nullable3; - } - unpacked = (unpacked + 1); - System.Nullable nullable4 = default(System.Nullable); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(5); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable4 = this._serializer2.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); - disposable0 = unpacker.ReadSubtree(); - try { - nullable4 = this._serializer2.UnpackFrom(disposable0); - } - finally { - if (((disposable0 == null) - == false)) { - disposable0.Dispose(); - } - } - } - } - if (nullable4.HasValue) { - result.Timestamp = nullable4; - } - unpacked = (unpacked + 1); - System.Nullable nullable5 = default(System.Nullable); - if ((unpacked < itemsCount)) { - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(6); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable5 = this._serializer3.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable1 = default(MsgPack.Unpacker); - disposable1 = unpacker.ReadSubtree(); - try { - nullable5 = this._serializer3.UnpackFrom(disposable1); - } - finally { - if (((disposable1 == null) - == false)) { - disposable1.Dispose(); - } - } - } - } - if (nullable5.HasValue) { - result.Ttl = nullable5; - } - unpacked = (unpacked + 1); - } - else { - int itemsCount0 = default(int); - itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); - for (int i = 0; (i < itemsCount0); i = (i + 1)) { - string key = default(string); - string nullable6 = default(string); - nullable6 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "MemberName"); - if (((nullable6 == null) - == false)) { - key = nullable6; - } - else { - throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); - } - if ((key == "Ttl")) { - System.Nullable nullable13 = default(System.Nullable); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable13 = this._serializer3.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable4 = default(MsgPack.Unpacker); - disposable4 = unpacker.ReadSubtree(); - try { - nullable13 = this._serializer3.UnpackFrom(disposable4); - } - finally { - if (((disposable4 == null) - == false)) { - disposable4.Dispose(); - } - } - } - if (nullable13.HasValue) { - result.Ttl = nullable13; - } - } - else { - if ((key == "Timestamp")) { - System.Nullable nullable12 = default(System.Nullable); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable12 = this._serializer2.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable3 = default(MsgPack.Unpacker); - disposable3 = unpacker.ReadSubtree(); - try { - nullable12 = this._serializer2.UnpackFrom(disposable3); - } - finally { - if (((disposable3 == null) - == false)) { - disposable3.Dispose(); - } - } - } - if (nullable12.HasValue) { - result.Timestamp = nullable12; - } - } - else { - if ((key == "Nonce")) { - string nullable11 = default(string); - nullable11 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String Nonce"); - if (((nullable11 == null) - == false)) { - result.Nonce = nullable11; - } - } - else { - if ((key == "Mac")) { - string nullable10 = default(string); - nullable10 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String Mac"); - if (((nullable10 == null) - == false)) { - result.Mac = nullable10; - } - } - else { - if ((key == "KeyName")) { - string nullable9 = default(string); - nullable9 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String KeyName"); - if (((nullable9 == null) - == false)) { - result.KeyName = nullable9; - } - } - else { - if ((key == "ClientId")) { - string nullable8 = default(string); - nullable8 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(IO.Ably.TokenRequest), "System.String ClientId"); - if (((nullable8 == null) - == false)) { - result.ClientId = nullable8; - } - } - else { - if ((key == "Capability")) { - IO.Ably.Capability nullable7 = default(IO.Ably.Capability); - if ((unpacker.Read() == false)) { - throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); - } - if (((unpacker.IsArrayHeader == false) - && (unpacker.IsMapHeader == false))) { - nullable7 = this._serializer1.UnpackFrom(unpacker); - } - else { - MsgPack.Unpacker disposable2 = default(MsgPack.Unpacker); - disposable2 = unpacker.ReadSubtree(); - try { - nullable7 = this._serializer1.UnpackFrom(disposable2); - } - finally { - if (((disposable2 == null) - == false)) { - disposable2.Dispose(); - } - } - } - if (((nullable7 == null) - == false)) { - result.Capability = nullable7; - } - } - else { - unpacker.Skip(); - } - } - } - } - } - } - } - } - } - return result; - } - - private static T @__Conditional(bool condition, T whenTrue, T whenFalse) - { - if (condition) { - return whenTrue; - } - else { - return whenFalse; - } - } - } -} diff --git a/tools/mono-install.sh b/tools/mono-install.sh deleted file mode 100755 index e001c2b2d..000000000 --- a/tools/mono-install.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -set -ex - -# Get the macos universal pkg installer download url -# for the version you want to install from: https://download.mono-project.com/archive/ -# and set it here as the value of this variable: -MONO_MACOS_PKG_DOWNLOAD_URL='https://download.mono-project.com/archive/6.12.0/macos-10-universal/MonoFramework-MDK-6.12.0.206.macos10.xamarin.universal.pkg' - -# create a temp dir and cd into it -mkdir -p /tmp/mono-install -cd /tmp/mono-install - -# debug: mono version before the install (if it exists) -if command -v mono &> /dev/null; then - echo "Mono is already installed:" - mono --version -else - echo "Mono is not currently installed" -fi - -# download mono mac installer (pkg) -wget -q -O ./mono-installer.pkg "$MONO_MACOS_PKG_DOWNLOAD_URL" - -# install it -sudo installer -pkg ./mono-installer.pkg -target / - -# debug: mono version after install, just to confirm it did overwrite the original version -mono --version - -# just for fun print this symlink too, which should point to the version we just installed -ls -alh /Library/Frameworks/Mono.framework/Versions/Current diff --git a/unity/Assets/Tests/AblySandbox/AblySandbox.cs b/unity/Assets/Tests/AblySandbox/AblySandbox.cs index 4a187c57b..576a5fc22 100644 --- a/unity/Assets/Tests/AblySandbox/AblySandbox.cs +++ b/unity/Assets/Tests/AblySandbox/AblySandbox.cs @@ -68,7 +68,7 @@ public async Task GetRestClient(Protocol protocol, Action GetRealtimeClient(Protocol protocol, Action _settings = new Dictionary(); + private static Protocol sandboxJsonProtocol = Protocol.Json; + public async Task GetSettings(string environment = null) { environment = environment ?? "sandbox"; @@ -47,11 +49,11 @@ private static async Task Initialise(string environment CipherMode.CBC, ((string)cipher["iv"]).FromBase64()); - var request = new AblyRequest("/apps", HttpMethod.Post); + var request = new AblyRequest("/apps", HttpMethod.Post, sandboxJsonProtocol); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); request.RequestBody = testAppSpec["post_apps"].ToString().GetBytes(); - request.Protocol = Protocol.Json; + request.Protocol = sandboxJsonProtocol; AblyHttpClient client = settings.GetHttpClient(environment); var response = await RetryExecute(() => client.Execute(request)); @@ -114,8 +116,8 @@ private static async Task SetupSampleStats(TestEnvironmentSettings settings) json = json.Replace("[[Interval3]]", interval3.ToString("yyyy-MM-dd:HH:mm")); AblyHttpClient client = settings.GetHttpClient(); - var request = new AblyRequest("/stats", HttpMethod.Post); - request.Protocol = Protocol.Json; + var request = new AblyRequest("/stats", HttpMethod.Post, sandboxJsonProtocol); + request.Protocol = sandboxJsonProtocol; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); diff --git a/unity/Assets/Tests/AblySandbox/TestTransportFactory.cs b/unity/Assets/Tests/AblySandbox/TestTransportFactory.cs index 742ee01ed..bdbf8cca3 100644 --- a/unity/Assets/Tests/AblySandbox/TestTransportFactory.cs +++ b/unity/Assets/Tests/AblySandbox/TestTransportFactory.cs @@ -28,7 +28,7 @@ public ITransport CreateTransport(TransportParams parameters) { var factory = IoC.TransportFactory; var transport - = new TestTransportWrapper(factory.CreateTransport(parameters), parameters.UseBinaryProtocol ? Defaults.Protocol : Protocol.Json); + = new TestTransportWrapper(factory.CreateTransport(parameters), parameters.UseBinaryProtocol ? Protocol.MsgPack : Protocol.Json); transport.BeforeDataProcessed = BeforeDataProcessed; OnTransportCreated(transport); diff --git a/unity/Assets/Tests/EditMode/AblyRealtimeSpecs.cs b/unity/Assets/Tests/EditMode/AblyRealtimeSpecs.cs index dcd4c64ed..53be78e80 100644 --- a/unity/Assets/Tests/EditMode/AblyRealtimeSpecs.cs +++ b/unity/Assets/Tests/EditMode/AblyRealtimeSpecs.cs @@ -217,7 +217,7 @@ public IEnumerator TestHttpUnityAgentHeader([ValueSource(nameof(_protocols))] Pr var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions(), handler); - await client.Execute(new AblyRequest("/test", HttpMethod.Get)); + await client.Execute(new AblyRequest("/test", HttpMethod.Get, protocol)); string[] values = handler.LastRequest.Headers.GetValues("Ably-Agent").ToArray(); Assert.AreEqual(1, values.Length); string[] agentValues = values[0].Split(' '); diff --git a/unity/Assets/Tests/EditMode/AuthSpecs.cs b/unity/Assets/Tests/EditMode/AuthSpecs.cs index e2fb55be4..79e74625f 100644 --- a/unity/Assets/Tests/EditMode/AuthSpecs.cs +++ b/unity/Assets/Tests/EditMode/AuthSpecs.cs @@ -9,7 +9,6 @@ using IO.Ably; using IO.Ably.Realtime; using NUnit.Framework; -using UnityEngine; using UnityEngine.TestTools; namespace Assets.Tests.EditMode @@ -374,7 +373,7 @@ public IEnumerator RealTimeWithAuthUrl_WhenTokenExpired_And_WithServerTime_And_N }; await Task.Delay(2000); // This makes sure we get server time - ((AblyAuth) mainClient.Auth).SetServerTime(); + await ((AblyAuth) mainClient.Auth).SetServerTime(); var ex = await E7Assert.ThrowsAsync(mainClient.StatsAsync()); Assert.AreSame(ErrorInfo.NonRenewableToken, ex.ErrorInfo); @@ -730,7 +729,7 @@ public IEnumerator TokenAuthWithoutClientId_ShouldNotSetClientIdOnMessagesAndThe { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); Assert.IsTrue(string.IsNullOrEmpty(tokenClient.AblyAuth.ClientId)); @@ -755,7 +754,7 @@ public IEnumerator TokenAuthWithoutClientIdAndAMessageWithExplicitId_ShouldThrow { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); await E7Assert.ThrowsAsync(tokenClient.Channels["test"] @@ -776,7 +775,7 @@ public IEnumerator TokenAuthWithWildcardClientId_ShouldPublishMessageSuccessfull { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -801,7 +800,7 @@ public IEnumerator TokenAuthWithWildcardClientId_WhenPublishingMessageWithClient { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -827,7 +826,7 @@ public IEnumerator TokenAuthUrlWhenPlainTextTokenIsReturn_ShouldBeAblyToPublishW { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = authUrlClient.Channels["pesisted:test"]; @@ -853,7 +852,7 @@ public IEnumerator TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToPublishWithNe { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20) }); @@ -881,7 +880,7 @@ public IEnumerator TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToConnect([Valu { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20), AutomaticNetworkStateMonitoring = false }); @@ -906,7 +905,7 @@ public IEnumerator TokenAuthUrlWithIncorrectJsonTokenReturned_ShouldNotBeAbleToC { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20), AutomaticNetworkStateMonitoring = false }); @@ -939,7 +938,7 @@ public IEnumerator TokenAuthCallbackWithTokenDetailsReturned_ShouldBeAbleToPubli options.AuthCallback = tokenParams => tokenClient.Auth.RequestTokenAsync(new TokenParams { ClientId = "*" }).Convert(); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"]; @@ -965,7 +964,7 @@ public IEnumerator TokenAuthCallbackWithTokenRequestReturned_ShouldBeAbleToGetAT options.AuthCallback = async tokenParams => await tokenClient.Auth.CreateTokenRequestAsync(new TokenParams { ClientId = "*" }); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"]; diff --git a/unity/Assets/Tests/PlayMode/AblyRealtimeSpecs.cs b/unity/Assets/Tests/PlayMode/AblyRealtimeSpecs.cs index 78a9486c6..220654c77 100644 --- a/unity/Assets/Tests/PlayMode/AblyRealtimeSpecs.cs +++ b/unity/Assets/Tests/PlayMode/AblyRealtimeSpecs.cs @@ -217,7 +217,7 @@ public IEnumerator TestHttpUnityAgentHeader([ValueSource(nameof(_protocols))] Pr var handler = new FakeHttpMessageHandler(response); var client = new AblyHttpClient(new AblyHttpOptions(), handler); - await client.Execute(new AblyRequest("/test", HttpMethod.Get)); + await client.Execute(new AblyRequest("/test", HttpMethod.Get, protocol)); string[] values = handler.LastRequest.Headers.GetValues("Ably-Agent").ToArray(); Assert.AreEqual(1, values.Length); string[] agentValues = values[0].Split(' '); diff --git a/unity/Assets/Tests/PlayMode/AuthSpecs.cs b/unity/Assets/Tests/PlayMode/AuthSpecs.cs index b6689fd08..f361e07a9 100644 --- a/unity/Assets/Tests/PlayMode/AuthSpecs.cs +++ b/unity/Assets/Tests/PlayMode/AuthSpecs.cs @@ -375,7 +375,7 @@ public IEnumerator RealTimeWithAuthUrl_WhenTokenExpired_And_WithServerTime_And_N }; await Task.Delay(2000); // This makes sure we get server time - ((AblyAuth) mainClient.Auth).SetServerTime(); + await ((AblyAuth) mainClient.Auth).SetServerTime(); var ex = await E7Assert.ThrowsAsync(mainClient.StatsAsync()); Assert.AreSame(ErrorInfo.NonRenewableToken, ex.ErrorInfo); @@ -731,7 +731,7 @@ public IEnumerator TokenAuthWithoutClientId_ShouldNotSetClientIdOnMessagesAndThe { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); Assert.IsTrue(string.IsNullOrEmpty(tokenClient.AblyAuth.ClientId)); @@ -756,7 +756,7 @@ public IEnumerator TokenAuthWithoutClientIdAndAMessageWithExplicitId_ShouldThrow { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); await E7Assert.ThrowsAsync(tokenClient.Channels["test"] @@ -777,7 +777,7 @@ public IEnumerator TokenAuthWithWildcardClientId_ShouldPublishMessageSuccessfull { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -802,7 +802,7 @@ public IEnumerator TokenAuthWithWildcardClientId_WhenPublishingMessageWithClient { TokenDetails = token, Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = tokenClient.Channels["pesisted:test"]; @@ -828,7 +828,7 @@ public IEnumerator TokenAuthUrlWhenPlainTextTokenIsReturn_ShouldBeAblyToPublishW { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol + UseBinaryProtocol = protocol.IsBinary() }); var channel = authUrlClient.Channels["pesisted:test"]; @@ -854,7 +854,7 @@ public IEnumerator TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToPublishWithNe { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20) }); @@ -882,7 +882,7 @@ public IEnumerator TokenAuthUrlWithJsonTokenReturned_ShouldBeAbleToConnect([Valu { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20), AutomaticNetworkStateMonitoring = false }); @@ -907,7 +907,7 @@ public IEnumerator TokenAuthUrlWithIncorrectJsonTokenReturned_ShouldNotBeAbleToC { AuthUrl = new Uri(authUrl), Environment = settings.Environment, - UseBinaryProtocol = protocol == Defaults.Protocol, + UseBinaryProtocol = protocol.IsBinary(), HttpRequestTimeout = new TimeSpan(0, 0, 20), AutomaticNetworkStateMonitoring = false }); @@ -940,7 +940,7 @@ public IEnumerator TokenAuthCallbackWithTokenDetailsReturned_ShouldBeAbleToPubli options.AuthCallback = tokenParams => tokenClient.Auth.RequestTokenAsync(new TokenParams { ClientId = "*" }).Convert(); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"]; @@ -966,7 +966,7 @@ public IEnumerator TokenAuthCallbackWithTokenRequestReturned_ShouldBeAbleToGetAT options.AuthCallback = async tokenParams => await tokenClient.Auth.CreateTokenRequestAsync(new TokenParams { ClientId = "*" }); options.Environment = settings.Environment; - options.UseBinaryProtocol = protocol == Defaults.Protocol; + options.UseBinaryProtocol = protocol.IsBinary(); }); var channel = authCallbackClient.Channels["pesisted:test"];