From 5b74b523e5995538e21b446dd3a9972062d1558e Mon Sep 17 00:00:00 2001 From: Jedd Morgan <45512892+JR-Morgan@users.noreply.github.com> Date: Fri, 14 Apr 2023 13:37:32 +0100 Subject: [PATCH] reformat(core): Re-reformat of core (#2425) * reformat(core): Leftover cleanup run * ci(navis): navisworks 2024 post build --------- Co-authored-by: Alan Rynne --- .vscode/extensions.json | 7 + .vscode/tasks.json | 65 +- All.sln.DotSettings | 139 ++--- .../ConnectorNavisworks2024.csproj | 2 +- Core/Core/Api/Exceptions.cs | 22 +- .../Client.CommitOperations.cs | 12 +- .../Client.ObjectOperations.cs | 24 +- .../Client.StreamOperations.cs | 16 +- .../Client.Subscriptions.Stream.cs | 2 +- Core/Core/Api/GraphQL/Client.cs | 8 +- Core/Core/Api/GraphQL/Models.cs | 4 +- .../Api/GraphQL/Serializer/MapConverter.cs | 7 +- Core/Core/Api/Helpers.cs | 8 +- .../Core/Api/Operations/Operations.Receive.cs | 9 +- Core/Core/Api/Operations/Operations.Send.cs | 2 +- .../Api/Operations/Operations.Serialize.cs | 33 +- Core/Core/Api/Operations/Operations.cs | 20 +- Core/Core/Credentials/Account.cs | 23 +- Core/Core/Credentials/AccountManager.cs | 19 +- Core/Core/Helpers/Http.cs | 1 - Core/Core/Kits/Attributes.cs | 9 +- Core/Core/Kits/ISpeckleKit.cs | 7 +- Core/Core/Kits/KitDeclaration.cs | 2 - Core/Core/Kits/KitManager.cs | 4 +- Core/Core/Logging/Analytics.cs | 10 +- Core/Core/Logging/Log.cs | 4 +- Core/Core/Logging/Setup.cs | 2 +- Core/Core/Logging/SpeckleException.cs | 4 +- Core/Core/Logging/SpeckleLog.cs | 2 +- Core/Core/Models/Base.cs | 7 +- Core/Core/Models/DynamicBase.cs | 2 - Core/Core/Models/Extras.cs | 10 +- .../Models/GraphTraversal/DefaultTraversal.cs | 1 + Core/Core/Models/InvalidPropNameException.cs | 4 + Core/Core/Models/Utilities.cs | 4 +- .../Serialisation/BaseObjectDeserializerV2.cs | 7 +- .../Serialisation/BaseObjectSerializer.cs | 16 +- .../Serialisation/BaseObjectSerializerV2.cs | 8 +- .../BaseObjectSerialzerUtilities.cs | 18 +- .../DeserializationWorkerThreads.cs | 10 +- Core/Core/Serialisation/ValueConverter.cs | 54 +- Core/Core/Transports/Memory.cs | 4 +- Core/Core/Transports/SQLite.cs | 11 +- Core/Core/Transports/Server.cs | 24 +- .../ServerUtils/ParallelServerAPI.cs | 10 +- Core/Core/Transports/ServerUtils/ServerAPI.cs | 18 +- Core/Core/Transports/ServerV2.cs | 16 +- Core/Examples/Program.cs | 579 +++++++++--------- Core/Examples/Subscriptions.cs | 61 +- Core/IntegrationTests/Api.cs | 4 +- Core/IntegrationTests/Fixtures.cs | 9 +- .../IntegrationTests/Subscriptions/Commits.cs | 2 +- Core/Tests/BaseTests.cs | 4 +- Core/Tests/ClosureTests.cs | 6 +- Core/Tests/Fixtures.cs | 6 +- Core/Tests/GraphQLClient.cs | 7 +- Core/Tests/Hashing.cs | 4 +- .../ObjectTraversal/GraphTraversalTests.cs | 24 +- Core/Tests/SendReceiveLocal.cs | 12 +- Core/Tests/SerializationTests.cs | 13 +- Core/Tests/SerializerNonBreakingChanges.cs | 6 +- Core/Tests/TestKit.cs | 38 +- Core/Tests/TraversalTests.cs | 6 +- .../Transports/DiskTransport/DiskTransport.cs | 9 +- Core/Transports/MongoDBTransport/MongoDB.cs | 4 +- Directory.Build.props | 3 +- 66 files changed, 710 insertions(+), 778 deletions(-) create mode 100644 .vscode/extensions.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000000..22db1723c7 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "rioj7.command-variable", + "k--kato.docomment", + "csharpier.csharpier-vscode" + ] +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 00d21cf94f..b7323eb98b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -4,10 +4,15 @@ "version": "2.0.0", "inputs": [ { - "type": "promptString", "id": "projectPath", - "description": "The path to the csproj, sln or slnf you want formatting", - "default": "./All.sln" + "type": "command", + "command": "extension.commandvariable.file.pickFile", + "args": { + "include": "**/*.{sln,slnf}", + "key": "projPath", + "keyRemember": "projPath", + "display": "fileName" + } } ], "tasks": [ @@ -17,11 +22,12 @@ "type": "shell", "args": ["csharpier", "${input:projectPath}/.."], "group": "build", - "presentation": { - "reveal": "silent" - }, "problemMatcher": "$msCompile", - "hide": true + "hide": true, + "presentation": { + "focus": true, + "showReuseMessage": false + } }, { "label": "speckle.format.style", @@ -29,11 +35,12 @@ "type": "shell", "args": ["format", "style", "${input:projectPath}"], "group": "build", - "presentation": { - "reveal": "silent" - }, "problemMatcher": "$msCompile", - "hide": true + "hide": true, + "presentation": { + "focus": true, + "showReuseMessage": false + } }, { "label": "speckle.format.whitespace", @@ -41,11 +48,12 @@ "type": "shell", "args": ["format", "whitespace", "${input:projectPath}"], "group": "build", - "presentation": { - "reveal": "silent" - }, "problemMatcher": "$msCompile", - "hide": true + "hide": true, + "presentation": { + "focus": true, + "showReuseMessage": false + } }, { "label": "speckle.format.analyzers", @@ -53,11 +61,12 @@ "type": "shell", "args": ["format", "analyzers", "${input:projectPath}"], "group": "build", - "presentation": { - "reveal": "silent" - }, "problemMatcher": "$msCompile", - "hide": true + "hide": false, + "presentation": { + "focus": true, + "showReuseMessage": false + } }, { "label": "speckle.format.resharper", @@ -69,19 +78,23 @@ "jb", "cleanupcode", "${input:projectPath}", - "--profile=\"Speckle:\\sCustom\\sCleanup\"", - "--settings=\"All.sln.DotSettings\"", + "--profile=\"Speckle:Cleanup\"", + "--settings=\"All.sln.DotSettings\"" ], "group": "build", - "problemMatcher": "$msCompile", - "hide": false + "problemMatcher": [], + "hide": false, + "presentation": { + "focus": true, + "showReuseMessage": false + } }, { "label": "Speckle: Format Code", "dependsOn": [ "speckle.format.whitespace", "speckle.format.style", - "speckle.format.csharpier", + "speckle.format.csharpier" ], "dependsOrder": "sequence", "problemMatcher": [] @@ -89,9 +102,11 @@ { "label": "Speckle: Cleanup Code", "dependsOn": [ - "Speckle: Format Code", + "speckle.format.whitespace", + "speckle.format.style", "speckle.format.analyzers", "speckle.format.resharper", + "speckle.format.csharpier" ], "dependsOrder": "sequence", "problemMatcher": [] diff --git a/All.sln.DotSettings b/All.sln.DotSettings index bcd3a0b513..176dbbe535 100644 --- a/All.sln.DotSettings +++ b/All.sln.DotSettings @@ -1,75 +1,70 @@  - - <?xml version="1.0" encoding="utf-16"?><Profile name="Speckle: Custom Cleanup"><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><CppCodeStyleCleanupDescriptor ArrangeBraces="True" ArrangeAuto="True" ArrangeFunctionDeclarations="True" ArrangeNestedNamespaces="True" ArrangeTypeAliases="True" ArrangeCVQualifiers="True" ArrangeSlashesInIncludeDirectives="True" ArrangeOverridingFunctions="True" SortIncludeDirectives="True" SortMemberInitializers="True" /><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" ArrangeArgumentsStyle="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeCodeBodyStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" ArrangeNamespaces="True" /><Xaml.RemoveRedundantNamespaceAlias>True</Xaml.RemoveRedundantNamespaceAlias><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><VBOptimizeImports>True</VBOptimizeImports><VBShortenReferences>True</VBShortenReferences><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><IDEA_SETTINGS>&lt;profile version="1.0"&gt; - &lt;option name="myName" value="Speckle: Custom Cleanup" /&gt; - &lt;inspection_tool class="ES6ShorthandObjectProperty" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="JSArrowFunctionBracesCanBeRemoved" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="JSPrimitiveTypeWrapperUsage" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="JSRemoveUnnecessaryParentheses" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="JSUnnecessarySemicolon" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="TypeScriptExplicitMemberType" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="UnnecessaryContinueJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="UnnecessaryLabelJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="UnnecessaryLabelOnBreakStatementJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="UnnecessaryLabelOnContinueStatementJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="UnnecessaryReturnJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; - &lt;inspection_tool class="WrongPropertyKeyValueDelimiter" enabled="false" level="WEAK WARNING" enabled_by_default="false" /&gt; -&lt;/profile&gt;</IDEA_SETTINGS><RIDER_SETTINGS>&lt;profile&gt; - &lt;Language id="CSS"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;Rearrange&gt;true&lt;/Rearrange&gt; - &lt;/Language&gt; - &lt;Language id="EditorConfig"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="HTML"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;Rearrange&gt;true&lt;/Rearrange&gt; - &lt;/Language&gt; - &lt;Language id="HTTP Request"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Handlebars"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Ini"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="JSON"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Jade"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="JavaScript"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;Rearrange&gt;true&lt;/Rearrange&gt; - &lt;/Language&gt; - &lt;Language id="Markdown"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Properties"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="RELAX-NG"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="SQL"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="VueExpr"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="XML"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;Rearrange&gt;true&lt;/Rearrange&gt; - &lt;/Language&gt; - &lt;Language id="yaml"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; + <?xml version="1.0" encoding="utf-16"?><Profile name="Speckle:Cleanup"><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><CppCodeStyleCleanupDescriptor ArrangeBraces="True" ArrangeAuto="True" ArrangeFunctionDeclarations="True" ArrangeNestedNamespaces="True" ArrangeTypeAliases="True" ArrangeCVQualifiers="True" ArrangeSlashesInIncludeDirectives="True" ArrangeOverridingFunctions="True" SortIncludeDirectives="True" SortMemberInitializers="True" /><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" ArrangeArgumentsStyle="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeCodeBodyStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" ArrangeNamespaces="True" /><Xaml.RemoveRedundantNamespaceAlias>True</Xaml.RemoveRedundantNamespaceAlias><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><VBOptimizeImports>True</VBOptimizeImports><VBShortenReferences>True</VBShortenReferences><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><IDEA_SETTINGS>&lt;profile version="1.0"&gt; + &lt;option name="myName" value="Speckle:Cleanup" /&gt; + &lt;inspection_tool class="ES6ShorthandObjectProperty" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="JSArrowFunctionBracesCanBeRemoved" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="JSPrimitiveTypeWrapperUsage" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="JSRemoveUnnecessaryParentheses" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="JSUnnecessarySemicolon" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="TypeScriptExplicitMemberType" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="UnnecessaryContinueJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="UnnecessaryLabelJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="UnnecessaryLabelOnBreakStatementJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="UnnecessaryLabelOnContinueStatementJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="UnnecessaryReturnJS" enabled="false" level="WARNING" enabled_by_default="false" /&gt; + &lt;inspection_tool class="WrongPropertyKeyValueDelimiter" enabled="false" level="WEAK WARNING" enabled_by_default="false" /&gt; +&lt;/profile&gt;</IDEA_SETTINGS><RIDER_SETTINGS>&lt;profile&gt; + &lt;Language id="CSS"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;Rearrange&gt;true&lt;/Rearrange&gt; + &lt;/Language&gt; + &lt;Language id="EditorConfig"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="HTML"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;Rearrange&gt;true&lt;/Rearrange&gt; + &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; + &lt;/Language&gt; + &lt;Language id="HTTP Request"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="Handlebars"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="Ini"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="JSON"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="Jade"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="JavaScript"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;Rearrange&gt;true&lt;/Rearrange&gt; + &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; + &lt;/Language&gt; + &lt;Language id="Markdown"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="Properties"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="RELAX-NG"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; + &lt;Language id="XML"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;Rearrange&gt;true&lt;/Rearrange&gt; + &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; + &lt;/Language&gt; + &lt;Language id="yaml"&gt; + &lt;Reformat&gt;false&lt;/Reformat&gt; + &lt;/Language&gt; &lt;/profile&gt;</RIDER_SETTINGS><CSReorderTypeMembers>True</CSReorderTypeMembers><RemoveCodeRedundancies>True</RemoveCodeRedundancies></Profile> - Speckle: Custom Cleanup + + + Speckle:Cleanup ExternalToolData|CSharpier|csharpier||csharpier|$FILE$ \ No newline at end of file diff --git a/ConnectorNavisworks/ConnectorNavisworks2024/ConnectorNavisworks2024.csproj b/ConnectorNavisworks/ConnectorNavisworks2024/ConnectorNavisworks2024.csproj index 07b1d44cc8..c28efabcc4 100644 --- a/ConnectorNavisworks/ConnectorNavisworks2024/ConnectorNavisworks2024.csproj +++ b/ConnectorNavisworks/ConnectorNavisworks2024/ConnectorNavisworks2024.csproj @@ -146,7 +146,7 @@ xcopy /e /i /y "$(TargetDir)*.*" "$(PluginVersionContentTarget)\" - + echo RELEASE copy from $(TargetDir) to $(SolutionDir)Release\Release\$(NavisworksVersion)\" xcopy /e /i /y "$(TargetDir)*.*" "$(SolutionDir)Release\Release$(NavisworksVersion)\" diff --git a/Core/Core/Api/Exceptions.cs b/Core/Core/Api/Exceptions.cs index b00e5c91b0..76dc8a4bc3 100644 --- a/Core/Core/Api/Exceptions.cs +++ b/Core/Core/Api/Exceptions.cs @@ -35,15 +35,18 @@ public SpeckleGraphQLException( ) : base(message, inner) { } - public IEnumerable ErrorMessages => - Response?.Errors != null ? Response.Errors.Select(e => e.Message) : new string[] { }; - - public IDictionary? Extensions => Response?.Extensions; - public SpeckleGraphQLException() { } public SpeckleGraphQLException(string message) : base(message) { } + + public SpeckleGraphQLException(string message, Exception innerException) + : base(message, innerException) { } + + public IEnumerable ErrorMessages => + Response?.Errors != null ? Response.Errors.Select(e => e.Message) : new string[] { }; + + public IDictionary? Extensions => Response?.Extensions; } public class SpeckleGraphQLException : SpeckleGraphQLException @@ -59,6 +62,9 @@ public SpeckleGraphQLException() { } public SpeckleGraphQLException(string message) : base(message) { } + + public SpeckleGraphQLException(string message, Exception innerException) + : base(message, innerException) { } } /// @@ -75,6 +81,9 @@ public SpeckleGraphQLForbiddenException() { } public SpeckleGraphQLForbiddenException(string message) : base(message) { } + + public SpeckleGraphQLForbiddenException(string message, Exception innerException) + : base(message, innerException) { } } public class SpeckleGraphQLInternalErrorException : SpeckleGraphQLException @@ -86,4 +95,7 @@ public SpeckleGraphQLInternalErrorException() { } public SpeckleGraphQLInternalErrorException(string message) : base(message) { } + + public SpeckleGraphQLInternalErrorException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs index d45f09190e..eeb932bf90 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs @@ -37,9 +37,9 @@ string commitId var request = new GraphQLRequest { Query = - $@"query Stream($streamId: String!, $commitId: String!) {{ - stream(id: $streamId) {{ - commit(id: $commitId){{ + @"query Stream($streamId: String!, $commitId: String!) { + stream(id: $streamId) { + commit(id: $commitId){ id, message, sourceApplication, @@ -49,9 +49,9 @@ string commitId createdAt, parents, authorName - }} - }} - }}", + } + } + }", Variables = new { streamId, commitId } }; diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs index 070e74e9e2..0c0b76bef4 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs @@ -35,16 +35,16 @@ string objectId var request = new GraphQLRequest { Query = - $@"query Stream($streamId: String!, $objectId: String!) {{ - stream(id: $streamId) {{ - object(id: $objectId){{ + @"query Stream($streamId: String!, $objectId: String!) { + stream(id: $streamId) { + object(id: $objectId){ id applicationId createdAt totalChildrenCount - }} - }} - }}", + } + } + }", Variables = new { streamId, objectId } }; @@ -80,13 +80,13 @@ string objectId var request = new GraphQLRequest { Query = - $@"query Stream($streamId: String!, $objectId: String!) {{ - stream(id: $streamId) {{ - object(id: $objectId){{ + @"query Stream($streamId: String!, $objectId: String!) { + stream(id: $streamId) { + object(id: $objectId){ totalChildrenCount - }} - }} - }}", + } + } + }", Variables = new { streamId, objectId } }; diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs index c5e33071be..4ff38b1534 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs @@ -485,20 +485,20 @@ string id var request = new GraphQLRequest { Query = - $@"query Stream($id: String!) {{ - stream(id: $id) {{ + @"query Stream($id: String!) { + stream(id: $id) { id - pendingCollaborators {{ + pendingCollaborators { id inviteId title role - user {{ + user { avatar - }} - }} - }} - }}", + } + } + } + }", Variables = new { id } }; var res = await GQLClient diff --git a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs index 0b7f76801e..69117a9286 100644 --- a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs +++ b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs @@ -71,7 +71,7 @@ public void SubscribeStreamUpdated(string id) /// public void SubscribeUserStreamRemoved() { - var request = new GraphQLRequest { Query = $@"subscription {{ userStreamRemoved }}" }; + var request = new GraphQLRequest { Query = @"subscription { userStreamRemoved }" }; UserStreamRemovedSubscription = SubscribeTo( request, diff --git a/Core/Core/Api/GraphQL/Client.cs b/Core/Core/Api/GraphQL/Client.cs index 0106e5c7ef..3618be71d0 100644 --- a/Core/Core/Api/GraphQL/Client.cs +++ b/Core/Core/Api/GraphQL/Client.cs @@ -32,7 +32,7 @@ public Client() { } public Client(Account account) { if (account == null) - throw new SpeckleException($"Provided account is null."); + throw new SpeckleException("Provided account is null."); Account = account; @@ -54,7 +54,7 @@ public Client(Account account) { EndPoint = new Uri(new Uri(account.serverInfo.url), "/graphql"), UseWebSocketForQueriesAndMutations = false, - ConfigureWebSocketConnectionInitPayload = (opts) => + ConfigureWebSocketConnectionInitPayload = opts => { return new { Authorization = $"Bearer {account.token}" }; }, @@ -71,7 +71,7 @@ public Client(Account account) $"WebSocketException: {we.Message} (WebSocketError {we.WebSocketErrorCode}, ErrorCode {we.ErrorCode}, NativeErrorCode {we.NativeErrorCode}" ); else - Console.WriteLine($"Exception in websocket receive stream: {e.ToString()}"); + Console.WriteLine($"Exception in websocket receive stream: {e}"); }); } @@ -319,7 +319,7 @@ internal IDisposable SubscribeTo(GraphQLRequest request, Action ca { try { - MaybeThrowFromGraphQLErrors(request, response); + MaybeThrowFromGraphQLErrors(request, response); if (response.Data != null) callback(this, response.Data); diff --git a/Core/Core/Api/GraphQL/Models.cs b/Core/Core/Api/GraphQL/Models.cs index bfee373b8b..99d542978b 100644 --- a/Core/Core/Api/GraphQL/Models.cs +++ b/Core/Core/Api/GraphQL/Models.cs @@ -428,7 +428,7 @@ public class CommentItem public List resources { get; set; } } -public partial class ContentContent +public class ContentContent { public string Type { get; set; } @@ -491,7 +491,7 @@ public Version( [JsonIgnore] public string DateTimeAgo => Helpers.TimeAgo(Date); - public bool Prerelease { get; set; } = false; + public bool Prerelease { get; set; } } /// diff --git a/Core/Core/Api/GraphQL/Serializer/MapConverter.cs b/Core/Core/Api/GraphQL/Serializer/MapConverter.cs index a1f1e2d721..d5bf976b13 100644 --- a/Core/Core/Api/GraphQL/Serializer/MapConverter.cs +++ b/Core/Core/Api/GraphQL/Serializer/MapConverter.cs @@ -27,10 +27,9 @@ JsonSerializer serializer var rootToken = JToken.ReadFrom(reader); if (rootToken is JObject) return (Map)ReadDictionary(rootToken, new Map()); - else - throw new ArgumentException( - "This converter can only parse when the root element is a JSON Object." - ); + throw new ArgumentException( + "This converter can only parse when the root element is a JSON Object." + ); } private object? ReadToken(JToken? token) diff --git a/Core/Core/Api/Helpers.cs b/Core/Core/Api/Helpers.cs index cf934e94c3..2878d6a7b2 100644 --- a/Core/Core/Api/Helpers.cs +++ b/Core/Core/Api/Helpers.cs @@ -98,10 +98,10 @@ public static async Task Receive( throw e; //Fallback to a non authed account - account = new Account() + account = new Account { token = "", - serverInfo = new ServerInfo() { url = sw.ServerUrl }, + serverInfo = new ServerInfo { url = sw.ServerUrl }, userInfo = new UserInfo() }; } @@ -131,7 +131,7 @@ public static async Task Receive( var branch = await client.BranchGet(sw.StreamId, branchName, 1).ConfigureAwait(false); if (!branch.commits.items.Any()) - throw new SpeckleException($"The selected branch has no commits."); + throw new SpeckleException("The selected branch has no commits."); commit = branch.commits.items[0]; objectId = branch.commits.items[0].referencedObject; @@ -140,7 +140,7 @@ public static async Task Receive( Analytics.TrackEvent( client.Account, Analytics.Events.Receive, - new Dictionary() + new Dictionary { { "sourceHostApp", HostApplications.GetHostAppFromString(commit.sourceApplication).Slug }, { "sourceHostAppVersion", commit.sourceApplication } diff --git a/Core/Core/Api/Operations/Operations.Receive.cs b/Core/Core/Api/Operations/Operations.Receive.cs index d78e8d8c06..f7218be93c 100644 --- a/Core/Core/Api/Operations/Operations.Receive.cs +++ b/Core/Core/Api/Operations/Operations.Receive.cs @@ -164,7 +164,7 @@ public static partial class Operations .ForContext("deserializerElapsed", serializerV2?.Elapsed) .ForContext( "transportElapsedBreakdown", - new ITransport?[] { localTransport, remoteTransport } + new[] { localTransport, remoteTransport } .Where(t => t != null) .ToDictionary(t => t!.TransportName, t => t!.Elapsed) ) @@ -176,7 +176,8 @@ public static partial class Operations ); return localRes; } - else if (remoteTransport == null) + + if (remoteTransport == null) { var ex = new SpeckleException( $"Could not find specified object using the local transport {localTransport.TransportName}, and you didn't provide a fallback remote from which to pull it." @@ -219,7 +220,7 @@ public static partial class Operations .ForContext("deserializerElapsed", serializerV2.Elapsed) .ForContext( "transportElapsedBreakdown", - new ITransport?[] { localTransport, remoteTransport } + new[] { localTransport, remoteTransport } .Where(t => t != null) .ToDictionary(t => t.TransportName, t => t.Elapsed) ) @@ -269,7 +270,7 @@ public static partial class Operations throw; serializerV2.OnErrorAction.Invoke( $"A deserialization error has occurred: {ex.Message}", - new SpeckleDeserializeException($"A deserialization error has occurred", ex) + new SpeckleDeserializeException("A deserialization error has occurred", ex) ); localRes = null; } diff --git a/Core/Core/Api/Operations/Operations.Send.cs b/Core/Core/Api/Operations/Operations.Send.cs index f68def6ef4..99f23b8fed 100644 --- a/Core/Core/Api/Operations/Operations.Send.cs +++ b/Core/Core/Api/Operations/Operations.Send.cs @@ -81,7 +81,7 @@ public static async Task Send( ); if (useDefaultCache) - transports.Insert(0, new SQLiteTransport() { TransportName = "LC" }); + transports.Insert(0, new SQLiteTransport { TransportName = "LC" }); var transportContext = transports.ToDictionary(t => t.TransportName, t => t.TransportContext); diff --git a/Core/Core/Api/Operations/Operations.Serialize.cs b/Core/Core/Api/Operations/Operations.Serialize.cs index 30a6722af0..39428365df 100644 --- a/Core/Core/Api/Operations/Operations.Serialize.cs +++ b/Core/Core/Api/Operations/Operations.Serialize.cs @@ -21,7 +21,7 @@ public static string Serialize(Base @object) } /// - /// Serializes a given object. Note: if you want to save and persist an object to Speckle Transport or Server, please use any of the "Send" methods. See . + /// Serializes a given object. Note: if you want to save and persist an object to Speckle Transport or Server, please use any of the "Send" methods. See . /// /// /// Propagates notification that operations should be canceled. @@ -76,7 +76,7 @@ public static string Serialize(Dictionary objects) } /// - /// Deserializes a given object. Note: if you want to pull an object from a Speckle Transport or Server, please use any of the . + /// Deserializes a given object. Note: if you want to pull an object from a Speckle Transport or Server, please use any of the . /// /// The json string representation of a speckle object that you want to deserialise. /// @@ -86,7 +86,7 @@ public static Base Deserialize(string @object) } /// - /// Deserializes a given object. Note: if you want to pull an object from a Speckle Transport or Server, please use any of the . + /// Deserializes a given object. Note: if you want to pull an object from a Speckle Transport or Server, please use any of the . /// /// The json string representation of a speckle object that you want to deserialise. /// Propagates notification that operations should be canceled. @@ -103,12 +103,10 @@ public static Base Deserialize( serializer.CancellationToken = cancellationToken; return JsonConvert.DeserializeObject(@object, settings); } - else - { - var deserializer = new BaseObjectDeserializerV2(); - deserializer.CancellationToken = cancellationToken; - return deserializer.Deserialize(@object); - } + + var deserializer = new BaseObjectDeserializerV2(); + deserializer.CancellationToken = cancellationToken; + return deserializer.Deserialize(@object); } /// @@ -129,16 +127,13 @@ public static List DeserializeArray( var (_, settings) = GetSerializerInstance(); return JsonConvert.DeserializeObject>(objectArr, settings); } - else - { - var deserializer = new BaseObjectDeserializerV2(); - List deserialized = - deserializer.DeserializeTransportObject(objectArr) as List; - List ret = new(); - foreach (object obj in deserialized) - ret.Add((Base)obj); - return ret; - } + + var deserializer = new BaseObjectDeserializerV2(); + List deserialized = deserializer.DeserializeTransportObject(objectArr) as List; + List ret = new(); + foreach (object obj in deserialized) + ret.Add((Base)obj); + return ret; } /// diff --git a/Core/Core/Api/Operations/Operations.cs b/Core/Core/Api/Operations/Operations.cs index ffa6aa5bd0..871b822cd0 100644 --- a/Core/Core/Api/Operations/Operations.cs +++ b/Core/Core/Api/Operations/Operations.cs @@ -20,7 +20,7 @@ public static partial class Operations public static (BaseObjectSerializer, JsonSerializerSettings) GetSerializerInstance() { var serializer = new BaseObjectSerializer(); - var settings = new JsonSerializerSettings() + var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), @@ -43,15 +43,13 @@ private static Action GetInternalProgressAction( Action> onProgressAction = null ) { - return new Action( - (name, processed) => - { - if (localProgressDict.ContainsKey(name)) - localProgressDict[name] += processed; - else - localProgressDict[name] = processed; - onProgressAction?.Invoke(localProgressDict); - } - ); + return (name, processed) => + { + if (localProgressDict.ContainsKey(name)) + localProgressDict[name] += processed; + else + localProgressDict[name] = processed; + onProgressAction?.Invoke(localProgressDict); + }; } } diff --git a/Core/Core/Credentials/Account.cs b/Core/Core/Credentials/Account.cs index 73bb58a089..1720e542d9 100644 --- a/Core/Core/Credentials/Account.cs +++ b/Core/Core/Credentials/Account.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using GraphQL; using GraphQL.Client.Http; @@ -10,11 +10,11 @@ namespace Speckle.Core.Credentials; +#pragma warning disable CS0659 CA1067 //TODO: Disabled to prevent GetHashCode from being added by the cleanup. + public class Account : IEquatable { - public Account() { } - - private string _id { get; set; } = null; + private string _id { get; set; } public string id { @@ -78,7 +78,7 @@ public async Task Validate() httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); using var gqlClient = new GraphQLHttpClient( - new GraphQLHttpClientOptions() { EndPoint = new Uri(new Uri(serverInfo.url), "/graphql") }, + new GraphQLHttpClientOptions { EndPoint = new Uri(new Uri(serverInfo.url), "/graphql") }, new NewtonsoftJsonSerializer(), httpClient ); @@ -93,6 +93,11 @@ public async Task Validate() return response.Data.user; } + public override string ToString() + { + return $"Account ({userInfo.email} | {serverInfo.url})"; + } + public bool Equals(Account other) { return other is not null @@ -100,17 +105,11 @@ public bool Equals(Account other) && other.serverInfo.url == serverInfo.url; } - public override string ToString() - { - return $"Account ({userInfo.email} | {serverInfo.url})"; - } - -#pragma warning disable CS0659 //TODO: Disabled to prevent GetHashCode from being added by the cleanup. public override bool Equals(object obj) { return obj is Account acc && Equals(acc); } -#pragma warning restore CS0659 #endregion } +#pragma warning restore CS0659 CA1067 diff --git a/Core/Core/Credentials/AccountManager.cs b/Core/Core/Credentials/AccountManager.cs index c31958ad09..7b1894ae99 100644 --- a/Core/Core/Credentials/AccountManager.cs +++ b/Core/Core/Credentials/AccountManager.cs @@ -28,7 +28,7 @@ namespace Speckle.Core.Credentials; public static class AccountManager { private static SQLiteTransport AccountStorage = new(scope: "Accounts"); - private static bool _isAddingAccount = false; + private static bool _isAddingAccount; private static SQLiteTransport AccountAddLockStorage = new(scope: "AccountAddFlow"); /// @@ -41,7 +41,7 @@ public static async Task GetServerInfo(string server) using var httpClient = Http.GetHttpProxyClient(); using var gqlClient = new GraphQLHttpClient( - new GraphQLHttpClientOptions() { EndPoint = new Uri(new Uri(server), "/graphql") }, + new GraphQLHttpClientOptions { EndPoint = new Uri(new Uri(server), "/graphql") }, new NewtonsoftJsonSerializer(), httpClient ); @@ -72,7 +72,7 @@ public static async Task GetUserInfo(string token, string server) httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); using var gqlClient = new GraphQLHttpClient( - new GraphQLHttpClientOptions() { EndPoint = new Uri(new Uri(server), "/graphql") }, + new GraphQLHttpClientOptions { EndPoint = new Uri(new Uri(server), "/graphql") }, new NewtonsoftJsonSerializer(), httpClient ); @@ -148,7 +148,7 @@ public static string GetDefaultServerUrl() Uri url = null; Uri.TryCreate(customServerUrl, UriKind.Absolute, out url); if (url != null) - defaultServerUrl = customServerUrl.TrimEnd(new[] { '/' }); + defaultServerUrl = customServerUrl.TrimEnd('/'); } return defaultServerUrl; @@ -332,7 +332,7 @@ private static string _ensureCorrectServerUrl(string server) localUrl ); } - return localUrl.TrimEnd(new[] { '/' }); + return localUrl.TrimEnd('/'); } private static void _ensureGetAccessCodeFlowIsSupported() @@ -443,7 +443,7 @@ string server var tokenResponse = await GetToken(accessCode, challenge, server).ConfigureAwait(false); var userResponse = await GetUserServerInfo(tokenResponse.token, server).ConfigureAwait(false); - var account = new Account() + var account = new Account { token = tokenResponse.token, refreshToken = tokenResponse.refreshToken, @@ -500,7 +500,6 @@ private static void _tryLockAccountAddFlow(TimeSpan timespan) // for ease of deletion and retrieval AccountAddLockStorage.SaveObjectSync(lockId, lockId); _isAddingAccount = true; - return; } private static void _unlockAccountAddFlow() @@ -580,8 +579,8 @@ string server { appId = "sca", appSecret = "sca", - accessCode = accessCode, - challenge = challenge + accessCode, + challenge }; var content = new StringContent(JsonConvert.SerializeObject(body)); @@ -613,7 +612,7 @@ string server { appId = "sca", appSecret = "sca", - refreshToken = refreshToken + refreshToken }; var content = new StringContent(JsonConvert.SerializeObject(body)); diff --git a/Core/Core/Helpers/Http.cs b/Core/Core/Helpers/Http.cs index e5c98cd0c2..52ec8c82fd 100644 --- a/Core/Core/Helpers/Http.cs +++ b/Core/Core/Helpers/Http.cs @@ -196,7 +196,6 @@ public class SpeckleHttpClientHandler : HttpClientHandler private IEnumerable _delay; public SpeckleHttpClientHandler(IEnumerable? delay = null) - : base() { _delay = delay ?? Http.DefaultDelay(); } diff --git a/Core/Core/Kits/Attributes.cs b/Core/Core/Kits/Attributes.cs index a3645b581f..4f7c843faf 100644 --- a/Core/Core/Kits/Attributes.cs +++ b/Core/Core/Kits/Attributes.cs @@ -2,7 +2,7 @@ namespace Speckle.Core.Kits; -[AttributeUsage(AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Constructor)] public sealed class SchemaInfo : Attribute { public SchemaInfo(string name, string description) @@ -28,7 +28,7 @@ public SchemaInfo(string name, string description, string category, string subca [AttributeUsage(AttributeTargets.Constructor)] public sealed class SchemaDeprecated : Attribute { } -[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Parameter)] public sealed class SchemaParamInfo : Attribute { public SchemaParamInfo(string description) @@ -43,10 +43,7 @@ public SchemaParamInfo(string description) /// Used to indicate which is the main input parameter of the schema builder component. Schema info will be attached to this object. /// [AttributeUsage(AttributeTargets.Parameter)] -public sealed class SchemaMainParam : Attribute -{ - public SchemaMainParam() { } -} +public sealed class SchemaMainParam : Attribute { } // TODO: this could be nuked, as it's only used to hide props on Base, // which we might want to expose anyways... diff --git a/Core/Core/Kits/ISpeckleKit.cs b/Core/Core/Kits/ISpeckleKit.cs index 34aee16629..c3eae1a443 100644 --- a/Core/Core/Kits/ISpeckleKit.cs +++ b/Core/Core/Kits/ISpeckleKit.cs @@ -56,10 +56,13 @@ public KitException(string message, ISpeckleKit kit, Exception? innerException = Kit = kit; } - public ISpeckleKit Kit { get; } - public KitException() { } public KitException(string message) : base(message) { } + + public KitException(string message, Exception innerException) + : base(message, innerException) { } + + public ISpeckleKit Kit { get; } } diff --git a/Core/Core/Kits/KitDeclaration.cs b/Core/Core/Kits/KitDeclaration.cs index 6c091b8025..92b93edae0 100644 --- a/Core/Core/Kits/KitDeclaration.cs +++ b/Core/Core/Kits/KitDeclaration.cs @@ -10,8 +10,6 @@ namespace Speckle.Core.Kits; /// public class CoreKit : ISpeckleKit { - public CoreKit() { } - public IEnumerable Types => GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); diff --git a/Core/Core/Kits/KitManager.cs b/Core/Core/Kits/KitManager.cs index 5bca7b254f..ece5745387 100644 --- a/Core/Core/Kits/KitManager.cs +++ b/Core/Core/Kits/KitManager.cs @@ -12,7 +12,7 @@ namespace Speckle.Core.Kits; public static class KitManager { - private static string? _kitsFolder = null; + private static string? _kitsFolder; public static readonly AssemblyName SpeckleAssemblyName = typeof(Base) .GetTypeInfo() @@ -22,7 +22,7 @@ public static class KitManager private static List _AvailableTypes = new(); - private static bool _initialized = false; + private static bool _initialized; /// /// Local installations store kits in C:\Users\USERNAME\AppData\Roaming\Speckle\Kits diff --git a/Core/Core/Logging/Analytics.cs b/Core/Core/Logging/Analytics.cs index efec8d3404..e81e8e66f9 100644 --- a/Core/Core/Logging/Analytics.cs +++ b/Core/Core/Logging/Analytics.cs @@ -66,7 +66,7 @@ public enum Events /// Event triggered by the Mapping Tool /// MappingsAction - }; + } private const string MixpanelToken = "acd87c5a50b56df91a795e999812a3a4"; private const string MixpanelServer = "https://analytics.speckle.systems"; @@ -187,7 +187,7 @@ private static void TrackEvent( { try { - var properties = new Dictionary() + var properties = new Dictionary { { "distinct_id", hashedEmail }, { "server_id", hashedServer }, @@ -234,13 +234,13 @@ internal static void AddConnectorToProfile(string hashedEmail, string connector) { try { - var data = new Dictionary() + var data = new Dictionary { { "$token", MixpanelToken }, { "$distinct_id", hashedEmail }, { "$union", - new Dictionary() + new Dictionary { { "Connectors", @@ -250,7 +250,7 @@ internal static void AddConnectorToProfile(string hashedEmail, string connector) }, { "set", - new Dictionary() { { "Identified", true } } + new Dictionary { { "Identified", true } } } }; string json = JsonConvert.SerializeObject(data); diff --git a/Core/Core/Logging/Log.cs b/Core/Core/Logging/Log.cs index 1a619025e0..0875207adc 100644 --- a/Core/Core/Logging/Log.cs +++ b/Core/Core/Logging/Log.cs @@ -14,7 +14,7 @@ namespace Speckle.Core.Logging; /// public static class OldLog { - private static bool _initialized = false; + private static bool _initialized; /// /// Initializes Sentry @@ -40,7 +40,7 @@ public static void Initialize() o.Dsn = dsn; o.Environment = env; o.Debug = debug; - o.Release = "SpeckleCore@" + Assembly.GetExecutingAssembly().GetName().Version.ToString(); + o.Release = "SpeckleCore@" + Assembly.GetExecutingAssembly().GetName().Version; o.StackTraceMode = StackTraceMode.Enhanced; o.AttachStacktrace = true; o.AddExceptionFilterForType(); diff --git a/Core/Core/Logging/Setup.cs b/Core/Core/Logging/Setup.cs index faa1ac8c33..11fd3e3309 100644 --- a/Core/Core/Logging/Setup.cs +++ b/Core/Core/Logging/Setup.cs @@ -13,7 +13,7 @@ public static class Setup { public static Mutex mutex; - private static bool initialized = false; + private static bool initialized; static Setup() { diff --git a/Core/Core/Logging/SpeckleException.cs b/Core/Core/Logging/SpeckleException.cs index 5715e91bd6..f9f8dbae14 100644 --- a/Core/Core/Logging/SpeckleException.cs +++ b/Core/Core/Logging/SpeckleException.cs @@ -39,8 +39,8 @@ public SpeckleException( ) : base(message, inner) { } - public List> GraphQLErrors { get; set; } - public SpeckleException(string message) : base(message) { } + + public List> GraphQLErrors { get; set; } } diff --git a/Core/Core/Logging/SpeckleLog.cs b/Core/Core/Logging/SpeckleLog.cs index ff63a114e7..97d93ee206 100644 --- a/Core/Core/Logging/SpeckleLog.cs +++ b/Core/Core/Logging/SpeckleLog.cs @@ -94,7 +94,7 @@ public SpeckleLogConfiguration( public static class SpeckleLog { private static ILogger? _logger; - private static bool _initialized = false; + private static bool _initialized; public static ILogger Logger => _logger diff --git a/Core/Core/Models/Base.cs b/Core/Core/Models/Base.cs index 3363740963..6a42faf3c8 100644 --- a/Core/Core/Models/Base.cs +++ b/Core/Core/Models/Base.cs @@ -98,7 +98,7 @@ public string GetId( { var (s, t) = Operations.GetSerializerInstance(); if (decompose) - s.WriteTransports = new List() { new MemoryTransport() }; + s.WriteTransports = new List { new MemoryTransport() }; var obj = JsonConvert.SerializeObject(this, t); return JObject.Parse(obj).GetValue(nameof(id)).ToString(); } @@ -106,7 +106,7 @@ public string GetId( { var s = new BaseObjectSerializerV2(); if (decompose) - s.WriteTransports = new List() { new MemoryTransport() }; + s.WriteTransports = new List { new MemoryTransport() }; var obj = s.Serialize(this); return JObject.Parse(obj).GetValue(nameof(id)).ToString(); } @@ -153,10 +153,7 @@ private static long CountDescendants(Base @base, HashSet parsed) // Simplified chunking count handling. var asList = value as IList; if (asList != null) - { count += asList.Count / chunkAttribute.MaxObjCountPerChunk; - continue; - } } } diff --git a/Core/Core/Models/DynamicBase.cs b/Core/Core/Models/DynamicBase.cs index e61a354c86..8755eb68ac 100644 --- a/Core/Core/Models/DynamicBase.cs +++ b/Core/Core/Models/DynamicBase.cs @@ -35,8 +35,6 @@ public class DynamicBase : DynamicObject, IDynamicMetaObjectProvider /// private Dictionary properties = new(); - public DynamicBase() { } - /// /// Sets and gets properties using the key accessor pattern. E.g.: ///
((dynamic)myObject)["superProperty"] = 42;
diff --git a/Core/Core/Models/Extras.cs b/Core/Core/Models/Extras.cs index 0389a51261..1cfa63bc1e 100644 --- a/Core/Core/Models/Extras.cs +++ b/Core/Core/Models/Extras.cs @@ -57,8 +57,6 @@ public object @base /// public class DataChunk : Base { - public DataChunk() { } - public List data { get; set; } = new(); } @@ -66,8 +64,6 @@ public class ObjectReference { public string speckle_type = "reference"; - public ObjectReference() { } - public string referencedId { get; set; } } @@ -239,10 +235,8 @@ public ApplicationObject UpdateReportObject(ApplicationObject obj) reportObject.Update(status: obj.Status); return reportObject; } - else - { - return null; - } + + return null; } [Obsolete("Use TryGetValue or Dictionary indexing", true)] diff --git a/Core/Core/Models/GraphTraversal/DefaultTraversal.cs b/Core/Core/Models/GraphTraversal/DefaultTraversal.cs index df274de385..471cdaf5fb 100644 --- a/Core/Core/Models/GraphTraversal/DefaultTraversal.cs +++ b/Core/Core/Models/GraphTraversal/DefaultTraversal.cs @@ -115,6 +115,7 @@ internal static IEnumerable ElementsAliases(Base _) } internal static readonly string[] displayValueAliases = { "displayValue", "@displayValue" }; + internal static readonly string[] ignoreProps = new[] { "@blockDefinition" } .Concat(displayValueAliases) .ToArray(); diff --git a/Core/Core/Models/InvalidPropNameException.cs b/Core/Core/Models/InvalidPropNameException.cs index a4ab2cae0c..2747f66b84 100644 --- a/Core/Core/Models/InvalidPropNameException.cs +++ b/Core/Core/Models/InvalidPropNameException.cs @@ -1,3 +1,4 @@ +using System; using Speckle.Core.Logging; namespace Speckle.Core.Models; @@ -11,4 +12,7 @@ public InvalidPropNameException() { } public InvalidPropNameException(string message) : base(message) { } + + public InvalidPropNameException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/Core/Core/Models/Utilities.cs b/Core/Core/Models/Utilities.cs index 55d800fd7d..91cbc2610c 100644 --- a/Core/Core/Models/Utilities.cs +++ b/Core/Core/Models/Utilities.cs @@ -88,7 +88,7 @@ private static string md5(string input) public static bool IsSimpleType(this Type type) { return type.IsPrimitive - || new Type[] + || new[] { typeof(string), typeof(decimal), @@ -196,7 +196,7 @@ public static void SetApplicationProps(object o, Type t, Base props) BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, o, - new object[] { value } + new[] { value } ); } catch { } diff --git a/Core/Core/Serialisation/BaseObjectDeserializerV2.cs b/Core/Core/Serialisation/BaseObjectDeserializerV2.cs index 92325eef93..483f732764 100644 --- a/Core/Core/Serialisation/BaseObjectDeserializerV2.cs +++ b/Core/Core/Serialisation/BaseObjectDeserializerV2.cs @@ -3,7 +3,6 @@ using System.Diagnostics; using System.IO; using System.Reflection; -using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Speckle.Core.Logging; @@ -16,7 +15,7 @@ namespace Speckle.Core.Serialisation; public class BaseObjectDeserializerV2 { - private bool Busy = false; + private bool Busy; private object CallbackLock = new(); // id -> Base if already deserialized or id -> Task if was handled by a bg thread @@ -31,8 +30,6 @@ public class BaseObjectDeserializerV2 private DeserializationWorkerThreads WorkerThreads; - public BaseObjectDeserializerV2() { } - public CancellationToken CancellationToken { get; set; } /// @@ -259,7 +256,7 @@ public object ConvertJsonElement(JToken doc) return Dict2Base(dict); default: - throw new Exception("Json value not supported: " + doc.Type.ToString()); + throw new Exception("Json value not supported: " + doc.Type); } } diff --git a/Core/Core/Serialisation/BaseObjectSerializer.cs b/Core/Core/Serialisation/BaseObjectSerializer.cs index 66c0884f56..c6335f1911 100644 --- a/Core/Core/Serialisation/BaseObjectSerializer.cs +++ b/Core/Core/Serialisation/BaseObjectSerializer.cs @@ -134,12 +134,12 @@ JsonSerializer serializer if (CancellationToken.IsCancellationRequested) return null; // Check for cancellation - var discriminator = Extensions.Value(objType); + var discriminator = objType.Value(); // Check for references. if (discriminator == "reference") { - var id = Extensions.Value(jObject.GetValue("referencedId")); + var id = jObject.GetValue("referencedId").Value(); string str = ""; if (ReadTransport != null) @@ -150,7 +150,7 @@ JsonSerializer serializer if (str != null && !string.IsNullOrEmpty(str)) { jObject = JObject.Parse(str); - discriminator = Extensions.Value(jObject.GetValue(TypeDiscriminator)); + discriminator = jObject.GetValue(TypeDiscriminator).Value(); } else { @@ -250,7 +250,7 @@ JsonSerializer serializer /// private Dictionary> RefMinDepthTracker { get; set; } - public int TotalProcessedCount = 0; + public int TotalProcessedCount; #endregion @@ -276,7 +276,7 @@ private void TrackReferenceInTree(string refId) } private bool FirstEntry = true, - FirstEntryWasListOrDict = false; + FirstEntryWasListOrDict; // While this function looks complicated, it's actually quite smooth: // The important things to remember is that serialization goes depth first: @@ -424,7 +424,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var refHash = ((JObject)what).GetValue("id").ToString(); - var reference = new ObjectReference() { referencedId = refHash }; + var reference = new ObjectReference { referencedId = refHash }; TrackReferenceInTree(refHash); jo.Add(prop, JToken.FromObject(reference)); } @@ -554,7 +554,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var refHash = ((JObject)what).GetValue("id").ToString(); - var reference = new ObjectReference() { referencedId = refHash }; + var reference = new ObjectReference { referencedId = refHash }; TrackReferenceInTree(refHash); arr.Add(JToken.FromObject(reference)); } @@ -608,7 +608,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var what = JToken.FromObject(kvp.Value, serializer); // Trigger next var refHash = ((JObject)what).GetValue("id").ToString(); - var reference = new ObjectReference() { referencedId = refHash }; + var reference = new ObjectReference { referencedId = refHash }; TrackReferenceInTree(refHash); jToken = JToken.FromObject(reference); } diff --git a/Core/Core/Serialisation/BaseObjectSerializerV2.cs b/Core/Core/Serialisation/BaseObjectSerializerV2.cs index ef9136c1d6..02a0485279 100644 --- a/Core/Core/Serialisation/BaseObjectSerializerV2.cs +++ b/Core/Core/Serialisation/BaseObjectSerializerV2.cs @@ -19,7 +19,7 @@ namespace Speckle.Core.Serialisation; public class BaseObjectSerializerV2 { private Stopwatch _stopwatch = new(); - private bool Busy = false; + private bool Busy; private Regex ChunkPropertyNameRegex = new(@"^@\((\d*)\)"); private List> ParentClosures = new(); @@ -34,8 +34,6 @@ public class BaseObjectSerializerV2 private Dictionary> TypedPropertiesCache = new(); - public BaseObjectSerializerV2() { } - public CancellationToken CancellationToken { get; set; } /// @@ -139,7 +137,7 @@ public object PreserializeObject( if (obj is DateTime t) return t.ToString("o", CultureInfo.InvariantCulture); if (obj is Matrix4x4 m) - return new List() + return new List { m.M11, m.M12, @@ -159,7 +157,7 @@ public object PreserializeObject( m.M44 }; - throw new Exception("Unsupported value in serialization: " + type.ToString()); + throw new Exception("Unsupported value in serialization: " + type); } public object PreserializeBase( diff --git a/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs b/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs index a14fd0b14a..3edae52c13 100644 --- a/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs +++ b/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs @@ -36,8 +36,7 @@ internal static object HandleValue( { if (jsonProperty != null) return value.ToObject(jsonProperty.PropertyType); - else - return ((JValue)value).Value; + return ((JValue)value).Value; } // Lists @@ -73,11 +72,11 @@ internal static object HandleValue( dataItem.GetType() ) ) - addMethod.Invoke(arr, new object[] { dataItem }); + addMethod.Invoke(arr, new[] { dataItem }); else addMethod.Invoke( arr, - new object[] + new[] { Convert.ChangeType( dataItem, @@ -88,17 +87,17 @@ internal static object HandleValue( } else { - addMethod.Invoke(arr, new object[] { dataItem }); + addMethod.Invoke(arr, new[] { dataItem }); } } else if (hasGenericType && !jsonProperty.PropertyType.GenericTypeArguments[0].IsInterface) { if (jsonProperty.PropertyType.GenericTypeArguments[0].IsAssignableFrom(item.GetType())) - addMethod.Invoke(arr, new object[] { item }); + addMethod.Invoke(arr, new[] { item }); else addMethod.Invoke( arr, - new object[] + new[] { Convert.ChangeType(item, jsonProperty.PropertyType.GenericTypeArguments[0]) } @@ -106,12 +105,13 @@ internal static object HandleValue( } else { - addMethod.Invoke(arr, new object[] { item }); + addMethod.Invoke(arr, new[] { item }); } } return arr; } - else if (jsonProperty != null) + + if (jsonProperty != null) { if (CancellationToken.IsCancellationRequested) return null; // Check for cancellation diff --git a/Core/Core/Serialisation/DeserializationWorkerThreads.cs b/Core/Core/Serialisation/DeserializationWorkerThreads.cs index ac7c09973e..c5d41b44fb 100644 --- a/Core/Core/Serialisation/DeserializationWorkerThreads.cs +++ b/Core/Core/Serialisation/DeserializationWorkerThreads.cs @@ -13,7 +13,7 @@ internal enum WorkerThreadTaskType internal class DeserializationWorkerThreads : IDisposable { - private int FreeThreadCount = 0; + private int FreeThreadCount; private object LockFreeThreads = new(); private BaseObjectDeserializerV2 Serializer; @@ -46,7 +46,7 @@ public void Start() { for (int i = 0; i < ThreadCount; i++) { - Thread t = new(new ThreadStart(ThreadMain)); + Thread t = new(ThreadMain); t.IsBackground = true; Threads.Add(t); t.Start(); @@ -94,9 +94,7 @@ internal Task TryStartTask(WorkerThreadTaskType taskType, object inputVa Tasks.Add((taskType, inputValue, tcs)); return tcs.Task; } - else - { - return null; - } + + return null; } } diff --git a/Core/Core/Serialisation/ValueConverter.cs b/Core/Core/Serialisation/ValueConverter.cs index d2d6229e31..0faf757f2c 100644 --- a/Core/Core/Serialisation/ValueConverter.cs +++ b/Core/Core/Serialisation/ValueConverter.cs @@ -61,64 +61,52 @@ public static bool ConvertValue(Type type, object value, out object convertedVal convertedValue = (long)value; return true; } - else - { - return false; - } + + return false; case "Int32": if (valueType == typeof(long)) { convertedValue = (int)(long)value; return true; } - else - { - return false; - } + + return false; case "Int16": if (valueType == typeof(long)) { convertedValue = (short)(long)value; return true; } - else - { - return false; - } + + return false; case "UInt64": if (valueType == typeof(long)) { convertedValue = (ulong)(long)value; return true; } - else - { - return false; - } + + return false; case "UInt32": if (valueType == typeof(long)) { convertedValue = (uint)(long)value; return true; } - else - { - return false; - } + + return false; case "UInt16": if (valueType == typeof(long)) { convertedValue = (ushort)(long)value; return true; } - else - { - return false; - } + + return false; case "Double": if (valueType == typeof(double)) { - convertedValue = (double)(double)value; + convertedValue = (double)value; return true; } if (valueType == typeof(long)) @@ -126,10 +114,8 @@ public static bool ConvertValue(Type type, object value, out object convertedVal convertedValue = (double)(long)value; return true; } - else - { - return false; - } + + return false; case "Single": if (valueType == typeof(double)) { @@ -141,10 +127,8 @@ public static bool ConvertValue(Type type, object value, out object convertedVal convertedValue = (float)(long)value; return true; } - else - { - return false; - } + + return false; #endregion } @@ -155,7 +139,7 @@ public static bool ConvertValue(Type type, object value, out object convertedVal if (!isList) return false; Type listElementType = type.GenericTypeArguments[0]; - IList ret = Activator.CreateInstance(type, new object[] { valueList.Count }) as IList; + IList ret = Activator.CreateInstance(type, valueList.Count) as IList; foreach (object inputListElement in valueList) { object convertedListElement; @@ -196,7 +180,7 @@ public static bool ConvertValue(Type type, object value, out object convertedVal if (!isList) return false; Type arrayElementType = type.GetElementType(); - Array ret = Activator.CreateInstance(type, new object[] { valueList.Count }) as Array; + Array ret = Activator.CreateInstance(type, valueList.Count) as Array; for (int i = 0; i < valueList.Count; i++) { object inputListElement = valueList[i]; diff --git a/Core/Core/Transports/Memory.cs b/Core/Core/Transports/Memory.cs index d1cc8fc88a..656f958e33 100644 --- a/Core/Core/Transports/Memory.cs +++ b/Core/Core/Transports/Memory.cs @@ -23,7 +23,7 @@ public MemoryTransport() public object Clone() { - return new MemoryTransport() + return new MemoryTransport { TransportName = TransportName, OnErrorAction = OnErrorAction, @@ -50,7 +50,7 @@ public void Dispose() public Action OnErrorAction { get; set; } - public int SavedObjectCount { get; set; } = 0; + public int SavedObjectCount { get; set; } public Dictionary TransportContext => new() { { "name", TransportName }, { "type", GetType().Name } }; diff --git a/Core/Core/Transports/SQLite.cs b/Core/Core/Transports/SQLite.cs index 4fafe3cc06..4b8c10689d 100644 --- a/Core/Core/Transports/SQLite.cs +++ b/Core/Core/Transports/SQLite.cs @@ -16,7 +16,7 @@ namespace Speckle.Core.Transports; public class SQLiteTransport : IDisposable, ICloneable, ITransport, IBlobCapableTransport { - private bool IS_WRITING = false; + private bool IS_WRITING; private int MAX_TRANSACTION_SIZE = 1000; private int PollInterval = 500; @@ -62,7 +62,7 @@ public SQLiteTransport( { Initialize(); - WriteTimer = new Timer() + WriteTimer = new Timer { AutoReset = true, Enabled = false, @@ -86,6 +86,7 @@ public SQLiteTransport( private SqliteConnection Connection { get; set; } private object ConnectionLock { get; set; } + public string BlobStorageFolder => SpecklePathProvider.BlobStoragePath(Path.Combine(_basePath, _applicationName)); @@ -278,7 +279,7 @@ public void UpdateObject(string hash, string serializedObject) using (var c = new SqliteConnection(ConnectionString)) { c.Open(); - var commandText = $"REPLACE INTO objects(hash, content) VALUES(@hash, @content)"; + var commandText = "REPLACE INTO objects(hash, content) VALUES(@hash, @content)"; using (var command = new SqliteCommand(commandText, c)) { command.Parameters.AddWithValue("@hash", hash); @@ -355,7 +356,7 @@ private void ConsumeQueue() c.Open(); using (var t = c.BeginTransaction()) { - var commandText = $"INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; + var commandText = "INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; while (i < MAX_TRANSACTION_SIZE && Queue.TryPeek(out result)) using (var command = new SqliteCommand(commandText, c, t)) @@ -431,7 +432,7 @@ public void SaveObjectSync(string hash, string serializedObject) using (var c = new SqliteConnection(ConnectionString)) { c.Open(); - var commandText = $"INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; + var commandText = "INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; using (var command = new SqliteCommand(commandText, c)) { command.Parameters.AddWithValue("@hash", hash); diff --git a/Core/Core/Transports/Server.cs b/Core/Core/Transports/Server.cs index 9d7ceda973..c757ea43ad 100644 --- a/Core/Core/Transports/Server.cs +++ b/Core/Core/Transports/Server.cs @@ -26,7 +26,7 @@ public class ServerTransportV1 : IDisposable, ICloneable, ITransport { private int DOWNLOAD_BATCH_SIZE = 1000; - private bool IS_WRITING = false; + private bool IS_WRITING; private int MAX_BUFFER_SIZE = 1_000_000; @@ -34,7 +34,7 @@ public class ServerTransportV1 : IDisposable, ICloneable, ITransport private ConcurrentQueue<(string, string, int)> Queue = new(); - private int TotalElapsed = 0, + private int TotalElapsed, PollInterval = 100; private Timer WriteTimer; @@ -53,7 +53,7 @@ public ServerTransportV1(Account account, string streamId, int timeoutSeconds = public bool CompressPayloads { get; set; } = true; - public int TotalSentBytes { get; set; } = 0; + public int TotalSentBytes { get; set; } public Account Account { get; set; } @@ -87,7 +87,7 @@ public void Dispose() public CancellationToken CancellationToken { get; set; } - public int SavedObjectCount { get; private set; } = 0; + public int SavedObjectCount { get; private set; } public Action OnProgressAction { get; set; } @@ -108,7 +108,7 @@ public void EndWrite() { } public async Task> HasObjects(List objectIds) { - var payload = new Dictionary() + var payload = new Dictionary { { "objects", JsonConvert.SerializeObject(objectIds) } }; @@ -140,7 +140,7 @@ private void Initialize( StreamId = streamId; Client = Http.GetHttpProxyClient( - new SpeckleHttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip } + new SpeckleHttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip } ); Client.BaseAddress = new Uri(baseUri); @@ -150,7 +150,7 @@ private void Initialize( Client.DefaultRequestHeaders.Add("Authorization", authorizationToken); else Client.DefaultRequestHeaders.Add("Authorization", $"Bearer {authorizationToken}"); - WriteTimer = new Timer() + WriteTimer = new Timer { AutoReset = true, Enabled = false, @@ -272,7 +272,7 @@ private async Task ConsumeQueue() return; IS_WRITING = true; - var message = new HttpRequestMessage() + var message = new HttpRequestMessage { RequestUri = new Uri($"/objects/{StreamId}", UriKind.Relative), Method = HttpMethod.Post @@ -430,7 +430,7 @@ public string GetObject(string hash) return null; } - var message = new HttpRequestMessage() + var message = new HttpRequestMessage { RequestUri = new Uri($"/objects/{StreamId}/{hash}/single", UriKind.Relative), Method = HttpMethod.Get @@ -455,7 +455,7 @@ Action onTotalChildrenCountKnown } // Get root object - var rootHttpMessage = new HttpRequestMessage() + var rootHttpMessage = new HttpRequestMessage { RequestUri = new Uri($"/objects/{StreamId}/{hash}/single", UriKind.Relative), Method = HttpMethod.Get @@ -522,7 +522,7 @@ private async Task CopyObjects(List hashes, ITransport targetTrans if (hashes.Count > 0) { - var childrenHttpMessage = new HttpRequestMessage() + var childrenHttpMessage = new HttpRequestMessage { RequestUri = new Uri($"/api/getobjects/{StreamId}", UriKind.Relative), Method = HttpMethod.Post @@ -570,7 +570,7 @@ private async Task CopyObjects(List hashes, ITransport targetTrans return false; } - var pcs = line.Split(new char[] { '\t' }, 2); + var pcs = line.Split(new[] { '\t' }, 2); targetTransport.SaveObject(pcs[0], pcs[1]); OnProgressAction?.Invoke(TransportName, 1); // possibly make this more friendly diff --git a/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs b/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs index f7f9207430..71db713c67 100644 --- a/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs +++ b/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs @@ -72,7 +72,7 @@ public async Task> HasObjects(string streamId, List> tasks = new(); List> splitObjectsIds; if (objectIds.Count <= 50) - splitObjectsIds = new List>() { objectIds }; + splitObjectsIds = new List> { objectIds }; else splitObjectsIds = SplitList(objectIds, NumThreads); @@ -119,7 +119,7 @@ CbObjectDownloaded onObjectCallback List> splitObjectsIds = SplitList(objectIds, NumThreads); object callbackLock = new(); - CbObjectDownloaded callbackWrapper = (string id, string json) => + CbObjectDownloaded callbackWrapper = (id, json) => { lock (callbackLock) onObjectCallback(id, json); @@ -156,7 +156,7 @@ public async Task UploadObjects(string streamId, List<(string, string)> objects) break; } if (totalSize < 500000) - splitObjects = new List>() { objects }; + splitObjects = new List> { objects }; else splitObjects = SplitList(objects, NumThreads); @@ -207,8 +207,8 @@ public void Start() throw new Exception("ServerAPI: Threads already started"); for (int i = 0; i < NumThreads; i++) { - Thread t = new(new ThreadStart(ThreadMain)); - t.Name = $"ParallelServerAPI"; + Thread t = new(ThreadMain); + t.Name = "ParallelServerAPI"; t.IsBackground = true; Threads.Add(t); t.Start(); diff --git a/Core/Core/Transports/ServerUtils/ServerAPI.cs b/Core/Core/Transports/ServerUtils/ServerAPI.cs index 0c390f142e..e11a1f3b89 100644 --- a/Core/Core/Transports/ServerUtils/ServerAPI.cs +++ b/Core/Core/Transports/ServerUtils/ServerAPI.cs @@ -42,7 +42,7 @@ public ServerApi( BlobStorageFolder = blobStorageFolder; Client = Http.GetHttpProxyClient( - new SpeckleHttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip } + new SpeckleHttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip } ); Client.BaseAddress = new Uri(baseUri); @@ -54,7 +54,7 @@ public ServerApi( Client.DefaultRequestHeaders.Add("Authorization", $"Bearer {authorizationToken}"); } - private int RetriedCount { get; set; } = 0; + private int RetriedCount { get; set; } public CancellationToken CancellationToken { get; set; } public bool CompressPayloads { get; set; } = true; @@ -75,7 +75,7 @@ public async Task DownloadSingleObject(string streamId, string objectId) CancellationToken.ThrowIfCancellationRequested(); // Get root object - var rootHttpMessage = new HttpRequestMessage() + var rootHttpMessage = new HttpRequestMessage { RequestUri = new Uri($"/objects/{streamId}/{objectId}/single", UriKind.Relative), Method = HttpMethod.Get @@ -236,7 +236,7 @@ public async Task UploadBlobs(string streamId, List<(string, string)> blobs) multipartFormDataContent.Add(fsc, $"hash:{hash}", fileName); } - var message = new HttpRequestMessage() + var message = new HttpRequestMessage { RequestUri = new Uri($"/api/stream/{streamId}/blob", UriKind.Relative), Method = HttpMethod.Post, @@ -270,7 +270,7 @@ CbBlobdDownloaded onBlobDownloaded foreach (var blobId in blobIds) try { - var blobMessage = new HttpRequestMessage() + var blobMessage = new HttpRequestMessage { RequestUri = new Uri($"api/stream/{streamId}/blob/{blobId}", UriKind.Relative), Method = HttpMethod.Get @@ -311,7 +311,7 @@ CbObjectDownloaded onObjectCallback CancellationToken.ThrowIfCancellationRequested(); - var childrenHttpMessage = new HttpRequestMessage() + var childrenHttpMessage = new HttpRequestMessage { RequestUri = new Uri($"/api/getobjects/{streamId}", UriKind.Relative), Method = HttpMethod.Post @@ -346,7 +346,7 @@ CbObjectDownloaded onObjectCallback { CancellationToken.ThrowIfCancellationRequested(); - var pcs = line.Split(new char[] { '\t' }, 2); + var pcs = line.Split(new[] { '\t' }, 2); onObjectCallback(pcs[0], pcs[1]); } } @@ -364,7 +364,7 @@ List objectIds // Stopwatch sw = new Stopwatch(); sw.Start(); string objectsPostParameter = JsonConvert.SerializeObject(objectIds); - var payload = new Dictionary() { { "objects", objectsPostParameter } }; + var payload = new Dictionary { { "objects", objectsPostParameter } }; string serializedPayload = JsonConvert.SerializeObject(payload); var uri = new Uri($"/api/diff/{streamId}", UriKind.Relative); HttpResponseMessage response = null; @@ -399,7 +399,7 @@ private async Task UploadObjectsImpl( CancellationToken.ThrowIfCancellationRequested(); - var message = new HttpRequestMessage() + var message = new HttpRequestMessage { RequestUri = new Uri($"/objects/{streamId}", UriKind.Relative), Method = HttpMethod.Post diff --git a/Core/Core/Transports/ServerV2.cs b/Core/Core/Transports/ServerV2.cs index 39245cedde..270aa17d8e 100644 --- a/Core/Core/Transports/ServerV2.cs +++ b/Core/Core/Transports/ServerV2.cs @@ -29,15 +29,15 @@ public class ServerTransportV2 : IDisposable, ICloneable, ITransport, IBlobCapab { private object ElapsedLock = new(); - private bool ErrorState = false; - private bool IsWriteComplete = false; + private bool ErrorState; + private bool IsWriteComplete; // TODO: make send buffer more flexible to accept blobs too private List<(string, string)> SendBuffer = new(); private object SendBufferLock = new(); - private Thread SendingThread = null; + private Thread SendingThread; - private bool ShouldSendThreadRun = false; + private bool ShouldSendThreadRun; public ServerTransportV2( Account account, @@ -55,7 +55,7 @@ public ServerTransportV2( Directory.CreateDirectory(BlobStorageFolder); } - public int TotalSentBytes { get; set; } = 0; + public int TotalSentBytes { get; set; } public Account Account { get; set; } public string BaseUri { get; private set; } @@ -117,7 +117,7 @@ public void Dispose() public CancellationToken CancellationToken { get; set; } public Action OnProgressAction { get; set; } public Action OnErrorAction { get; set; } - public int SavedObjectCount { get; private set; } = 0; + public int SavedObjectCount { get; private set; } public TimeSpan Elapsed { get; set; } = TimeSpan.Zero; public async Task CopyObjectAndChildren( @@ -165,7 +165,7 @@ public async Task CopyObjectAndChildren( await api.DownloadObjects( StreamId, newChildrenIds, - (string id, string json) => + (id, json) => { stopwatch.Stop(); targetTransport.SaveObject(id, json); @@ -268,7 +268,7 @@ public void BeginWrite() ErrorState = false; ShouldSendThreadRun = true; - SendingThread = new Thread(new ThreadStart(SendingThreadMain)); + SendingThread = new Thread(SendingThreadMain); SendingThread.Name = "ServerTransportSender"; SendingThread.IsBackground = true; SendingThread.Start(); diff --git a/Core/Examples/Program.cs b/Core/Examples/Program.cs index 3c3d37486b..320ce0aa02 100644 --- a/Core/Examples/Program.cs +++ b/Core/Examples/Program.cs @@ -2,13 +2,10 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Threading.Tasks; -using Serilog; using Serilog.Context; using Speckle.Core.Api; using Speckle.Core.Credentials; -using Speckle.Core.Helpers; using Speckle.Core.Logging; using Speckle.Core.Models; using Speckle.Core.Transports; @@ -17,366 +14,342 @@ /// /// Quick and dirty tests/examples of Speckle usage. /// -namespace ExampleApp +namespace ExampleApp; + +//////////////////////////////////////////////////////////////////////////// +/// NOTE: /// +/// These tests don't run without a server running locally. /// +/// Check out https://github.com/specklesystems/server for /// +/// more info on the server. /// +/// Also, please make sure you have a default speckle account. /// +//////////////////////////////////////////////////////////////////////////// +internal class Program { - //////////////////////////////////////////////////////////////////////////// - /// NOTE: /// - /// These tests don't run without a server running locally. /// - /// Check out https://github.com/specklesystems/server for /// - /// more info on the server. /// - /// Also, please make sure you have a default speckle account. /// - //////////////////////////////////////////////////////////////////////////// - - class Program + private static async Task Main(string[] args) { - static async Task Main(string[] args) + // Step 1. make sure to initialize the logger with the proper parameters + // note, this initialization is part of the current default setup, with sane + SpeckleLog.Initialize("Enterprise ", "NCC-1701-D", new SpeckleLogConfiguration()); + + // by default, this: + // logs to file in the Speckle folder / Logs / hostApplicationName + // reports errors to sentry + // sends all log events above the configured level to seq + // logs to the stdout console (useful when debugging) + // note, not all props are available in the file and console log, context is not rendered there + + SpeckleLog.Logger.Information( + "Captain's first log, stardate {stardate:.0}. This is the beginning of our journey", + 40759.5123 + ); + + var log = SpeckleLog.Logger + .ForContext("currentSpeed", "warp 5") + .ForContext("captain", "Jean-Luc Picard"); + + SpeckleLog.Logger.Information( + "We're traveling to {destination} our current speed is {currentSpeed}", + "Fairpoint station" + ); + + GlobalLogContext.PushProperty("captain", "Picard"); + + using (LogContext.PushProperty("actingEnsign", "Wesley Crusher")) { - // Step 1. make sure to initialize the logger with the proper parameters - // note, this initialization is part of the current default setup, with sane - SpeckleLog.Initialize( - hostApplicationName: "Enterprise ", - hostApplicationVersion: "NCC-1701-D", - logConfiguration: new(Serilog.Events.LogEventLevel.Debug, logToConsole: true) - ); - - // by default, this: - // logs to file in the Speckle folder / Logs / hostApplicationName - // reports errors to sentry - // sends all log events above the configured level to seq - // logs to the stdout console (useful when debugging) - // note, not all props are available in the file and console log, context is not rendered there - - SpeckleLog.Logger.Information( - "Captain's first log, stardate {stardate:.0}. This is the beginning of our journey", - 40759.5123 - ); - - var log = SpeckleLog.Logger - .ForContext("currentSpeed", "warp 5") - .ForContext("captain", "Jean-Luc Picard"); - - SpeckleLog.Logger.Information( - "We're traveling to {destination} our current speed is {currentSpeed}", - "Fairpoint station" - ); - - GlobalLogContext.PushProperty("captain", "Picard"); + var bearing = new { bearing = 25, mark = 134 }; + SpeckleLog.Logger.Information("Picking up an anomaly, bearing {@bearing}", bearing); + } + try + { + SpeckleLog.Logger.Warning("Yellow alert, shields up"); + throw new Exception("Shields are not responding."); + } + catch (Exception ex) + { + SpeckleLog.Logger.Error(ex, "Cannot raise shields, {reason}", ex.Message); + SpeckleLog.Logger.Fatal(ex, "Cannot raise shields, {reason}", ex.Message); + } - using (LogContext.PushProperty("actingEnsign", "Wesley Crusher")) - { - var bearing = new { bearing = 25, mark = 134 }; - SpeckleLog.Logger.Information("Picking up an anomaly, bearing {@bearing}", bearing); - } - try - { - SpeckleLog.Logger.Warning("Yellow alert, shields up"); - throw new Exception("Shields are not responding."); - } - catch (Exception ex) - { - SpeckleLog.Logger.Error(ex, "Cannot raise shields, {reason}", ex.Message); - SpeckleLog.Logger.Fatal(ex, "Cannot raise shields, {reason}", ex.Message); - } + // await Subscriptions.SubscriptionConnection(); - // await Subscriptions.SubscriptionConnection(); + // Console.Clear(); - // Console.Clear(); + // //await SendAndReceive(1_000); - // //await SendAndReceive(1_000); + // Console.Clear(); - // Console.Clear(); + // //await SendReceiveLargeSingleObjects(50_000); // pass in 500k for a 500k vertices mesh. gzipped size: ± 5.4mb, decompressed json: 21.7mb. Works :) - // //await SendReceiveLargeSingleObjects(50_000); // pass in 500k for a 500k vertices mesh. gzipped size: ± 5.4mb, decompressed json: 21.7mb. Works :) + // Console.Clear(); - // Console.Clear(); + // //await SendReceiveManyLargeObjects(); // defaults to 10k meshes with 1k vertices and faces - // //await SendReceiveManyLargeObjects(); // defaults to 10k meshes with 1k vertices and faces + // var foo = new Base() { }; - // var foo = new Base() { }; + // var chld1 = new ObjectReference(); + // chld1.referencedId = "f048873d78d8833e1a2c0d7c2391a9bb"; - // var chld1 = new ObjectReference(); - // chld1.referencedId = "f048873d78d8833e1a2c0d7c2391a9bb"; + // foo["Members"] = new[] { chld1 }; - // foo["Members"] = new[] { chld1 }; + // var ser = Operations.Serialize(foo); - // var ser = Operations.Serialize(foo); + Console.WriteLine("Press any key to exit"); + Console.ReadLine(); + } - Console.WriteLine("Press any key to exit"); - Console.ReadLine(); + /// + /// Sends many large objects. It's more of a stress test. + /// + /// + /// + /// + public static async Task SendReceiveManyLargeObjects( + int numVertices = 1000, + int numObjects = 10_000 + ) + { + var objs = new List(); - return; - } + Console.WriteLine( + $"Generating {numObjects} meshes with {numVertices} each. That's like {numVertices * numObjects} points. Might take a while?" + ); - /// - /// Sends many large objects. It's more of a stress test. - /// - /// - /// - /// - public static async Task SendReceiveManyLargeObjects( - int numVertices = 1000, - int numObjects = 10_000 - ) + for (int i = 1; i <= numObjects; i++) { - var objs = new List(); - - Console.WriteLine( - $"Generating {numObjects} meshes with {numVertices} each. That's like {numVertices * numObjects} points. Might take a while?" - ); - - for (int i = 1; i <= numObjects; i++) + Console.CursorTop = 1; + Console.WriteLine($"Generating mesh {i}"); + var myMesh = new Mesh(); + for (int j = 1; j <= numVertices; j++) { - Console.CursorTop = 1; - Console.WriteLine($"Generating mesh {i}"); - var myMesh = new Mesh(); - for (int j = 1; j <= numVertices; j++) - { - myMesh.Points.Add(new Point(j / 0.3f, 2 * j + 3.2301000111, 0.22229 * j)); - myMesh.Faces.AddRange(new int[] { j, j + i, j + 3, j + 23 + i, 100 % i + j }); - } - objs.Add(myMesh); + myMesh.Points.Add(new Point(j / 0.3f, 2 * j + 3.2301000111, 0.22229 * j)); + myMesh.Faces.AddRange(new[] { j, j + i, j + 3, j + 23 + i, 100 % i + j }); } + objs.Add(myMesh); + } - Console.Clear(); - Console.WriteLine("Done generating objects."); + Console.Clear(); + Console.WriteLine("Done generating objects."); - var myClient = new Client(AccountManager.GetDefaultAccount()); - var streamId = await myClient - .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) - .ConfigureAwait(false); - var myServer = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); + var myClient = new Client(AccountManager.GetDefaultAccount()); + var streamId = await myClient + .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) + .ConfigureAwait(false); + var myServer = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); - var myObject = new Base(); - myObject["items"] = objs; + var myObject = new Base(); + myObject["items"] = objs; - var res = await Operations - .Send( - myObject, - new List() { myServer }, - onProgressAction: dict => - { - Console.CursorLeft = 0; - Console.CursorTop = 2; + var res = await Operations + .Send( + myObject, + new List { myServer }, + onProgressAction: dict => + { + Console.CursorLeft = 0; + Console.CursorTop = 2; - foreach (var kvp in dict) - Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); - } - ) - .ConfigureAwait(false); + foreach (var kvp in dict) + Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); + } + ) + .ConfigureAwait(false); - Console.WriteLine($"Big commit id is {res}"); + Console.WriteLine($"Big commit id is {res}"); - var receivedCommit = await Operations - .Receive( - res, - remoteTransport: myServer, - onProgressAction: dict => - { - Console.CursorLeft = 0; - Console.CursorTop = 7; + var receivedCommit = await Operations + .Receive( + res, + myServer, + onProgressAction: dict => + { + Console.CursorLeft = 0; + Console.CursorTop = 7; - foreach (var kvp in dict) - Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); - } - ) - .ConfigureAwait(false); + foreach (var kvp in dict) + Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); + } + ) + .ConfigureAwait(false); - Console.Clear(); - Console.WriteLine($"Received big commit {res}"); - } + Console.Clear(); + Console.WriteLine($"Received big commit {res}"); + } - /// - /// Speckle 1.0 had some inherited limitations on object size from MongoDB. Since we've moved to postgres, let's flex. - /// - /// - /// - public static async Task SendReceiveLargeSingleObjects(int numVertices = 100_000) - { - Console.Clear(); - Console.WriteLine( - $"Big mesh time! ({numVertices} vertices, and some {numVertices * 1.5} faces" - ); - var myMesh = new Mesh(); + /// + /// Speckle 1.0 had some inherited limitations on object size from MongoDB. Since we've moved to postgres, let's flex. + /// + /// + /// + public static async Task SendReceiveLargeSingleObjects(int numVertices = 100_000) + { + Console.Clear(); + Console.WriteLine( + $"Big mesh time! ({numVertices} vertices, and some {numVertices * 1.5} faces" + ); + var myMesh = new Mesh(); - for (int i = 1; i <= numVertices; i++) - { - myMesh.Points.Add(new Point(i / 0.3f, 2 * i + 3.2301000111, 0.22229 * i)); - myMesh.Faces.AddRange(new int[] { i, i + i, i + 3, 23 + i, 100 % i }); - } + for (int i = 1; i <= numVertices; i++) + { + myMesh.Points.Add(new Point(i / 0.3f, 2 * i + 3.2301000111, 0.22229 * i)); + myMesh.Faces.AddRange(new[] { i, i + i, i + 3, 23 + i, 100 % i }); + } - var myClient = new Client(AccountManager.GetDefaultAccount()); - var streamId = await myClient - .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) - .ConfigureAwait(false); - var server = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); + var myClient = new Client(AccountManager.GetDefaultAccount()); + var streamId = await myClient + .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) + .ConfigureAwait(false); + var server = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); - var res = await Operations - .Send(myMesh, transports: new List() { server }) - .ConfigureAwait(false); - ; + var res = await Operations.Send(myMesh, new List { server }).ConfigureAwait(false); + ; - Console.WriteLine($"Big mesh id is {res}"); + Console.WriteLine($"Big mesh id is {res}"); - var cp = res; + var cp = res; - var pullMyMesh = await Operations.Receive(res).ConfigureAwait(false); + var pullMyMesh = await Operations.Receive(res).ConfigureAwait(false); - Console.WriteLine("Pulled back big mesh."); - } + Console.WriteLine("Pulled back big mesh."); + } - /// - /// A more generic version of the above. - /// - /// - /// - public static async Task SendAndReceive(int numObjects = 3000) - { - var sw = new Stopwatch(); - sw.Start(); + /// + /// A more generic version of the above. + /// + /// + /// + public static async Task SendAndReceive(int numObjects = 3000) + { + var sw = new Stopwatch(); + sw.Start(); - // Create a bunch of objects! - var objects = new List(); - for (int i = 0; i < numObjects; i++) + // Create a bunch of objects! + var objects = new List(); + for (int i = 0; i < numObjects; i++) + if (i % 2 == 0) { - if (i % 2 == 0) - { - objects.Add(new Point(i / 5, i / 2, i + 12.3233)); - ((dynamic)objects[i])["@bobba"] = new Point(2 + i + i, 42, i); // This will throw our progress reporting off, as our total object count will not reflect detached objects. C'est la vie. - } - else - { - objects.Add( - new Polyline - { - Points = new List() - { - new Point(i * 3.23, i / 3 * 7, i * 3), - new Point(i / 2, i / 2, i / 2) - } - } - ); - for (int j = 0; j < 54; j++) + objects.Add(new Point(i / 5, i / 2, i + 12.3233)); + ((dynamic)objects[i])["@bobba"] = new Point(2 + i + i, 42, i); // This will throw our progress reporting off, as our total object count will not reflect detached objects. C'est la vie. + } + else + { + objects.Add( + new Polyline { - ((Polyline)objects[i]).Points.Add(new Point(j + i, 12.2 + j, 42.32 + j)); + Points = new List { new(i * 3.23, i / 3 * 7, i * 3), new(i / 2, i / 2, i / 2) } } - } + ); + for (int j = 0; j < 54; j++) + ((Polyline)objects[i]).Points.Add(new Point(j + i, 12.2 + j, 42.32 + j)); } - var myRevision = new Base(); - ((dynamic)myRevision)["@LolLayer"] = objects.GetRange(0, 30); - ((dynamic)myRevision)["@WooTLayer"] = objects.GetRange(30, 100); - ((dynamic)myRevision)["@FTW"] = objects.GetRange(130, objects.Count - 130 - 1); + var myRevision = new Base(); + ((dynamic)myRevision)["@LolLayer"] = objects.GetRange(0, 30); + ((dynamic)myRevision)["@WooTLayer"] = objects.GetRange(30, 100); + ((dynamic)myRevision)["@FTW"] = objects.GetRange(130, objects.Count - 130 - 1); - var step = sw.ElapsedMilliseconds; - Console.WriteLine( - $"Finished generating {numObjects} objs in ${sw.ElapsedMilliseconds / 1000f} seconds." - ); + var step = sw.ElapsedMilliseconds; + Console.WriteLine( + $"Finished generating {numObjects} objs in ${sw.ElapsedMilliseconds / 1000f} seconds." + ); + + Console.Clear(); - Console.Clear(); + // This action will get invoked on progress. + var pushProgressAction = new Action>(progress => + { + Console.CursorLeft = 0; + Console.CursorTop = 0; - // This action will get invoked on progress. - var pushProgressAction = new Action>( - (progress) => + // The provided dictionary has an individual kvp for each provided transport/process. + foreach (var kvp in progress) + Console.WriteLine($">>> {kvp.Key} : {kvp.Value} / {numObjects + 1}"); + }); + + // Let's set up some fake server transports. + var myClient = new Client(AccountManager.GetDefaultAccount()); + var streamId = await myClient + .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) + .ConfigureAwait(false); + var firstServer = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); + + var mySecondClient = new Client(AccountManager.GetDefaultAccount()); + var secondStreamId = await myClient + .StreamCreate(new StreamCreateInput { name = "test2", description = "this is a second test" }) + .ConfigureAwait(false); + var secondServer = new ServerTransport(AccountManager.GetDefaultAccount(), secondStreamId); + + var res = await Operations + .Send( + myRevision, + new List { firstServer, secondServer }, + onProgressAction: pushProgressAction + ) + .ConfigureAwait(false); + + Console.Clear(); + Console.CursorLeft = 0; + Console.CursorTop = 0; + + Console.WriteLine( + $"Finished sending {numObjects} objs or more in ${(sw.ElapsedMilliseconds - step) / 1000f} seconds." + ); + Console.WriteLine($"Parent object id: {res}"); + + Console.Clear(); + + // Time for getting our revision object back. + var res2 = await Operations + .Receive( + res, + firstServer, + onProgressAction: dict => { Console.CursorLeft = 0; Console.CursorTop = 0; - // The provided dictionary has an individual kvp for each provided transport/process. - foreach (var kvp in progress) - Console.WriteLine($">>> {kvp.Key} : {kvp.Value} / {numObjects + 1}"); + foreach (var kvp in dict) + Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); } - ); - - // Let's set up some fake server transports. - var myClient = new Client(AccountManager.GetDefaultAccount()); - var streamId = await myClient - .StreamCreate(new StreamCreateInput { name = "test", description = "this is a test" }) - .ConfigureAwait(false); - var firstServer = new ServerTransport(AccountManager.GetDefaultAccount(), streamId); - - var mySecondClient = new Client(AccountManager.GetDefaultAccount()); - var secondStreamId = await myClient - .StreamCreate( - new StreamCreateInput { name = "test2", description = "this is a second test" } - ) - .ConfigureAwait(false); - var secondServer = new ServerTransport(AccountManager.GetDefaultAccount(), secondStreamId); - - var res = await Operations - .Send( - @object: myRevision, - transports: new List() { firstServer, secondServer }, - onProgressAction: pushProgressAction - ) - .ConfigureAwait(false); - - Console.Clear(); - Console.CursorLeft = 0; - Console.CursorTop = 0; - - Console.WriteLine( - $"Finished sending {numObjects} objs or more in ${(sw.ElapsedMilliseconds - step) / 1000f} seconds." - ); - Console.WriteLine($"Parent object id: {res}"); - - Console.Clear(); - - // Time for getting our revision object back. - var res2 = await Operations - .Receive( - res, - remoteTransport: firstServer, - onProgressAction: dict => - { - Console.CursorLeft = 0; - Console.CursorTop = 0; - - foreach (var kvp in dict) - Console.WriteLine($"<<<< {kvp.Key} progress: {kvp.Value} / {numObjects + 1}"); - } - ) - .ConfigureAwait(false); + ) + .ConfigureAwait(false); - Console.Clear(); - Console.WriteLine("Got those objects back"); - } + Console.Clear(); + Console.WriteLine("Got those objects back"); + } - /// - /// Some stress tests for the sqlite transport. Perhaps useful later. - /// - /// - public static async Task SqliteStressTest() - { - int numObjects = 100_000; - var transport = new SQLiteTransport(); - var rand = new Random(); - var stopWatch = new Stopwatch(); + /// + /// Some stress tests for the sqlite transport. Perhaps useful later. + /// + /// + public static async Task SqliteStressTest() + { + int numObjects = 100_000; + var transport = new SQLiteTransport(); + var rand = new Random(); + var stopWatch = new Stopwatch(); - Console.WriteLine($"-------------------------------------------------\n"); - Console.WriteLine($"Starting to save {numObjects} of objects"); + Console.WriteLine("-------------------------------------------------\n"); + Console.WriteLine($"Starting to save {numObjects} of objects"); - stopWatch.Start(); + stopWatch.Start(); - for (int i = 0; i < numObjects; i++) - { - //var hash = Speckle.Core.Models.Utilities.hashString($"hash-{i}-{rand.NextDouble()}"); - transport.SaveObject( - $"hash-{i}-{rand.NextDouble()}", - $"content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}" - ); - } + for (int i = 0; i < numObjects; i++) + //var hash = Speckle.Core.Models.Utilities.hashString($"hash-{i}-{rand.NextDouble()}"); + transport.SaveObject( + $"hash-{i}-{rand.NextDouble()}", + $"content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}content-longer-maye-it's-ok-{i}" + ); - // waits for the buffer to be empty. - await transport.WriteComplete().ConfigureAwait(false); + // waits for the buffer to be empty. + await transport.WriteComplete().ConfigureAwait(false); - var stopWatchStep = stopWatch.ElapsedMilliseconds; - var objsPerSecond = (double)numObjects / (stopWatchStep / 1000); - Console.WriteLine($"-------------------------------------------------"); - Console.WriteLine( - $"BufferedWriteTest: Wrote {numObjects} in {stopWatchStep} ms -> {objsPerSecond} objects per second" - ); - Console.WriteLine($"-------------------------------------------------\n"); - } + var stopWatchStep = stopWatch.ElapsedMilliseconds; + var objsPerSecond = (double)numObjects / (stopWatchStep / 1000); + Console.WriteLine("-------------------------------------------------"); + Console.WriteLine( + $"BufferedWriteTest: Wrote {numObjects} in {stopWatchStep} ms -> {objsPerSecond} objects per second" + ); + Console.WriteLine("-------------------------------------------------\n"); } } diff --git a/Core/Examples/Subscriptions.cs b/Core/Examples/Subscriptions.cs index 3d80eb157e..e1e672ec61 100644 --- a/Core/Examples/Subscriptions.cs +++ b/Core/Examples/Subscriptions.cs @@ -5,45 +5,44 @@ using Speckle.Core.Api.SubscriptionModels; using Speckle.Core.Credentials; -namespace ExampleApp +namespace ExampleApp; + +public static class Subscriptions { - public static class Subscriptions + public static async Task SubscriptionConnection() { - public static async Task SubscriptionConnection() - { - var myClient = new Client(AccountManager.GetDefaultAccount()); + var myClient = new Client(AccountManager.GetDefaultAccount()); - Console.WriteLine("Client created..."); + Console.WriteLine("Client created..."); - Console.WriteLine( - "Subscribing to stream created. On first created event will subscribe to that stream's updates." - ); + Console.WriteLine( + "Subscribing to stream created. On first created event will subscribe to that stream's updates." + ); - myClient.SubscribeUserStreamAdded(); + myClient.SubscribeUserStreamAdded(); - bool first = true; + bool first = true; - myClient.OnUserStreamAdded += (sender, e) => - { - if (first) - { - first = false; - myClient.SubscribeStreamUpdated(e.id); - myClient.OnStreamUpdated += MyClient_OnStreamUpdated; - ; - } - - Console.WriteLine("UserStreamCreated Fired"); - Console.WriteLine(JsonConvert.SerializeObject(e)); - }; - - Console.ReadLine(); - } - - private static void MyClient_OnStreamUpdated(object sender, StreamInfo e) + myClient.OnUserStreamAdded += (sender, e) => { - Console.WriteLine("StreamUpdated Fired"); + if (first) + { + first = false; + myClient.SubscribeStreamUpdated(e.id); + myClient.OnStreamUpdated += MyClient_OnStreamUpdated; + ; + } + + Console.WriteLine("UserStreamCreated Fired"); Console.WriteLine(JsonConvert.SerializeObject(e)); - } + }; + + Console.ReadLine(); + } + + private static void MyClient_OnStreamUpdated(object sender, StreamInfo e) + { + Console.WriteLine("StreamUpdated Fired"); + Console.WriteLine(JsonConvert.SerializeObject(e)); } } diff --git a/Core/IntegrationTests/Api.cs b/Core/IntegrationTests/Api.cs index 9005984da2..385f3b9d8d 100644 --- a/Core/IntegrationTests/Api.cs +++ b/Core/IntegrationTests/Api.cs @@ -290,7 +290,7 @@ public async Task CommitCreate() objectId = await Operations .Send( myObject, - new List() { myServerTransport }, + new List { myServerTransport }, false, disposeTransports: true, onErrorAction: (s, e) => @@ -328,7 +328,7 @@ public async Task CommitCreate() message = "Fabber Fabbo", sourceApplication = "Tests", totalChildrenCount = 100, - parents = new List() { commitId } + parents = new List { commitId } } ) .ConfigureAwait(false); diff --git a/Core/IntegrationTests/Fixtures.cs b/Core/IntegrationTests/Fixtures.cs index 0ee0f07465..14343ce1b2 100644 --- a/Core/IntegrationTests/Fixtures.cs +++ b/Core/IntegrationTests/Fixtures.cs @@ -2,7 +2,6 @@ using System.Text; using System.Web; using Newtonsoft.Json; -using Serilog.Events; using Speckle.Core.Api; using Speckle.Core.Credentials; using Speckle.Core.Logging; @@ -19,7 +18,7 @@ public void BeforeAll() SpeckleLog.Initialize( "Core", "Testing", - new SpeckleLogConfiguration(LogEventLevel.Debug, true, logToFile: false, logToSeq: false) + new SpeckleLogConfiguration(logToFile: false, logToSeq: false) ); SpeckleLog.Logger.Information("Initialized logger for testing"); } @@ -38,7 +37,7 @@ public static async Task SeedUser() user["password"] = "12ABC3456789DEF0GHO"; user["name"] = $"{seed.Substring(0, 5)} Name"; - var httpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false }); + var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }); httpClient.BaseAddress = new Uri(Server.url); string redirectUrl; @@ -67,7 +66,7 @@ public static async Task SeedUser() var accessCode = query["access_code"] ?? throw new Exception("Redirect Uri has no 'access_code'."); - var tokenBody = new Dictionary() + var tokenBody = new Dictionary { ["accessCode"] = accessCode, ["appId"] = "spklwebapp", @@ -132,7 +131,7 @@ public static Base GenerateNestedObject() public static Blob[] GenerateThreeBlobs() { - return new Blob[] + return new[] { GenerateBlob("blob 1 data"), GenerateBlob("blob 2 data"), diff --git a/Core/IntegrationTests/Subscriptions/Commits.cs b/Core/IntegrationTests/Subscriptions/Commits.cs index 2740c55da3..8dd789503b 100644 --- a/Core/IntegrationTests/Subscriptions/Commits.cs +++ b/Core/IntegrationTests/Subscriptions/Commits.cs @@ -69,7 +69,7 @@ public async Task SubscribeCommitCreated() var objectId = await Operations .Send( myObject, - new List() { myServerTransport }, + new List { myServerTransport }, false, onErrorAction: (name, err) => { diff --git a/Core/Tests/BaseTests.cs b/Core/Tests/BaseTests.cs index 8e326b3829..bdc55aa126 100755 --- a/Core/Tests/BaseTests.cs +++ b/Core/Tests/BaseTests.cs @@ -230,8 +230,6 @@ public void CanShallowCopy() public class SampleObject : Base { - public SampleObject() { } - [Chunkable, DetachProperty] public List list { get; set; } = new(); @@ -243,7 +241,7 @@ public SampleObject() { } public SampleProp attachedProp { get; set; } - public string @crazyProp { get; set; } + public string crazyProp { get; set; } [SchemaIgnore] public string IgnoredSchemaProp { get; set; } diff --git a/Core/Tests/ClosureTests.cs b/Core/Tests/ClosureTests.cs index 4d676c5170..0edfeec3e4 100644 --- a/Core/Tests/ClosureTests.cs +++ b/Core/Tests/ClosureTests.cs @@ -35,7 +35,7 @@ public void CorrectDecompositionTracking() var transport = new MemoryTransport(); - var result = Operations.Send(d1, new List() { transport }, false).Result; + var result = Operations.Send(d1, new List { transport }, false).Result; var test = Operations.Receive(result, localTransport: transport).Result; @@ -89,7 +89,7 @@ public void DescendantsCounting() var dictionary = new Dictionary(); for (int i = 0; i < 10; i++) { - var smolBase = new Base() { applicationId = i.ToString() }; + var smolBase = new Base { applicationId = i.ToString() }; dictionary[$"key {i}"] = smolBase; } @@ -107,7 +107,7 @@ public void DescendantsCounting() Assert.That(tableKidsCount, Is.EqualTo(10)); // Explicitely test for recurisve references! - var recursiveRef = new Base() { applicationId = "random" }; + var recursiveRef = new Base { applicationId = "random" }; recursiveRef["@recursive"] = recursiveRef; var supriseCount = recursiveRef.GetTotalChildrenCount(); diff --git a/Core/Tests/Fixtures.cs b/Core/Tests/Fixtures.cs index fa2017bc44..033cf33166 100644 --- a/Core/Tests/Fixtures.cs +++ b/Core/Tests/Fixtures.cs @@ -1,6 +1,5 @@ -using Newtonsoft.Json; +using Newtonsoft.Json; using NUnit.Framework; -using Serilog.Events; using Speckle.Core.Credentials; using Speckle.Core.Helpers; using Speckle.Core.Logging; @@ -17,7 +16,7 @@ public void BeforeAll() SpeckleLog.Initialize( "Core", "Testing", - new SpeckleLogConfiguration(LogEventLevel.Debug, true, logToFile: false, logToSeq: false) + new SpeckleLogConfiguration(logToFile: false, logToSeq: false) ); SpeckleLog.Logger.Information("Initialized logger for testing"); } @@ -26,6 +25,7 @@ public void BeforeAll() public abstract class Fixtures { private static SQLiteTransport AccountStorage = new(scope: "Accounts"); + private static string accountPath = Path.Combine( SpecklePathProvider.AccountsFolderPath, "TestAccount.json" diff --git a/Core/Tests/GraphQLClient.cs b/Core/Tests/GraphQLClient.cs index 458402ff20..9e6979ea85 100644 --- a/Core/Tests/GraphQLClient.cs +++ b/Core/Tests/GraphQLClient.cs @@ -48,7 +48,7 @@ public void TestExceptionThrowingFromGraphQLErrors(Type exType, Map extensions) Assert.Throws( exType, () => - _client.MaybeThrowFromGraphQLErrors( + _client.MaybeThrowFromGraphQLErrors( new GraphQLRequest(), new GraphQLResponse { @@ -61,10 +61,7 @@ public void TestExceptionThrowingFromGraphQLErrors(Type exType, Map extensions) [Test] public void TestMaybeThrowsDoesntThrowForNoErrors() { - _client.MaybeThrowFromGraphQLErrors( - new GraphQLRequest(), - new GraphQLResponse() - ); + _client.MaybeThrowFromGraphQLErrors(new GraphQLRequest(), new GraphQLResponse()); // We're just checking that the prev function didn't throw Assert.True(true); } diff --git a/Core/Tests/Hashing.cs b/Core/Tests/Hashing.cs index 1c6fb35150..cf64edc7f7 100644 --- a/Core/Tests/Hashing.cs +++ b/Core/Tests/Hashing.cs @@ -38,7 +38,7 @@ public void HashingPerformance() var polyline = new Polyline(); for (int i = 0; i < 1000; i++) - polyline.Points.Add(new Point() { X = i * 2, Y = i % 2 }); + polyline.Points.Add(new Point { X = i * 2, Y = i % 2 }); var stopWatch = new Stopwatch(); stopWatch.Start(); @@ -57,7 +57,7 @@ public void HashingPerformance() ); Console.WriteLine($"Big obj hash duration: {diff1} ms"); - var pt = new Point() + var pt = new Point { X = 10, Y = 12, diff --git a/Core/Tests/ObjectTraversal/GraphTraversalTests.cs b/Core/Tests/ObjectTraversal/GraphTraversalTests.cs index 5c0ca211ce..d4f0d507b5 100644 --- a/Core/Tests/ObjectTraversal/GraphTraversalTests.cs +++ b/Core/Tests/ObjectTraversal/GraphTraversalTests.cs @@ -30,14 +30,14 @@ public void Traverse_TraversesListMembers() .Select(kvp => kvp.Key) ); - var expectTraverse = new Base() { id = "List Member" }; - var expectIgnored = new Base() { id = "Not List Member" }; + var expectTraverse = new Base { id = "List Member" }; + var expectIgnored = new Base { id = "Not List Member" }; TraversalMock testCase = new() { - ListChildren = new List() { expectTraverse }, - DictChildren = new Dictionary() { ["myprop"] = expectIgnored }, + ListChildren = new List { expectTraverse }, + DictChildren = new Dictionary { ["myprop"] = expectIgnored }, Child = expectIgnored }; @@ -65,14 +65,14 @@ public void Traverse_TraversesDictMembers() .Select(kvp => kvp.Key) ); - var expectTraverse = new Base() { id = "Dict Member" }; - var expectIgnored = new Base() { id = "Not Dict Member" }; + var expectTraverse = new Base { id = "Dict Member" }; + var expectIgnored = new Base { id = "Not Dict Member" }; TraversalMock testCase = new() { - ListChildren = new List() { expectIgnored }, - DictChildren = new Dictionary() { ["myprop"] = expectTraverse }, + ListChildren = new List { expectIgnored }, + DictChildren = new Dictionary { ["myprop"] = expectTraverse }, Child = expectIgnored }; @@ -95,8 +95,8 @@ public void Traverse_TraversesDynamic() .When(_ => true) .ContinueTraversing(x => x.GetMembers(DynamicBaseMemberType.Dynamic).Select(kvp => kvp.Key)); - var expectTraverse = new Base() { id = "List Member" }; - var expectIgnored = new Base() { id = "Not List Member" }; + var expectTraverse = new Base { id = "List Member" }; + var expectIgnored = new Base { id = "Not List Member" }; TraversalMock testCase = new() @@ -120,8 +120,8 @@ public void Traverse_TraversesDynamic() [Test] public void Traverse_ExclusiveRule() { - var expectTraverse = new Base() { id = "List Member" }; - var expectIgnored = new Base() { id = "Not List Member" }; + var expectTraverse = new Base { id = "List Member" }; + var expectIgnored = new Base { id = "Not List Member" }; var traverseListsRule = TraversalRule .NewTraversalRule() diff --git a/Core/Tests/SendReceiveLocal.cs b/Core/Tests/SendReceiveLocal.cs index 1bff0e5f15..7dbebfe336 100644 --- a/Core/Tests/SendReceiveLocal.cs +++ b/Core/Tests/SendReceiveLocal.cs @@ -178,7 +178,7 @@ public async Task UploadProgressReports() commitId_02 = await Operations .Send( myObject, - onProgressAction: (dict) => + onProgressAction: dict => { progress = dict; } @@ -196,7 +196,7 @@ public async Task DownloadProgressReports() var pulledCommit = await Operations .Receive( commitId_02, - onProgressAction: (dict) => + onProgressAction: dict => { progress = dict; } @@ -216,14 +216,14 @@ public async Task ShouldDisposeTransports() var myLocalTransport = new SQLiteTransport(); var id = await Operations - .Send(@base, new List() { myLocalTransport }, false, disposeTransports: true) + .Send(@base, new List { myLocalTransport }, false, disposeTransports: true) .ConfigureAwait(false); // Send try { await Operations - .Send(@base, new List() { myLocalTransport }, false, disposeTransports: true) + .Send(@base, new List { myLocalTransport }, false, disposeTransports: true) .ConfigureAwait(false); Assert.Fail("Send operation did not dispose of transport."); } @@ -256,10 +256,10 @@ public async Task ShouldNotDisposeTransports() var myLocalTransport = new SQLiteTransport(); var id = await Operations - .Send(@base, new List() { myLocalTransport }, false) + .Send(@base, new List { myLocalTransport }, false) .ConfigureAwait(false); await Operations - .Send(@base, new List() { myLocalTransport }, false) + .Send(@base, new List { myLocalTransport }, false) .ConfigureAwait(false); var obj = await Operations.Receive(id, null, myLocalTransport).ConfigureAwait(false); diff --git a/Core/Tests/SerializationTests.cs b/Core/Tests/SerializationTests.cs index d99effcdec..651e711927 100644 --- a/Core/Tests/SerializationTests.cs +++ b/Core/Tests/SerializationTests.cs @@ -21,7 +21,7 @@ public void SimpleSerialization() var polyline = new Polyline(); for (int i = 0; i < 100; i++) - polyline.Points.Add(new Point() { X = i * 2, Y = i % 2 }); + polyline.Points.Add(new Point { X = i * 2, Y = i % 2 }); var strPoly = Operations.Serialize(polyline); var dePoly = Operations.Deserialize(strPoly); @@ -61,7 +61,7 @@ public void InterfacePropHandling() { var cat = new PolygonalFeline(); - cat.Tail = new Line() { Start = new Point(0, 0, 0), End = new Point(42, 42, 42) }; + cat.Tail = new Line { Start = new Point(0, 0, 0), End = new Point(42, 42, 42) }; for (int i = 0; i < 10; i++) { @@ -107,7 +107,7 @@ public void InterfacePropHandling() [Test] public void InheritanceTests() { - var superPoint = new SuperPoint() + var superPoint = new SuperPoint { X = 10, Y = 10, @@ -209,11 +209,8 @@ public void EmptyListSerialisationTests() test["@emptyDetachableList"] = new List(); // Note: nested empty lists should be preserved. - test["nestedList"] = new List() { new List() { new List() } }; - test["@nestedDetachableList"] = new List() - { - new List() { new List() } - }; + test["nestedList"] = new List { new List { new List() } }; + test["@nestedDetachableList"] = new List { new List { new List() } }; var serialised = Operations.Serialize(test); var isCorrect = diff --git a/Core/Tests/SerializerNonBreakingChanges.cs b/Core/Tests/SerializerNonBreakingChanges.cs index de2a70de88..de46f49a3a 100644 --- a/Core/Tests/SerializerNonBreakingChanges.cs +++ b/Core/Tests/SerializerNonBreakingChanges.cs @@ -68,7 +68,7 @@ public void IntToString(long testCase) { new double[] { }, new double[] { 0, 1, int.MaxValue, int.MinValue }, - new double[] { default, double.Epsilon, double.MaxValue, double.MinValue } + new[] { default, double.Epsilon, double.MaxValue, double.MinValue } }; [Test, TestCaseSource(nameof(ArrayTestCases))] @@ -132,7 +132,7 @@ public void StringToInt_ShouldThrow() [Test, TestCaseSource(nameof(MyEnums))] public void StringToEnum_ShouldThrow(MyEnum testCase) { - var from = new StringValueMock() { value = testCase.ToString() }; + var from = new StringValueMock { value = testCase.ToString() }; Assert.Throws(() => { @@ -252,6 +252,7 @@ public abstract class PrimitiveTestFixture double.MaxValue, double.MinValue }; + public static float[] Float32TestCases = { default, @@ -259,6 +260,7 @@ public abstract class PrimitiveTestFixture float.MaxValue, float.MinValue }; + public static Half[] Float16TestCases = { default, Half.Epsilon, Half.MaxValue, Half.MinValue }; public static float[] FloatIntegralTestCases = { 0, 1, int.MaxValue, int.MinValue }; diff --git a/Core/Tests/TestKit.cs b/Core/Tests/TestKit.cs index accc529857..d50c1fa745 100644 --- a/Core/Tests/TestKit.cs +++ b/Core/Tests/TestKit.cs @@ -9,8 +9,6 @@ namespace Tests; /// public class TestKit : ISpeckleKit { - public TestKit() { } - public IEnumerable Types => GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); @@ -62,15 +60,13 @@ public void SetContextDocument(object @object) public class FakeMesh : Base { - public FakeMesh() { } - [DetachProperty, Chunkable] public List Vertices { get; set; } = new(); - [DetachProperty, Chunkable(1000)] + [DetachProperty, Chunkable] public double[] ArrayOfDoubles { get; set; } - [DetachProperty, Chunkable(1000)] + [DetachProperty, Chunkable] public TableLeg[] ArrayOfLegs { get; set; } [DetachProperty, Chunkable(2500)] @@ -81,13 +77,13 @@ public class DiningTable : Base { public DiningTable() { - LegOne = new TableLeg() { height = 2 * 3, radius = 10 }; - LegTwo = new TableLeg() { height = 1, radius = 5 }; + LegOne = new TableLeg { height = 2 * 3, radius = 10 }; + LegTwo = new TableLeg { height = 1, radius = 5 }; - MoreLegs.Add(new TableLeg() { height = 4 }); - MoreLegs.Add(new TableLeg() { height = 10 }); + MoreLegs.Add(new TableLeg { height = 4 }); + MoreLegs.Add(new TableLeg { height = 10 }); - Tabletop = new Tabletop() + Tabletop = new Tabletop { length = 200, width = 12, @@ -112,8 +108,6 @@ public DiningTable() public class Tabletop : Base { - public Tabletop() { } - public double length { get; set; } public double width { get; set; } public double thickness { get; set; } @@ -121,8 +115,6 @@ public Tabletop() { } public class TableLeg : Base { - public TableLeg() { } - public double height { get; set; } public double radius { get; set; } @@ -132,8 +124,6 @@ public TableLeg() { } public class TableLegFixture : Base { - public TableLegFixture() { } - public string nails { get; set; } = "MANY NAILS WOW "; } @@ -155,8 +145,6 @@ public Point(double X, double Y, double Z) public class SuperPoint : Point { - public SuperPoint() { } - public double W { get; set; } } @@ -167,11 +155,9 @@ public class Mesh : Base [JsonIgnore] public List Points = new(); - public Mesh() { } - public List Vertices { - get => Points.SelectMany(pt => new List() { pt.X, pt.Y, pt.Z }).ToList(); + get => Points.SelectMany(pt => new List { pt.X, pt.Y, pt.Z }).ToList(); set { for (int i = 0; i < value.Count; i += 3) @@ -193,11 +179,9 @@ public class Polyline : Base, ICurve [JsonIgnore] public List Points = new(); - public Polyline() { } - public List Vertices { - get => Points.SelectMany(pt => new List() { pt.X, pt.Y, pt.Z }).ToList(); + get => Points.SelectMany(pt => new List { pt.X, pt.Y, pt.Z }).ToList(); set { for (int i = 0; i < value.Count; i += 3) @@ -208,8 +192,6 @@ public List Vertices public class Line : Base, ICurve { - public Line() { } - public Point Start { get; set; } public Point End { get; set; } } @@ -219,8 +201,6 @@ public Line() { } /// public class PolygonalFeline : Base { - public PolygonalFeline() { } - public List Whiskers { get; set; } = new(); public Dictionary Claws { get; set; } = new(); diff --git a/Core/Tests/TraversalTests.cs b/Core/Tests/TraversalTests.cs index 974c22cd64..66e57b406d 100644 --- a/Core/Tests/TraversalTests.cs +++ b/Core/Tests/TraversalTests.cs @@ -15,13 +15,13 @@ public void TestFlattenWithBreaker() new() { id = "root", - ["child"] = new Base() + ["child"] = new Base { id = "traverse through me", - ["child"] = new Base() + ["child"] = new Base { id = "break on me, go no further", - ["child"] = new Base() { id = "should have ignored me" } + ["child"] = new Base { id = "should have ignored me" } } } }; diff --git a/Core/Transports/DiskTransport/DiskTransport.cs b/Core/Transports/DiskTransport/DiskTransport.cs index 7648350469..8e7f966e50 100644 --- a/Core/Transports/DiskTransport/DiskTransport.cs +++ b/Core/Transports/DiskTransport/DiskTransport.cs @@ -30,7 +30,7 @@ public DiskTransport(string basePath = null) public object Clone() { - return new DiskTransport() + return new DiskTransport { RootPath = RootPath, CancellationToken = CancellationToken, @@ -56,7 +56,7 @@ public object Clone() public Action OnErrorAction { get; set; } - public int SavedObjectCount { get; private set; } = 0; + public int SavedObjectCount { get; private set; } public TimeSpan Elapsed { get; set; } = TimeSpan.Zero; @@ -105,10 +105,7 @@ public void SaveObject(string id, ITransport sourceTransport) SaveObject(id, serializedObject); } - public async Task WriteComplete() - { - return; - } + public async Task WriteComplete() { } public async Task CopyObjectAndChildren( string id, diff --git a/Core/Transports/MongoDBTransport/MongoDB.cs b/Core/Transports/MongoDBTransport/MongoDB.cs index d309685e6d..e252ea06ed 100644 --- a/Core/Transports/MongoDBTransport/MongoDB.cs +++ b/Core/Transports/MongoDBTransport/MongoDB.cs @@ -23,7 +23,7 @@ public enum Field // Explore storing partially serialized Speckle objects with dynamically generated fields instead of just a content string? public class MongoDBTransport : IDisposable, ITransport { - private bool IS_WRITING = false; + private bool IS_WRITING; private int MAX_TRANSACTION_SIZE = 1000; private int PollInterval = 500; @@ -51,7 +51,7 @@ public MongoDBTransport( Initialize(); - WriteTimer = new Timer() + WriteTimer = new Timer { AutoReset = true, Enabled = false, diff --git a/Directory.Build.props b/Directory.Build.props index 0749270784..2af6843a1b 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -15,6 +15,7 @@ latest + x64 true latest-AllEnabledByDefault @@ -63,4 +64,4 @@ PackagePath="" Visible="false"/> - + \ No newline at end of file