diff --git a/.vscode/tasks.json b/.vscode/tasks.json index b7323eb98b..ca33c5f2f1 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -33,7 +33,12 @@ "label": "speckle.format.style", "command": "dotnet", "type": "shell", - "args": ["format", "style", "${input:projectPath}"], + "args": [ + "format", + "style", + "${input:projectPath}", + "--exclude=Objects/Converters/StructuralUtilities/Triangle" + ], "group": "build", "problemMatcher": "$msCompile", "hide": true, @@ -46,7 +51,12 @@ "label": "speckle.format.whitespace", "command": "dotnet", "type": "shell", - "args": ["format", "whitespace", "${input:projectPath}"], + "args": [ + "format", + "whitespace", + "${input:projectPath}", + "--exclude=Objects/Converters/StructuralUtilities/Triangle" + ], "group": "build", "problemMatcher": "$msCompile", "hide": true, @@ -59,7 +69,12 @@ "label": "speckle.format.analyzers", "command": "dotnet", "type": "shell", - "args": ["format", "analyzers", "${input:projectPath}"], + "args": [ + "format", + "analyzers", + "${input:projectPath}", + "--exclude=Objects/Converters/StructuralUtilities/Triangle" + ], "group": "build", "problemMatcher": "$msCompile", "hide": false, @@ -79,7 +94,9 @@ "cleanupcode", "${input:projectPath}", "--profile=\"Speckle:Cleanup\"", - "--settings=\"All.sln.DotSettings\"" + "--settings=\"All.sln.DotSettings\"", + "--exclude=Objects/Converters/StructuralUtilities/Triangle", + "--properties:WarningLevel=0" ], "group": "build", "problemMatcher": [], @@ -91,11 +108,7 @@ }, { "label": "Speckle: Format Code", - "dependsOn": [ - "speckle.format.whitespace", - "speckle.format.style", - "speckle.format.csharpier" - ], + "dependsOn": ["speckle.format.style", "speckle.format.csharpier"], "dependsOrder": "sequence", "problemMatcher": [] }, diff --git a/Core/.csharpierrc b/Core/.csharpierrc deleted file mode 100644 index d16343e5ab..0000000000 --- a/Core/.csharpierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "printWidth": 100, - "useTabs": false, - "tabWidth": 2, - "preprocessorSymbolSets": ["", "DEBUG", "DEBUG,CODE_STYLE"] -} \ No newline at end of file diff --git a/Core/Core/Api/Exceptions.cs b/Core/Core/Api/Exceptions.cs index 76dc8a4bc3..0e8a6f270d 100644 --- a/Core/Core/Api/Exceptions.cs +++ b/Core/Core/Api/Exceptions.cs @@ -16,23 +16,14 @@ public class SpeckleGraphQLException : SpeckleException private GraphQLRequest _request; public GraphQLResponse? Response; - public SpeckleGraphQLException( - string message, - GraphQLRequest request, - GraphQLResponse? response - ) + public SpeckleGraphQLException(string message, GraphQLRequest request, GraphQLResponse? response) : base(message) { _request = request; Response = response; } - public SpeckleGraphQLException( - string message, - Exception inner, - GraphQLRequest request, - GraphQLResponse? response - ) + public SpeckleGraphQLException(string message, Exception inner, GraphQLRequest request, GraphQLResponse? response) : base(message, inner) { } public SpeckleGraphQLException() { } @@ -51,11 +42,7 @@ public SpeckleGraphQLException(string message, Exception innerException) public class SpeckleGraphQLException : SpeckleGraphQLException { - public SpeckleGraphQLException( - string message, - GraphQLRequest request, - GraphQLResponse? response - ) + public SpeckleGraphQLException(string message, GraphQLRequest request, GraphQLResponse? response) : base(message, request, response) { } public SpeckleGraphQLException() { } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ActivityOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ActivityOperations.cs index 1f3398186d..30e6e7ead3 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ActivityOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ActivityOperations.cs @@ -29,15 +29,7 @@ public Task> StreamGetActivity( int limit = 10 ) { - return StreamGetActivity( - CancellationToken.None, - streamId, - after, - before, - cursor, - actionType, - limit - ); + return StreamGetActivity(CancellationToken.None, streamId, after, before, cursor, actionType, limit); } /// @@ -94,8 +86,7 @@ public async Task> StreamGetActivity( } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.activity.items; } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.BranchOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.BranchOperations.cs index 6240d96ed6..386cccdfcd 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.BranchOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.BranchOperations.cs @@ -17,11 +17,7 @@ public partial class Client /// Max number of branches to retrieve /// Max number of commits to retrieve /// - public Task> StreamGetBranches( - string streamId, - int branchesLimit = 10, - int commitsLimit = 10 - ) + public Task> StreamGetBranches(string streamId, int branchesLimit = 10, int commitsLimit = 10) { return StreamGetBranches(CancellationToken.None, streamId, branchesLimit, commitsLimit); } @@ -73,8 +69,7 @@ public async Task> StreamGetBranches( }}", Variables = new { streamId } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.branches.items; } @@ -93,20 +88,15 @@ public Task BranchCreate(BranchCreateInput branchInput) /// /// /// The branch id. - public async Task BranchCreate( - CancellationToken cancellationToken, - BranchCreateInput branchInput - ) + public async Task BranchCreate(CancellationToken cancellationToken, BranchCreateInput branchInput) { var request = new GraphQLRequest { - Query = - @"mutation branchCreate($myBranch: BranchCreateInput!){ branchCreate(branch: $myBranch)}", + Query = @"mutation branchCreate($myBranch: BranchCreateInput!){ branchCreate(branch: $myBranch)}", Variables = new { myBranch = branchInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (string)res["branchCreate"]; } @@ -166,8 +156,7 @@ public async Task BranchGet( Variables = new { streamId, branchName } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.branch; } @@ -186,20 +175,15 @@ public Task BranchUpdate(BranchUpdateInput branchInput) /// /// /// The stream's id. - public async Task BranchUpdate( - CancellationToken cancellationToken, - BranchUpdateInput branchInput - ) + public async Task BranchUpdate(CancellationToken cancellationToken, BranchUpdateInput branchInput) { var request = new GraphQLRequest { - Query = - @"mutation branchUpdate($myBranch: BranchUpdateInput!){ branchUpdate(branch: $myBranch)}", + Query = @"mutation branchUpdate($myBranch: BranchUpdateInput!){ branchUpdate(branch: $myBranch)}", Variables = new { myBranch = branchInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["branchUpdate"]; } @@ -218,20 +202,15 @@ public Task BranchDelete(BranchDeleteInput branchInput) /// /// /// - public async Task BranchDelete( - CancellationToken cancellationToken, - BranchDeleteInput branchInput - ) + public async Task BranchDelete(CancellationToken cancellationToken, BranchDeleteInput branchInput) { var request = new GraphQLRequest { - Query = - @"mutation branchDelete($myBranch: BranchDeleteInput!){ branchDelete(branch: $myBranch)}", + Query = @"mutation branchDelete($myBranch: BranchDeleteInput!){ branchDelete(branch: $myBranch)}", Variables = new { myBranch = branchInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["branchDelete"]; } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommentOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommentOperations.cs index cfcea2bf61..a6a34cbf44 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommentOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommentOperations.cs @@ -83,8 +83,7 @@ public async Task StreamGetComments( } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.comments; } @@ -107,11 +106,7 @@ public Task StreamGetCommentScreenshot(string id, string streamId) /// Id of the stream to get the comment from /// /// - public async Task StreamGetCommentScreenshot( - CancellationToken cancellationToken, - string id, - string streamId - ) + public async Task StreamGetCommentScreenshot(CancellationToken cancellationToken, string id, string streamId) { var request = new GraphQLRequest { @@ -126,8 +121,7 @@ string streamId Variables = new { id, streamId } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.comment.screenshot; } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs index eeb932bf90..04d49356c9 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.CommitOperations.cs @@ -28,11 +28,7 @@ public Task CommitGet(string streamId, string commitId) /// Id of the stream to get the commit from /// Id of the commit to get /// - public async Task CommitGet( - CancellationToken cancellationToken, - string streamId, - string commitId - ) + public async Task CommitGet(CancellationToken cancellationToken, string streamId, string commitId) { var request = new GraphQLRequest { @@ -55,8 +51,7 @@ string commitId Variables = new { streamId, commitId } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.commit; } @@ -79,11 +74,7 @@ public Task> StreamGetCommits(string streamId, int limit = 10) /// Max number of commits to get /// /// - public async Task> StreamGetCommits( - CancellationToken cancellationToken, - string streamId, - int limit = 10 - ) + public async Task> StreamGetCommits(CancellationToken cancellationToken, string streamId, int limit = 10) { var request = new GraphQLRequest { @@ -110,8 +101,7 @@ public async Task> StreamGetCommits( Variables = new { streamId, limit } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.commits.items; } @@ -127,20 +117,15 @@ public Task CommitCreate(CommitCreateInput commitInput) /// /// - public async Task CommitCreate( - CancellationToken cancellationToken, - CommitCreateInput commitInput - ) + public async Task CommitCreate(CancellationToken cancellationToken, CommitCreateInput commitInput) { var request = new GraphQLRequest { - Query = - @"mutation commitCreate($myCommit: CommitCreateInput!){ commitCreate(commit: $myCommit)}", + Query = @"mutation commitCreate($myCommit: CommitCreateInput!){ commitCreate(commit: $myCommit)}", Variables = new { myCommit = commitInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (string)res["commitCreate"]; } @@ -159,20 +144,15 @@ public Task CommitUpdate(CommitUpdateInput commitInput) /// /// /// The stream's id. - public async Task CommitUpdate( - CancellationToken cancellationToken, - CommitUpdateInput commitInput - ) + public async Task CommitUpdate(CancellationToken cancellationToken, CommitUpdateInput commitInput) { var request = new GraphQLRequest { - Query = - @"mutation commitUpdate($myCommit: CommitUpdateInput!){ commitUpdate(commit: $myCommit)}", + Query = @"mutation commitUpdate($myCommit: CommitUpdateInput!){ commitUpdate(commit: $myCommit)}", Variables = new { myCommit = commitInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["commitUpdate"]; } @@ -191,20 +171,15 @@ public Task CommitDelete(CommitDeleteInput commitInput) /// /// /// - public async Task CommitDelete( - CancellationToken cancellationToken, - CommitDeleteInput commitInput - ) + public async Task CommitDelete(CancellationToken cancellationToken, CommitDeleteInput commitInput) { var request = new GraphQLRequest { - Query = - @"mutation commitDelete($myCommit: CommitDeleteInput!){ commitDelete(commit: $myCommit)}", + Query = @"mutation commitDelete($myCommit: CommitDeleteInput!){ commitDelete(commit: $myCommit)}", Variables = new { myCommit = commitInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["commitDelete"]; } @@ -221,10 +196,7 @@ public Task CommitReceived(CommitReceivedInput commitReceivedInput) /// /// - public async Task CommitReceived( - CancellationToken cancellationToken, - CommitReceivedInput commitReceivedInput - ) + public async Task CommitReceived(CancellationToken cancellationToken, CommitReceivedInput commitReceivedInput) { var request = new GraphQLRequest { @@ -232,8 +204,7 @@ CommitReceivedInput commitReceivedInput Variables = new { myInput = commitReceivedInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["commitReceive"]; } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs index 0c0b76bef4..406cf194a8 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ObjectOperations.cs @@ -26,11 +26,7 @@ public Task ObjectGet(string streamId, string objectId) /// Id of the stream to get the object from /// Id of the object to get /// - public async Task ObjectGet( - CancellationToken cancellationToken, - string streamId, - string objectId - ) + public async Task ObjectGet(CancellationToken cancellationToken, string streamId, string objectId) { var request = new GraphQLRequest { @@ -48,8 +44,7 @@ string objectId Variables = new { streamId, objectId } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.@object; } @@ -71,11 +66,7 @@ public Task ObjectCountGet(string streamId, string objectId) /// /// /// - public async Task ObjectCountGet( - CancellationToken cancellationToken, - string streamId, - string objectId - ) + public async Task ObjectCountGet(CancellationToken cancellationToken, string streamId, string objectId) { var request = new GraphQLRequest { @@ -90,8 +81,7 @@ string objectId Variables = new { streamId, objectId } }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.stream.@object; } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ServerOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ServerOperations.cs index 79196294a9..63b9291251 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ServerOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.ServerOperations.cs @@ -29,8 +29,7 @@ public partial class Client }" }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); if (res.serverInfo.version.Contains("dev")) return new System.Version(999, 999, 999); diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs index 4ff38b1534..c1ea953ee7 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.StreamOperations.cs @@ -28,11 +28,7 @@ public Task StreamGet(string id, int branchesLimit = 10) /// Id of the stream to get /// Max number of branches to retrieve /// - public async Task StreamGet( - CancellationToken cancellationToken, - string id, - int branchesLimit = 10 - ) + public async Task StreamGet(CancellationToken cancellationToken, string id, int branchesLimit = 10) { var request = new GraphQLRequest { @@ -71,9 +67,7 @@ public async Task StreamGet( }}", Variables = new { id } }; - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ).stream; + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)).stream; } /// @@ -133,8 +127,7 @@ public async Task> StreamsGet(CancellationToken cancellationToken, }}" }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); if (res?.activeUser == null) throw new SpeckleException( @@ -153,10 +146,7 @@ public Task> FavoriteStreamsGet(int limit = 10) /// /// Max number of streams to return /// - public async Task> FavoriteStreamsGet( - CancellationToken cancellationToken, - int limit = 10 - ) + public async Task> FavoriteStreamsGet(CancellationToken cancellationToken, int limit = 10) { var request = new GraphQLRequest { @@ -197,9 +187,7 @@ public async Task> FavoriteStreamsGet( }} }}" }; - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ) + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)) .activeUser .favoriteStreams .items; @@ -222,11 +210,7 @@ public Task> StreamSearch(string query, int limit = 10) /// String query to search for /// Max number of streams to return /// - public async Task> StreamSearch( - CancellationToken cancellationToken, - string query, - int limit = 10 - ) + public async Task> StreamSearch(CancellationToken cancellationToken, string query, int limit = 10) { var request = new GraphQLRequest { @@ -256,14 +240,8 @@ public async Task> StreamSearch( Variables = new { query, limit } }; - var res = await GQLClient - .SendMutationAsync(request, cancellationToken) - .ConfigureAwait(false); - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ) - .streams - .items; + var res = await GQLClient.SendMutationAsync(request, cancellationToken).ConfigureAwait(false); + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)).streams.items; } /// @@ -281,19 +259,14 @@ public Task StreamCreate(StreamCreateInput streamInput) /// /// /// The stream's id. - public async Task StreamCreate( - CancellationToken cancellationToken, - StreamCreateInput streamInput - ) + public async Task StreamCreate(CancellationToken cancellationToken, StreamCreateInput streamInput) { var request = new GraphQLRequest { - Query = - @"mutation streamCreate($myStream: StreamCreateInput!) { streamCreate(stream: $myStream) }", + Query = @"mutation streamCreate($myStream: StreamCreateInput!) { streamCreate(stream: $myStream) }", Variables = new { myStream = streamInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (string)res["streamCreate"]; } @@ -313,20 +286,15 @@ public Task StreamUpdate(StreamUpdateInput streamInput) /// /// Note: the id field needs to be a valid stream id. /// The stream's id. - public async Task StreamUpdate( - CancellationToken cancellationToken, - StreamUpdateInput streamInput - ) + public async Task StreamUpdate(CancellationToken cancellationToken, StreamUpdateInput streamInput) { var request = new GraphQLRequest { - Query = - @"mutation streamUpdate($myStream: StreamUpdateInput!) { streamUpdate(stream:$myStream) }", + Query = @"mutation streamUpdate($myStream: StreamUpdateInput!) { streamUpdate(stream:$myStream) }", Variables = new { myStream = streamInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamUpdate"]; } @@ -354,8 +322,7 @@ public async Task StreamDelete(CancellationToken cancellationToken, string Query = @"mutation streamDelete($id: String!) { streamDelete(id:$id) }", Variables = new { id } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamDelete"]; } @@ -392,8 +359,7 @@ mutation streamGrantPermission($permissionParams: StreamGrantPermissionInput!) { Variables = new { permissionParams = permissionInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamGrantPermission"]; } @@ -427,8 +393,7 @@ StreamRevokePermissionInput permissionInput Variables = new { permissionParams = permissionInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamRevokePermission"]; } @@ -454,8 +419,7 @@ mutation streamUpdatePermission($permissionParams: StreamUpdatePermissionInput!) Variables = new { permissionParams = updatePermissionInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamUpdatePermission"]; } @@ -477,10 +441,7 @@ public Task StreamGetPendingCollaborators(string id) /// Id of the stream to get /// Max number of branches to retrieve /// - public async Task StreamGetPendingCollaborators( - CancellationToken cancellationToken, - string id - ) + public async Task StreamGetPendingCollaborators(CancellationToken cancellationToken, string id) { var request = new GraphQLRequest { @@ -501,12 +462,8 @@ string id }", Variables = new { id } }; - var res = await GQLClient - .SendMutationAsync(request, cancellationToken) - .ConfigureAwait(false); - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ).stream; + var res = await GQLClient.SendMutationAsync(request, cancellationToken).ConfigureAwait(false); + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)).stream; } /// @@ -531,9 +488,7 @@ StreamInviteCreateInput inviteCreateInput ) { if ((inviteCreateInput.email == null) & (inviteCreateInput.userId == null)) - throw new ArgumentException( - "You must provide either an email or a user id to create a stream invite" - ); + throw new ArgumentException("You must provide either an email or a user id to create a stream invite"); var request = new GraphQLRequest { Query = @@ -544,8 +499,7 @@ mutation streamInviteCreate($input: StreamInviteCreateInput!) { Variables = new { input = inviteCreateInput } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamInviteCreate"]; } @@ -572,8 +526,7 @@ mutation streamInviteCancel( $streamId: String!, $inviteId: String! ) { Variables = new { streamId, inviteId } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamInviteCancel"]; } @@ -584,9 +537,7 @@ mutation streamInviteCancel( $streamId: String!, $inviteId: String! ) { /// true if invites are supported /// if Speckle Server version is less than v2.6.4 [Obsolete("We're not supporting 2.6.4 version any more", true)] - public async Task _CheckStreamInvitesSupported( - CancellationToken cancellationToken = default - ) + public async Task _CheckStreamInvitesSupported(CancellationToken cancellationToken = default) { var version = ServerVersion ?? await GetServerVersion(cancellationToken).ConfigureAwait(false); if (version < new System.Version("2.6.4")) @@ -625,14 +576,11 @@ mutation streamInviteUse( $accept: Boolean!, $streamId: String!, $token: String! } }; - var res = await ExecuteGraphQLRequest>(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest>(request, cancellationToken).ConfigureAwait(false); return (bool)res["streamInviteUse"]; } - public async Task> GetAllPendingInvites( - CancellationToken cancellationToken = default - ) + public async Task> GetAllPendingInvites(CancellationToken cancellationToken = default) { var request = new GraphQLRequest { @@ -657,8 +605,7 @@ query StreamInvites { }" }; - var res = await ExecuteGraphQLRequest(request, cancellationToken) - .ConfigureAwait(false); + var res = await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false); return res.streamInvites; } } diff --git a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.UserOperations.cs b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.UserOperations.cs index 0ac05bbc90..ead77232ed 100644 --- a/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.UserOperations.cs +++ b/Core/Core/Api/GraphQL/Client.GraphqlCleintOperations/Client.UserOperations.cs @@ -42,9 +42,7 @@ public async Task ActiveUserGet(CancellationToken cancellationToken) } }" }; - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ).activeUser; + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)).activeUser; } /// @@ -82,9 +80,7 @@ public async Task OtherUserGet(CancellationToken cancellationToken, }", Variables = new { id } }; - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ).otherUser; + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)).otherUser; } /// @@ -104,11 +100,7 @@ public Task> UserSearch(string query, int limit = 10) /// String to search for. Must be at least 3 characters /// Max number of users to return /// - public async Task> UserSearch( - CancellationToken cancellationToken, - string query, - int limit = 10 - ) + public async Task> UserSearch(CancellationToken cancellationToken, string query, int limit = 10) { var request = new GraphQLRequest { @@ -129,9 +121,7 @@ public async Task> UserSearch( }", Variables = new { query, limit } }; - return ( - await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false) - ) + return (await ExecuteGraphQLRequest(request, cancellationToken).ConfigureAwait(false)) .userSearch .items; } diff --git a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Branch.cs b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Branch.cs index 7990033c04..dcb95c1c0b 100644 --- a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Branch.cs +++ b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Branch.cs @@ -24,10 +24,7 @@ public partial class Client /// public void SubscribeBranchCreated(string streamId) { - var request = new GraphQLRequest - { - Query = $@"subscription {{ branchCreated (streamId: ""{streamId}"") }}" - }; + var request = new GraphQLRequest { Query = $@"subscription {{ branchCreated (streamId: ""{streamId}"") }}" }; BranchCreatedSubscription = SubscribeTo( request, @@ -55,8 +52,7 @@ public void SubscribeBranchUpdated(string streamId, string branchId = null) { var request = new GraphQLRequest { - Query = - $@"subscription {{ branchUpdated (streamId: ""{streamId}"", branchId: ""{branchId}"") }}" + Query = $@"subscription {{ branchUpdated (streamId: ""{streamId}"", branchId: ""{branchId}"") }}" }; BranchUpdatedSubscription = SubscribeTo( request, @@ -81,10 +77,7 @@ public void SubscribeBranchUpdated(string streamId, string branchId = null) /// public void SubscribeBranchDeleted(string streamId) { - var request = new GraphQLRequest - { - Query = $@"subscription {{ branchDeleted (streamId: ""{streamId}"") }}" - }; + var request = new GraphQLRequest { Query = $@"subscription {{ branchDeleted (streamId: ""{streamId}"") }}" }; BranchDeletedSubscription = SubscribeTo( request, diff --git a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Commit.cs b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Commit.cs index 2b044ea6d4..ff264699a8 100644 --- a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Commit.cs +++ b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Commit.cs @@ -19,10 +19,7 @@ public partial class Client /// public void SubscribeCommitCreated(string streamId) { - var request = new GraphQLRequest - { - Query = $@"subscription {{ commitCreated (streamId: ""{streamId}"") }}" - }; + var request = new GraphQLRequest { Query = $@"subscription {{ commitCreated (streamId: ""{streamId}"") }}" }; CommitCreatedSubscription = SubscribeTo( request, @@ -49,8 +46,7 @@ public void SubscribeCommitUpdated(string streamId, string commitId = null) { var request = new GraphQLRequest { - Query = - $@"subscription {{ commitUpdated (streamId: ""{streamId}"", commitId: ""{commitId}"") }}" + Query = $@"subscription {{ commitUpdated (streamId: ""{streamId}"", commitId: ""{commitId}"") }}" }; var res = GQLClient.CreateSubscriptionStream(request); @@ -77,10 +73,7 @@ public void SubscribeCommitUpdated(string streamId, string commitId = null) /// public void SubscribeCommitDeleted(string streamId) { - var request = new GraphQLRequest - { - Query = $@"subscription {{ commitDeleted (streamId: ""{streamId}"") }}" - }; + var request = new GraphQLRequest { Query = $@"subscription {{ commitDeleted (streamId: ""{streamId}"") }}" }; CommitDeletedSubscription = SubscribeTo( request, (sender, result) => OnCommitDeleted?.Invoke(sender, result.commitDeleted) 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 69117a9286..062f0e22bb 100644 --- a/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs +++ b/Core/Core/Api/GraphQL/Client.Subscriptions/Client.Subscriptions.Stream.cs @@ -44,10 +44,7 @@ public void SubscribeUserStreamAdded() /// streamId public void SubscribeStreamUpdated(string id) { - var request = new GraphQLRequest - { - Query = $@"subscription {{ streamUpdated( streamId: ""{id}"") }}" - }; + var request = new GraphQLRequest { Query = $@"subscription {{ streamUpdated( streamId: ""{id}"") }}" }; StreamUpdatedSubscription = SubscribeTo( request, (sender, result) => OnStreamUpdated?.Invoke(sender, result.streamUpdated) diff --git a/Core/Core/Api/GraphQL/Client.cs b/Core/Core/Api/GraphQL/Client.cs index 3618be71d0..07840bd638 100644 --- a/Core/Core/Api/GraphQL/Client.cs +++ b/Core/Core/Api/GraphQL/Client.cs @@ -152,17 +152,11 @@ internal async Task ExecuteWithResiliencePolicies(Func> func) return await graphqlRetry.ExecuteAsync(func).ConfigureAwait(false); } - internal async Task ExecuteGraphQLRequest( - GraphQLRequest request, - CancellationToken? cancellationToken - ) + internal async Task ExecuteGraphQLRequest(GraphQLRequest request, CancellationToken? cancellationToken) { using (LogContext.Push(_createEnrichers(request))) { - SpeckleLog.Logger.Debug( - "Starting execution of graphql request to get {resultType}", - typeof(T).Name - ); + SpeckleLog.Logger.Debug("Starting execution of graphql request to get {resultType}", typeof(T).Name); var timer = new Stopwatch(); var success = false; timer.Start(); @@ -264,9 +258,7 @@ internal void MaybeThrowFromGraphQLErrors(GraphQLRequest request, GraphQLResp errors.Any( e => e.Extensions != null - && e.Extensions.Contains( - new KeyValuePair("code", "INTERNAL_SERVER_ERROR") - ) + && e.Extensions.Contains(new KeyValuePair("code", "INTERNAL_SERVER_ERROR")) ) ) throw new SpeckleGraphQLInternalErrorException(request, response); @@ -294,11 +286,8 @@ private ILogEventEnricher[] _createEnrichers(GraphQLRequest request) { // i know this is double (de)serializing, but we need a recursive convert to // dict here - var expando = JsonConvert.DeserializeObject( - JsonConvert.SerializeObject(request.Variables) - ); - var variables = - request.Variables != null && expando != null ? _convertExpandoToDict(expando) : null; + var expando = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(request.Variables)); + var variables = request.Variables != null && expando != null ? _convertExpandoToDict(expando) : null; return new ILogEventEnricher[] { new PropertyEnricher("serverUrl", ServerUrl), @@ -326,10 +315,7 @@ internal IDisposable SubscribeTo(GraphQLRequest request, Action ca else SpeckleLog.Logger .ForContext("graphqlResponse", response) - .Error( - "Cannot execute graphql callback for {resultType}, the response has no data.", - typeof(T).Name - ); + .Error("Cannot execute graphql callback for {resultType}, the response has no data.", typeof(T).Name); } // we catch forbidden to rethrow, making sure its not logged. catch (SpeckleGraphQLForbiddenException) diff --git a/Core/Core/Api/GraphQL/Models.cs b/Core/Core/Api/GraphQL/Models.cs index 99d542978b..a3e4b4721e 100644 --- a/Core/Core/Api/GraphQL/Models.cs +++ b/Core/Core/Api/GraphQL/Models.cs @@ -467,12 +467,7 @@ public class Connector public class Version { - public Version( - string number, - string url, - Os os = Os.Win, - Architecture architecture = Architecture.Any - ) + public Version(string number, string url, Os os = Os.Win, Architecture architecture = Architecture.Any) { Number = number; Url = url; diff --git a/Core/Core/Api/GraphQL/Serializer/ConstantCaseEnumConverter.cs b/Core/Core/Api/GraphQL/Serializer/ConstantCaseEnumConverter.cs index 76cac71149..01ab102dee 100644 --- a/Core/Core/Api/GraphQL/Serializer/ConstantCaseEnumConverter.cs +++ b/Core/Core/Api/GraphQL/Serializer/ConstantCaseEnumConverter.cs @@ -20,10 +20,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var enumString = ((Enum)value).ToString("G"); var memberName = value .GetType() - .GetMember( - enumString, - BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public - ) + .GetMember(enumString, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public) .FirstOrDefault() ?.Name; if (string.IsNullOrEmpty(memberName)) diff --git a/Core/Core/Api/GraphQL/Serializer/MapConverter.cs b/Core/Core/Api/GraphQL/Serializer/MapConverter.cs index d5bf976b13..ae97a2672d 100644 --- a/Core/Core/Api/GraphQL/Serializer/MapConverter.cs +++ b/Core/Core/Api/GraphQL/Serializer/MapConverter.cs @@ -27,9 +27,7 @@ JsonSerializer serializer var rootToken = JToken.ReadFrom(reader); if (rootToken is JObject) return (Map)ReadDictionary(rootToken, new Map()); - 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) @@ -40,20 +38,9 @@ JsonSerializer serializer JArray jArray => ReadArray(jArray).ToList(), JValue jValue => jValue.Value, JConstructor _ - => throw new ArgumentOutOfRangeException( - nameof(token.Type), - "cannot deserialize a JSON constructor" - ), - JProperty _ - => throw new ArgumentOutOfRangeException( - nameof(token.Type), - "cannot deserialize a JSON property" - ), - JContainer _ - => throw new ArgumentOutOfRangeException( - nameof(token.Type), - "cannot deserialize a JSON comment" - ), + => throw new ArgumentOutOfRangeException(nameof(token.Type), "cannot deserialize a JSON constructor"), + JProperty _ => throw new ArgumentOutOfRangeException(nameof(token.Type), "cannot deserialize a JSON property"), + JContainer _ => throw new ArgumentOutOfRangeException(nameof(token.Type), "cannot deserialize a JSON comment"), _ => throw new ArgumentOutOfRangeException(nameof(token.Type)) }; } @@ -81,8 +68,6 @@ private Dictionary ReadDictionary(JToken element, Dictionary new() { - ContractResolver = new CamelCasePropertyNamesContractResolver - { - IgnoreIsSpecifiedMembers = true - }, + ContractResolver = new CamelCasePropertyNamesContractResolver { IgnoreIsSpecifiedMembers = true }, MissingMemberHandling = MissingMemberHandling.Ignore, Converters = { new ConstantCaseEnumConverter() } }; @@ -49,16 +46,12 @@ public byte[] SerializeToBytes(GraphQLWebSocketRequest request) return Encoding.UTF8.GetBytes(json); } - public Task DeserializeToWebsocketResponseWrapperAsync( - System.IO.Stream stream - ) + public Task DeserializeToWebsocketResponseWrapperAsync(System.IO.Stream stream) { return DeserializeFromUtf8Stream(stream); } - public GraphQLWebSocketResponse< - GraphQLResponse - > DeserializeToWebsocketResponse(byte[] bytes) + public GraphQLWebSocketResponse> DeserializeToWebsocketResponse(byte[] bytes) { return JsonConvert.DeserializeObject>>( Encoding.UTF8.GetString(bytes), diff --git a/Core/Core/Api/Helpers.cs b/Core/Core/Api/Helpers.cs index 2878d6a7b2..3f4d268325 100644 --- a/Core/Core/Api/Helpers.cs +++ b/Core/Core/Api/Helpers.cs @@ -32,8 +32,7 @@ public static class Helpers /// /// The location of the Speckle installation folder [Obsolete("Please use Helpers/SpecklePathProvider.InstallSpeckleFolderPath", true)] - public static string InstallSpeckleFolderPath => - Path.Combine(InstallApplicationDataPath, "Speckle"); + public static string InstallSpeckleFolderPath => Path.Combine(InstallApplicationDataPath, "Speckle"); /// /// Returns the correct location of the Speckle folder for the current user. Usually this would be the user's %appdata%/Speckle folder. @@ -64,10 +63,7 @@ public static class Helpers public static string UserApplicationDataPath => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(_speckleUserDataEnvVar)) ? Environment.GetEnvironmentVariable(_speckleUserDataEnvVar) - : Environment.GetFolderPath( - Environment.SpecialFolder.ApplicationData, - Environment.SpecialFolderOption.Create - ); + : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create); /// /// Helper method to Receive from a Speckle Server. @@ -209,14 +205,7 @@ public static async Task Send( var branchName = string.IsNullOrEmpty(sw.BranchName) ? "main" : sw.BranchName; var objectId = await Operations - .Send( - data, - new List { transport }, - useDefaultCache, - onProgressAction, - onErrorAction, - true - ) + .Send(data, new List { transport }, useDefaultCache, onProgressAction, onErrorAction, true) .ConfigureAwait(false); Analytics.TrackEvent(client.Account, Analytics.Events.Send); @@ -253,19 +242,14 @@ public static async Task IsConnectorUpdateAvailable(string slug) try { HttpClient client = Http.GetHttpProxyClient(); - var response = await client - .GetStringAsync($"{_feedsEndpoint}/{slug}.json") - .ConfigureAwait(false); + var response = await client.GetStringAsync($"{_feedsEndpoint}/{slug}.json").ConfigureAwait(false); var connector = JsonSerializer.Deserialize(response); var os = Os.Win; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) os = Os.OSX; - var versions = connector.Versions - .Where(x => x.Os == os) - .OrderByDescending(x => x.Date) - .ToList(); + var versions = connector.Versions.Where(x => x.Os == os).OrderByDescending(x => x.Date).ToList(); var stables = versions.Where(x => !x.Prerelease); if (!stables.Any()) return false; diff --git a/Core/Core/Api/Operations/Operations.Receive.cs b/Core/Core/Api/Operations/Operations.Receive.cs index f7218be93c..b87d6946ff 100644 --- a/Core/Core/Api/Operations/Operations.Receive.cs +++ b/Core/Core/Api/Operations/Operations.Receive.cs @@ -142,21 +142,11 @@ public static partial class Operations if (partial.__closure != null) onTotalChildrenCountKnown?.Invoke(partial.__closure.Count); - Base? localRes = DeserializeStringToBase( - serializerVersion, - objString, - settings, - serializerV2 - ); + Base? localRes = DeserializeStringToBase(serializerVersion, objString, settings, serializerV2); - if ( - (disposeTransports || !hasUserProvidedLocalTransport) - && localTransport is IDisposable dispLocal - ) + if ((disposeTransports || !hasUserProvidedLocalTransport) && localTransport is IDisposable dispLocal) dispLocal.Dispose(); - if ( - disposeTransports && remoteTransport != null && remoteTransport is IDisposable dispRemote - ) + if (disposeTransports && remoteTransport != null && remoteTransport is IDisposable dispRemote) dispRemote.Dispose(); timer.Stop(); @@ -183,11 +173,7 @@ public static partial class Operations $"Could not find specified object using the local transport {localTransport.TransportName}, and you didn't provide a fallback remote from which to pull it." ); - SpeckleLog.Logger.Error( - ex, - "Cannot receive object from the given transports {exceptionMessage}", - ex.Message - ); + SpeckleLog.Logger.Error(ex, "Cannot receive object from the given transports {exceptionMessage}", ex.Message); throw ex; } @@ -261,11 +247,7 @@ public static partial class Operations } catch (Exception ex) { - SpeckleLog.Logger.Error( - ex, - "A deserialization error has occurred {exceptionMessage}", - ex.Message - ); + SpeckleLog.Logger.Error(ex, "A deserialization error has occurred {exceptionMessage}", ex.Message); if (serializerV2.OnErrorAction == null) throw; serializerV2.OnErrorAction.Invoke( diff --git a/Core/Core/Api/Operations/Operations.Send.cs b/Core/Core/Api/Operations/Operations.Send.cs index 99f23b8fed..36aff1f75f 100644 --- a/Core/Core/Api/Operations/Operations.Send.cs +++ b/Core/Core/Api/Operations/Operations.Send.cs @@ -167,10 +167,7 @@ public static async Task Send( if (cancellationToken.IsCancellationRequested) { - SpeckleLog.Logger.Information( - "Send operation cancelled after {elapsed}", - sendTimer.Elapsed.TotalSeconds - ); + SpeckleLog.Logger.Information("Send operation cancelled after {elapsed}", sendTimer.Elapsed.TotalSeconds); cancellationToken.ThrowIfCancellationRequested(); } @@ -181,14 +178,8 @@ public static async Task Send( sendTimer.Stop(); SpeckleLog.Logger - .ForContext( - "transportElapsedBreakdown", - transports.ToDictionary(t => t.TransportName, t => t.Elapsed) - ) - .ForContext( - "note", - "the elapsed summary doesn't need to add up to the total elapsed... Threading magic..." - ) + .ForContext("transportElapsedBreakdown", transports.ToDictionary(t => t.TransportName, t => t.Elapsed)) + .ForContext("note", "the elapsed summary doesn't need to add up to the total elapsed... Threading magic...") .ForContext("serializerElapsed", serializerV2?.Elapsed) .Information( "Finished sending {objectCount} objects after {elapsed}, result {objectId}", diff --git a/Core/Core/Api/Operations/Operations.Serialize.cs b/Core/Core/Api/Operations/Operations.Serialize.cs index 39428365df..f906bbab32 100644 --- a/Core/Core/Api/Operations/Operations.Serialize.cs +++ b/Core/Core/Api/Operations/Operations.Serialize.cs @@ -52,9 +52,7 @@ public static string Serialize( /// /// /// - [Obsolete( - "Please use the Serialize(Base @object) function. This function will be removed in later versions." - )] + [Obsolete("Please use the Serialize(Base @object) function. This function will be removed in later versions.")] public static string Serialize(List objects) { var (_, settings) = GetSerializerInstance(); @@ -66,9 +64,7 @@ public static string Serialize(List objects) /// /// /// - [Obsolete( - "Please use the Serialize(Base @object) function. This function will be removed in later versions." - )] + [Obsolete("Please use the Serialize(Base @object) function. This function will be removed in later versions.")] public static string Serialize(Dictionary objects) { var (_, settings) = GetSerializerInstance(); @@ -114,9 +110,7 @@ public static Base Deserialize( /// /// /// - [Obsolete( - "Please use the Deserialize(Base @object) function. This function will be removed in later versions." - )] + [Obsolete("Please use the Deserialize(Base @object) function. This function will be removed in later versions.")] public static List DeserializeArray( string objectArr, SerializerVersion serializerVersion = SerializerVersion.V2 @@ -141,9 +135,7 @@ public static List DeserializeArray( /// /// /// - [Obsolete( - "Please use the Deserialize(Base @object) function. This function will be removed in later versions." - )] + [Obsolete("Please use the Deserialize(Base @object) function. This function will be removed in later versions.")] public static Dictionary DeserializeDictionary(string dictionary) { var (_, settings) = GetSerializerInstance(); diff --git a/Core/Core/Credentials/Account.cs b/Core/Core/Credentials/Account.cs index 1720e542d9..0978a1f975 100644 --- a/Core/Core/Credentials/Account.cs +++ b/Core/Core/Credentials/Account.cs @@ -24,9 +24,7 @@ public string id { if (serverInfo == null || userInfo == null) throw new SpeckleException("Incomplete account info: cannot generate id."); - _id = Utilities - .hashString(userInfo.email + serverInfo.url, Utilities.HashingFuctions.MD5) - .ToUpper(); + _id = Utilities.hashString(userInfo.email + serverInfo.url, Utilities.HashingFuctions.MD5).ToUpper(); } return _id; } @@ -100,9 +98,7 @@ public override string ToString() public bool Equals(Account other) { - return other is not null - && other.userInfo.email == userInfo.email - && other.serverInfo.url == serverInfo.url; + return other is not null && other.userInfo.email == userInfo.email && other.serverInfo.url == serverInfo.url; } public override bool Equals(object obj) diff --git a/Core/Core/Credentials/AccountManager.cs b/Core/Core/Credentials/AccountManager.cs index 7b1894ae99..ec98b2753b 100644 --- a/Core/Core/Credentials/AccountManager.cs +++ b/Core/Core/Credentials/AccountManager.cs @@ -48,9 +48,7 @@ public static async Task GetServerInfo(string server) var request = new GraphQLRequest { Query = @" query { serverInfo { name company } }" }; - var response = await gqlClient - .SendQueryAsync(request) - .ConfigureAwait(false); + var response = await gqlClient.SendQueryAsync(request).ConfigureAwait(false); if (response.Errors != null) return null; @@ -175,9 +173,7 @@ public static Account GetDefaultAccount() { var firstAccount = GetAccounts().FirstOrDefault(); if (firstAccount == null) - SpeckleLog.Logger.Information( - "No Speckle accounts found. Visit the Speckle web app to create one." - ); + SpeckleLog.Logger.Information("No Speckle accounts found. Visit the Speckle web app to create one."); return firstAccount; } return defaultAccount; @@ -189,9 +185,7 @@ public static Account GetDefaultAccount() /// public static IEnumerable GetAccounts() { - var sqlAccounts = AccountStorage - .GetAllObjects() - .Select(x => JsonConvert.DeserializeObject(x)); + var sqlAccounts = AccountStorage.GetAllObjects().Select(x => JsonConvert.DeserializeObject(x)); var localAccounts = GetLocalAccounts(); //prevent invalid account from slipping out @@ -256,19 +250,12 @@ public static async Task UpdateAccounts() //the token has expired //TODO: once we get a token expired exception from the server use that instead - if ( - userServerInfo == null || userServerInfo.user == null || userServerInfo.serverInfo == null - ) + if (userServerInfo == null || userServerInfo.user == null || userServerInfo.serverInfo == null) { - var tokenResponse = await GetRefreshedToken(account.refreshToken, url) - .ConfigureAwait(false); + var tokenResponse = await GetRefreshedToken(account.refreshToken, url).ConfigureAwait(false); userServerInfo = await GetUserServerInfo(tokenResponse.token, url).ConfigureAwait(false); - if ( - userServerInfo == null - || userServerInfo.user == null - || userServerInfo.serverInfo == null - ) + if (userServerInfo == null || userServerInfo.user == null || userServerInfo.serverInfo == null) throw new SpeckleException("Could not refresh token"); account.token = tokenResponse.token; @@ -344,25 +331,15 @@ private static void _ensureGetAccessCodeFlowIsSupported() } } - private static async Task _getAccessCode( - string server, - string challenge, - TimeSpan timeout - ) + private static async Task _getAccessCode(string server, string challenge, TimeSpan timeout) { _ensureGetAccessCodeFlowIsSupported(); - SpeckleLog.Logger.Debug( - "Starting auth process for {server}/authn/verify/sca/{challenge}", - server, - challenge - ); + SpeckleLog.Logger.Debug("Starting auth process for {server}/authn/verify/sca/{challenge}", server, challenge); var accessCode = ""; - Process.Start( - new ProcessStartInfo($"{server}/authn/verify/sca/{challenge}") { UseShellExecute = true } - ); + Process.Start(new ProcessStartInfo($"{server}/authn/verify/sca/{challenge}") { UseShellExecute = true }); var listener = new HttpListener(); @@ -381,8 +358,7 @@ TimeSpan timeout SpeckleLog.Logger.Debug("Got access code {accessCode}", accessCode); var message = ""; if (accessCode != null) - message = - "Success!

You can close this window now."; + message = "Success!

You can close this window now."; else message = "Oups, something went wrong...!"; @@ -432,11 +408,7 @@ TimeSpan timeout return accessCode; } - private static async Task _createAccount( - string accessCode, - string challenge, - string server - ) + private static async Task _createAccount(string accessCode, string challenge, string server) { try { @@ -458,10 +430,7 @@ string server } catch (Exception ex) { - throw new SpeckleAccountManagerException( - "Failed to create account from access code and challenge", - ex - ); + throw new SpeckleAccountManagerException("Failed to create account from access code and challenge", ex); } } @@ -540,11 +509,7 @@ public static async Task AddAccount(string server = "") //if the account already exists it will not be added again AccountStorage.SaveObject(account.id, JsonConvert.SerializeObject(account)); - SpeckleLog.Logger.Debug( - "Finished adding account {accountId} for {serverUrl}", - account.id, - server - ); + SpeckleLog.Logger.Debug("Finished adding account {accountId} for {serverUrl}", account.id, server); } catch (SpeckleAccountManagerException ex) { @@ -563,11 +528,7 @@ public static async Task AddAccount(string server = "") } } - private static async Task GetToken( - string accessCode, - string challenge, - string server - ) + private static async Task GetToken(string accessCode, string challenge, string server) { try { @@ -597,10 +558,7 @@ await response.Content.ReadAsStringAsync().ConfigureAwait(false) } } - private static async Task GetRefreshedToken( - string refreshToken, - string server - ) + private static async Task GetRefreshedToken(string refreshToken, string server) { try { diff --git a/Core/Core/Credentials/StreamWrapper.cs b/Core/Core/Credentials/StreamWrapper.cs index 83702ff0ca..10daed8ce5 100644 --- a/Core/Core/Credentials/StreamWrapper.cs +++ b/Core/Core/Credentials/StreamWrapper.cs @@ -74,9 +74,7 @@ public StreamWrapperType Type return StreamWrapperType.Branch; // If we reach here and there is no stream id, it means that the stream is invalid for some reason. - return !string.IsNullOrEmpty(StreamId) - ? StreamWrapperType.Stream - : StreamWrapperType.Undefined; + return !string.IsNullOrEmpty(StreamId) ? StreamWrapperType.Stream : StreamWrapperType.Undefined; } } @@ -85,9 +83,7 @@ private void StreamWrapperFromId(string streamId) Account account = AccountManager.GetDefaultAccount(); if (account == null) - throw new SpeckleException( - "You do not have any account. Please create one or add it to the Speckle Manager." - ); + throw new SpeckleException("You do not have any account. Please create one or add it to the Speckle Manager."); ServerUrl = account.serverInfo.url; UserId = account.userInfo.id; diff --git a/Core/Core/Helpers/Http.cs b/Core/Core/Helpers/Http.cs index 52ec8c82fd..7f05abc4c2 100644 --- a/Core/Core/Helpers/Http.cs +++ b/Core/Core/Helpers/Http.cs @@ -62,9 +62,7 @@ public static IEnumerable DefaultDelay() return Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromMilliseconds(100), 5); } - public static AsyncRetryPolicy HttpAsyncPolicy( - IEnumerable? delay = null - ) + public static AsyncRetryPolicy HttpAsyncPolicy(IEnumerable? delay = null) { return HttpPolicyExtensions .HandleTransientHttpError() @@ -102,9 +100,7 @@ public static async Task UserHasInternet() bool hasInternet = await HttpPing(defaultServer).ConfigureAwait(false); if (!hasInternet) - SpeckleLog.Logger - .ForContext("defaultServer", defaultServer) - .Warning("Failed to ping internet"); + SpeckleLog.Logger.ForContext("defaultServer", defaultServer).Warning("Failed to ping internet"); return hasInternet; } @@ -143,9 +139,7 @@ public static async Task Ping(string hostnameOrAddress) byte[] buffer = new byte[32]; int timeout = 1000; PingOptions pingOptions = new(); - PingReply reply = await myPing - .SendPingAsync(hostname, timeout, buffer, pingOptions) - .ConfigureAwait(false); + PingReply reply = await myPing.SendPingAsync(hostname, timeout, buffer, pingOptions).ConfigureAwait(false); if (reply.Status != IPStatus.Success) throw new Exception($"The ping operation failed with status {reply.Status}"); return true; @@ -212,10 +206,7 @@ CancellationToken cancellationToken using (LogContext.PushProperty("targetUrl", request.RequestUri)) using (LogContext.PushProperty("httpMethod", request.Method)) { - SpeckleLog.Logger.Debug( - "Starting execution of http request to {targetUrl}", - request.RequestUri - ); + SpeckleLog.Logger.Debug("Starting execution of http request to {targetUrl}", request.RequestUri); var timer = new Stopwatch(); timer.Start(); context.Add("retryCount", 0); diff --git a/Core/Core/Helpers/Path.cs b/Core/Core/Helpers/Path.cs index 84e4707563..b87f39afef 100644 --- a/Core/Core/Helpers/Path.cs +++ b/Core/Core/Helpers/Path.cs @@ -37,20 +37,17 @@ public static class SpecklePathProvider /// /// Get the path where the Speckle applications should be installed /// - public static string InstallSpeckleFolderPath => - EnsureFolderExists(InstallApplicationDataPath, _applicationName); + public static string InstallSpeckleFolderPath => EnsureFolderExists(InstallApplicationDataPath, _applicationName); /// /// Get the folder where the user's Speckle data should be stored. /// - public static string UserSpeckleFolderPath => - EnsureFolderExists(UserApplicationDataPath(), _applicationName); + public static string UserSpeckleFolderPath => EnsureFolderExists(UserApplicationDataPath(), _applicationName); /// /// Get the folder where the Speckle kits should be stored. /// - public static string KitsFolderPath => - EnsureFolderExists(InstallSpeckleFolderPath, _kitsFolderName); + public static string KitsFolderPath => EnsureFolderExists(InstallSpeckleFolderPath, _kitsFolderName); /// /// @@ -60,8 +57,7 @@ public static class SpecklePathProvider /// /// Get the folder where the Speckle accounts data should be stored. /// - public static string AccountsFolderPath => - EnsureFolderExists(UserSpeckleFolderPath, _accountsFolderName); + public static string AccountsFolderPath => EnsureFolderExists(UserSpeckleFolderPath, _accountsFolderName); /// /// Override the global Speckle application name. diff --git a/Core/Core/Kits/KitDeclaration.cs b/Core/Core/Kits/KitDeclaration.cs index 92b93edae0..18a99a438d 100644 --- a/Core/Core/Kits/KitDeclaration.cs +++ b/Core/Core/Kits/KitDeclaration.cs @@ -10,8 +10,7 @@ namespace Speckle.Core.Kits; /// public class CoreKit : ISpeckleKit { - public IEnumerable Types => - GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); + public IEnumerable Types => GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); public string Description => "Base Speckle models for revisions, streams, etc."; diff --git a/Core/Core/Kits/KitManager.cs b/Core/Core/Kits/KitManager.cs index ece5745387..d2e281964f 100644 --- a/Core/Core/Kits/KitManager.cs +++ b/Core/Core/Kits/KitManager.cs @@ -14,9 +14,7 @@ public static class KitManager { private static string? _kitsFolder; - public static readonly AssemblyName SpeckleAssemblyName = typeof(Base) - .GetTypeInfo() - .Assembly.GetName(); + public static readonly AssemblyName SpeckleAssemblyName = typeof(Base).GetTypeInfo().Assembly.GetName(); private static Dictionary _SpeckleKits = new(); @@ -134,10 +132,7 @@ private static void Initialize() private static void Load() { - SpeckleLog.Logger.Information( - "Initializing Kit Manager in {KitsFolder}", - SpecklePathProvider.KitsFolderPath - ); + SpeckleLog.Logger.Information("Initializing Kit Manager in {KitsFolder}", SpecklePathProvider.KitsFolderPath); GetLoadedSpeckleReferencingAssemblies(); LoadSpeckleReferencingAssemblies(); diff --git a/Core/Core/Kits/Units.cs b/Core/Core/Kits/Units.cs index 41f27268af..28465f08ac 100644 --- a/Core/Core/Kits/Units.cs +++ b/Core/Core/Kits/Units.cs @@ -19,19 +19,7 @@ public static class Units public const string USFeet = "us_ft"; // it happened, absolutely gross private static List SupportedUnits = - new() - { - Millimeters, - Centimeters, - Meters, - Kilometers, - Inches, - Feet, - USFeet, - Yards, - Miles, - None - }; + new() { Millimeters, Centimeters, Meters, Kilometers, Inches, Feet, USFeet, Yards, Miles, None }; public static bool IsUnitSupported(string unit) { diff --git a/Core/Core/Logging/Analytics.cs b/Core/Core/Logging/Analytics.cs index e81e8e66f9..7eeba054bf 100644 --- a/Core/Core/Logging/Analytics.cs +++ b/Core/Core/Logging/Analytics.cs @@ -113,8 +113,7 @@ public static void TrackEvent( .GetAllNetworkInterfaces() .Where( nic => - nic.OperationalStatus == OperationalStatus.Up - && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback + nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback ) .Select(nic => nic.GetPhysicalAddress().ToString()) .FirstOrDefault(); @@ -150,13 +149,7 @@ public static void TrackEvent( if (account == null) TrackEvent(eventName, customProperties, isAction); else - TrackEvent( - account.GetHashedEmail(), - account.GetHashedServer(), - eventName, - customProperties, - isAction - ); + TrackEvent(account.GetHashedEmail(), account.GetHashedServer(), eventName, customProperties, isAction); } /// @@ -202,17 +195,11 @@ private static void TrackEvent( properties.Add("type", "action"); if (customProperties != null) - properties = properties - .Concat(customProperties) - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + properties = properties.Concat(customProperties).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - string json = JsonConvert.SerializeObject( - new { @event = eventName.ToString(), properties } - ); + string json = JsonConvert.SerializeObject(new { @event = eventName.ToString(), properties }); - var query = new StreamContent( - new MemoryStream(Encoding.UTF8.GetBytes("data=" + HttpUtility.UrlEncode(json))) - ); + var query = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("data=" + HttpUtility.UrlEncode(json)))); HttpClient client = Http.GetHttpProxyClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); query.Headers.ContentType = new MediaTypeHeaderValue("application/json"); @@ -255,9 +242,7 @@ internal static void AddConnectorToProfile(string hashedEmail, string connector) }; string json = JsonConvert.SerializeObject(data); - var query = new StreamContent( - new MemoryStream(Encoding.UTF8.GetBytes("data=" + HttpUtility.UrlEncode(json))) - ); + var query = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("data=" + HttpUtility.UrlEncode(json)))); HttpClient client = Http.GetHttpProxyClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); query.Headers.ContentType = new MediaTypeHeaderValue("application/json"); diff --git a/Core/Core/Logging/Setup.cs b/Core/Core/Logging/Setup.cs index 11fd3e3309..370aec7fae 100644 --- a/Core/Core/Logging/Setup.cs +++ b/Core/Core/Logging/Setup.cs @@ -36,8 +36,7 @@ static Setup() /// /// Set from the connectors, defines which current host application we're running on - includes the version. /// - internal static string VersionedHostApplication { get; private set; } = - HostApplications.Other.Slug; + internal static string VersionedHostApplication { get; private set; } = HostApplications.Other.Slug; public static void Init(string versionedHostApplication, string hostApplication) { @@ -55,10 +54,7 @@ public static void Init(string versionedHostApplication, string hostApplication) #if !NETSTANDARD1_5_OR_GREATER //needed by older .net frameworks, eg Revit 2019 ServicePointManager.SecurityProtocol = - SecurityProtocolType.Ssl3 - | SecurityProtocolType.Tls - | SecurityProtocolType.Tls11 - | SecurityProtocolType.Tls12; + SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; #endif SpeckleLog.Initialize(hostApplication, versionedHostApplication); diff --git a/Core/Core/Logging/SpeckleException.cs b/Core/Core/Logging/SpeckleException.cs index f9f8dbae14..50a246ce34 100644 --- a/Core/Core/Logging/SpeckleException.cs +++ b/Core/Core/Logging/SpeckleException.cs @@ -18,25 +18,13 @@ public SpeckleException(string message, Exception? inner = null) public SpeckleException(string message, bool log, SentryLevel level = SentryLevel.Info) : base(message) { } - public SpeckleException( - string message, - GraphQLError[] errors, - bool log = true, - SentryLevel level = SentryLevel.Info - ) + public SpeckleException(string message, GraphQLError[] errors, bool log = true, SentryLevel level = SentryLevel.Info) : base(message) { - GraphQLErrors = errors - .Select(error => new KeyValuePair("error", error.Message)) - .ToList(); + GraphQLErrors = errors.Select(error => new KeyValuePair("error", error.Message)).ToList(); } - public SpeckleException( - string message, - Exception? inner, - bool log = true, - SentryLevel level = SentryLevel.Info - ) + public SpeckleException(string message, Exception? inner, bool log = true, SentryLevel level = SentryLevel.Info) : base(message, inner) { } public SpeckleException(string message) diff --git a/Core/Core/Logging/SpeckleLog.cs b/Core/Core/Logging/SpeckleLog.cs index 97d93ee206..989ecb8796 100644 --- a/Core/Core/Logging/SpeckleLog.cs +++ b/Core/Core/Logging/SpeckleLog.cs @@ -57,8 +57,7 @@ public class SpeckleLogConfiguration /// /// Flag to override the default Sentry DNS /// - public string sentryDns = - "https://f29ec716d14d4121bb2a71c4f3ef7786@o436188.ingest.sentry.io/5396846"; + public string sentryDns = "https://f29ec716d14d4121bb2a71c4f3ef7786@o436188.ingest.sentry.io/5396846"; /// /// Default SpeckleLogConfiguration constructor. @@ -266,15 +265,9 @@ private static void _addHostOsInfoToGlobalContext() GlobalLogContext.PushProperty("hostOsArchitecture", osArchitecture); } - private static void _addHostApplicationDataToGlobalContext( - string hostApplicationName, - string? hostApplicationVersion - ) + private static void _addHostApplicationDataToGlobalContext(string hostApplicationName, string? hostApplicationVersion) { - GlobalLogContext.PushProperty( - "hostApplication", - $"{hostApplicationName}{hostApplicationVersion ?? ""}" - ); + GlobalLogContext.PushProperty("hostApplication", $"{hostApplicationName}{hostApplicationVersion ?? ""}"); SentrySdk.ConfigureScope(scope => { diff --git a/Core/Core/Models/Base.cs b/Core/Core/Models/Base.cs index 6a42faf3c8..8b324788f8 100644 --- a/Core/Core/Models/Base.cs +++ b/Core/Core/Models/Base.cs @@ -89,10 +89,7 @@ public virtual string speckle_type /// /// If true, will decompose the object in the process of hashing. /// - public string GetId( - bool decompose = false, - SerializerVersion serializerVersion = SerializerVersion.V2 - ) + public string GetId(bool decompose = false, SerializerVersion serializerVersion = SerializerVersion.V2) { if (serializerVersion == SerializerVersion.V1) { @@ -134,8 +131,7 @@ private static long CountDescendants(Base @base, HashSet parsed) foreach (var prop in typedProps.Where(p => p.CanRead)) { bool isIgnored = - prop.IsDefined(typeof(ObsoleteAttribute), true) - || prop.IsDefined(typeof(JsonIgnoreAttribute), true); + prop.IsDefined(typeof(ObsoleteAttribute), true) || prop.IsDefined(typeof(JsonIgnoreAttribute), true); if (isIgnored) continue; @@ -241,9 +237,7 @@ public Base ShallowCopy() foreach ( var kvp in GetMembers( - DynamicBaseMemberType.Instance - | DynamicBaseMemberType.Dynamic - | DynamicBaseMemberType.SchemaIgnored + DynamicBaseMemberType.Instance | DynamicBaseMemberType.Dynamic | DynamicBaseMemberType.SchemaIgnored ) ) { diff --git a/Core/Core/Models/DynamicBase.cs b/Core/Core/Models/DynamicBase.cs index 8755eb68ac..63955a2f05 100644 --- a/Core/Core/Models/DynamicBase.cs +++ b/Core/Core/Models/DynamicBase.cs @@ -237,9 +237,7 @@ public IEnumerable GetMemberNames() /// /// Specifies which members should be included in the resulting dictionary. Can be concatenated with "|" /// A dictionary containing the key's and values of the object. - public Dictionary GetMembers( - DynamicBaseMemberType includeMembers = DefaultIncludeMembers - ) + public Dictionary GetMembers(DynamicBaseMemberType includeMembers = DefaultIncludeMembers) { // Initialize an empty dict var dic = new Dictionary(); @@ -272,10 +270,7 @@ public Dictionary GetMembers( if (includeMembers.HasFlag(DynamicBaseMemberType.SchemaComputed)) GetType() .GetMethods() - .Where( - e => - e.IsDefined(typeof(SchemaComputedAttribute)) && !e.IsDefined(typeof(ObsoleteAttribute)) - ) + .Where(e => e.IsDefined(typeof(SchemaComputedAttribute)) && !e.IsDefined(typeof(ObsoleteAttribute))) .ToList() .ForEach(e => { diff --git a/Core/Core/Models/Extensions.cs b/Core/Core/Models/Extensions.cs index 99dd4e2fa3..80c0a4cc82 100644 --- a/Core/Core/Models/Extensions.cs +++ b/Core/Core/Models/Extensions.cs @@ -23,10 +23,7 @@ public static class BaseExtensions /// Optional predicate function to determine whether to break (or continue) traversal of a object's children. /// A flat List of objects. /// - public static IEnumerable Flatten( - this Base root, - BaseRecursionBreaker recursionBreaker = null - ) + public static IEnumerable Flatten(this Base root, BaseRecursionBreaker recursionBreaker = null) { recursionBreaker ??= b => false; diff --git a/Core/Core/Models/Extras.cs b/Core/Core/Models/Extras.cs index 1cfa63bc1e..d3695086b9 100644 --- a/Core/Core/Models/Extras.cs +++ b/Core/Core/Models/Extras.cs @@ -187,18 +187,13 @@ public void Update( if (status.HasValue) Status = status.Value; if (log != null) - log.Where(o => !string.IsNullOrEmpty(o) && !Log.Contains(o)) - ?.ToList() - .ForEach(o => Log.Add(o)); + log.Where(o => !string.IsNullOrEmpty(o) && !Log.Contains(o))?.ToList().ForEach(o => Log.Add(o)); if (!string.IsNullOrEmpty(logItem) && !Log.Contains(logItem)) Log.Add(logItem); if (convertedItem != null && !Converted.Contains(convertedItem)) Converted.Add(convertedItem); if (converted != null) - converted - .Where(o => o != null && !Converted.Contains(o)) - ?.ToList() - .ForEach(o => Converted.Add(o)); + converted.Where(o => o != null && !Converted.Contains(o))?.ToList().ForEach(o => Converted.Add(o)); if (!string.IsNullOrEmpty(container)) Container = container; if (!string.IsNullOrEmpty(descriptor)) diff --git a/Core/Core/Models/GraphTraversal/DefaultTraversal.cs b/Core/Core/Models/GraphTraversal/DefaultTraversal.cs index f5d5372dfa..10e8e35e10 100644 --- a/Core/Core/Models/GraphTraversal/DefaultTraversal.cs +++ b/Core/Core/Models/GraphTraversal/DefaultTraversal.cs @@ -34,10 +34,7 @@ public static GraphTraversal CreateTraverseFunc(ISpeckleConverter converter) .When(o => o.speckle_type.Contains("Objects.Structural.Results")) .ContinueTraversing(None); - var defaultRule = TraversalRule - .NewTraversalRule() - .When(_ => true) - .ContinueTraversing(Members()); + var defaultRule = TraversalRule.NewTraversalRule().When(_ => true).ContinueTraversing(Members()); return new GraphTraversal(convertableRule, ignoreResultsRule, defaultRule); } @@ -54,10 +51,7 @@ public static GraphTraversal CreateTraverseFunc(ISpeckleConverter converter) /// public static GraphTraversal CreateRevitTraversalFunc(ISpeckleConverter converter) { - var convertableRule = TraversalRule - .NewTraversalRule() - .When(converter.CanConvertToNative) - .ContinueTraversing(None); + var convertableRule = TraversalRule.NewTraversalRule().When(converter.CanConvertToNative).ContinueTraversing(None); var displayValueRule = TraversalRule .NewTraversalRule() @@ -79,10 +73,7 @@ public static GraphTraversal CreateRevitTraversalFunc(ISpeckleConverter converte .When(o => o.speckle_type.Contains("Objects.Structural.Results")) .ContinueTraversing(None); - var defaultRule = TraversalRule - .NewTraversalRule() - .When(_ => true) - .ContinueTraversing(Members()); + var defaultRule = TraversalRule.NewTraversalRule().When(_ => true).ContinueTraversing(Members()); return new GraphTraversal(convertableRule, displayValueRule, ignoreResultsRule, defaultRule); } @@ -105,10 +96,7 @@ public static GraphTraversal CreateBIMTraverseFunc(ISpeckleConverter converter) .When(o => o.speckle_type.Contains("Objects.Structural.Results")) .ContinueTraversing(None); - var defaultRule = TraversalRule - .NewTraversalRule() - .When(_ => true) - .ContinueTraversing(Members()); + var defaultRule = TraversalRule.NewTraversalRule().When(_ => true).ContinueTraversing(Members()); return new GraphTraversal(bimElementRule, ignoreResultsRule, defaultRule); } @@ -126,9 +114,7 @@ internal static IEnumerable ElementsAliases(Base _) internal static readonly string[] displayValueAliases = { "displayValue", "@displayValue" }; - internal static readonly string[] ignoreProps = new[] { "@blockDefinition" } - .Concat(displayValueAliases) - .ToArray(); + internal static readonly string[] ignoreProps = new[] { "@blockDefinition" }.Concat(displayValueAliases).ToArray(); internal static IEnumerable DisplayValueAliases(Base _) { @@ -140,9 +126,7 @@ internal static IEnumerable None(Base _) return Enumerable.Empty(); } - internal static SelectMembers Members( - DynamicBaseMemberType includeMembers = DynamicBase.DefaultIncludeMembers - ) + internal static SelectMembers Members(DynamicBaseMemberType includeMembers = DynamicBase.DefaultIncludeMembers) { return x => x.GetMembers(includeMembers).Keys; } diff --git a/Core/Core/Models/Utilities.cs b/Core/Core/Models/Utilities.cs index 91cbc2610c..6e17d73f5e 100644 --- a/Core/Core/Models/Utilities.cs +++ b/Core/Core/Models/Utilities.cs @@ -46,11 +46,7 @@ public static string hashFile(string filePath, HashingFuctions func = HashingFuc using (var stream = File.OpenRead(filePath)) { var hash = hashAlgorithm.ComputeHash(stream); - return BitConverter - .ToString(hash) - .Replace("-", "") - .ToLowerInvariant() - .Substring(0, HashLength); + return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant().Substring(0, HashLength); } } @@ -108,12 +104,7 @@ public static bool IsSimpleType(this Type type) /// Set to true to also retrieve simple props of direct parent type /// Names of props to ignore /// - public static Base GetApplicationProps( - object o, - Type t, - bool getParentProps = false, - List ignore = null - ) + public static Base GetApplicationProps(object o, Type t, bool getParentProps = false, List ignore = null) { var appProps = new Base(); appProps["class"] = t.Name; @@ -121,11 +112,7 @@ public static Base GetApplicationProps( try { // set primitive writeable props - foreach ( - var propInfo in t.GetProperties( - BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public - ) - ) + foreach (var propInfo in t.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { if (ignore != null && ignore.Contains(propInfo.Name)) continue; diff --git a/Core/Core/Serialisation/BaseObjectDeserializerV2.cs b/Core/Core/Serialisation/BaseObjectDeserializerV2.cs index 483f732764..0b99b34865 100644 --- a/Core/Core/Serialisation/BaseObjectDeserializerV2.cs +++ b/Core/Core/Serialisation/BaseObjectDeserializerV2.cs @@ -123,10 +123,7 @@ public Base Deserialize(string rootObjectJson) private object DeserializeTransportObjectProxy(string objectJson) { // Try background work - Task bgResult = WorkerThreads.TryStartTask( - WorkerThreadTaskType.Deserialize, - objectJson - ); + Task bgResult = WorkerThreads.TryStartTask(WorkerThreadTaskType.Deserialize, objectJson); if (bgResult != null) return bgResult; @@ -269,20 +266,13 @@ private Base Dict2Base(Dictionary dictObj) dictObj.Remove(TypeDiscriminator); dictObj.Remove("__closure"); - Dictionary staticProperties = SerializationUtilities.GetTypePropeties( - typeName - ); - List onDeserializedCallbacks = SerializationUtilities.GetOnDeserializedCallbacks( - typeName - ); + Dictionary staticProperties = SerializationUtilities.GetTypePropeties(typeName); + List onDeserializedCallbacks = SerializationUtilities.GetOnDeserializedCallbacks(typeName); foreach (KeyValuePair entry in dictObj) { string lowerPropertyName = entry.Key.ToLower(); - if ( - staticProperties.ContainsKey(lowerPropertyName) - && staticProperties[lowerPropertyName].CanWrite - ) + if (staticProperties.ContainsKey(lowerPropertyName) && staticProperties[lowerPropertyName].CanWrite) { PropertyInfo property = staticProperties[lowerPropertyName]; if (entry.Value == null) @@ -295,21 +285,13 @@ private Base Dict2Base(Dictionary dictObj) Type targetValueType = property.PropertyType; object convertedValue; - bool conversionOk = ValueConverter.ConvertValue( - targetValueType, - entry.Value, - out convertedValue - ); + bool conversionOk = ValueConverter.ConvertValue(targetValueType, entry.Value, out convertedValue); if (conversionOk) property.SetValue(baseObj, convertedValue); else // Cannot convert the value in the json to the static property type throw new Exception( - string.Format( - "Cannot deserialize {0} to {1}", - entry.Value.GetType().FullName, - targetValueType.FullName - ) + string.Format("Cannot deserialize {0} to {1}", entry.Value.GetType().FullName, targetValueType.FullName) ); } else diff --git a/Core/Core/Serialisation/BaseObjectSerializer.cs b/Core/Core/Serialisation/BaseObjectSerializer.cs index c6335f1911..c233c02bd2 100644 --- a/Core/Core/Serialisation/BaseObjectSerializer.cs +++ b/Core/Core/Serialisation/BaseObjectSerializer.cs @@ -70,12 +70,7 @@ public override bool CanConvert(Type objectType) #region Read Json - public override object ReadJson( - JsonReader reader, - Type objectType, - object existingValue, - JsonSerializer serializer - ) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (CancellationToken.IsCancellationRequested) return null; // Check for cancellation @@ -122,11 +117,7 @@ JsonSerializer serializer if (CancellationToken.IsCancellationRequested) return null; // Check for cancellation - dict[val.Key] = SerializationUtilities.HandleValue( - val.Value, - serializer, - CancellationToken - ); + dict[val.Key] = SerializationUtilities.HandleValue(val.Value, serializer, CancellationToken); } return dict; } @@ -154,9 +145,7 @@ JsonSerializer serializer } else { - throw new SpeckleException( - "Cannot resolve reference. The provided transport could not find it." - ); + throw new SpeckleException("Cannot resolve reference. The provided transport could not find it."); } } @@ -199,12 +188,7 @@ JsonSerializer serializer } else { - var val = SerializationUtilities.HandleValue( - jProperty.Value, - serializer, - CancellationToken, - property - ); + var val = SerializationUtilities.HandleValue(jProperty.Value, serializer, CancellationToken, property); property.ValueProvider.SetValue(obj, val); } } @@ -328,8 +312,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var jo = new JObject(); var propertyNames = obj.GetDynamicMemberNames(); - var contract = (JsonDynamicContract) - serializer.ContractResolver.ResolveContract(value.GetType()); + var contract = (JsonDynamicContract)serializer.ContractResolver.ResolveContract(value.GetType()); // Iterate through the object's properties, one by one, checking for ignored ones foreach (var prop in propertyNames) @@ -357,25 +340,16 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s // Check if this property is marked for detachment: either by the presence of "@" at the beginning of the name, or by the presence of a DetachProperty attribute on a typed property. if (property != null) { - var detachableAttributes = property.AttributeProvider.GetAttributes( - typeof(DetachProperty), - true - ); + var detachableAttributes = property.AttributeProvider.GetAttributes(typeof(DetachProperty), true); if (detachableAttributes.Count > 0) DetachLineage.Add(((DetachProperty)detachableAttributes[0]).Detachable); else DetachLineage.Add(false); - var chunkableAttributes = property.AttributeProvider.GetAttributes( - typeof(Chunkable), - true - ); + var chunkableAttributes = property.AttributeProvider.GetAttributes(typeof(Chunkable), true); if (chunkableAttributes.Count > 0) //DetachLineage.Add(true); // NOOPE - serializer.Context = new StreamingContext( - StreamingContextStates.Other, - chunkableAttributes[0] - ); + serializer.Context = new StreamingContext(StreamingContextStates.Other, chunkableAttributes[0]); else //DetachLineage.Add(false); serializer.Context = new StreamingContext(); @@ -507,9 +481,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s JArray arr = new(); // Chunking large lists into manageable parts. - if ( - DetachLineage[DetachLineage.Count - 1] && serializer.Context.Context is Chunkable chunkInfo - ) + if (DetachLineage[DetachLineage.Count - 1] && serializer.Context.Context is Chunkable chunkInfo) { var maxCount = chunkInfo.MaxObjCountPerChunk; var i = 0; diff --git a/Core/Core/Serialisation/BaseObjectSerializerV2.cs b/Core/Core/Serialisation/BaseObjectSerializerV2.cs index 02a0485279..8988a13a5c 100644 --- a/Core/Core/Serialisation/BaseObjectSerializerV2.cs +++ b/Core/Core/Serialisation/BaseObjectSerializerV2.cs @@ -31,8 +31,7 @@ public class BaseObjectSerializerV2 /// public string TypeDiscriminator = "speckle_type"; - private Dictionary> TypedPropertiesCache = - new(); + private Dictionary> TypedPropertiesCache = new(); public CancellationToken CancellationToken { get; set; } @@ -58,8 +57,7 @@ public string Serialize(Base baseObj) { _stopwatch.Start(); Busy = true; - Dictionary converted = - PreserializeObject(baseObj, true) as Dictionary; + Dictionary converted = PreserializeObject(baseObj, true) as Dictionary; string serialized = Dict2Json(converted); StoreObject(converted["id"] as string, serialized); return serialized; @@ -176,9 +174,7 @@ public object PreserializeBase( if (computeClosures || inheritedDetachInfo.IsDetachable || baseObj is Blob) ParentClosures.Add(closure); - List<(PropertyInfo, PropertyAttributeInfo)> typedProperties = GetTypedPropertiesWithCache( - baseObj - ); + List<(PropertyInfo, PropertyAttributeInfo)> typedProperties = GetTypedPropertiesWithCache(baseObj); IEnumerable dynamicProperties = baseObj.GetDynamicMembers(); // propertyName -> (originalValue, isDetachable, isChunkable, chunkSize) @@ -206,10 +202,7 @@ public object PreserializeBase( var match = ChunkPropertyNameRegex.Match(propName); isChunkable = int.TryParse(match.Groups[match.Groups.Count - 1].Value, out chunkSize); } - allProperties[propName] = ( - baseValue, - new PropertyAttributeInfo(isDetachable, isChunkable, chunkSize, null) - ); + allProperties[propName] = (baseValue, new PropertyAttributeInfo(isDetachable, isChunkable, chunkSize, null)); } // Convert all properties @@ -263,9 +256,7 @@ public object PreserializeBase( private object PreserializeBasePropertyValue(object baseValue, PropertyAttributeInfo detachInfo) { bool computeClosuresForChild = - (detachInfo.IsDetachable || detachInfo.IsChunkable) - && WriteTransports != null - && WriteTransports.Count > 0; + (detachInfo.IsDetachable || detachInfo.IsChunkable) && WriteTransports != null && WriteTransports.Count > 0; // If there are no WriteTransports, keep everything attached. if (WriteTransports == null || WriteTransports.Count == 0) @@ -288,10 +279,7 @@ private object PreserializeBasePropertyValue(object baseValue, PropertyAttribute } if (crtChunk.data.Count > 0) chunks.Add(crtChunk); - return PreserializeObject( - chunks, - inheritedDetachInfo: new PropertyAttributeInfo(true, false, 0, null) - ); + return PreserializeObject(chunks, inheritedDetachInfo: new PropertyAttributeInfo(true, false, 0, null)); } return PreserializeObject(baseValue, inheritedDetachInfo: detachInfo); @@ -304,10 +292,7 @@ private void UpdateParentClosures(string objectId) int childDepth = ParentClosures.Count - parentLevel; if (!ParentClosures[parentLevel].ContainsKey(objectId)) ParentClosures[parentLevel][objectId] = childDepth; - ParentClosures[parentLevel][objectId] = Math.Min( - ParentClosures[parentLevel][objectId], - childDepth - ); + ParentClosures[parentLevel][objectId] = Math.Min(ParentClosures[parentLevel][objectId], childDepth); } } @@ -386,23 +371,13 @@ private void StoreBlob(Blob obj) object baseValue = typedProperty.GetValue(baseObj); - List detachableAttributes = typedProperty - .GetCustomAttributes(true) - .ToList(); - List chunkableAttributes = typedProperty - .GetCustomAttributes(true) - .ToList(); + List detachableAttributes = typedProperty.GetCustomAttributes(true).ToList(); + List chunkableAttributes = typedProperty.GetCustomAttributes(true).ToList(); bool isDetachable = detachableAttributes.Count > 0 && detachableAttributes[0].Detachable; bool isChunkable = chunkableAttributes.Count > 0; int chunkSize = isChunkable ? chunkableAttributes[0].MaxObjCountPerChunk : 1000; - JsonPropertyAttribute jsonPropertyAttribute = - typedProperty.GetCustomAttribute(); - ret.Add( - ( - typedProperty, - new PropertyAttributeInfo(isDetachable, isChunkable, chunkSize, jsonPropertyAttribute) - ) - ); + JsonPropertyAttribute jsonPropertyAttribute = typedProperty.GetCustomAttribute(); + ret.Add((typedProperty, new PropertyAttributeInfo(isDetachable, isChunkable, chunkSize, jsonPropertyAttribute))); } TypedPropertiesCache[type.FullName] = ret; diff --git a/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs b/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs index 3edae52c13..32ea3500f2 100644 --- a/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs +++ b/Core/Core/Serialisation/BaseObjectSerialzerUtilities.cs @@ -67,22 +67,12 @@ internal static object HandleValue( foreach (var dataItem in chunk.data) if (hasGenericType && !jsonProperty.PropertyType.GenericTypeArguments[0].IsInterface) { - if ( - jsonProperty.PropertyType.GenericTypeArguments[0].IsAssignableFrom( - dataItem.GetType() - ) - ) + if (jsonProperty.PropertyType.GenericTypeArguments[0].IsAssignableFrom(dataItem.GetType())) addMethod.Invoke(arr, new[] { dataItem }); else addMethod.Invoke( arr, - new[] - { - Convert.ChangeType( - dataItem, - jsonProperty.PropertyType.GenericTypeArguments[0] - ) - } + new[] { Convert.ChangeType(dataItem, jsonProperty.PropertyType.GenericTypeArguments[0]) } ); } else @@ -97,10 +87,7 @@ internal static object HandleValue( else addMethod.Invoke( arr, - new[] - { - Convert.ChangeType(item, jsonProperty.PropertyType.GenericTypeArguments[0]) - } + new[] { Convert.ChangeType(item, jsonProperty.PropertyType.GenericTypeArguments[0]) } ); } else @@ -116,9 +103,7 @@ internal static object HandleValue( if (CancellationToken.IsCancellationRequested) return null; // Check for cancellation - var arr = Activator.CreateInstance( - typeof(List<>).MakeGenericType(jsonProperty.PropertyType.GetElementType()) - ); + var arr = Activator.CreateInstance(typeof(List<>).MakeGenericType(jsonProperty.PropertyType.GetElementType())); foreach (var val in (JArray)value) { @@ -133,26 +118,19 @@ internal static object HandleValue( { foreach (var dataItem in chunk.data) if (!jsonProperty.PropertyType.GetElementType().IsInterface) - ((IList)arr).Add( - Convert.ChangeType(dataItem, jsonProperty.PropertyType.GetElementType()) - ); + ((IList)arr).Add(Convert.ChangeType(dataItem, jsonProperty.PropertyType.GetElementType())); else ((IList)arr).Add(dataItem); } else { if (!jsonProperty.PropertyType.GetElementType().IsInterface) - ((IList)arr).Add( - Convert.ChangeType(item, jsonProperty.PropertyType.GetElementType()) - ); + ((IList)arr).Add(Convert.ChangeType(item, jsonProperty.PropertyType.GetElementType())); else ((IList)arr).Add(item); } } - var actualArr = Array.CreateInstance( - jsonProperty.PropertyType.GetElementType(), - ((IList)arr).Count - ); + var actualArr = Array.CreateInstance(jsonProperty.PropertyType.GetElementType(), ((IList)arr).Count); ((IList)arr).CopyTo(actualArr, 0); return actualArr; } @@ -190,9 +168,7 @@ internal static object HandleValue( return value.ToObject(serializer); var dict = - jsonProperty != null - ? Activator.CreateInstance(jsonProperty.PropertyType) - : new Dictionary(); + jsonProperty != null ? Activator.CreateInstance(jsonProperty.PropertyType) : new Dictionary(); foreach (var prop in (JObject)value) { if (CancellationToken.IsCancellationRequested) @@ -273,9 +249,7 @@ internal static List GetOnDeserializedCallbacks(string objFullType) { List ret = new(); Type type = GetType(objFullType); - MethodInfo[] methods = type.GetMethods( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ); + MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo method in methods) { List onDeserializedAttributes = method @@ -323,9 +297,7 @@ JsonSerializer serializer var pieces = assemblyQualifiedName.Split(',').Select(s => s.Trim()).ToArray(); - var myAssembly = AppDomain.CurrentDomain - .GetAssemblies() - .FirstOrDefault(ass => ass.GetName().Name == pieces[1]); + var myAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(ass => ass.GetName().Name == pieces[1]); if (myAssembly == null) throw new SpeckleException("Could not load abstract object's assembly."); @@ -350,10 +322,7 @@ internal static class CallSiteCache // https://github.com/mgravell/fast-member/blob/master/FastMember/CallSiteCache.cs // by Marc Gravell, https://github.com/mgravell - private static readonly Dictionary< - string, - CallSite> - > setters = new(); + private static readonly Dictionary>> setters = new(); public static void SetValue(string propertyName, object target, object value) { @@ -374,9 +343,7 @@ public static void SetValue(string propertyName, object target, object value) CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) } ); - setters[propertyName] = site = CallSite>.Create( - binder - ); + setters[propertyName] = site = CallSite>.Create(binder); } site.Target(site, target, value); diff --git a/Core/Core/Serialisation/DeserializationWorkerThreads.cs b/Core/Core/Serialisation/DeserializationWorkerThreads.cs index c5d41b44fb..efe0fa6cbb 100644 --- a/Core/Core/Serialisation/DeserializationWorkerThreads.cs +++ b/Core/Core/Serialisation/DeserializationWorkerThreads.cs @@ -18,8 +18,7 @@ internal class DeserializationWorkerThreads : IDisposable private object LockFreeThreads = new(); private BaseObjectDeserializerV2 Serializer; - private BlockingCollection<(WorkerThreadTaskType, object, TaskCompletionSource)> Tasks = - new(); + private BlockingCollection<(WorkerThreadTaskType, object, TaskCompletionSource)> Tasks = new(); private List Threads = new(); @@ -59,8 +58,7 @@ private void ThreadMain() { lock (LockFreeThreads) FreeThreadCount++; - (WorkerThreadTaskType taskType, object inputValue, TaskCompletionSource tcs) = - Tasks.Take(); + (WorkerThreadTaskType taskType, object inputValue, TaskCompletionSource tcs) = Tasks.Take(); if (tcs == null) return; diff --git a/Core/Core/Transports/Memory.cs b/Core/Core/Transports/Memory.cs index 656f958e33..820d887bad 100644 --- a/Core/Core/Transports/Memory.cs +++ b/Core/Core/Transports/Memory.cs @@ -52,8 +52,7 @@ public void Dispose() public int SavedObjectCount { get; set; } - public Dictionary TransportContext => - new() { { "name", TransportName }, { "type", GetType().Name } }; + public Dictionary TransportContext => new() { { "name", TransportName }, { "type", GetType().Name } }; public TimeSpan Elapsed { get; set; } = TimeSpan.Zero; diff --git a/Core/Core/Transports/SQLite.cs b/Core/Core/Transports/SQLite.cs index 4b8c10689d..79a123d6bf 100644 --- a/Core/Core/Transports/SQLite.cs +++ b/Core/Core/Transports/SQLite.cs @@ -27,11 +27,7 @@ public class SQLiteTransport : IDisposable, ICloneable, ITransport, IBlobCapable /// private Timer WriteTimer; - public SQLiteTransport( - string basePath = null, - string applicationName = null, - string scope = "Data" - ) + public SQLiteTransport(string basePath = null, string applicationName = null, string scope = "Data") { if (basePath == null) basePath = SpecklePathProvider.UserApplicationDataPath(); @@ -87,8 +83,7 @@ public SQLiteTransport( private SqliteConnection Connection { get; set; } private object ConnectionLock { get; set; } - public string BlobStorageFolder => - SpecklePathProvider.BlobStoragePath(Path.Combine(_basePath, _applicationName)); + public string BlobStorageFolder => SpecklePathProvider.BlobStoragePath(Path.Combine(_basePath, _applicationName)); public void SaveBlob(Blob obj) { @@ -463,12 +458,7 @@ public string GetObject(string hash) lock (ConnectionLock) { var stopwatch = Stopwatch.StartNew(); - using ( - var command = new SqliteCommand( - "SELECT * FROM objects WHERE hash = @hash LIMIT 1 ", - Connection - ) - ) + using (var command = new SqliteCommand("SELECT * FROM objects WHERE hash = @hash LIMIT 1 ", Connection)) { command.Parameters.AddWithValue("@hash", hash); using (var reader = command.ExecuteReader()) diff --git a/Core/Core/Transports/Server.cs b/Core/Core/Transports/Server.cs index c757ea43ad..7b92199113 100644 --- a/Core/Core/Transports/Server.cs +++ b/Core/Core/Transports/Server.cs @@ -108,10 +108,7 @@ public void EndWrite() { } public async Task> HasObjects(List objectIds) { - var payload = new Dictionary - { - { "objects", JsonConvert.SerializeObject(objectIds) } - }; + var payload = new Dictionary { { "objects", JsonConvert.SerializeObject(objectIds) } }; var uri = new Uri($"/api/diff/{StreamId}", UriKind.Relative); var response = await Client .PostAsync( @@ -127,12 +124,7 @@ public async Task> HasObjects(List objectIds) return hasObjects; } - private void Initialize( - string baseUri, - string streamId, - string authorizationToken, - int timeoutSeconds = 60 - ) + private void Initialize(string baseUri, string streamId, string authorizationToken, int timeoutSeconds = 60) { SpeckleLog.Logger.Information("Initializing New Remote V1 Transport for {baseUri}", baseUri); @@ -292,8 +284,7 @@ private async Task ConsumeQueue() return; } - (int consumedQueuedObjects, List<(string, string, int)> batch) = await ConsumeNewBatch() - .ConfigureAwait(false); + (int consumedQueuedObjects, List<(string, string, int)> batch) = await ConsumeNewBatch().ConfigureAwait(false); if (batch == null) { // Canceled or error happened (which was already reported) @@ -328,11 +319,7 @@ private async Task ConsumeQueue() } else { - multipart.Add( - new StringContent(_ct, Encoding.UTF8), - $"batch-{addedMpCount}", - $"batch-{addedMpCount}" - ); + multipart.Add(new StringContent(_ct, Encoding.UTF8), $"batch-{addedMpCount}", $"batch-{addedMpCount}"); } addedMpCount++; @@ -359,10 +346,7 @@ private async Task ConsumeQueue() IS_WRITING = false; OnErrorAction?.Invoke( TransportName, - new Exception( - $"Remote error: {Account.serverInfo.url} is not reachable. \n {e.Message}", - e - ) + new Exception($"Remote error: {Account.serverInfo.url} is not reachable. \n {e.Message}", e) ); Queue = new ConcurrentQueue<(string, string, int)>(); @@ -483,8 +467,7 @@ Action onTotalChildrenCountKnown onTotalChildrenCountKnown?.Invoke(childrenIds.Count); var childrenFoundMap = await targetTransport.HasObjects(childrenIds).ConfigureAwait(false); - List newChildrenIds = - new(from objId in childrenFoundMap.Keys where !childrenFoundMap[objId] select objId); + List newChildrenIds = new(from objId in childrenFoundMap.Keys where !childrenFoundMap[objId] select objId); targetTransport.BeginWrite(); @@ -496,8 +479,7 @@ Action onTotalChildrenCountKnown childrenIdBatch.Add(objectId); if (childrenIdBatch.Count >= DOWNLOAD_BATCH_SIZE) { - downloadBatchResult = await CopyObjects(childrenIdBatch, targetTransport) - .ConfigureAwait(false); + downloadBatchResult = await CopyObjects(childrenIdBatch, targetTransport).ConfigureAwait(false); if (!downloadBatchResult) return null; childrenIdBatch = new List(DOWNLOAD_BATCH_SIZE); @@ -505,8 +487,7 @@ Action onTotalChildrenCountKnown } if (childrenIdBatch.Count > 0) { - downloadBatchResult = await CopyObjects(childrenIdBatch, targetTransport) - .ConfigureAwait(false); + downloadBatchResult = await CopyObjects(childrenIdBatch, targetTransport).ConfigureAwait(false); if (!downloadBatchResult) return null; } @@ -537,11 +518,7 @@ private async Task CopyObjects(List hashes, ITransport targetTrans try { childrenHttpResponse = await Client - .SendAsync( - childrenHttpMessage, - HttpCompletionOption.ResponseHeadersRead, - CancellationToken - ) + .SendAsync(childrenHttpMessage, HttpCompletionOption.ResponseHeadersRead, CancellationToken) .ConfigureAwait(false); childrenHttpResponse.EnsureSuccessStatusCode(); } diff --git a/Core/Core/Transports/ServerUtils/IServerApi.cs b/Core/Core/Transports/ServerUtils/IServerApi.cs index 8bc52ca531..96d6da2f7f 100644 --- a/Core/Core/Transports/ServerUtils/IServerApi.cs +++ b/Core/Core/Transports/ServerUtils/IServerApi.cs @@ -10,11 +10,7 @@ internal interface IServerApi { public Task DownloadSingleObject(string streamId, string objectId); - public Task DownloadObjects( - string streamId, - List objectIds, - CbObjectDownloaded onObjectCallback - ); + public Task DownloadObjects(string streamId, List objectIds, CbObjectDownloaded onObjectCallback); public Task> HasObjects(string streamId, List objectIds); @@ -22,9 +18,5 @@ CbObjectDownloaded onObjectCallback public Task UploadBlobs(string streamId, List<(string, string)> objects); - public Task DownloadBlobs( - string streamId, - List blobIds, - CbBlobdDownloaded onBlobCallback - ); + public Task DownloadBlobs(string streamId, List blobIds, CbBlobdDownloaded onBlobCallback); } diff --git a/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs b/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs index 71db713c67..4d9379be5f 100644 --- a/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs +++ b/Core/Core/Transports/ServerUtils/ParallelServerAPI.cs @@ -48,9 +48,7 @@ public ParallelServerApi( BlobStorageFolder = blobStorageFolder; - Tasks = new BlockingCollection<(ServerApiOperation, object, TaskCompletionSource)>( - numBufferedOperations - ); + Tasks = new BlockingCollection<(ServerApiOperation, object, TaskCompletionSource)>(numBufferedOperations); } public CancellationToken CancellationToken { get; set; } @@ -80,17 +78,13 @@ public async Task> HasObjects(string streamId, List op = QueueOperation( - ServerApiOperation.HasObjects, - (streamId, splitObjectsIds[i]) - ); + Task op = QueueOperation(ServerApiOperation.HasObjects, (streamId, splitObjectsIds[i])); tasks.Add(op); } Dictionary ret = new(); foreach (Task task in tasks) { - Dictionary taskResult = - await task.ConfigureAwait(false) as Dictionary; + Dictionary taskResult = await task.ConfigureAwait(false) as Dictionary; foreach (KeyValuePair kv in taskResult) ret[kv.Key] = kv.Value; } @@ -106,11 +100,7 @@ public async Task DownloadSingleObject(string streamId, string objectId) return result as string; } - public async Task DownloadObjects( - string streamId, - List objectIds, - CbObjectDownloaded onObjectCallback - ) + public async Task DownloadObjects(string streamId, List objectIds, CbObjectDownloaded onObjectCallback) { // Stopwatch sw = new Stopwatch(); sw.Start(); // TODO: remove @@ -164,10 +154,7 @@ public async Task UploadObjects(string streamId, List<(string, string)> objects) { if (splitObjects.Count <= i || splitObjects[i].Count == 0) continue; - Task op = QueueOperation( - ServerApiOperation.UploadObjects, - (streamId, splitObjects[i]) - ); + Task op = QueueOperation(ServerApiOperation.UploadObjects, (streamId, splitObjects[i])); tasks.Add(op); } await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); @@ -181,17 +168,10 @@ public async Task UploadBlobs(string streamId, List<(string, string)> blobs) await op.ConfigureAwait(false); } - public async Task DownloadBlobs( - string streamId, - List blobIds, - CbBlobdDownloaded onBlobDownloaded - ) + public async Task DownloadBlobs(string streamId, List blobIds, CbBlobdDownloaded onBlobDownloaded) { EnsureStarted(); - Task op = QueueOperation( - ServerApiOperation.DownloadBlobs, - (streamId, blobIds, onBlobDownloaded) - ); + Task op = QueueOperation(ServerApiOperation.DownloadBlobs, (streamId, blobIds, onBlobDownloaded)); await op.ConfigureAwait(false); } @@ -246,8 +226,7 @@ private void ThreadMain() while (true) { - (ServerApiOperation operation, object inputValue, TaskCompletionSource tcs) = - Tasks.Take(); + (ServerApiOperation operation, object inputValue, TaskCompletionSource tcs) = Tasks.Take(); if (tcs == null) return; @@ -276,27 +255,18 @@ private void ThreadMain() tcs.SetResult(hoResult); break; case ServerApiOperation.UploadObjects: - (string uoStreamId, List<(string, string)> uoObjects) = (( - string, - List<(string, string)> - ))inputValue; + (string uoStreamId, List<(string, string)> uoObjects) = ((string, List<(string, string)>))inputValue; serialApi.UploadObjects(uoStreamId, uoObjects).Wait(); // TODO: pass errors? tcs.SetResult(null); break; case ServerApiOperation.UploadBlobs: - (string ubStreamId, List<(string, string)> ubBlobs) = (( - string, - List<(string, string)> - ))inputValue; + (string ubStreamId, List<(string, string)> ubBlobs) = ((string, List<(string, string)>))inputValue; serialApi.UploadBlobs(ubStreamId, ubBlobs).Wait(); tcs.SetResult(null); break; case ServerApiOperation.HasBlobs: - (string hbStreamId, List<(string, string)> hBlobs) = (( - string, - List<(string, string)> - ))inputValue; + (string hbStreamId, List<(string, string)> hBlobs) = ((string, List<(string, string)>))inputValue; var hasBlobResult = serialApi .HasBlobs(hbStreamId, hBlobs.Select(b => b.Item1.Split(':')[1]).ToList()) .Result; diff --git a/Core/Core/Transports/ServerUtils/ServerAPI.cs b/Core/Core/Transports/ServerUtils/ServerAPI.cs index e11a1f3b89..a418550804 100644 --- a/Core/Core/Transports/ServerUtils/ServerAPI.cs +++ b/Core/Core/Transports/ServerUtils/ServerAPI.cs @@ -29,12 +29,7 @@ public class ServerApi : IDisposable, IServerApi private HashSet RETRY_CODES = new() { 408, 502, 503, 504 }; private int RETRY_COUNT = 3; - public ServerApi( - string baseUri, - string authorizationToken, - string blobStorageFolder, - int timeoutSeconds = 60 - ) + public ServerApi(string baseUri, string authorizationToken, string blobStorageFolder, int timeoutSeconds = 60) { BaseUri = baseUri; CancellationToken = CancellationToken.None; @@ -92,11 +87,7 @@ public async Task DownloadSingleObject(string streamId, string objectId) return rootObjectStr; } - public async Task DownloadObjects( - string streamId, - List objectIds, - CbObjectDownloaded onObjectCallback - ) + public async Task DownloadObjects(string streamId, List objectIds, CbObjectDownloaded onObjectCallback) { if (objectIds.Count == 0) return; @@ -131,8 +122,7 @@ public async Task> HasObjects(string streamId, List= BATCH_SIZE_HAS_OBJECTS) { - Dictionary batchResult = await HasObjectsImpl(streamId, crtBatch) - .ConfigureAwait(false); + Dictionary batchResult = await HasObjectsImpl(streamId, crtBatch).ConfigureAwait(false); foreach (KeyValuePair kv in batchResult) ret[kv.Key] = kv.Value; crtBatch = new List(BATCH_SIZE_HAS_OBJECTS); @@ -140,8 +130,7 @@ public async Task> HasObjects(string streamId, List 0) { - Dictionary batchResult = await HasObjectsImpl(streamId, crtBatch) - .ConfigureAwait(false); + Dictionary batchResult = await HasObjectsImpl(streamId, crtBatch).ConfigureAwait(false); foreach (KeyValuePair kv in batchResult) ret[kv.Key] = kv.Value; } @@ -196,9 +185,7 @@ public async Task UploadObjects(string streamId, List<(string, string)> objects) { List<(string, string)> multipart = multipartedObjects[i]; int multipartSize = multipartedObjectsSize[i]; - if ( - crtRequestSize + multipartSize > MAX_REQUEST_SIZE || crtRequest.Count >= MAX_MULTIPART_COUNT - ) + if (crtRequestSize + multipartSize > MAX_REQUEST_SIZE || crtRequest.Count >= MAX_MULTIPART_COUNT) { await UploadObjectsImpl(streamId, crtRequest).ConfigureAwait(false); OnBatchSent?.Invoke(crtObjectCount, crtRequestSize); @@ -261,11 +248,7 @@ public async Task UploadBlobs(string streamId, List<(string, string)> blobs) } } - public async Task DownloadBlobs( - string streamId, - List blobIds, - CbBlobdDownloaded onBlobDownloaded - ) + public async Task DownloadBlobs(string streamId, List blobIds, CbBlobdDownloaded onBlobDownloaded) { foreach (var blobId in blobIds) try @@ -281,9 +264,7 @@ CbBlobdDownloaded onBlobDownloaded response.Content.Headers.TryGetValues("Content-Disposition", out cdHeaderValues); var cdHeader = cdHeaderValues.First(); - var fileName = cdHeader.Split(new[] { "filename=" }, StringSplitOptions.None)[1] - .TrimStart('"') - .TrimEnd('"'); + var fileName = cdHeader.Split(new[] { "filename=" }, StringSplitOptions.None)[1].TrimStart('"').TrimEnd('"'); string fileLocation = Path.Combine( BlobStorageFolder, @@ -301,11 +282,7 @@ CbBlobdDownloaded onBlobDownloaded } } - private async Task DownloadObjectsImpl( - string streamId, - List objectIds, - CbObjectDownloaded onObjectCallback - ) + private async Task DownloadObjectsImpl(string streamId, List objectIds, CbObjectDownloaded onObjectCallback) { // Stopwatch sw = new Stopwatch(); sw.Start(); @@ -320,11 +297,7 @@ CbObjectDownloaded onObjectCallback Dictionary postParameters = new(); postParameters.Add("objects", JsonConvert.SerializeObject(objectIds)); string serializedPayload = JsonConvert.SerializeObject(postParameters); - childrenHttpMessage.Content = new StringContent( - serializedPayload, - Encoding.UTF8, - "application/json" - ); + childrenHttpMessage.Content = new StringContent(serializedPayload, Encoding.UTF8, "application/json"); childrenHttpMessage.Headers.Add("Accept", "text/plain"); HttpResponseMessage childrenHttpResponse = null; @@ -334,9 +307,7 @@ CbObjectDownloaded onObjectCallback .ConfigureAwait(false); childrenHttpResponse.EnsureSuccessStatusCode(); - Stream childrenStream = await childrenHttpResponse.Content - .ReadAsStreamAsync() - .ConfigureAwait(false); + Stream childrenStream = await childrenHttpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); using (childrenStream) using (var reader = new StreamReader(childrenStream, Encoding.UTF8)) @@ -354,10 +325,7 @@ CbObjectDownloaded onObjectCallback // Console.WriteLine($"ServerApi::DownloadObjects({objectIds.Count}) request in {sw.ElapsedMilliseconds / 1000.0} sec"); } - private async Task> HasObjectsImpl( - string streamId, - List objectIds - ) + private async Task> HasObjectsImpl(string streamId, List objectIds) { CancellationToken.ThrowIfCancellationRequested(); @@ -370,11 +338,7 @@ List objectIds HttpResponseMessage response = null; while (ShouldRetry(response)) response = await Client - .PostAsync( - uri, - new StringContent(serializedPayload, Encoding.UTF8, "application/json"), - CancellationToken - ) + .PostAsync(uri, new StringContent(serializedPayload, Encoding.UTF8, "application/json"), CancellationToken) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); @@ -390,10 +354,7 @@ List objectIds return hasObjects; } - private async Task UploadObjectsImpl( - string streamId, - List> multipartedObjects - ) + private async Task UploadObjectsImpl(string streamId, List> multipartedObjects) { // Stopwatch sw = new Stopwatch(); sw.Start(); @@ -452,11 +413,7 @@ public async Task> HasBlobs(string streamId, List blobIds) HttpResponseMessage response = null; while (ShouldRetry(response)) //TODO: can we get rid of this now we have polly? response = await Client - .PostAsync( - uri, - new StringContent(payload, Encoding.UTF8, "application/json"), - CancellationToken - ) + .PostAsync(uri, new StringContent(payload, Encoding.UTF8, "application/json"), CancellationToken) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); diff --git a/Core/Core/Transports/ServerV2.cs b/Core/Core/Transports/ServerV2.cs index 270aa17d8e..5e53a011ca 100644 --- a/Core/Core/Transports/ServerV2.cs +++ b/Core/Core/Transports/ServerV2.cs @@ -16,12 +16,7 @@ namespace Speckle.Core.Transports; public class ServerTransport : ServerTransportV2 { - public ServerTransport( - Account account, - string streamId, - int timeoutSeconds = 60, - string blobStorageFolder = null - ) + public ServerTransport(Account account, string streamId, int timeoutSeconds = 60, string blobStorageFolder = null) : base(account, streamId, timeoutSeconds, blobStorageFolder) { } } @@ -39,12 +34,7 @@ public class ServerTransportV2 : IDisposable, ICloneable, ITransport, IBlobCapab private bool ShouldSendThreadRun; - public ServerTransportV2( - Account account, - string streamId, - int timeoutSeconds = 60, - string blobStorageFolder = null - ) + public ServerTransportV2(Account account, string streamId, int timeoutSeconds = 60, string blobStorageFolder = null) { Account = account; CancellationToken = CancellationToken.None; @@ -132,9 +122,7 @@ public async Task CopyObjectAndChildren( if (CancellationToken.IsCancellationRequested) return null; - using ( - ParallelServerApi api = new(BaseUri, AuthorizationToken, BlobStorageFolder, TimeoutSeconds) - ) + using (ParallelServerApi api = new(BaseUri, AuthorizationToken, BlobStorageFolder, TimeoutSeconds)) { var stopwatch = Stopwatch.StartNew(); api.CancellationToken = CancellationToken; @@ -144,10 +132,7 @@ public async Task CopyObjectAndChildren( List allIds = ParseChildrenIds(rootObjectJson); List childrenIds = allIds.Where(id => !id.Contains("blob:")).ToList(); - List blobIds = allIds - .Where(id => id.Contains("blob:")) - .Select(id => id.Remove(0, 5)) - .ToList(); + List blobIds = allIds.Where(id => id.Contains("blob:")).Select(id => id.Remove(0, 5)).ToList(); onTotalChildrenCountKnown?.Invoke(allIds.Count); @@ -194,9 +179,7 @@ await api.DownloadObjects( .ToList(); var newBlobIds = blobIds - .Where( - id => !localBlobTrimmedHashes.Contains(id.Substring(0, Blob.LocalHashPrefixLength)) - ) + .Where(id => !localBlobTrimmedHashes.Contains(id.Substring(0, Blob.LocalHashPrefixLength))) .ToList(); await api.DownloadBlobs( @@ -294,12 +277,7 @@ public void EndWrite() SendingThread = null; } - private void Initialize( - string baseUri, - string streamId, - string authorizationToken, - int timeoutSeconds = 60 - ) + private void Initialize(string baseUri, string streamId, string authorizationToken, int timeoutSeconds = 60) { SpeckleLog.Logger.Information("Initializing a new Remote Transport for {baseUri}", baseUri); @@ -364,12 +342,8 @@ private async void SendingThreadMain() } try { - List<(string, string)> bufferObjects = buffer - .Where(tuple => !tuple.Item1.Contains("blob")) - .ToList(); - List<(string, string)> bufferBlobs = buffer - .Where(tuple => tuple.Item1.Contains("blob")) - .ToList(); + List<(string, string)> bufferObjects = buffer.Where(tuple => !tuple.Item1.Contains("blob")).ToList(); + List<(string, string)> bufferBlobs = buffer.Where(tuple => tuple.Item1.Contains("blob")).ToList(); List objectIds = new(bufferObjects.Count); @@ -377,8 +351,7 @@ private async void SendingThreadMain() if (id != "blob") objectIds.Add(id); - Dictionary hasObjects = await Api.HasObjects(StreamId, objectIds) - .ConfigureAwait(false); + Dictionary hasObjects = await Api.HasObjects(StreamId, objectIds).ConfigureAwait(false); List<(string, string)> newObjects = new(); foreach ((string id, object json) in bufferObjects) if (!hasObjects[id]) @@ -393,9 +366,7 @@ private async void SendingThreadMain() { var blobIdsToUpload = await Api.HasBlobs(StreamId, bufferBlobs).ConfigureAwait(false); var formattedIds = blobIdsToUpload.Select(id => $"blob:{id}").ToList(); - var newBlobs = bufferBlobs - .Where(tuple => formattedIds.IndexOf(tuple.Item1) != -1) - .ToList(); + var newBlobs = bufferBlobs.Where(tuple => formattedIds.IndexOf(tuple.Item1) != -1).ToList(); if (newBlobs.Count != 0) await Api.UploadBlobs(StreamId, newBlobs).ConfigureAwait(false); } diff --git a/Core/Examples/Program.cs b/Core/Examples/Program.cs index 320ce0aa02..12f217c596 100644 --- a/Core/Examples/Program.cs +++ b/Core/Examples/Program.cs @@ -43,9 +43,7 @@ private static async Task Main(string[] args) 40759.5123 ); - var log = SpeckleLog.Logger - .ForContext("currentSpeed", "warp 5") - .ForContext("captain", "Jean-Luc Picard"); + 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}", @@ -104,10 +102,7 @@ private static async Task Main(string[] args) /// /// /// - public static async Task SendReceiveManyLargeObjects( - int numVertices = 1000, - int numObjects = 10_000 - ) + public static async Task SendReceiveManyLargeObjects(int numVertices = 1000, int numObjects = 10_000) { var objs = new List(); @@ -184,9 +179,7 @@ public static async Task SendReceiveManyLargeObjects( public static async Task SendReceiveLargeSingleObjects(int numVertices = 100_000) { Console.Clear(); - Console.WriteLine( - $"Big mesh time! ({numVertices} vertices, and some {numVertices * 1.5} faces" - ); + Console.WriteLine($"Big mesh time! ({numVertices} vertices, and some {numVertices * 1.5} faces"); var myMesh = new Mesh(); for (int i = 1; i <= numVertices; i++) @@ -249,9 +242,7 @@ public static async Task SendAndReceive(int numObjects = 3000) ((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." - ); + Console.WriteLine($"Finished generating {numObjects} objs in ${sw.ElapsedMilliseconds / 1000f} seconds."); Console.Clear(); @@ -280,11 +271,7 @@ public static async Task SendAndReceive(int numObjects = 3000) var secondServer = new ServerTransport(AccountManager.GetDefaultAccount(), secondStreamId); var res = await Operations - .Send( - myRevision, - new List { firstServer, secondServer }, - onProgressAction: pushProgressAction - ) + .Send(myRevision, new List { firstServer, secondServer }, onProgressAction: pushProgressAction) .ConfigureAwait(false); Console.Clear(); diff --git a/Core/Examples/Subscriptions.cs b/Core/Examples/Subscriptions.cs index e1e672ec61..de98dc3cfb 100644 --- a/Core/Examples/Subscriptions.cs +++ b/Core/Examples/Subscriptions.cs @@ -15,9 +15,7 @@ public static async Task SubscriptionConnection() 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(); diff --git a/Core/IntegrationTests/Api.cs b/Core/IntegrationTests/Api.cs index 385f3b9d8d..be7f2870ef 100644 --- a/Core/IntegrationTests/Api.cs +++ b/Core/IntegrationTests/Api.cs @@ -143,9 +143,7 @@ public async Task StreamInviteCreate() Assert.ThrowsAsync( async () => - await myClient - .StreamInviteCreate(new StreamInviteCreateInput { streamId = streamId }) - .ConfigureAwait(false) + await myClient.StreamInviteCreate(new StreamInviteCreateInput { streamId = streamId }).ConfigureAwait(false) ); } @@ -162,9 +160,7 @@ public async Task StreamInviteUse() { var invites = await secondClient.GetAllPendingInvites().ConfigureAwait(false); - var res = await secondClient - .StreamInviteUse(invites[0].streamId, invites[0].token) - .ConfigureAwait(false); + var res = await secondClient.StreamInviteUse(invites[0].streamId, invites[0].token).ConfigureAwait(false); Assert.IsTrue(res); } @@ -191,11 +187,7 @@ public async Task StreamRevokePermission() { var res = await myClient .StreamRevokePermission( - new StreamRevokePermissionInput - { - streamId = streamId, - userId = secondUserAccount.userInfo.id - } + new StreamRevokePermissionInput { streamId = streamId, userId = secondUserAccount.userInfo.id } ) .ConfigureAwait(false); diff --git a/Core/IntegrationTests/Fixtures.cs b/Core/IntegrationTests/Fixtures.cs index 14343ce1b2..4f9f8f9b87 100644 --- a/Core/IntegrationTests/Fixtures.cs +++ b/Core/IntegrationTests/Fixtures.cs @@ -15,19 +15,14 @@ public class SetUp [OneTimeSetUp] public void BeforeAll() { - SpeckleLog.Initialize( - "Core", - "Testing", - new SpeckleLogConfiguration(logToFile: false, logToSeq: false) - ); + SpeckleLog.Initialize("Core", "Testing", new SpeckleLogConfiguration(logToFile: false, logToSeq: false)); SpeckleLog.Logger.Information("Initialized logger for testing"); } } public static class Fixtures { - public static readonly ServerInfo Server = - new() { url = "http://localhost:3000", name = "Docker Server" }; + public static readonly ServerInfo Server = new() { url = "http://localhost:3000", name = "Docker Server" }; public static async Task SeedUser() { @@ -47,11 +42,7 @@ public static async Task SeedUser() .PostAsync( "/auth/local/register?challenge=challengingchallenge", // $"{Server.url}/auth/local/register?challenge=challengingchallenge", - new StringContent( - JsonConvert.SerializeObject(user), - Encoding.UTF8, - MediaTypeNames.Application.Json - ) + new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, MediaTypeNames.Application.Json) ) .ConfigureAwait(false); redirectUrl = response.Headers.Location.AbsoluteUri; @@ -64,8 +55,7 @@ public static async Task SeedUser() var uri = new Uri(redirectUrl); var query = HttpUtility.ParseQueryString(uri.Query); - var accessCode = - query["access_code"] ?? throw new Exception("Redirect Uri has no 'access_code'."); + var accessCode = query["access_code"] ?? throw new Exception("Redirect Uri has no 'access_code'."); var tokenBody = new Dictionary { ["accessCode"] = accessCode, @@ -77,11 +67,7 @@ public static async Task SeedUser() var tokenResponse = await httpClient .PostAsync( "/auth/token", - new StringContent( - JsonConvert.SerializeObject(tokenBody), - Encoding.UTF8, - MediaTypeNames.Application.Json - ) + new StringContent(JsonConvert.SerializeObject(tokenBody), Encoding.UTF8, MediaTypeNames.Application.Json) ) .ConfigureAwait(false); var deserialised = JsonConvert.DeserializeObject>( @@ -131,12 +117,7 @@ public static Base GenerateNestedObject() public static Blob[] GenerateThreeBlobs() { - return new[] - { - GenerateBlob("blob 1 data"), - GenerateBlob("blob 2 data"), - GenerateBlob("blob 3 data") - }; + return new[] { GenerateBlob("blob 1 data"), GenerateBlob("blob 2 data"), GenerateBlob("blob 3 data") }; } private static Blob GenerateBlob(string content) diff --git a/Core/IntegrationTests/ServerTransportTests.cs b/Core/IntegrationTests/ServerTransportTests.cs index 3248760cc4..9a9d479b0a 100644 --- a/Core/IntegrationTests/ServerTransportTests.cs +++ b/Core/IntegrationTests/ServerTransportTests.cs @@ -25,9 +25,7 @@ public async Task InitialSetup() account = await Fixtures.SeedUser().ConfigureAwait(false); client = new Client(account); - streamId = client - .StreamCreate(new StreamCreateInput { description = "Flobber", name = "Blobber" }) - .Result; + streamId = client.StreamCreate(new StreamCreateInput { description = "Flobber", name = "Blobber" }).Result; } [SetUp] @@ -59,9 +57,7 @@ public async Task SendObject() { var myObject = Fixtures.GenerateNestedObject(); - var objectId = await Operations - .Send(myObject, new List { transport }) - .ConfigureAwait(false); + var objectId = await Operations.Send(myObject, new List { transport }).ConfigureAwait(false); var test = objectId; Assert.IsNotNull(test); @@ -73,9 +69,7 @@ public async Task SendAndReceiveObjectWithBlobs() var myObject = Fixtures.GenerateSimpleObject(); myObject["blobs"] = Fixtures.GenerateThreeBlobs(); - var sentObjectId = await Operations - .Send(myObject, new List { transport }) - .ConfigureAwait(false); + var sentObjectId = await Operations.Send(myObject, new List { transport }).ConfigureAwait(false); // NOTE: used to debug diffing // await Operations.Send(myObject, new List { transport }); diff --git a/Core/IntegrationTests/Subscriptions/Branches.cs b/Core/IntegrationTests/Subscriptions/Branches.cs index a8176a99de..1a28e405e3 100644 --- a/Core/IntegrationTests/Subscriptions/Branches.cs +++ b/Core/IntegrationTests/Subscriptions/Branches.cs @@ -24,11 +24,7 @@ public async Task Setup() [Test, Order(0)] public async Task SubscribeBranchCreated() { - var streamInput = new StreamCreateInput - { - description = "Hello World", - name = "Super Stream 01" - }; + var streamInput = new StreamCreateInput { description = "Hello World", name = "Super Stream 01" }; streamId = await client.StreamCreate(streamInput).ConfigureAwait(false); Assert.NotNull(streamId); diff --git a/Core/IntegrationTests/Subscriptions/Commits.cs b/Core/IntegrationTests/Subscriptions/Commits.cs index 8dd789503b..e28651b179 100644 --- a/Core/IntegrationTests/Subscriptions/Commits.cs +++ b/Core/IntegrationTests/Subscriptions/Commits.cs @@ -33,11 +33,7 @@ public async Task Setup() //[Ignore("Ironically, it fails.")] public async Task SubscribeCommitCreated() { - var streamInput = new StreamCreateInput - { - description = "Hello World", - name = "Super Stream 01" - }; + var streamInput = new StreamCreateInput { description = "Hello World", name = "Super Stream 01" }; streamId = await client.StreamCreate(streamInput).ConfigureAwait(false); Assert.NotNull(streamId); diff --git a/Core/IntegrationTests/Subscriptions/Streams.cs b/Core/IntegrationTests/Subscriptions/Streams.cs index ee8a348ce8..87d6d13e7a 100644 --- a/Core/IntegrationTests/Subscriptions/Streams.cs +++ b/Core/IntegrationTests/Subscriptions/Streams.cs @@ -29,11 +29,7 @@ public async Task SubscribeStreamAdded() Thread.Sleep(1000); //let server catch-up - var streamInput = new StreamCreateInput - { - description = "Hello World", - name = "Super Stream 01" - }; + var streamInput = new StreamCreateInput { description = "Hello World", name = "Super Stream 01" }; var res = await client.StreamCreate(streamInput).ConfigureAwait(true); streamId = res; diff --git a/Core/Tests/BaseTests.cs b/Core/Tests/BaseTests.cs index bdc55aa126..b78cd75cff 100755 --- a/Core/Tests/BaseTests.cs +++ b/Core/Tests/BaseTests.cs @@ -126,9 +126,7 @@ public void CanGetMembers() Assert.That(names, Has.Member(nameof(@base.attachedProp))); } - [Test( - Description = "Checks that only instance properties are returned, excluding obsolete and ignored." - )] + [Test(Description = "Checks that only instance properties are returned, excluding obsolete and ignored.")] public void CanGetMembers_OnlyInstance() { var @base = new SampleObject(); @@ -156,9 +154,7 @@ public void CanGetMembers_OnlyInstance_IncludeIgnored() var @base = new SampleObject(); @base["dynamicProp"] = 123; - var names = @base - .GetMembers(DynamicBaseMemberType.Instance | DynamicBaseMemberType.SchemaIgnored) - .Keys; + var names = @base.GetMembers(DynamicBaseMemberType.Instance | DynamicBaseMemberType.SchemaIgnored).Keys; Assert.That(names, Has.Member(nameof(@base.IgnoredSchemaProp))); Assert.That(names, Has.Member(nameof(@base.attachedProp))); } @@ -169,9 +165,7 @@ public void CanGetMembers_OnlyInstance_IncludeObsolete() var @base = new SampleObject(); @base["dynamicProp"] = 123; - var names = @base - .GetMembers(DynamicBaseMemberType.Instance | DynamicBaseMemberType.Obsolete) - .Keys; + var names = @base.GetMembers(DynamicBaseMemberType.Instance | DynamicBaseMemberType.Obsolete).Keys; Assert.That(names, Has.Member(nameof(@base.ObsoleteSchemaProp))); Assert.That(names, Has.Member(nameof(@base.attachedProp))); } @@ -215,9 +209,7 @@ public void CanShallowCopy() var copy = sample.ShallowCopy(); var selectedMembers = - DynamicBaseMemberType.Dynamic - | DynamicBaseMemberType.Instance - | DynamicBaseMemberType.SchemaIgnored; + DynamicBaseMemberType.Dynamic | DynamicBaseMemberType.Instance | DynamicBaseMemberType.SchemaIgnored; var sampleMembers = sample.GetMembers(selectedMembers); var copyMembers = copy.GetMembers(selectedMembers); diff --git a/Core/Tests/Fixtures.cs b/Core/Tests/Fixtures.cs index 033cf33166..cc60e28e59 100644 --- a/Core/Tests/Fixtures.cs +++ b/Core/Tests/Fixtures.cs @@ -13,11 +13,7 @@ public class SetUp [OneTimeSetUp] public void BeforeAll() { - SpeckleLog.Initialize( - "Core", - "Testing", - new SpeckleLogConfiguration(logToFile: false, logToSeq: false) - ); + SpeckleLog.Initialize("Core", "Testing", new SpeckleLogConfiguration(logToFile: false, logToSeq: false)); SpeckleLog.Logger.Information("Initialized logger for testing"); } } @@ -26,10 +22,7 @@ public abstract class Fixtures { private static SQLiteTransport AccountStorage = new(scope: "Accounts"); - private static string accountPath = Path.Combine( - SpecklePathProvider.AccountsFolderPath, - "TestAccount.json" - ); + private static string accountPath = Path.Combine(SpecklePathProvider.AccountsFolderPath, "TestAccount.json"); public static void UpdateOrSaveAccount(Account account) { diff --git a/Core/Tests/GraphQLClient.cs b/Core/Tests/GraphQLClient.cs index 9e6979ea85..afb232808a 100644 --- a/Core/Tests/GraphQLClient.cs +++ b/Core/Tests/GraphQLClient.cs @@ -36,10 +36,7 @@ private static IEnumerable ErrorCases() typeof(SpeckleGraphQLInternalErrorException), new Map { { "code", "INTERNAL_SERVER_ERROR" } } ); - yield return new TestCaseData( - typeof(SpeckleGraphQLException), - new Map { { "foo", "bar" } } - ); + yield return new TestCaseData(typeof(SpeckleGraphQLException), new Map { { "foo", "bar" } }); } [Test, TestCaseSource(nameof(ErrorCases))] @@ -111,10 +108,7 @@ public async Task TestExecuteWithResiliencePoliciesRetry() { counter++; if (counter < maxRetryCount) - throw new SpeckleGraphQLInternalErrorException( - new GraphQLRequest(), - new GraphQLResponse() - ); + throw new SpeckleGraphQLInternalErrorException(new GraphQLRequest(), new GraphQLResponse()); return expectedResult; }) .ConfigureAwait(false); diff --git a/Core/Tests/Hashing.cs b/Core/Tests/Hashing.cs index cf64edc7f7..23c8f9e352 100644 --- a/Core/Tests/Hashing.cs +++ b/Core/Tests/Hashing.cs @@ -51,10 +51,7 @@ public void HashingPerformance() var h2 = polyline.GetId(); var diff1 = stopWatch.ElapsedMilliseconds - stopWatchStep; - Assert.True( - diff1 < 300, - $"Hashing shouldn't take that long ({diff1} ms) for the test object used." - ); + Assert.True(diff1 < 300, $"Hashing shouldn't take that long ({diff1} ms) for the test object used."); Console.WriteLine($"Big obj hash duration: {diff1} ms"); var pt = new Point @@ -67,16 +64,11 @@ public void HashingPerformance() var h3 = pt.GetId(); var diff2 = stopWatch.ElapsedMilliseconds - stopWatchStep; - Assert.True( - diff2 < 10, - $"Hashing shouldn't take that long ({diff2} ms)for the point object used." - ); + Assert.True(diff2 < 10, $"Hashing shouldn't take that long ({diff2} ms)for the point object used."); Console.WriteLine($"Small obj hash duration: {diff2} ms"); } - [Test( - Description = "The hash of a decomposed object is different that that of a non-decomposed object." - )] + [Test(Description = "The hash of a decomposed object is different that that of a non-decomposed object.")] public void DecompositionHashes() { var table = new DiningTable(); diff --git a/Core/Tests/ObjectTraversal/GraphTraversalTests.cs b/Core/Tests/ObjectTraversal/GraphTraversalTests.cs index d4f0d507b5..18a501e002 100644 --- a/Core/Tests/ObjectTraversal/GraphTraversalTests.cs +++ b/Core/Tests/ObjectTraversal/GraphTraversalTests.cs @@ -8,10 +8,7 @@ namespace TestsUnit.ObjectTraversal; [TestFixture, TestOf(typeof(GraphTraversal))] public class GraphTraversalTests { - private static IEnumerable Traverse( - Base testCase, - params ITraversalRule[] rules - ) + private static IEnumerable Traverse(Base testCase, params ITraversalRule[] rules) { var sut = new GraphTraversal(rules); return sut.Traverse(testCase); @@ -24,10 +21,7 @@ public void Traverse_TraversesListMembers() .NewTraversalRule() .When(_ => true) .ContinueTraversing( - x => - x.GetMembers(DynamicBaseMemberType.All) - .Where(p => p.Value is IList) - .Select(kvp => kvp.Key) + x => x.GetMembers(DynamicBaseMemberType.All).Where(p => p.Value is IList).Select(kvp => kvp.Key) ); var expectTraverse = new Base { id = "List Member" }; @@ -59,10 +53,7 @@ public void Traverse_TraversesDictMembers() .NewTraversalRule() .When(_ => true) .ContinueTraversing( - x => - x.GetMembers(DynamicBaseMemberType.All) - .Where(p => p.Value is IDictionary) - .Select(kvp => kvp.Key) + x => x.GetMembers(DynamicBaseMemberType.All).Where(p => p.Value is IDictionary).Select(kvp => kvp.Key) ); var expectTraverse = new Base { id = "Dict Member" }; diff --git a/Core/Tests/SendReceiveLocal.cs b/Core/Tests/SendReceiveLocal.cs index 7dbebfe336..6aa91d4905 100644 --- a/Core/Tests/SendReceiveLocal.cs +++ b/Core/Tests/SendReceiveLocal.cs @@ -23,9 +23,7 @@ public void LocalUpload() myObject["@items"] = new List(); for (int i = 0; i < numObjects; i++) - ((List)myObject["@items"]).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-___/---" } - ); + ((List)myObject["@items"]).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-___/---" }); objId_01 = Operations.Send(myObject).Result; @@ -51,9 +49,7 @@ public void LocalUploadDownload() var rand = new Random(); for (int i = 0; i < numObjects; i++) - ((List)myObject["@items"]).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-___/---" } - ); + ((List)myObject["@items"]).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-___/---" }); objId_01 = Operations.Send(myObject).Result; @@ -72,9 +68,7 @@ public async Task LocalUploadDownloadSmall() var rand = new Random(); for (int i = 0; i < 30; i++) - ((List)myObject["@items"]).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-ugh/---" } - ); + ((List)myObject["@items"]).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-ugh/---" }); objId_01 = await Operations.Send(myObject).ConfigureAwait(false); @@ -105,10 +99,7 @@ public async Task LocalUploadDownloadListDic() Assert.NotNull(objId_01); var objsPulled = await Operations.Receive(objId_01).ConfigureAwait(false); - Assert.That( - ((List)((Dictionary)objsPulled["@dictionary"])["a"]).First(), - Is.EqualTo(1) - ); + Assert.That(((List)((Dictionary)objsPulled["@dictionary"])["a"]).First(), Is.EqualTo(1)); Assert.That(((List)objsPulled["@list"]).Last(), Is.EqualTo("ciao")); } @@ -124,19 +115,13 @@ public async Task UploadDownloadNonCommitObject() var rand = new Random(); for (int i = 0; i < 30; i++) - ((List)((dynamic)obj).LayerA).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "foo" } - ); + ((List)((dynamic)obj).LayerA).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "foo" }); for (int i = 0; i < 30; i++) - ((List)((dynamic)obj).LayerB).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "bar" } - ); + ((List)((dynamic)obj).LayerB).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "bar" }); for (int i = 0; i < 30; i++) - ((List)((dynamic)obj)["@LayerC"]).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "baz" } - ); + ((List)((dynamic)obj)["@LayerC"]).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "baz" }); objId_01 = await Operations.Send(obj).ConfigureAwait(false); @@ -170,9 +155,7 @@ public async Task UploadProgressReports() var rand = new Random(); for (int i = 0; i < 30; i++) - ((List)myObject["items"]).Add( - new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-fab/---" } - ); + ((List)myObject["items"]).Add(new Point(i, i, i + rand.NextDouble()) { applicationId = i + "-fab/---" }); ConcurrentDictionary progress = null; commitId_02 = await Operations @@ -206,9 +189,7 @@ public async Task DownloadProgressReports() Assert.GreaterOrEqual(progress.Keys.Count, 1); } - [Test( - Description = "Should dispose of transports after a send or receive operation if so specified." - )] + [Test(Description = "Should dispose of transports after a send or receive operation if so specified.")] public async Task ShouldDisposeTransports() { var @base = new Base(); @@ -233,9 +214,7 @@ await Operations } myLocalTransport = myLocalTransport.Clone() as SQLiteTransport; - var obj = await Operations - .Receive(id, null, myLocalTransport, disposeTransports: true) - .ConfigureAwait(false); + var obj = await Operations.Receive(id, null, myLocalTransport, disposeTransports: true).ConfigureAwait(false); try { @@ -255,12 +234,8 @@ public async Task ShouldNotDisposeTransports() @base["test"] = "the best"; var myLocalTransport = new SQLiteTransport(); - var id = await Operations - .Send(@base, new List { myLocalTransport }, false) - .ConfigureAwait(false); - await Operations - .Send(@base, new List { myLocalTransport }, false) - .ConfigureAwait(false); + var id = await Operations.Send(@base, new List { myLocalTransport }, false).ConfigureAwait(false); + await Operations.Send(@base, new List { myLocalTransport }, false).ConfigureAwait(false); var obj = await Operations.Receive(id, null, myLocalTransport).ConfigureAwait(false); await Operations.Receive(id, null, myLocalTransport).ConfigureAwait(false); diff --git a/Core/Tests/SerializationTests.cs b/Core/Tests/SerializationTests.cs index 651e711927..4fd6602b50 100644 --- a/Core/Tests/SerializationTests.cs +++ b/Core/Tests/SerializationTests.cs @@ -74,11 +74,7 @@ public void InterfacePropHandling() if (i % 2 == 0) { cat.Whiskers.Add( - new Line - { - Start = new Point(i / 2, i / 2, i / 2), - End = new Point(i + 3.14, i + 3.14, i + 3.14) - } + new Line { Start = new Point(i / 2, i / 2, i / 2), End = new Point(i + 3.14, i + 3.14, i + 3.14) } ); } else @@ -90,11 +86,7 @@ public void InterfacePropHandling() cat.Whiskers.Add(brokenWhisker); } - cat.Fur[i] = new Line - { - Start = new Point(i, i, i), - End = new Point(i + 3.14, i + 3.14, i + 3.14) - }; + cat.Fur[i] = new Line { Start = new Point(i, i, i), End = new Point(i + 3.14, i + 3.14, i + 3.14) }; } var result = Operations.Serialize(cat); diff --git a/Core/Tests/SerializerNonBreakingChanges.cs b/Core/Tests/SerializerNonBreakingChanges.cs index de46f49a3a..be4307b4d7 100644 --- a/Core/Tests/SerializerNonBreakingChanges.cs +++ b/Core/Tests/SerializerNonBreakingChanges.cs @@ -12,9 +12,7 @@ namespace Tests.Models; /// [ TestFixture, - Description( - "For certain types, changing property from one type to another should be implicitly backwards compatible" - ) + Description("For certain types, changing property from one type to another should be implicitly backwards compatible") ] public class SerializerNonBreakingChanges : PrimitiveTestFixture { @@ -142,9 +140,7 @@ public void StringToEnum_ShouldThrow(MyEnum testCase) [ Test, - Description( - "Deserialization of a JTokenType.Float to a .NET short/int/long should throw exception" - ), + Description("Deserialization of a JTokenType.Float to a .NET short/int/long should throw exception"), TestCaseSource(nameof(Float64TestCases)), TestCase(1e+30) ] @@ -245,21 +241,9 @@ public abstract class PrimitiveTestFixture public static int[] Int32TestCases = { int.MinValue, int.MaxValue }; public static long[] Int64TestCases = { long.MaxValue, long.MinValue }; - public static double[] Float64TestCases = - { - default, - double.Epsilon, - double.MaxValue, - double.MinValue - }; + public static double[] Float64TestCases = { default, double.Epsilon, double.MaxValue, double.MinValue }; - public static float[] Float32TestCases = - { - default, - float.Epsilon, - float.MaxValue, - float.MinValue - }; + public static float[] Float32TestCases = { default, float.Epsilon, 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 d50c1fa745..29123f9857 100644 --- a/Core/Tests/TestKit.cs +++ b/Core/Tests/TestKit.cs @@ -9,8 +9,7 @@ namespace Tests; /// public class TestKit : ISpeckleKit { - public IEnumerable Types => - GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); + public IEnumerable Types => GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); public string Description => "Simple object model for with some types for tests."; diff --git a/Core/Tests/TraversalTests.cs b/Core/Tests/TraversalTests.cs index 66e57b406d..eb68223f41 100644 --- a/Core/Tests/TraversalTests.cs +++ b/Core/Tests/TraversalTests.cs @@ -38,13 +38,7 @@ public void TestFlattenWithBreaker() Assert.That(ret.Where(x => x.id.Contains("should have ignored me")), Is.Empty); } - [ - Test, - TestCase(5, 5), - TestCase(5, 10), - TestCase(10, 5), - Description("Tests breaking after a fixed number of items") - ] + [Test, TestCase(5, 5), TestCase(5, 10), TestCase(10, 5), Description("Tests breaking after a fixed number of items")] public void TestBreakerFixed(int nestDepth, int flattenDepth) { //Setup @@ -67,11 +61,7 @@ public void TestBreakerFixed(int nestDepth, int flattenDepth) Assert.That(ret, Is.Unique); } - [ - Test, - Timeout(2000), - Description("Tests that the flatten function does not get stuck on circular references") - ] + [Test, Timeout(2000), Description("Tests that the flatten function does not get stuck on circular references")] public void TestCircularReference() { //Setup diff --git a/Core/Tests/Wrapper.cs b/Core/Tests/Wrapper.cs index 1861f06efa..a3828834d1 100644 --- a/Core/Tests/Wrapper.cs +++ b/Core/Tests/Wrapper.cs @@ -22,9 +22,7 @@ public void ParseBranch() Assert.That(wrapperCrazy.BranchName, Is.EqualTo("🍕⬅🌟 you wat?")); Assert.That(wrapperCrazy.Type, Is.EqualTo(StreamWrapperType.Branch)); - wrapperCrazy = new StreamWrapper( - "https://testing.speckle.dev/streams/4c3ce1459c/branches/next%20level" - ); + wrapperCrazy = new StreamWrapper("https://testing.speckle.dev/streams/4c3ce1459c/branches/next%20level"); Assert.That(wrapperCrazy.BranchName, Is.EqualTo("next level")); Assert.That(wrapperCrazy.Type, Is.EqualTo(StreamWrapperType.Branch)); } @@ -41,9 +39,7 @@ public void ParseObject() [Test] public void ParseCommit() { - var wrapper = new StreamWrapper( - "https://testing.speckle.dev/streams/4c3ce1459c/commits/8b9b831792" - ); + var wrapper = new StreamWrapper("https://testing.speckle.dev/streams/4c3ce1459c/commits/8b9b831792"); Assert.That(wrapper.Type, Is.EqualTo(StreamWrapperType.Commit)); } @@ -57,9 +53,7 @@ public void ParseGlobalAsBranch() [Test] public void ParseGlobalAsCommit() { - var wrapper = new StreamWrapper( - "https://testing.speckle.dev/streams/0c6ad366c4/globals/abd3787893" - ); + var wrapper = new StreamWrapper("https://testing.speckle.dev/streams/0c6ad366c4/globals/abd3787893"); Assert.That(wrapper.Type, Is.EqualTo(StreamWrapperType.Commit)); } } diff --git a/Core/Transports/MongoDBTransport/MongoDB.cs b/Core/Transports/MongoDBTransport/MongoDB.cs index e252ea06ed..9422fd0d5a 100644 --- a/Core/Transports/MongoDBTransport/MongoDB.cs +++ b/Core/Transports/MongoDBTransport/MongoDB.cs @@ -75,8 +75,7 @@ public void Dispose() public string TransportName { get; set; } = "MongoTransport"; - public Dictionary TransportContext => - new() { { "name", TransportName }, { "type", GetType().Name } }; + public Dictionary TransportContext => new() { { "name", TransportName }, { "type", GetType().Name } }; public CancellationToken CancellationToken { get; set; } @@ -224,11 +223,7 @@ public void SaveObject(string hash, ITransport sourceTransport) /// public void SaveObjectSync(string hash, string serializedObject) { - var document = new BsonDocument - { - { Field.hash.ToString(), hash }, - { Field.content.ToString(), serializedObject } - }; + var document = new BsonDocument { { Field.hash.ToString(), hash }, { Field.content.ToString(), serializedObject } }; Collection.InsertOne(document); } diff --git a/Directory.Build.props b/Directory.Build.props index 2af6843a1b..64b5e4460d 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -25,6 +25,7 @@ CS1591;CS1573;CS1572;CS1570;CS1587;CS1574;CS1711;CS1734; CS8618;CS8602;CS8600; CS1998; IDE0007; CS0618 + CA1054 diff --git a/Objects/Objects/BuiltElements/AdvanceSteel/AsteelPlate.cs b/Objects/Objects/BuiltElements/AdvanceSteel/AsteelPlate.cs index 3404d136eb..7382661ac6 100644 --- a/Objects/Objects/BuiltElements/AdvanceSteel/AsteelPlate.cs +++ b/Objects/Objects/BuiltElements/AdvanceSteel/AsteelPlate.cs @@ -18,7 +18,7 @@ public AsteelPlate(SectionProfile profile, Polyline outline, string units, Struc } public AsteelPlate() { } - + [SchemaInfo("AsteelPlate", "Creates a Advance Steel plate.", "Advance Steel", "Structure")] public AsteelPlate(Polyline outline, string units, StructuralMaterial material = null) { diff --git a/Objects/Objects/BuiltElements/AdvanceSteel/AsteelSlab.cs b/Objects/Objects/BuiltElements/AdvanceSteel/AsteelSlab.cs index 422471b48d..ec8086bdb5 100644 --- a/Objects/Objects/BuiltElements/AdvanceSteel/AsteelSlab.cs +++ b/Objects/Objects/BuiltElements/AdvanceSteel/AsteelSlab.cs @@ -1,30 +1,25 @@ using System.Collections.Generic; using Objects.Geometry; using Objects.Structural.Materials; -using Objects.Structural.Properties.Profiles; using Speckle.Core.Kits; using Speckle.Core.Models; -namespace Objects.BuiltElements.AdvanceSteel +namespace Objects.BuiltElements.AdvanceSteel; + +public class AsteelSlab : Area, IDisplayValue>, IHasArea, IHasVolume, IAsteelObject { - public class AsteelSlab : Area, IDisplayValue>, IHasArea, IHasVolume, IAsteelObject + [SchemaInfo("AsteelSlab", "Creates a Advance Steel slab.", "Advance Steel", "Structure")] + public AsteelSlab(Polyline outline, string units, StructuralMaterial material = null) { - [DetachProperty] - public StructuralMaterial material { get; set; } - - public Base userAttributes { get; set; } + this.outline = outline; + this.material = material; + this.units = units; + } - [SchemaInfo("AsteelSlab", "Creates a Advance Steel slab.", "Advance Steel", "Structure")] - public AsteelSlab(Polyline outline, string units, StructuralMaterial material = null) - { - this.outline = outline; - this.material = material; - this.units = units; - } + public AsteelSlab() { } + [DetachProperty] + public StructuralMaterial material { get; set; } - public AsteelSlab() - { - } - } + public Base userAttributes { get; set; } } diff --git a/Objects/Objects/Geometry/BrepEdge.cs b/Objects/Objects/Geometry/BrepEdge.cs index 1b0540ada4..c8f3c8d06a 100644 --- a/Objects/Objects/Geometry/BrepEdge.cs +++ b/Objects/Objects/Geometry/BrepEdge.cs @@ -34,6 +34,7 @@ Interval domain [JsonIgnore] public Brep Brep { get; set; } + public int Curve3dIndex { get; set; } public int[] TrimIndices { get; set; } public int StartIndex { get; set; } diff --git a/Objects/Objects/Geometry/BrepFace.cs b/Objects/Objects/Geometry/BrepFace.cs index dc993c5a33..6f9d52a7e0 100644 --- a/Objects/Objects/Geometry/BrepFace.cs +++ b/Objects/Objects/Geometry/BrepFace.cs @@ -23,6 +23,7 @@ public BrepFace(Brep brep, int surfaceIndex, List loopIndices, int outerLoo [JsonIgnore] public Brep Brep { get; set; } + public int SurfaceIndex { get; set; } public List LoopIndices { get; set; } public int OuterLoopIndex { get; set; } diff --git a/Objects/Objects/Geometry/BrepLoop.cs b/Objects/Objects/Geometry/BrepLoop.cs index 782d0a3ff5..b84246ed7e 100644 --- a/Objects/Objects/Geometry/BrepLoop.cs +++ b/Objects/Objects/Geometry/BrepLoop.cs @@ -22,6 +22,7 @@ public BrepLoop(Brep brep, int faceIndex, List trimIndices, BrepLoopType ty [JsonIgnore] public Brep Brep { get; set; } + public int FaceIndex { get; set; } public List TrimIndices { get; set; } public BrepLoopType Type { get; set; } diff --git a/Objects/Objects/Geometry/BrepTrim.cs b/Objects/Objects/Geometry/BrepTrim.cs index 9e525122f3..8040f29fe3 100644 --- a/Objects/Objects/Geometry/BrepTrim.cs +++ b/Objects/Objects/Geometry/BrepTrim.cs @@ -36,6 +36,7 @@ int endIndex [JsonIgnore] public Brep Brep { get; set; } + public int EdgeIndex { get; set; } public int StartIndex { get; set; } public int EndIndex { get; set; } diff --git a/Objects/Objects/Geometry/Mesh.cs b/Objects/Objects/Geometry/Mesh.cs index 3bf9159636..93dc2410be 100644 --- a/Objects/Objects/Geometry/Mesh.cs +++ b/Objects/Objects/Geometry/Mesh.cs @@ -148,7 +148,7 @@ public List GetPoints() /// Gets a texture coordinate as a by /// /// The index of the texture coordinate - /// Texture coordinate as a + /// Texture coordinate as a public (double, double) GetTextureCoordinate(int index) { index *= 2; diff --git a/Objects/Objects/Geometry/Point.cs b/Objects/Objects/Geometry/Point.cs index 3535bdebd5..d5f61998d9 100644 --- a/Objects/Objects/Geometry/Point.cs +++ b/Objects/Objects/Geometry/Point.cs @@ -110,7 +110,7 @@ public bool TransformTo(Transform transform, out ITransformable transformed) /// A list of coordinates {x, y, z} public List ToList() { - return new List() { x, y, z }; + return new List { x, y, z }; } /// diff --git a/Objects/Tests/GenericTests.cs b/Objects/Tests/GenericTests.cs index f229410b56..bcc522b9b4 100644 --- a/Objects/Tests/GenericTests.cs +++ b/Objects/Tests/GenericTests.cs @@ -21,17 +21,23 @@ public static IEnumerable NonAbstractTypesInKit() { return AvailableTypesInKit().Where(t => !t.IsAbstract); } - - [Test(Description = "Checks that all objects inside the Default Kit have empty constructors.")] - [TestCaseSource(nameof(NonAbstractTypesInKit))] + + [ + Test(Description = "Checks that all objects inside the Default Kit have empty constructors."), + TestCaseSource(nameof(NonAbstractTypesInKit)) + ] public void ObjectHasEmptyConstructor(Type t) { var constructor = t.GetConstructor(Type.EmptyTypes); Assert.That(constructor, Is.Not.Null); } - [Test(Description = "Checks that all methods with the 'SchemaComputed' attribute inside the Default Kit have no parameters.")] - [TestCaseSource(nameof(AvailableTypesInKit))] + [ + Test( + Description = "Checks that all methods with the 'SchemaComputed' attribute inside the Default Kit have no parameters." + ), + TestCaseSource(nameof(AvailableTypesInKit)) + ] public void SchemaComputedMethod_CanBeCalledWithNoParameters(Type t) { t.GetMethods() diff --git a/Objects/Tests/NUnit_Fixtures.cs b/Objects/Tests/NUnit_Fixtures.cs index 8f43c57c85..ad5253ebff 100644 --- a/Objects/Tests/NUnit_Fixtures.cs +++ b/Objects/Tests/NUnit_Fixtures.cs @@ -12,11 +12,7 @@ public void RunBeforeAnyTests() SpeckleLog.Initialize( "ObjectsTests", "Testing", - new SpeckleLogConfiguration( - logToConsole: false, - logToFile: false, - logToSeq: false - ) + new SpeckleLogConfiguration(logToConsole: false, logToFile: false, logToSeq: false) ); SpeckleLog.Logger.Information("Initialized logger for testing"); }