From 5f8b2614b04c6a6a8a57fff340a5b2ff7a1096f8 Mon Sep 17 00:00:00 2001 From: Sylwia Szunejko Date: Thu, 27 Mar 2025 11:35:20 +0100 Subject: [PATCH] Run dotnet format to fix formatting and run it in the CI --- .github/workflows/main.yml | 6 + .../Ado/AdoBasicTests.cs | 8 +- .../BaseIntegrationTest.cs | 32 ++--- .../Core/BasicTypeTests.cs | 12 +- .../Core/ClientTimeoutTests.cs | 24 ++-- .../Core/ClientWarningsTests.cs | 8 +- .../Core/ClusterPeersV2SimulacronTests.cs | 2 +- .../Core/ClusterTests.cs | 8 +- .../Core/CollectionsNestedTests.cs | 4 +- .../Core/CollectionsTests.cs | 124 ++++++++--------- .../Core/CompressionTests.cs | 2 +- .../Core/ConnectionSimulacronTests.cs | 16 +-- .../Core/ConnectionTests.cs | 20 +-- .../Core/ConsistencyTests.cs | 20 +-- .../Core/ControlConnectionSimulatorTests.cs | 2 +- .../Core/ControlConnectionTests.cs | 10 +- .../Core/CustomPayloadTests.cs | 4 +- .../Core/EmptyColumnTests.cs | 12 +- .../Core/ExceptionsTests.cs | 10 +- .../Core/HeartbeatTests.cs | 4 +- .../Core/LargeDataTests.cs | 2 +- .../Core/MetadataTests.cs | 14 +- .../Core/MultiThreadingTests.cs | 14 +- .../Core/PagingTests.cs | 6 +- .../Core/ParameterizedStatementsTests.cs | 8 +- .../Core/PoolShortTests.cs | 6 +- .../Core/PoolTests.cs | 2 +- .../Core/PrepareSimulatorTests.cs | 16 +-- .../Core/PreparedStatementsTests.cs | 128 +++++++++--------- .../Core/ReconnectionTests.cs | 26 ++-- .../Core/SchemaMetadataTests.cs | 12 +- .../Core/SessionExecuteAsyncTests.cs | 4 +- .../Core/SessionTests.cs | 4 +- .../Core/SpeculativeExecutionShortTests.cs | 4 +- .../Core/StressTests.cs | 6 +- .../Core/TimeUuidSerializationTests.cs | 6 +- .../Core/TimestampTests.cs | 2 +- .../Core/TypeSerializersTests.cs | 36 ++--- .../Core/UdfTests.cs | 20 +-- .../Core/UdtMappingsTests.cs | 28 ++-- .../CqlFunctions/Tests/MaxTimeUuid.cs | 2 +- .../CqlFunctions/Tests/Token.cs | 12 +- .../DataStax/Auth/ProxyAuthenticationTests.cs | 2 +- .../DataStax/Auth/SspiClientTests.cs | 14 +- .../DataStax/Cloud/CloudIntegrationTests.cs | 14 +- .../DataStax/Graph/CoreGraphTests.cs | 40 +++--- .../DataStax/Graph/GraphMultiNodeTests.cs | 16 +-- .../DataStax/Graph/GraphTests.cs | 40 +++--- .../Insights/InsightsIntegrationTests.cs | 10 +- .../DurationTests.cs | 6 +- .../LinqExecutionProfileTests.cs | 22 +-- .../MapperExecutionProfileTests.cs | 6 +- .../FoundBugs/FoundBugTests.cs | 4 +- .../Geometry/GeometryTests.cs | 6 +- .../Linq/CqlOperatorTests/Prepend.cs | 18 +-- .../Linq/LinqMethods/Counter.cs | 4 +- .../Linq/LinqMethods/Delete.cs | 40 +++--- .../Linq/LinqMethods/DeleteIf.cs | 8 +- .../Linq/LinqMethods/First.cs | 8 +- .../Linq/LinqMethods/FirstOrDefault.cs | 8 +- .../Linq/LinqMethods/Select.cs | 14 +- .../Linq/LinqMethods/Take.cs | 6 +- .../Linq/LinqMethods/UpdateIfTests.cs | 6 +- .../Linq/LinqMethods/Where.cs | 102 +++++++------- .../Linq/LinqRealClusterTests.cs | 8 +- .../Linq/LinqTable/CreateTable.cs | 88 ++++++------ .../Linq/LinqTable/GetTable.cs | 20 +-- .../Linq/Structures/AllDataTypesEntity.cs | 22 +-- .../Linq/Structures/AllDataTypesEntityUtil.cs | 10 +- .../Structures/EmptyClusteringColumnName.cs | 2 +- .../EntityWithAllCollectionTypes.cs | 2 +- .../Linq/Structures/EntityWithArrayType.cs | 2 +- .../Structures/EntityWithDictionaryType.cs | 4 +- .../Linq/Structures/EntityWithListType.cs | 2 +- .../Linq/Structures/ManyDataTypesEntity.cs | 4 +- .../Linq/Structures/Movie.cs | 18 +-- .../Mapping/Structures/Author.cs | 2 +- .../Mapping/Structures/ManyDataTypesPoco.cs | 4 +- .../Mapping/Tests/Attributes.cs | 2 +- .../Mapping/Tests/Counter.cs | 8 +- .../Mapping/Tests/CqlClientConfig.cs | 2 +- .../Mapping/Tests/Fetch.cs | 10 +- .../Mapping/Tests/First.cs | 12 +- .../Mapping/Tests/InsertTests.cs | 40 +++--- .../Mapping/Tests/Update.cs | 22 +-- .../TokenMapTopologyChangeTests.cs | 2 +- .../Metrics/MetricsTests.cs | 8 +- .../OpenTelemetry/OpenTelemetryTests.cs | 12 +- .../Tests/ColumnEncryptionPolicyTests.cs | 12 +- .../Policies/Tests/ConsistencyTests.cs | 6 +- .../Tests/LoadBalancingPolicyShortTests.cs | 8 +- .../Policies/Tests/ReconnectionPolicyTests.cs | 34 ++--- .../Policies/Util/PolicyTestTools.cs | 10 +- .../SharedCloudClusterTest.cs | 4 +- .../SharedClusterTest.cs | 10 +- .../SharedSimulacronTests.cs | 8 +- .../SimulacronAPI/DataType.cs | 18 +-- .../ConsistencyLevelEnumConverter.cs | 2 +- .../Converters/QueryTypeEnumConverter.cs | 2 +- .../SimulacronAPI/Models/Logs/BaseMessage.cs | 2 +- .../SimulacronAPI/Models/Logs/BatchMessage.cs | 4 +- .../SimulacronAPI/Models/Logs/Frame.cs | 12 +- .../SimulacronAPI/Models/Logs/QueryMessage.cs | 2 +- .../Models/Logs/QueryMessageOptions.cs | 16 +-- .../SimulacronAPI/Models/Logs/RequestLog.cs | 12 +- .../SimulacronAPI/PrimeBuilder/IWhenFluent.cs | 12 +- .../PrimeBuilder/PrimeRequestBuilder.cs | 2 +- .../PrimeBuilder/Then/ServerError.cs | 6 +- .../PrimeBuilder/Then/ThenAlreadyExists.cs | 2 +- .../PrimeBuilder/Then/ThenReadFailure.cs | 10 +- .../PrimeBuilder/Then/ThenWriteFailure.cs | 10 +- .../PrimeBuilder/When/IWhenQueryBuilder.cs | 6 +- .../PrimeBuilder/When/WhenBatchBuilder.cs | 4 +- .../PrimeBuilder/When/WhenQueryBuilder.cs | 12 +- .../SystemTables/StubTableColumn.cs | 8 +- .../SimulacronTest.cs | 18 +-- .../TestBase/QueryTools.cs | 4 +- .../TestBase/Randomm.cs | 16 +-- .../TestBase/TestHttpClient.cs | 2 +- .../TestBase/TestInfrastructureException.cs | 2 +- .../TestBase/TestUtils.cs | 12 +- .../TestClusterManagement/CcmBridge.cs | 4 +- .../TestClusterManagement/CcmCluster.cs | 8 +- .../CcmProcessExecuter.cs | 4 +- .../TestClusterManagement/CloudCluster.cs | 18 +-- .../TestClusterManagement/ITestCluster.cs | 4 +- .../LocalCcmProcessExecuter.cs | 2 +- .../RemoteCcmProcessExecuter.cs | 2 +- .../Simulacron/SimulacronCluster.cs | 10 +- .../Simulacron/SimulacronDataCenter.cs | 2 +- .../Simulacron/SimulacronNode.cs | 2 +- .../TestCloudClusterManager.cs | 4 +- .../TestClusterManager.cs | 2 +- .../TestDataTypes/Contact.cs | 4 +- .../TestDataTypes/Phone.cs | 2 +- .../TestDataTypes/UserFeedback.cs | 2 +- src/Cassandra.Tests/AbstractResponseTest.cs | 6 +- src/Cassandra.Tests/AdoUnitTests.cs | 2 +- src/Cassandra.Tests/ApiTests.cs | 2 +- .../AppMetricsExtension/HistogramTests.cs | 2 +- src/Cassandra.Tests/BuilderTests.cs | 30 ++-- src/Cassandra.Tests/ClusterTests.cs | 18 +-- src/Cassandra.Tests/CollectionTests.cs | 2 +- src/Cassandra.Tests/ConnectionTests.cs | 18 +-- .../Control/ControlConnectionTests.cs | 18 +-- .../Control/HostnameContactPointTests.cs | 26 ++-- .../Control/ResolvedContactPointTests.cs | 22 +-- .../Control/TopologyRefresherTests.cs | 64 ++++----- .../Connections/HostConnectionPoolTests.cs | 4 +- .../SniContactPointAndResolverTests.cs | 62 ++++----- .../TestHelpers/FakeConnectionEndPoint.cs | 2 +- .../TestHelpers/FakeConnectionFactory.cs | 6 +- .../TestHelpers/FakeMetadataRequestHandler.cs | 10 +- .../CustomTypeSerializerTests.cs | 2 +- .../Auth/DsePlainTextAuthProviderTests.cs | 4 +- .../Cloud/CloudConfigurationParserTests.cs | 52 +++---- .../Cloud/CloudMetadataServiceTests.cs | 2 +- .../CustomCaCertificateValidatorTests.cs | 2 +- .../DataStax/Graph/ExecuteGraphTests.cs | 12 +- .../DataStax/Graph/GraphNodeGraphSON1Tests.cs | 32 ++--- .../Insights/InsightTypeConverterTests.cs | 4 +- .../DataStax/Insights/InsightsClientTests.cs | 26 ++-- .../Insights/InsightsSupportVerifierTests.cs | 14 +- .../InsightsMessageFactoryTests.cs | 8 +- .../Search/DateRangeSerializerTests.cs | 2 +- .../DataStax/Search/DateRangeTests.cs | 18 +-- src/Cassandra.Tests/DataTypeParserTests.cs | 26 ++-- src/Cassandra.Tests/DurationTests.cs | 2 +- src/Cassandra.Tests/ExceptionsUnitTest.cs | 10 +- .../ExecutionProfiles/ClusterTests.cs | 82 +++++------ .../ExecutionProfiles/ConfigurationTests.cs | 24 ++-- .../ExecutionProfileBuilderTests.cs | 10 +- .../ExecutionProfiles/RequestHandlerTests.cs | 26 ++-- .../ExecutionProfileBuilderExtensions.cs | 2 +- .../Extensions/NumericTypeConstraint.cs | 4 +- .../Serializers/BigDecimalSerializer.cs | 4 +- .../Serializers/UdtSerializerWrapper.cs | 4 +- src/Cassandra.Tests/FrameParserTests.cs | 58 ++++---- .../Geometry/LineStringTests.cs | 2 +- src/Cassandra.Tests/Geometry/PointTests.cs | 8 +- src/Cassandra.Tests/Geometry/PolygonTests.cs | 2 +- .../HostConnectionPoolTests.cs | 16 +-- src/Cassandra.Tests/HostTests.cs | 4 +- src/Cassandra.Tests/IOUnitTests.cs | 6 +- src/Cassandra.Tests/KeyspaceMetadataTests.cs | 70 +++++----- src/Cassandra.Tests/LocalDateTests.cs | 4 +- src/Cassandra.Tests/LocalTimeTests.cs | 2 +- .../AttributeBasedTypeDefinitionTests.cs | 4 +- .../Mapping/CqlGeneratorTests.cs | 4 +- src/Cassandra.Tests/Mapping/DeleteTests.cs | 6 +- src/Cassandra.Tests/Mapping/FetchTests.cs | 22 +-- .../FluentMappings/FluentUserMapping.cs | 4 +- .../Linq/LinqBatchStatementUnitTests.cs | 2 +- .../Mapping/Linq/LinqEntryPointsTests.cs | 4 +- .../Mapping/Linq/LinqExecutionProfileTests.cs | 16 +-- .../Linq/LinqStatementPropertiesTests.cs | 6 +- .../Mapping/Linq/LinqToCqlFunctionTests.cs | 8 +- .../Mapping/Linq/LinqToCqlInsertUnitTests.cs | 42 +++--- .../Mapping/Linq/LinqToCqlSelectUnitTests.cs | 80 +++++------ .../Mapping/Linq/LinqToCqlUnitTests.cs | 60 ++++---- .../Mapping/Linq/LinqToCqlUpdateUnitTests.cs | 65 ++++----- .../LinqAttributeBasedTypeDefinitionTests.cs | 2 +- .../Mapping/MapperExecutionProfileTests.cs | 22 +-- .../Mapping/MappingTestBase.cs | 6 +- .../Mapping/Pocos/AttributeMappingClass.cs | 4 +- .../LinqDecoratedCaseInsensitiveEntity.cs | 2 +- .../Mapping/Pocos/PocoWithEnumCollections.cs | 4 +- .../Mapping/Pocos/PocoWithNumericTypes.cs | 2 +- src/Cassandra.Tests/Mapping/Pocos/Song.cs | 2 +- .../Mapping/Pocos/VectorEntity.cs | 2 +- .../Mapping/StatementFactoryTests.cs | 38 +++--- .../Mapping/TestData/TestDataGenerator.cs | 4 +- .../Mapping/TestData/TestDataHelper.cs | 8 +- .../Mapping/TypeConverterTests.cs | 6 +- src/Cassandra.Tests/Mapping/UpdateTests.cs | 42 +++--- .../Mapping/Utils/CqlIdentifierHelperTests.cs | 2 +- .../EverywhereStrategyTests.cs | 2 +- .../NetworkTopologyStrategyTests.cs | 18 +-- .../MetadataHelpers/ReplicationFactorTests.cs | 2 +- .../ReplicationStrategyTestData.cs | 4 +- .../MetadataHelpers/SimpleStrategyTests.cs | 6 +- .../TestHelpers/FakeSchemaParserFactory.cs | 2 +- .../MetadataTests/TaskBasedTimerTests.cs | 8 +- src/Cassandra.Tests/Metrics/MetricsTests.cs | 24 ++-- src/Cassandra.Tests/ObsoletedMemberTests.cs | 4 +- src/Cassandra.Tests/OpenTelemetryTests.cs | 8 +- .../OperationStateExtensions.cs | 6 +- .../Policies/DefaultLoadBalancingTests.cs | 2 +- src/Cassandra.Tests/PoliciesUnitTests.cs | 12 +- src/Cassandra.Tests/PreparedStatementTests.cs | 16 +-- src/Cassandra.Tests/ProtocolTests.cs | 10 +- src/Cassandra.Tests/RequestExecutionTests.cs | 18 +-- .../RequestHandlerMockTests.cs | 4 +- src/Cassandra.Tests/RequestHandlerTests.cs | 16 +-- .../GraphTypeSerializerFactoryTests.cs | 24 ++-- .../Requests/PrepareHandlerTests.cs | 106 +++++++-------- .../Requests/StartupOptionsFactoryTests.cs | 2 +- src/Cassandra.Tests/ResponseFrameTest.cs | 2 +- src/Cassandra.Tests/RowSetUnitTests.cs | 14 +- src/Cassandra.Tests/SchemaParserTests.cs | 22 +-- src/Cassandra.Tests/SerializerTests.cs | 64 ++++----- src/Cassandra.Tests/SessionTests.cs | 4 +- src/Cassandra.Tests/StatementTests.cs | 22 +-- src/Cassandra.Tests/TaskTests.cs | 4 +- .../TestAttributes/WinOnlyAttribute.cs | 2 +- src/Cassandra.Tests/TestCategory.cs | 8 +- .../TestConfigurationBuilder.cs | 6 +- src/Cassandra.Tests/TestHelper.cs | 2 +- .../TestHelpers/FakeInitializer.cs | 2 +- src/Cassandra.Tests/TestTimeoutAttribute.cs | 2 +- src/Cassandra.Tests/ThreadPerTaskScheduler.cs | 2 +- src/Cassandra.Tests/TimeUuidTests.cs | 12 +- src/Cassandra.Tests/TimeoutTests.cs | 14 +- src/Cassandra.Tests/TokenTests.cs | 80 +++++------ src/Cassandra.Tests/UtilsTests.cs | 10 +- src/Cassandra/AggregateMetadata.cs | 4 +- src/Cassandra/BeConverter.cs | 8 +- src/Cassandra/BigIntegerTypeAdapter.cs | 4 +- src/Cassandra/BoundStatement.cs | 20 +-- src/Cassandra/Builder.cs | 30 ++-- .../CassandraConnectionStringBuilder.cs | 4 +- src/Cassandra/Cluster.cs | 24 ++-- src/Cassandra/Collections/ArrayBackedList.cs | 3 +- .../Collections/ByteArrayComparer.cs | 2 +- .../Collections/CopyOnWriteDictionary.cs | 6 +- .../Collections/ReadOnlyCollection.cs | 2 +- .../Compression/Snappy/SnappyDecompressor.cs | 12 +- src/Cassandra/Configuration.cs | 12 +- src/Cassandra/Connections/Connection.cs | 14 +- .../Connections/ConnectionEndpoint.cs | 2 +- .../Connections/ConnectionFactory.cs | 8 +- .../Connections/Control/ContactPointParser.cs | 36 ++--- .../Connections/Control/ControlConnection.cs | 26 ++-- .../Control/ControlConnectionFactory.cs | 12 +- .../Connections/Control/IControlConnection.cs | 6 +- .../Control/IControlConnectionFactory.cs | 4 +- .../Control/IProtocolVersionNegotiator.cs | 2 +- .../Control/IpLiteralContactPoint.cs | 2 +- .../Connections/Control/TopologyRefresher.cs | 30 ++-- src/Cassandra/Connections/EndPointResolver.cs | 2 +- .../Connections/HostConnectionPool.cs | 40 +++--- .../Connections/HostnameContactPoint.cs | 10 +- src/Cassandra/Connections/IConnection.cs | 12 +- .../Connections/IConnectionEndpoint.cs | 2 +- .../Connections/IHostConnectionPool.cs | 8 +- src/Cassandra/Connections/RequestError.cs | 8 +- src/Cassandra/Connections/TcpSocket.cs | 12 +- src/Cassandra/CqlQueryTools.cs | 2 +- src/Cassandra/Data/CqlCommand.cs | 9 +- src/Cassandra/Data/CqlConnection.cs | 4 +- src/Cassandra/Data/CqlParameter.cs | 2 +- src/Cassandra/Data/CqlParameterCollection.cs | 8 +- src/Cassandra/Data/CqlProviderFactory.cs | 2 +- src/Cassandra/Data/CqlReader.cs | 24 ++-- src/Cassandra/Data/Linq/Batch.cs | 10 +- src/Cassandra/Data/Linq/BatchV1.cs | 2 +- src/Cassandra/Data/Linq/BatchV2.cs | 2 +- .../Data/Linq/ClientProjectionCqlQuery.cs | 2 +- .../Data/Linq/CqlConditionalCommand.cs | 8 +- .../Data/Linq/CqlExpressionVisitor.cs | 82 +++++------ src/Cassandra/Data/Linq/CqlFunction.cs | 8 +- src/Cassandra/Data/Linq/CqlMthHelps.cs | 28 ++-- src/Cassandra/Data/Linq/CqlOperator.cs | 8 +- src/Cassandra/Data/Linq/CqlQuery.cs | 8 +- src/Cassandra/Data/Linq/CqlQueryBase.cs | 12 +- src/Cassandra/Data/Linq/CqlQueryExtensions.cs | 44 +++--- .../Data/Linq/CqlQuerySingleElement.cs | 4 +- src/Cassandra/Data/Linq/CqlScalar.cs | 4 +- src/Cassandra/Data/Linq/CqlToken.cs | 12 +- .../ExpressionParsing/BinaryConditionItem.cs | 2 +- .../LinqAttributeBasedColumnDefinition.cs | 12 +- .../Linq/LinqAttributeBasedTypeDefinition.cs | 4 +- src/Cassandra/Data/Linq/ParsePhase.cs | 4 +- src/Cassandra/Data/Linq/SessionExtensions.cs | 8 +- src/Cassandra/Data/Linq/Table.cs | 6 +- src/Cassandra/Data/Linq/TableAttribute.cs | 2 +- src/Cassandra/Data/Linq/VisitingParam.cs | 2 +- src/Cassandra/DataCollectionMetadata.cs | 2 +- .../DataStax/Auth/DseGssapiAuthProvider.cs | 2 +- .../Auth/Sspi/Buffers/SecureBuffer.cs | 4 +- .../Auth/Sspi/Buffers/SecureBufferAdapter.cs | 44 +++--- .../Auth/Sspi/Buffers/SecureBufferDesc.cs | 2 +- .../Auth/Sspi/Buffers/SecureBufferType.cs | 2 +- .../DataStax/Auth/Sspi/ByteWriter.cs | 34 ++--- .../Auth/Sspi/Contexts/ClientContext.cs | 50 +++---- .../DataStax/Auth/Sspi/Contexts/Context.cs | 74 +++++----- .../Auth/Sspi/Contexts/ContextAttrib.cs | 10 +- .../Sspi/Contexts/ContextNativeMethods.cs | 104 +++++++------- .../Auth/Sspi/Contexts/ContextQueries.cs | 4 +- .../Auth/Sspi/Contexts/SafeContextHandle.cs | 2 +- .../Auth/Sspi/Credentials/ClientCredential.cs | 4 +- .../Auth/Sspi/Credentials/Credential.cs | 40 +++--- .../Credentials/CredentialNativeMethods.cs | 12 +- .../Sspi/Credentials/CurrentCredential.cs | 12 +- .../Auth/Sspi/Credentials/QueryNameSupport.cs | 2 +- .../Sspi/Credentials/SafeCredentialHandle.cs | 2 +- .../Auth/Sspi/Credentials/ServerCredential.cs | 4 +- src/Cassandra/DataStax/Auth/Sspi/EnumMgr.cs | 28 ++-- .../DataStax/Auth/Sspi/NativeMethods.cs | 18 +-- .../DataStax/Auth/Sspi/PackageSupport.cs | 42 +++--- .../DataStax/Auth/Sspi/SecPkgInfo.cs | 46 +++---- .../DataStax/Auth/Sspi/SecurityStatus.cs | 108 +++++++-------- .../DataStax/Auth/Sspi/SspiException.cs | 36 ++--- .../DataStax/Auth/Sspi/SspiHandle.cs | 10 +- src/Cassandra/DataStax/Auth/Sspi/TimeStamp.cs | 8 +- src/Cassandra/DataStax/Auth/SspiClient.cs | 2 +- .../DataStax/Cloud/CloudConfiguration.cs | 2 +- .../Cloud/CloudConfigurationParser.cs | 4 +- .../DataStax/Cloud/CloudMetadataService.cs | 10 +- src/Cassandra/DataStax/Cloud/ContactInfo.cs | 2 +- .../Cloud/CustomCACertificateValidator.cs | 2 +- src/Cassandra/DataStax/Graph/Edge.cs | 2 +- src/Cassandra/DataStax/Graph/Element.cs | 6 +- src/Cassandra/DataStax/Graph/EnumWrapper.cs | 2 +- .../DataStax/Graph/FluentGraphStatement.cs | 18 +-- src/Cassandra/DataStax/Graph/GraphNode.cs | 10 +- src/Cassandra/DataStax/Graph/GraphOptions.cs | 14 +- .../DataStax/Graph/IGraphStatement.cs | 2 +- src/Cassandra/DataStax/Graph/IPath.cs | 2 +- src/Cassandra/DataStax/Graph/IProperty.cs | 2 +- src/Cassandra/DataStax/Graph/Path.cs | 2 +- src/Cassandra/DataStax/Graph/Property.cs | 12 +- .../DataStax/Graph/SimpleGraphStatement.cs | 2 +- src/Cassandra/DataStax/Graph/Traverser.cs | 2 +- src/Cassandra/DataStax/Graph/Vertex.cs | 18 +-- .../DataStax/Graph/VertexProperty.cs | 18 +-- .../ConfigAntiPatternsInfoProvider.cs | 22 +-- .../StartupMessage/DataCentersInfoProvider.cs | 2 +- .../ExecutionProfileInfoProvider.cs | 2 +- .../ReconnectionPolicyInfoProvider.cs | 12 +- .../StartupMessage/RetryPolicyInfoProvider.cs | 2 +- .../DataStax/Insights/InsightsClient.cs | 14 +- .../Insights/InsightsSupportVerifier.cs | 2 +- .../InsightsMetadataTimestampGenerator.cs | 2 +- .../InsightsStartupMessageFactory.cs | 6 +- .../CompressionTypeInsightsConverter.cs | 2 +- .../ConsistencyInsightsConverter.cs | 2 +- .../InsightTypeInsightsConverter.cs | 2 +- .../Converters/InsightsEnumConverter.cs | 6 +- .../DataStax/Insights/Schema/Insight.cs | 2 +- .../StartupMessage/ExecutionProfileInfo.cs | 2 +- .../StatusMessage/InsightsStatusData.cs | 2 +- src/Cassandra/DataStax/Search/DateRange.cs | 4 +- .../DataStax/Search/DateRangeBound.cs | 18 +-- .../DataStax/Search/DateRangePrecision.cs | 10 +- src/Cassandra/DecimalTypeAdapter.cs | 2 +- src/Cassandra/Duration.cs | 22 +-- src/Cassandra/DynamicCompositeTypeAdapter.cs | 4 +- src/Cassandra/EndianBitConverter.cs | 24 ++-- src/Cassandra/Exceptions/BusyPoolException.cs | 4 +- src/Cassandra/Exceptions/DriverException.cs | 4 +- .../Exceptions/DriverInternalError.cs | 4 +- .../Exceptions/FunctionFailureException.cs | 2 +- .../Exceptions/InitFatalErrorException.cs | 2 +- .../Exceptions/NoHostAvailableException.cs | 12 +- .../PreparedQueryNotFoundException.cs | 2 +- .../PreparedStatementIdMismatchException.cs | 12 +- .../UnsupportedProtocolVersionException.cs | 4 +- .../Exceptions/WriteFailureException.cs | 2 +- .../Exceptions/WriteTimeoutException.cs | 6 +- .../ExecutionProfiles/ExecutionProfile.cs | 44 +++--- .../ExecutionProfileBuilder.cs | 6 +- .../ExecutionProfileOptions.cs | 10 +- .../ExecutionProfiles/IRequestOptions.cs | 2 +- .../ExecutionProfiles/RequestOptions.cs | 30 ++-- .../ExecutionProfiles/RequestOptionsMapper.cs | 2 +- src/Cassandra/FrameHeader.cs | 8 +- src/Cassandra/FrameParser.cs | 2 +- src/Cassandra/FrameReader.cs | 2 +- src/Cassandra/FrameWriter.cs | 8 +- src/Cassandra/FunctionMetadata.cs | 4 +- src/Cassandra/Geometry/Geometry.cs | 4 +- src/Cassandra/Geometry/LineString.cs | 2 +- src/Cassandra/Geometry/Point.cs | 6 +- src/Cassandra/Geometry/Polygon.cs | 26 ++-- src/Cassandra/HeaderFlags.cs | 2 +- src/Cassandra/Helpers/AssemblyHelpers.cs | 6 +- src/Cassandra/Helpers/CollectionHelpers.cs | 2 +- src/Cassandra/Helpers/PlatformHelper.cs | 2 +- src/Cassandra/Host.cs | 2 +- src/Cassandra/Hosts.cs | 2 +- src/Cassandra/IAuthInfoProvider.cs | 2 +- src/Cassandra/ICluster.cs | 6 +- src/Cassandra/IExecutionProfile.cs | 10 +- src/Cassandra/IExecutionProfileBuilder.cs | 8 +- src/Cassandra/IMetadataQueryProvider.cs | 2 +- src/Cassandra/ISession.cs | 18 +-- src/Cassandra/IndexMetadata.cs | 4 +- src/Cassandra/KeyspaceMetadata.cs | 28 ++-- src/Cassandra/LocalDate.cs | 36 ++--- src/Cassandra/LocalTime.cs | 16 +-- src/Cassandra/Logger.cs | 4 +- src/Cassandra/M3PToken.cs | 70 +++++----- .../AttributeBasedColumnDefinition.cs | 10 +- .../Mapping/Attributes/TableAttribute.cs | 2 +- src/Cassandra/Mapping/ColumnMap.cs | 2 +- src/Cassandra/Mapping/Cql.cs | 2 +- src/Cassandra/Mapping/CqlBatch.cs | 10 +- src/Cassandra/Mapping/ICqlBatch.cs | 4 +- src/Cassandra/Mapping/ICqlQueryAsyncClient.cs | 2 +- src/Cassandra/Mapping/ICqlQueryClient.cs | 2 +- src/Cassandra/Mapping/ICqlWriteAsyncClient.cs | 4 +- src/Cassandra/Mapping/ICqlWriteClient.cs | 6 +- src/Cassandra/Mapping/IMapper.cs | 24 ++-- src/Cassandra/Mapping/IPage.cs | 4 +- src/Cassandra/Mapping/Map.cs | 12 +- src/Cassandra/Mapping/MapperFactory.cs | 66 ++++----- src/Cassandra/Mapping/Mappings.cs | 2 +- src/Cassandra/Mapping/PocoDataFactory.cs | 2 +- src/Cassandra/Mapping/SortOrder.cs | 2 +- .../Mapping/Statements/CqlGenerator.cs | 14 +- .../Mapping/Statements/StatementFactory.cs | 2 +- .../NullableEnumStringMapper.cs | 2 +- .../Mapping/TypeConversion/TypeConverter.cs | 92 ++++++------- .../Mapping/Utils/CqlIdentifierHelper.cs | 4 +- .../Mapping/Utils/EnumerableExtensions.cs | 2 +- .../Mapping/Utils/ICqlIdentifierHelper.cs | 2 +- .../Mapping/Utils/LookupKeyedCollection.cs | 2 +- src/Cassandra/MaterializedViewMetadata.cs | 2 +- src/Cassandra/Metadata.cs | 18 +-- .../DatacenterReplicationFactor.cs | 6 +- .../MetadataHelpers/EverywhereStrategy.cs | 2 +- .../MetadataHelpers/IReplicationStrategy.cs | 2 +- .../IReplicationStrategyFactory.cs | 2 +- .../MetadataHelpers/LocalStrategy.cs | 2 +- .../NetworkTopologyStrategy.cs | 6 +- .../NetworkTopologyTokenMapContext.cs | 4 +- .../MetadataHelpers/ReplicationFactor.cs | 8 +- .../ReplicationStrategyFactory.cs | 6 +- .../MetadataHelpers/SimpleStrategy.cs | 12 +- src/Cassandra/MetadataSyncOptions.cs | 8 +- .../Metrics/Abstractions/IDriverCounter.cs | 2 +- .../Abstractions/IDriverMetricsProvider.cs | 8 +- src/Cassandra/Metrics/DriverMetricsOptions.cs | 6 +- src/Cassandra/Metrics/IDriverMetrics.cs | 4 +- src/Cassandra/Metrics/IMetricsRegistry.cs | 4 +- .../Metrics/Internal/IMetricsManager.cs | 2 +- .../Metrics/Internal/MetricsManager.cs | 8 +- src/Cassandra/Metrics/NodeMetric.cs | 38 +++--- .../Providers/Null/NullDriverCounter.cs | 4 +- .../Metrics/Providers/Null/NullDriverMeter.cs | 2 +- .../Null/NullDriverMetricsProvider.cs | 2 +- .../Metrics/Providers/Null/NullDriverTimer.cs | 2 +- .../Registries/IInternalMetricsRegistry.cs | 2 +- .../Metrics/Registries/INodeMetrics.cs | 2 +- .../Metrics/Registries/ISessionMetrics.cs | 2 +- .../Registries/InternalMetricsRegistry.cs | 4 +- .../Metrics/Registries/NodeMetrics.cs | 2 +- src/Cassandra/Metrics/SessionMetric.cs | 6 +- src/Cassandra/MonitorReportingOptions.cs | 6 +- src/Cassandra/NoneAuthProvider.cs | 5 +- src/Cassandra/NullTypeAdapter.cs | 4 +- .../Composite/CompositeRequestObserver.cs | 2 +- .../RequestTracker/RequestTrackerObserver.cs | 2 +- src/Cassandra/Outputs/OutputPrepared.cs | 2 +- src/Cassandra/Outputs/OutputReadTimeout.cs | 2 +- src/Cassandra/Outputs/OutputRows.cs | 2 +- .../Outputs/OutputUnavailableException.cs | 2 +- src/Cassandra/Outputs/OutputWriteTimeout.cs | 2 +- .../Policies/AesColumnEncryptionPolicy.cs | 2 +- .../AtomicMonotonicTimestampGenerator.cs | 8 +- ...AtomicMonotonicWinApiTimestampGenerator.cs | 6 +- .../Policies/BaseColumnEncryptionPolicy.cs | 2 +- .../ConstantSpeculativeExecutionPolicy.cs | 4 +- .../Policies/DCAwareRoundRobinPolicy.cs | 2 +- .../Policies/DefaultLoadBalancingPolicy.cs | 4 +- .../Policies/ExponentialReconnectionPolicy.cs | 4 +- .../Policies/IExtendedRetryPolicy.cs | 2 +- .../Policies/IReconnectionSchedule.cs | 2 +- src/Cassandra/Policies/IRetryPolicy.cs | 2 +- src/Cassandra/Policies/LoggingRetryPolicy.cs | 4 +- .../Policies/NoSpeculativeExecutionPolicy.cs | 6 +- src/Cassandra/Policies/Policies.cs | 6 +- .../Policies/RetryLoadBalancingPolicy.cs | 2 +- .../RetryLoadBalancingPolicyEventArgs.cs | 2 +- src/Cassandra/Policies/RoundRobinPolicy.cs | 2 +- src/Cassandra/PreparedStatement.cs | 2 +- .../ProtocolEvents/ProtocolEventDebouncer.cs | 2 +- .../SlidingWindowExclusiveTimer.cs | 8 +- src/Cassandra/ProtocolOptions.cs | 6 +- src/Cassandra/ProtocolVersion.cs | 8 +- src/Cassandra/QueryOptions.cs | 4 +- src/Cassandra/QueryProtocolOptions.cs | 14 +- src/Cassandra/QueryTrace.cs | 2 +- src/Cassandra/RPToken.cs | 16 +-- src/Cassandra/RecyclableMemoryStream.cs | 4 +- src/Cassandra/ReplicationStrategies.cs | 8 +- src/Cassandra/Requests/BaseRequest.cs | 4 +- src/Cassandra/Requests/BatchRequest.cs | 6 +- src/Cassandra/Requests/BatchType.cs | 2 +- src/Cassandra/Requests/ExecuteRequest.cs | 16 +-- .../Requests/GraphTypeSerializerFactory.cs | 18 +-- .../Requests/IGraphTypeSerializerFactory.cs | 2 +- src/Cassandra/Requests/IReprepareHandler.cs | 12 +- src/Cassandra/Requests/IRequestHandler.cs | 2 +- .../Requests/IRequestHandlerFactory.cs | 2 +- .../Requests/InternalPrepareRequest.cs | 6 +- src/Cassandra/Requests/PrepareHandler.cs | 12 +- src/Cassandra/Requests/QueryRequest.cs | 2 +- src/Cassandra/Requests/ReprepareHandler.cs | 16 +-- src/Cassandra/Requests/RequestExecution.cs | 30 ++-- src/Cassandra/Requests/RequestHandler.cs | 12 +- .../Requests/StartupOptionsFactory.cs | 8 +- src/Cassandra/Requests/ValidHost.cs | 2 +- src/Cassandra/Responses/Response.cs | 4 +- src/Cassandra/Responses/ResultResponse.cs | 2 +- src/Cassandra/RoutingKey.cs | 6 +- src/Cassandra/RowPopulators/ExecutionInfo.cs | 4 +- src/Cassandra/RowPopulators/RowSetMetadata.cs | 46 +++---- src/Cassandra/SSLOptions.cs | 4 +- src/Cassandra/SchemaParser.cs | 10 +- .../Serialization/CollectionSerializer.cs | 6 +- src/Cassandra/Serialization/DataTypeParser.cs | 2 +- .../Serialization/DictionarySerializer.cs | 2 +- .../Serialization/DurationSerializer.cs | 4 +- .../Serialization/GenericSerializer.cs | 34 ++--- .../Geometry/LineStringSerializer.cs | 4 +- .../Serialization/Geometry/PointSerializer.cs | 4 +- .../Geometry/PolygonSerializer.cs | 6 +- .../Graph/GraphSON1/GraphSON1Converter.cs | 2 +- .../GraphSON1/GraphSON1TypeSerializer.cs | 2 +- .../Graph/GraphSON2/GraphTypeSerializer.cs | 4 +- .../Graph/GraphSON2/StringBasedSerializer.cs | 4 +- .../GraphSON2/Structure/EdgeDeserializer.cs | 4 +- .../GraphSON2/Structure/PathDeserializer.cs | 4 +- .../Structure/PropertyDeserializer.cs | 4 +- .../GraphSON2/Structure/PropertySerializer.cs | 2 +- .../Structure/VertexPropertyDeserializer.cs | 6 +- .../Tinkerpop/TinkerpopDateDeserializer.cs | 4 +- .../TinkerpopTimestampDeserializer.cs | 2 +- .../Tinkerpop/TraverserDeserializer.cs | 4 +- .../Graph/GraphSON3/CustomGraphSON3Reader.cs | 22 +-- .../Dse/ComplexTypeDefinitionHelper.cs | 4 +- .../GraphSON3/Dse/Duration3Serializer.cs | 10 +- .../GraphSON3/Dse/TupleGraphSONSerializer.cs | 4 +- .../GraphSON3/Dse/UdtGraphSONDeserializer.cs | 18 +-- .../GraphSON3/Structure/Path3Deserializer.cs | 24 ++-- .../Tinkerpop/ByteBufferDeserializer.cs | 2 +- .../Graph/IGraphTypeSerializer.cs | 2 +- src/Cassandra/Serialization/Graph/INode.cs | 2 +- .../Structure/IO/GraphSON/ClassSerializer.cs | 2 +- .../Structure/IO/GraphSON/GraphSON2Reader.cs | 6 +- .../Structure/IO/GraphSON/GraphSON2Writer.cs | 8 +- .../Structure/IO/GraphSON/ListSerializer.cs | 2 +- .../Structure/IO/GraphSON/MapSerializer.cs | 2 +- .../Serialization/LegacyTypeSerializer.cs | 4 +- .../Primitive/BooleanSerializer.cs | 2 +- .../Primitive/DecimalSerializer.cs | 4 +- .../Search/DateRangeSerializer.cs | 34 ++--- .../Serialization/SerializerManager.cs | 2 +- .../Serialization/TupleSerializer.cs | 2 +- src/Cassandra/Serialization/TypeSerializer.cs | 10 +- .../TypeSerializerDefinitions.cs | 2 +- .../SessionManagement/IInternalCluster.cs | 2 +- .../SessionManagement/IInternalSession.cs | 2 +- src/Cassandra/SessionRequestInfo.cs | 2 +- src/Cassandra/SessionState.cs | 2 +- src/Cassandra/SocketOptions.cs | 2 +- src/Cassandra/Statement.cs | 2 +- src/Cassandra/TableMetadata.cs | 4 +- src/Cassandra/Tasks/HashedWheelTimer.cs | 2 +- src/Cassandra/Tasks/TaskHelper.cs | 8 +- src/Cassandra/TimeUuid.cs | 10 +- src/Cassandra/TokenMap.cs | 30 ++-- src/Cassandra/UdtMap.cs | 2 +- src/Cassandra/Utils.cs | 4 +- 606 files changed, 3473 insertions(+), 3461 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 4eb25a4dd..1b84dc15d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -64,5 +64,11 @@ jobs: exit 1 fi + - name: Run dotnet format (checks formatting) + run: | + dotnet format --verify-no-changes --severity warn --verbosity diagnostic src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj + dotnet format --verify-no-changes --severity warn --verbosity diagnostic src/Cassandra/Cassandra.csproj + dotnet format --verify-no-changes --severity warn --verbosity diagnostic src/Cassandra.Tests/Cassandra.Tests.csproj + - name: Run integration tests on Scylla run: SCYLLA_EXT_OPTS="--smp 2 --memory 4G" SIMULACRON_PATH=../../../../../ci/simulacron-standalone-0.12.0.jar dotnet test src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj -f net8 -l "console;verbosity=detailed" --filter "(FullyQualifiedName!~ClientWarningsTests & FullyQualifiedName!~CustomPayloadTests & FullyQualifiedName!~Connect_With_Ssl_Test & FullyQualifiedName!~Should_UpdateHosts_When_HostIpChanges & FullyQualifiedName!~Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain & FullyQualifiedName!~Should_RemoveNodeMetricsAndDisposeMetricsContext_When_HostIsRemoved & FullyQualifiedName!~Virtual_Keyspaces_Are_Included & FullyQualifiedName!~Virtual_Table_Metadata_Test & FullyQualifiedName!~SessionAuthenticationTests & FullyQualifiedName!~TypeSerializersTests & FullyQualifiedName!~Custom_MetadataTest & FullyQualifiedName!~LinqWhere_WithVectors & FullyQualifiedName!~SimpleStatement_With_No_Compact_Enabled_Should_Reveal_Non_Schema_Columns & FullyQualifiedName!~SimpleStatement_With_No_Compact_Disabled_Should_Not_Reveal_Non_Schema_Columns & FullyQualifiedName!~ColumnClusteringOrderReversedTest & FullyQualifiedName!~GetMaterializedView_Should_Refresh_View_Metadata_Via_Events & FullyQualifiedName!~MaterializedView_Base_Table_Column_Addition & FullyQualifiedName!~MultipleSecondaryIndexTest & FullyQualifiedName!~RaiseErrorOnInvalidMultipleSecondaryIndexTest & FullyQualifiedName!~TableMetadataAllTypesTest & FullyQualifiedName!~TableMetadataClusteringOrderTest & FullyQualifiedName!~TableMetadataCollectionsSecondaryIndexTest & FullyQualifiedName!~TableMetadataCompositePartitionKeyTest & FullyQualifiedName!~TupleMetadataTest & FullyQualifiedName!~Udt_Case_Sensitive_Metadata_Test & FullyQualifiedName!~UdtMetadataTest & FullyQualifiedName!~Should_Retrieve_Table_Metadata & FullyQualifiedName!~CreateTable_With_Frozen_Key & FullyQualifiedName!~CreateTable_With_Frozen_Udt & FullyQualifiedName!~CreateTable_With_Frozen_Value & FullyQualifiedName!~Should_AllMetricsHaveValidValues_When_AllNodesAreUp & FullyQualifiedName!~SimpleStatement_Dictionary_Parameters_CaseInsensitivity_ExcessOfParams & FullyQualifiedName!~SimpleStatement_Dictionary_Parameters_CaseInsensitivity_NoOverload & FullyQualifiedName!~TokenAware_TransientReplication_NoHopsAndOnlyFullReplicas & FullyQualifiedName!~GetFunction_Should_Return_Most_Up_To_Date_Metadata_Via_Events & FullyQualifiedName!~LargeDataTests & FullyQualifiedName!~MetadataTests & FullyQualifiedName!~MultiThreadingTests & FullyQualifiedName!~PoolTests & FullyQualifiedName!~PrepareLongTests & FullyQualifiedName!~SpeculativeExecutionLongTests & FullyQualifiedName!~StressTests & FullyQualifiedName!~TransitionalAuthenticationTests & FullyQualifiedName!~ProxyAuthenticationTests & FullyQualifiedName!~SessionDseAuthenticationTests & FullyQualifiedName!~CloudIntegrationTests & FullyQualifiedName!~CoreGraphTests & FullyQualifiedName!~GraphTests & FullyQualifiedName!~InsightsIntegrationTests & FullyQualifiedName!~DateRangeTests & FullyQualifiedName!~FoundBugTests & FullyQualifiedName!~GeometryTests & FullyQualifiedName!~LoadBalancingPolicyTests & FullyQualifiedName!~ConsistencyTests & FullyQualifiedName!~LoadBalancingPolicyTests & FullyQualifiedName!~ReconnectionPolicyTests & FullyQualifiedName!~RetryPolicyTests)" diff --git a/src/Cassandra.IntegrationTests/Ado/AdoBasicTests.cs b/src/Cassandra.IntegrationTests/Ado/AdoBasicTests.cs index f38cfcc47..2ea48fad2 100644 --- a/src/Cassandra.IntegrationTests/Ado/AdoBasicTests.cs +++ b/src/Cassandra.IntegrationTests/Ado/AdoBasicTests.cs @@ -33,7 +33,7 @@ public override void SetUp() base.SetUp(); var cb = new CassandraConnectionStringBuilder { - ContactPoints = new[] { TestCluster.InitialContactPoint.Address.ToString() }, + ContactPoints = new[] { TestCluster.InitialContactPoint.Address.ToString() }, Port = 9042 }; _connection = new CqlConnection(cb.ToString()); @@ -80,7 +80,7 @@ public void ExecuteNonQueryInsertAndSelectTest() int RowsNo = 300; for (int i = 0; i < RowsNo; i++) { - longQ.AppendFormat("INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", tableName, guids[i], i, i%2 == 0 ? "false" : "true"); + longQ.AppendFormat("INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", tableName, guids[i], i, i % 2 == 0 ? "false" : "true"); } longQ.AppendLine("APPLY BATCH;"); cmd.CommandText = longQ.ToString(); @@ -94,7 +94,7 @@ public void ExecuteNonQueryInsertAndSelectTest() TestCluster.PrimeFluent( b => b.WhenQuery($"SELECT * from {tableName} LIMIT 10000;") .ThenRowsSuccess( - new[] {"tweet_id", "author", "body", "isok"}, + new[] { "tweet_id", "author", "body", "isok" }, r => r.WithRows(guids.Select((guid, idx) => new object[] { guid, $"test{idx}", $"body{idx}", idx % 2 != 0 }).ToArray()))); cmd.CommandText = string.Format(@"SELECT * from {0} LIMIT 10000;", tableName); @@ -118,7 +118,7 @@ public void ExecuteScalarReturnsFirstColumn() TestCluster.PrimeFluent( b => b.WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { "key" }, r => r.WithRow("local"))); + .ThenRowsSuccess(new[] { "key" }, r => r.WithRow("local"))); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * FROM system.local WHERE key = 'does not exist'") diff --git a/src/Cassandra.IntegrationTests/BaseIntegrationTest.cs b/src/Cassandra.IntegrationTests/BaseIntegrationTest.cs index d67f16b02..866c83f6b 100644 --- a/src/Cassandra.IntegrationTests/BaseIntegrationTest.cs +++ b/src/Cassandra.IntegrationTests/BaseIntegrationTest.cs @@ -42,7 +42,7 @@ protected BaseIntegrationTest() "schema.propertyKey('title').Text().ifNotExists().create();\n" + "schema.propertyKey('tags').Text().multiple().ifNotExists().create();\n" + "schema.vertexLabel('movie').properties('title', 'tags').ifNotExists().create();\n"; - + protected const string CoreSchemaGremlinQuery = "schema.vertexLabel('person')" + ".partitionBy('name', Text)" + @@ -66,7 +66,7 @@ protected BaseIntegrationTest() ".create();\n" + "schema.type('address')" + ".property('address1', Text)" + - ".property('address2', Text)" + + ".property('address2', Text)" + ".property('city_code', Text)" + ".property('state_code', Text)" + ".property('zip_code', Text)" + @@ -86,12 +86,12 @@ protected BaseIntegrationTest() ".property('emails', setOf(Text))" + ".property('nullable_long', Bigint)" + ".create();\n" + - "schema.vertexLabel('users')" + - ".partitionBy('id', Int)" + + "schema.vertexLabel('users')" + + ".partitionBy('id', Int)" + ".property('main_phone', frozen(typeOf('phone')))" + ".create();\n" + - "schema.vertexLabel('users_contacts')" + - ".partitionBy('id', Int)" + + "schema.vertexLabel('users_contacts')" + + ".partitionBy('id', Int)" + ".property('contacts', listOf(frozen(typeOf('contact'))))" + ".create();\n" + "schema.type('user_feedback')" + @@ -102,19 +102,19 @@ protected BaseIntegrationTest() ".from('users').to('software')" + ".property('feedback', typeOf('user_feedback'))" + ".create();\n" + - "schema.vertexLabel('tuple_test')" + - ".partitionBy('id', Int)" + + "schema.vertexLabel('tuple_test')" + + ".partitionBy('id', Int)" + ".property('tuple_property', tupleOf(typeOf('phone'), Instant, UUID, listOf(Text), setOf(Int),mapOf(Text, Int)))" + ".create();\n"; /// /// Reference graph: http://www.tinkerpop.com/docs/3.0.0.M1/ /// - protected const string CoreLoadGremlinQuery = + protected const string CoreLoadGremlinQuery = "g.addV('person')" + ".property('name', 'marko')" + ".property('age', 29)" + - ".as('marko')" + + ".as('marko')" + ".addV('person')" + ".property('name', 'vadas')" + ".property('age', 27)" + @@ -122,7 +122,7 @@ protected BaseIntegrationTest() ".addV('software')" + ".property('name', 'lop')" + ".property('lang', 'java')" + - ".as('lop')" + + ".as('lop')" + ".addV('person')" + ".property('name', 'josh')" + ".property('age', 32)" + @@ -155,7 +155,7 @@ protected BaseIntegrationTest() ".from('peter').to('lop')" + ".addV('users_contacts')" + ".property('id', 1923)" + - ".property('contacts', " + + ".property('contacts', " + "[ " + "typeOf('contact').create(" + "'Jimmy', " + @@ -182,7 +182,7 @@ protected BaseIntegrationTest() /// /// Reference graph: http://www.tinkerpop.com/docs/3.0.0.M1/ /// - protected const string ClassicLoadGremlinQuery = + protected const string ClassicLoadGremlinQuery = "Vertex marko = graph.addVertex(label, 'person', 'name', 'marko', 'age', 29);\n" + "Vertex vadas = graph.addVertex(label, 'person', 'name', 'vadas', 'age', 27);\n" + "Vertex lop = graph.addVertex(label, 'software', 'name', 'lop', 'lang', 'java');\n" + @@ -198,7 +198,7 @@ protected BaseIntegrationTest() protected const string MakeStrict = "schema.config().option(\"graph.schema_mode\").set(\"production\");"; protected const string AllowScans = "schema.config().option(\"graph.allow_scan\").set(\"true\");"; - + /// /// Creates a graph using the current session /// @@ -231,7 +231,7 @@ public void CreateClassicGraph(string contactPoint, string name) CreateClassicGraph(cluster.Connect(), name); } } - + /// /// Creates a core graph using the current session /// @@ -279,7 +279,7 @@ private void WaitUntilKeyspaceMetadataRefresh(ISession session, string graphName Task.Delay(500).GetAwaiter().GetResult(); } - + Assert.Fail("Keyspace metadata does not have the correct graph engine."); } } diff --git a/src/Cassandra.IntegrationTests/Core/BasicTypeTests.cs b/src/Cassandra.IntegrationTests/Core/BasicTypeTests.cs index ef813c5a7..1f9d47df4 100644 --- a/src/Cassandra.IntegrationTests/Core/BasicTypeTests.cs +++ b/src/Cassandra.IntegrationTests/Core/BasicTypeTests.cs @@ -174,11 +174,11 @@ public void DecimalWithNegativeScaleTest() TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * FROM decimal_neg_scale") - .ThenRowsSuccess(new[] {"id", "value"}, r => r.WithRow(firstRowValues.First(), (decimal) 50))); + .ThenRowsSuccess(new[] { "id", "value" }, r => r.WithRow(firstRowValues.First(), (decimal)50))); var row = Session.Execute("SELECT * FROM decimal_neg_scale").First(); var decValue = row.GetValue("value"); - + Assert.AreEqual(50, decValue); } @@ -245,7 +245,7 @@ public void ExceedingCassandraType(Type toExceed, Type toExceedWith, bool sameOu TestCluster.PrimeFluent( b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.One)) .ThenRowsSuccess( - new[] {"tweet_id", "label", "number"}, + new[] { "tweet_id", "label", "number" }, r => r.WithRow(toInsertAndCheck[0][0], toInsertAndCheck[0][1], toInsertAndCheck[0][2]) .WithRow(toInsertAndCheck[1][0], toInsertAndCheck[1][1], toInsertAndCheck[1][2]))); @@ -282,7 +282,7 @@ public void TestCounters() TestCluster.PrimeFluent( b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.LocalOne)) - .ThenRowsSuccess(new[] {"tweet_id", "incdec"}, r => r.WithRow(tweet_id, (Int64) 50))); + .ThenRowsSuccess(new[] { "tweet_id", "incdec" }, r => r.WithRow(tweet_id, (Int64)50))); QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};", Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), @@ -310,7 +310,7 @@ public void InsertingSingleValue(Type tp) var query = $"INSERT INTO {tableName}(tweet_id,value) VALUES (" + $"{toInsert[0][0]}, " + - $"{(row1[1].GetType() == typeof(byte[]) ? "0x" + CqlQueryTools.ToHex((byte[]) toInsert[0][1]) : "'" + toInsert[0][1] + "'")}" + + $"{(row1[1].GetType() == typeof(byte[]) ? "0x" + CqlQueryTools.ToHex((byte[])toInsert[0][1]) : "'" + toInsert[0][1] + "'")}" + ");"; QueryTools.ExecuteSyncNonQuery(Session, query, null); VerifyStatement(QueryType.Query, query, 1); @@ -333,7 +333,7 @@ public void InsertingSingleValue(Type tp) TestCluster.PrimeFluent( b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.LocalOne)) - .ThenRowsSuccess(new[] {"tweet_id", "value"}, r => r.WithRow(toInsert[0][0], toInsert[0][1]))); + .ThenRowsSuccess(new[] { "tweet_id", "value" }, r => r.WithRow(toInsert[0][0], toInsert[0][1]))); QueryTools.ExecuteSyncQuery( Session, $"SELECT * FROM {tableName};", Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert); diff --git a/src/Cassandra.IntegrationTests/Core/ClientTimeoutTests.cs b/src/Cassandra.IntegrationTests/Core/ClientTimeoutTests.cs index 8e2bf93e7..500f89ad6 100644 --- a/src/Cassandra.IntegrationTests/Core/ClientTimeoutTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ClientTimeoutTests.cs @@ -58,7 +58,7 @@ public void Should_Move_To_Next_Host_For_Simple_Queries() var node = nodes[0]; node.PrimeFluent(b => b .WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(2000)); TestHelper.Invoke(() => { @@ -85,7 +85,7 @@ public void Should_Move_To_Next_Host_For_Bound_Statements() var node = nodes[0]; node.PrimeFluent( b => b.WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(2000)); TestHelper.Invoke(() => { @@ -135,7 +135,7 @@ public void Should_Throw_OperationTimedOutException_When_Retry_Is_False() var node = nodes[1]; node.PrimeFluent( b => b.WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(2000)); var coordinators = new HashSet(); var exceptions = new List(); @@ -166,7 +166,7 @@ public void Should_Wait_When_ReadTimeout_Is_Zero() const string cql = "SELECT key FROM system.local"; simulacronCluster.PrimeFluent( b => b.WhenQuery(cql) - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(30000)); using (var cluster = ClusterBuilder().AddContactPoint(simulacronCluster.InitialContactPoint).WithSocketOptions(socketOptions).Build()) @@ -213,7 +213,7 @@ public void Should_Use_Statement_ReadTimeout() var node = nodes[0]; node.PrimeFluent( b => b.WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(30000)); var stopWatch = new Stopwatch(); stopWatch.Start(); @@ -259,7 +259,7 @@ public void Should_Throw_NoHostAvailableException_When_All_Hosts_Down() TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10); _testCluster.PrimeFluent( b => b.WhenQuery("SELECT key FROM system.local") - .ThenRowsSuccess(new [] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) + .ThenRowsSuccess(new[] { ("key", DataType.Ascii) }, rows => rows.WithRow("123")) .WithDelayInMs(10000)); var ex = Assert.Throws(() => session.Execute("SELECT key FROM system.local")); Assert.AreEqual(2, ex.Errors.Count); @@ -296,7 +296,7 @@ public void Should_Not_Leak_Connections_Test() var listeners = new List(); foreach (var l in Trace.Listeners) { - listeners.Add((TraceListener) l); + listeners.Add((TraceListener)l); } Trace.Listeners.Clear(); @@ -395,7 +395,7 @@ public void Should_Not_Leak_Connections_Test() } } } - + /// /// CSHARP-958 /// @@ -405,7 +405,7 @@ public async Task Should_Not_Leak_Connections_With_InvalidKeyspace_Test() var listeners = new List(); foreach (var l in Trace.Listeners) { - listeners.Add((TraceListener) l); + listeners.Add((TraceListener)l); } Trace.Listeners.Clear(); @@ -478,7 +478,7 @@ public async Task Should_Not_Leak_Connections_With_InvalidKeyspace_Test() Exception ex = null; try { - using (await c.ConnectAsync($"keyspace_{i+numberOfDefaultKsClusters}").ConfigureAwait(false)) + using (await c.ConnectAsync($"keyspace_{i + numberOfDefaultKsClusters}").ConfigureAwait(false)) { } } @@ -514,12 +514,12 @@ public async Task Should_Not_Leak_Connections_With_InvalidKeyspace_Test() await Task.Delay(1000).ConfigureAwait(false); decimal initialMemory = GC.GetTotalMemory(true); - + await connectClustersFunc(100).ConfigureAwait(false); GC.Collect(); await Task.Delay(1000).ConfigureAwait(false); - + var connectedPorts = await _testCluster.GetConnectedPortsAsync().ConfigureAwait(false); Assert.AreEqual(20, connectedPorts.Count); // control connections diff --git a/src/Cassandra.IntegrationTests/Core/ClientWarningsTests.cs b/src/Cassandra.IntegrationTests/Core/ClientWarningsTests.cs index 45337e4ca..95b34b618 100644 --- a/src/Cassandra.IntegrationTests/Core/ClientWarningsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ClientWarningsTests.cs @@ -88,7 +88,7 @@ public void Should_QueryTrace_When_Enabled() Assert.Greater(rs.Info.QueryTrace.Events.Count, 0); if (Session.BinaryProtocolVersion >= 4) { - Assert.NotNull(rs.Info.QueryTrace.ClientAddress); + Assert.NotNull(rs.Info.QueryTrace.ClientAddress); } else { @@ -114,7 +114,7 @@ public void Should_NotGenerateWarning_When_RegularBehavior() [Test, TestCassandraVersion(2, 2)] public void Should_Warning_When_BatchExceedsLength() { - var rs = Session.Execute(GetBatchAsSimpleStatement(5*1025)); + var rs = Session.Execute(GetBatchAsSimpleStatement(5 * 1025)); Assert.NotNull(rs.Info.Warnings); Assert.AreEqual(1, rs.Info.Warnings.Length); StringAssert.Contains("batch", rs.Info.Warnings[0].ToLowerInvariant()); @@ -147,7 +147,7 @@ public void Should_ThrowInvalidException_When_BatchIsTooBig() [Test, TestCassandraVersion(2, 2)] public void Should_WarningAndGetPayload_When_UsingMirrorPayload() { - var statement = GetBatchAsSimpleStatement(5*1025); + var statement = GetBatchAsSimpleStatement(5 * 1025); var outgoing = GetPayload(); var rs = Session.Execute(statement.SetOutgoingPayload(GetPayload())); Assert.NotNull(rs.Info.Warnings); @@ -161,7 +161,7 @@ public void Should_WarningAndGetPayload_When_UsingMirrorPayload() [Test, TestCassandraVersion(2, 2)] public void Should_WarningAndTracingAndGetPayload_When_UsingMirrorPayloadAndEnableTracing() { - var statement = GetBatchAsSimpleStatement(5*1025); + var statement = GetBatchAsSimpleStatement(5 * 1025); var outgoing = new Dictionary { {"k1", Encoding.UTF8.GetBytes("value1")}, diff --git a/src/Cassandra.IntegrationTests/Core/ClusterPeersV2SimulacronTests.cs b/src/Cassandra.IntegrationTests/Core/ClusterPeersV2SimulacronTests.cs index 803dc5f47..519e9cd37 100644 --- a/src/Cassandra.IntegrationTests/Core/ClusterPeersV2SimulacronTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ClusterPeersV2SimulacronTests.cs @@ -46,7 +46,7 @@ public void Should_SendRequestsToAllHosts_When_PeersOnSameAddress() // doesn't exist but doesn't matter Session.Execute(query); } - + Assert.AreEqual(3, Session.Cluster.AllHosts().Count); Assert.IsTrue(Session.Cluster.AllHosts().All(h => h.IsUp)); diff --git a/src/Cassandra.IntegrationTests/Core/ClusterTests.cs b/src/Cassandra.IntegrationTests/Core/ClusterTests.cs index 656a7a952..ea92e6401 100644 --- a/src/Cassandra.IntegrationTests/Core/ClusterTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ClusterTests.cs @@ -168,8 +168,8 @@ await TestGlobals.ConnectAndDispose(cluster, false, session => TestHelper.RetryAssert(() => { Assert.True(TestUtils.IsNodeReachable(newNodeIpAddress)); - //New node should be part of the metadata - Assert.AreEqual(2, cluster.AllHosts().Count); + //New node should be part of the metadata + Assert.AreEqual(2, cluster.AllHosts().Count); var host = cluster.AllHosts().FirstOrDefault(h => h.Address.Address.Equals(newNodeIpAddress)); Assert.IsNotNull(host); }, @@ -212,8 +212,8 @@ await TestGlobals.ConnectAndDispose(cluster, false, session => { decommisionedNode = _realCluster.ClusterIpPrefix + 3; Assert.False(TestUtils.IsNodeReachable(IPAddress.Parse(decommisionedNode))); - //New node should be part of the metadata - Assert.AreEqual(2, cluster.AllHosts().Count); + //New node should be part of the metadata + Assert.AreEqual(2, cluster.AllHosts().Count); }, 100, 100); var queried = false; for (var i = 0; i < 10; i++) diff --git a/src/Cassandra.IntegrationTests/Core/CollectionsNestedTests.cs b/src/Cassandra.IntegrationTests/Core/CollectionsNestedTests.cs index eb243fd5f..b8f2e7209 100644 --- a/src/Cassandra.IntegrationTests/Core/CollectionsNestedTests.cs +++ b/src/Cassandra.IntegrationTests/Core/CollectionsNestedTests.cs @@ -258,8 +258,8 @@ public void NestedCollections_BatchStatements() /// Nested Collection Helpers /////////////////////////////////////// - private static void ValidateSelectedNestedFrozenRow(Row row, - Dictionary> expectedMap1 = null, + private static void ValidateSelectedNestedFrozenRow(Row row, + Dictionary> expectedMap1 = null, Dictionary> expectedMap2 = null, List> expectedList1 = null) { diff --git a/src/Cassandra.IntegrationTests/Core/CollectionsTests.cs b/src/Cassandra.IntegrationTests/Core/CollectionsTests.cs index df48be173..e91ffd762 100644 --- a/src/Cassandra.IntegrationTests/Core/CollectionsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/CollectionsTests.cs @@ -42,11 +42,11 @@ public override void OneTimeSetUp() public void DecodeCollectionTest() { var id = "c9850ed4-c139-4b75-affe-098649f9de93"; - var insertQuery = string.Format("INSERT INTO {0} (id, map_sample, list_sample, set_sample) VALUES ({1}, {2}, {3}, {4})", - AllTypesTableName, - id, - "{'fruit': 'apple', 'band': 'Beatles'}", - "['one', 'two']", + var insertQuery = string.Format("INSERT INTO {0} (id, map_sample, list_sample, set_sample) VALUES ({1}, {2}, {3}, {4})", + AllTypesTableName, + id, + "{'fruit': 'apple', 'band': 'Beatles'}", + "['one', 'two']", "{'set_1one', 'set_2two'}"); Session.Execute(insertQuery); @@ -139,23 +139,23 @@ public void Decode_List_With_NullValue_Should_Return_Correct_Results() AllTypesTableName)); var list = new List { "apple", "queen" }; var set = new List { "fruit", "band" }; - var map = new Dictionary { { "fruit", "apple" }, { "band", "queen" } }; + var map = new Dictionary { { "fruit", "apple" }, { "band", "queen" } }; var stmt = insertQuery.Bind(id, map, set, list, ttlInsert); localSession.Execute(stmt); insertQuery = localSession.Prepare(string.Format("INSERT INTO {0} (id, map_sample, set_sample, list_sample) VALUES (?, ?, ?, ?)", AllTypesTableName)); stmt = insertQuery.Bind(id2, map, set, list); localSession.Execute(stmt); - + var rowSet = localSession.Execute( - new SimpleStatement($"select ttl(list_sample), ttl(map_sample), ttl(set_sample) from {AllTypesTableName} where id=?",id2)).ToList(); - - CollectionAssert.AreEqual(new int? [] { null, null }, rowSet.Single().GetValue(0)); - CollectionAssert.AreEqual(new int? [] { null, null }, rowSet.Single().GetValue>(1)); - CollectionAssert.AreEqual(new int? [] { null, null }, rowSet.Single().GetValue>(2)); + new SimpleStatement($"select ttl(list_sample), ttl(map_sample), ttl(set_sample) from {AllTypesTableName} where id=?", id2)).ToList(); + + CollectionAssert.AreEqual(new int?[] { null, null }, rowSet.Single().GetValue(0)); + CollectionAssert.AreEqual(new int?[] { null, null }, rowSet.Single().GetValue>(1)); + CollectionAssert.AreEqual(new int?[] { null, null }, rowSet.Single().GetValue>(2)); rowSet = localSession.Execute( - new SimpleStatement($"select writetime(list_sample), writetime(map_sample), ttl(list_sample), ttl(map_sample), ttl(set_sample) from {AllTypesTableName} where id=?",id)).ToList(); + new SimpleStatement($"select writetime(list_sample), writetime(map_sample), ttl(list_sample), ttl(map_sample), ttl(set_sample) from {AllTypesTableName} where id=?", id)).ToList(); Assert.IsTrue(rowSet.Single().GetValue(0).All(i => i > 0) && rowSet.Single().GetValue(0).Length == 2); Assert.IsTrue(rowSet.Single().GetValue(1).All(i => i > 0) && rowSet.Single().GetValue(1).Length == 2); Assert.IsTrue(rowSet.Single().GetValue(2).All(i => i > 0) && rowSet.Single().GetValue(2).Length == 2); @@ -163,7 +163,7 @@ public void Decode_List_With_NullValue_Should_Return_Correct_Results() Assert.IsTrue(rowSet.Single().GetValue>(4).All(ttl => ttl <= ttlInsert && ttl >= (ttlInsert - 100)) && rowSet.Single().GetValue>(4).Count() == 2); } - public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null,string pendingMode = "") + public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null, string pendingMode = "") { string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed); string openBracket = CassandraCollectionType == "list" ? "[" : "{"; @@ -177,12 +177,12 @@ public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeO string cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap); mapSyntax = cassandraKeyDataTypeName + ","; - if (TypeOfKeyForMap == typeof (DateTimeOffset)) + if (TypeOfKeyForMap == typeof(DateTimeOffset)) randomKeyValue = - Randomm.RandomVal(typeof (DateTimeOffset)) + Randomm.RandomVal(typeof(DateTimeOffset)) .GetType() - .GetMethod("ToString", new[] {typeof (string)}) - .Invoke(Randomm.RandomVal(typeof (DateTimeOffset)), new object[1] {"yyyy-MM-dd H:mm:sszz00"}) + "' : '"; + .GetMethod("ToString", new[] { typeof(string) }) + .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] { "yyyy-MM-dd H:mm:sszz00" }) + "' : '"; else randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed) + "' : '"; } @@ -213,7 +213,7 @@ public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeO for (int i = 0; i < collectionElementsNo; i++) { - int data = i*(i%2); + int data = i * (i % 2); longQ.AppendFormat(@"UPDATE {0} SET some_collection = " + inputSide + " WHERE tweet_id = {2};" , tableName, openBracket + randomKeyValue + data + closeBracket, tweet_id); orderedAsInputed.Add(data); @@ -237,7 +237,7 @@ public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeO foreach (Row row in rs.GetRows()) foreach (object value in row[1] as IEnumerable) { - Assert.True(orderedAsInputed[ind] == (int) value); + Assert.True(orderedAsInputed[ind] == (int)value); ind++; } } @@ -256,11 +256,11 @@ public void InsertingSingleCollection(string cassandraCollectionType, Type typeO string mapSyntax = ""; object randomValue = Randomm.RandomVal(typeOfDataToBeInputed); - if (typeOfDataToBeInputed == typeof (string)) + if (typeOfDataToBeInputed == typeof(string)) randomValue = "'" + randomValue.ToString().Replace("'", "''") + "'"; else if (typeOfDataToBeInputed == typeof(double)) { - randomValue = ((double) randomValue).ToString(CultureInfo.InvariantCulture); + randomValue = ((double)randomValue).ToString(CultureInfo.InvariantCulture); } string randomKeyValue = string.Empty; @@ -270,15 +270,15 @@ public void InsertingSingleCollection(string cassandraCollectionType, Type typeO cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(typeOfKeyForMap); mapSyntax = cassandraKeyDataTypeName + ","; - if (typeOfKeyForMap == typeof (DateTimeOffset)) + if (typeOfKeyForMap == typeof(DateTimeOffset)) randomKeyValue = "'" + - (Randomm.RandomVal(typeof (DateTimeOffset)) + (Randomm.RandomVal(typeof(DateTimeOffset)) .GetType() - .GetMethod("ToString", new[] {typeof (string)}) - .Invoke(Randomm.RandomVal(typeof (DateTimeOffset)), new object[1] {"yyyy-MM-dd H:mm:sszz00"}) + "'"); - else if (typeOfKeyForMap == typeof (string)) + .GetMethod("ToString", new[] { typeof(string) }) + .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] { "yyyy-MM-dd H:mm:sszz00" }) + "'"); + else if (typeOfKeyForMap == typeof(string)) randomKeyValue = "'" + Randomm.RandomVal(typeOfDataToBeInputed).ToString().Replace("'", "''") + "'"; - else if (typeOfKeyForMap == typeof (double)) + else if (typeOfKeyForMap == typeof(double)) randomKeyValue = ((double)Randomm.RandomVal(typeOfDataToBeInputed)).ToString(CultureInfo.InvariantCulture); else randomKeyValue = Randomm.RandomVal(typeOfDataToBeInputed).ToString(); @@ -312,11 +312,11 @@ public void InsertingSingleCollection(string cassandraCollectionType, Type typeO for (int i = 0; i < CollectionElementsNo; i++) { object val = rval; - if (typeOfDataToBeInputed == typeof (string)) + if (typeOfDataToBeInputed == typeof(string)) val = "'" + val.ToString().Replace("'", "''") + "'"; else if (typeOfDataToBeInputed == typeof(double)) { - val = ((double) val).ToString(CultureInfo.InvariantCulture); + val = ((double)val).ToString(CultureInfo.InvariantCulture); } longQ.AppendFormat(@"UPDATE {0} SET some_collection = some_collection + {1} WHERE tweet_id = {2};" @@ -342,14 +342,14 @@ public void insertingSingleCollectionPrepared(string CassandraCollectionType, Ty if (CassandraCollectionType == "list" || CassandraCollectionType == "set") { - Type openType = CassandraCollectionType == "list" ? typeof (List<>) : typeof (HashSet<>); + Type openType = CassandraCollectionType == "list" ? typeof(List<>) : typeof(HashSet<>); Type listType = openType.MakeGenericType(TypeOfDataToBeInputed); valueCollection = Activator.CreateInstance(listType); MethodInfo addM = listType.GetMethod("Add"); for (int i = 0; i < Cnt; i++) { object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed); - addM.Invoke(valueCollection, new[] {randomValue}); + addM.Invoke(valueCollection, new[] { randomValue }); } } else if (CassandraCollectionType == "map") @@ -357,18 +357,18 @@ public void insertingSingleCollectionPrepared(string CassandraCollectionType, Ty cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap); mapSyntax = cassandraKeyDataTypeName + ","; - Type openType = typeof (SortedDictionary<,>); + Type openType = typeof(SortedDictionary<,>); Type dicType = openType.MakeGenericType(TypeOfKeyForMap, TypeOfDataToBeInputed); valueCollection = Activator.CreateInstance(dicType); MethodInfo addM = dicType.GetMethod("Add"); for (int i = 0; i < Cnt; i++) { - RETRY: + RETRY: try { object randomKey = Randomm.RandomVal(TypeOfKeyForMap); object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed); - addM.Invoke(valueCollection, new[] {randomKey, randomValue}); + addM.Invoke(valueCollection, new[] { randomKey, randomValue }); } catch { @@ -400,163 +400,163 @@ public void insertingSingleCollectionPrepared(string CassandraCollectionType, Ty [Test] public void ListOrderPrepending() { - CheckingOrderOfCollection("list", typeof (Int32), null, "prepending"); + CheckingOrderOfCollection("list", typeof(Int32), null, "prepending"); } [Test] public void ListOrderAppending() { - CheckingOrderOfCollection("list", typeof (Int32), null, "appending"); + CheckingOrderOfCollection("list", typeof(Int32), null, "appending"); } [Test] public void SetOrder() { - CheckingOrderOfCollection("set", typeof (Int32)); + CheckingOrderOfCollection("set", typeof(Int32)); } [Test] public void Map() { - InsertingSingleCollection("map", typeof (string), typeof (DateTimeOffset)); + InsertingSingleCollection("map", typeof(string), typeof(DateTimeOffset)); } [Test] public void MapDouble() { - InsertingSingleCollection("map", typeof (Double), typeof (DateTimeOffset)); + InsertingSingleCollection("map", typeof(Double), typeof(DateTimeOffset)); } [Test] public void MapInt32() { - InsertingSingleCollection("map", typeof (Int32), typeof (DateTimeOffset)); + InsertingSingleCollection("map", typeof(Int32), typeof(DateTimeOffset)); } [Test] public void MapInt64() { - InsertingSingleCollection("map", typeof (Int64), typeof (DateTimeOffset)); + InsertingSingleCollection("map", typeof(Int64), typeof(DateTimeOffset)); } [Test] public void ListDouble() { - InsertingSingleCollection("list", typeof (Double)); + InsertingSingleCollection("list", typeof(Double)); } [Test] public void ListInt64() { - InsertingSingleCollection("list", typeof (Int64)); + InsertingSingleCollection("list", typeof(Int64)); } [Test] public void ListInt32() { - InsertingSingleCollection("list", typeof (Int32)); + InsertingSingleCollection("list", typeof(Int32)); } [Test] public void ListString() { - InsertingSingleCollection("list", typeof (string)); + InsertingSingleCollection("list", typeof(string)); } [Test] public void SetString() { - InsertingSingleCollection("set", typeof (string)); + InsertingSingleCollection("set", typeof(string)); } [Test] public void SetDouble() { - InsertingSingleCollection("set", typeof (Double)); + InsertingSingleCollection("set", typeof(Double)); } [Test] public void SetInt32() { - InsertingSingleCollection("set", typeof (Int32)); + InsertingSingleCollection("set", typeof(Int32)); } [Test] public void SetInt64() { - InsertingSingleCollection("set", typeof (Int64)); + InsertingSingleCollection("set", typeof(Int64)); } [Test] public void MapPrepared() { - insertingSingleCollectionPrepared("map", typeof (string), typeof (DateTimeOffset)); + insertingSingleCollectionPrepared("map", typeof(string), typeof(DateTimeOffset)); } [Test] public void MapDoublePrepared() { - insertingSingleCollectionPrepared("map", typeof (Double), typeof (DateTimeOffset)); + insertingSingleCollectionPrepared("map", typeof(Double), typeof(DateTimeOffset)); } [Test] public void MapInt32Prepared() { - insertingSingleCollectionPrepared("map", typeof (Int32), typeof (DateTimeOffset)); + insertingSingleCollectionPrepared("map", typeof(Int32), typeof(DateTimeOffset)); } [Test] public void MapInt64Prepared() { - insertingSingleCollectionPrepared("map", typeof (Int64), typeof (DateTimeOffset)); + insertingSingleCollectionPrepared("map", typeof(Int64), typeof(DateTimeOffset)); } [Test] public void ListDoublePrepared() { - insertingSingleCollectionPrepared("list", typeof (Double)); + insertingSingleCollectionPrepared("list", typeof(Double)); } [Test] public void ListInt64Prepared() { - insertingSingleCollectionPrepared("list", typeof (Int64)); + insertingSingleCollectionPrepared("list", typeof(Int64)); } [Test] public void ListInt32Prepared() { - insertingSingleCollectionPrepared("list", typeof (Int32)); + insertingSingleCollectionPrepared("list", typeof(Int32)); } [Test] public void ListStringPrepared() { - insertingSingleCollectionPrepared("list", typeof (string)); + insertingSingleCollectionPrepared("list", typeof(string)); } [Test] public void SetStringPrepared() { - insertingSingleCollectionPrepared("set", typeof (string)); + insertingSingleCollectionPrepared("set", typeof(string)); } [Test] public void SetDoublePrepared() { - insertingSingleCollectionPrepared("set", typeof (Double)); + insertingSingleCollectionPrepared("set", typeof(Double)); } [Test] public void SetInt32Prepared() { - insertingSingleCollectionPrepared("set", typeof (Int32)); + insertingSingleCollectionPrepared("set", typeof(Int32)); } [Test] public void SetInt64Prepared() { - insertingSingleCollectionPrepared("set", typeof (Int64)); + insertingSingleCollectionPrepared("set", typeof(Int64)); } } } diff --git a/src/Cassandra.IntegrationTests/Core/CompressionTests.cs b/src/Cassandra.IntegrationTests/Core/CompressionTests.cs index e178457ba..6489b7f96 100644 --- a/src/Cassandra.IntegrationTests/Core/CompressionTests.cs +++ b/src/Cassandra.IntegrationTests/Core/CompressionTests.cs @@ -39,7 +39,7 @@ public void Lz4_Compression_Under_Heavy_Concurrency_Test() session.Execute(string.Format("CREATE TABLE {0} (id uuid PRIMARY KEY, value text)", table)); var psInsert = session.Prepare(string.Format("INSERT INTO {0} (id, value) VALUES (?, ?)", table)); var psSelect = session.Prepare(string.Format("SELECT * FROM {0}", table)); - var values = new [] + var values = new[] { //different values string.Join("", Enumerable.Repeat("abc", 10)), // 3 * 10 + 16 + header + metadata = ~ 80 b on select diff --git a/src/Cassandra.IntegrationTests/Core/ConnectionSimulacronTests.cs b/src/Cassandra.IntegrationTests/Core/ConnectionSimulacronTests.cs index 89fcf5d2f..0b569dbe1 100644 --- a/src/Cassandra.IntegrationTests/Core/ConnectionSimulacronTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ConnectionSimulacronTests.cs @@ -245,11 +245,11 @@ public async Task Should_KeepOperationsInWriteQueue_When_ServerAppliesTcpBackPre var maxRequestsPerConnection = Session.Cluster.Configuration .GetOrCreatePoolingOptions(Session.Cluster.Metadata.ControlConnection.ProtocolVersion) .GetMaxRequestsPerConnection(); - + var tenKbBuffer = new byte[10240]; await TestCluster.PauseReadsAsync().ConfigureAwait(false); - + var pools = InternalSession.GetPools().ToList(); var connections = pools.SelectMany(kvp => kvp.Value.ConnectionsSnapshot).ToList(); var requests = new List(); @@ -295,9 +295,9 @@ public async Task Should_KeepOperationsInWriteQueue_When_ServerAppliesTcpBackPre var moreFailedRequests = moreRequests.Where(t => t.IsFaulted).ToList(); Assert.Greater(moreFailedRequests.Count, 1); Assert.AreEqual(moreRequests.Count, moreFailedRequests.Count); - + Assert.GreaterOrEqual(connections.Sum(c => c.InFlight), maxRequestsPerConnection * Session.Cluster.AllHosts().Count); - + // ReSharper disable once PossibleNullReferenceException Assert.IsTrue(moreFailedRequests.All(t => t.IsFaulted && ((NoHostAvailableException)t.Exception.InnerException).Errors.All(e => e.Value is BusyPoolException))); var newWriteQueueSizes = @@ -310,7 +310,7 @@ public async Task Should_KeepOperationsInWriteQueue_When_ServerAppliesTcpBackPre Assert.GreaterOrEqual(newWriteQueueSizes[kvp.Key], kvp.Value); Assert.Greater(newWriteQueueSizes[kvp.Key], 1); } - + foreach (var kvp in pendingOps) { Assert.AreEqual(newPendingsOps[kvp.Key], kvp.Value); @@ -329,9 +329,9 @@ public async Task Should_KeepOperationsInWriteQueue_When_ServerAppliesTcpBackPre } Assert.AreEqual( - requests.Count, - requests.Count(t => t.IsCompleted && !t.IsFaulted && !t.IsCanceled) - + requests.Count(t => t.IsFaulted && + requests.Count, + requests.Count(t => t.IsCompleted && !t.IsFaulted && !t.IsCanceled) + + requests.Count(t => t.IsFaulted && ((NoHostAvailableException)t.Exception.InnerException) .Errors.All(e => e.Value is BusyPoolException))); } diff --git a/src/Cassandra.IntegrationTests/Core/ConnectionTests.cs b/src/Cassandra.IntegrationTests/Core/ConnectionTests.cs index 0f10f213c..1b025bd7c 100644 --- a/src/Cassandra.IntegrationTests/Core/ConnectionTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ConnectionTests.cs @@ -54,7 +54,7 @@ public void SetupFixture() // we just need to make sure that there is a query-able cluster _testCluster = TestClusterManager.GetTestCluster(1, DefaultMaxClusterCreateRetries, true, false); } - + [Test] public void Basic_Startup_Test() { @@ -127,8 +127,8 @@ public void Execute_Prepared_Test() //Execute the prepared query var executeRequest = new ExecuteRequest( - GetSerializer(), - prepareOutput.QueryId, + GetSerializer(), + prepareOutput.QueryId, new ResultMetadata(prepareOutput.ResultMetadataId, prepareOutput.ResultRowsMetadata), QueryProtocolOptions.Default, false, @@ -157,8 +157,8 @@ public void Execute_Prepared_With_Param_Test() var options = new QueryProtocolOptions(ConsistencyLevel.One, new object[] { "local" }, false, 100, null, ConsistencyLevel.Any, null, null, prepareOutput.VariablesRowsMetadata); var executeRequest = new ExecuteRequest( - GetSerializer(), - prepareOutput.QueryId, + GetSerializer(), + prepareOutput.QueryId, new ResultMetadata(prepareOutput.ResultMetadataId, prepareOutput.ResultRowsMetadata), options, false, @@ -787,7 +787,7 @@ public async Task Heartbeat_Should_Be_Enabled_By_Default() { await connection.Open().ConfigureAwait(false); Assert.AreEqual(defaultHeartbeatInterval, connection.Configuration.PoolingOptions.GetHeartBeatInterval()); - + //execute a dummy query await Query(connection, "SELECT * FROM system.local", QueryProtocolOptions.Default).ConfigureAwait(false); @@ -835,10 +835,10 @@ public async Task Should_Have_InFlight_Set_To_Zero_After_Successful_And_Failed_R } private Connection CreateConnection( - ProtocolOptions protocolOptions = null, - SocketOptions socketOptions = null, - PoolingOptions poolingOptions = null, - ProtocolVersion? version = null, + ProtocolOptions protocolOptions = null, + SocketOptions socketOptions = null, + PoolingOptions poolingOptions = null, + ProtocolVersion? version = null, string contactPoint = null) { if (socketOptions == null) diff --git a/src/Cassandra.IntegrationTests/Core/ConsistencyTests.cs b/src/Cassandra.IntegrationTests/Core/ConsistencyTests.cs index a8d9811bf..c89d89194 100644 --- a/src/Cassandra.IntegrationTests/Core/ConsistencyTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ConsistencyTests.cs @@ -41,7 +41,7 @@ public class ConsistencyTests : TestGlobals [Test] public void Should_UseCLLocalOne_When_NotSpecifiedXDefaultX() { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" })) using (var cluster = ClusterBuilder() .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) { @@ -63,7 +63,7 @@ public void Should_UseCLLocalOne_When_NotSpecifiedXDefaultX() [TestCase(ConsistencyLevel.LocalQuorum)] public void Should_UseQueryOptionsCL_When_NotSetAtSimpleStatement(ConsistencyLevel consistencyLevel) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .WithQueryOptions(new QueryOptions().SetConsistencyLevel(consistencyLevel)) .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) @@ -81,7 +81,7 @@ public void Should_UseQueryOptionsCL_When_NotSetAtSimpleStatement(ConsistencyLev [TestCase(ConsistencyLevel.LocalSerial)] public void Should_UseQueryOptionsSerialCL_When_NotSetAtSimpleStatement(ConsistencyLevel serialConsistency) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .WithQueryOptions(new QueryOptions().SetSerialConsistencyLevel(serialConsistency)) .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) @@ -106,7 +106,7 @@ public void Should_UseQueryOptionsSerialCL_When_NotSetAtSimpleStatement(Consiste [TestCase(ConsistencyLevel.LocalQuorum)] public void Should_UseSimpleStatementCL_When_Set(ConsistencyLevel consistencyLevel) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.Any)) .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) @@ -125,7 +125,7 @@ public void Should_UseSimpleStatementCL_When_Set(ConsistencyLevel consistencyLev public void Should_UseSerialConsistencyLevelSpecified_When_ConditionalQuery( ConsistencyLevel consistencyLevel, ConsistencyLevel serialConsistency) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) { @@ -146,7 +146,7 @@ public void Should_UseSerialConsistencyLevelSpecified_When_ConditionalQuery( public void Should_UseSerialConsistencyLevel_From_QueryOptions( ConsistencyLevel consistencyLevel, ConsistencyLevel serialConsistency) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .AddContactPoint(simulacronCluster.InitialContactPoint) .WithQueryOptions(new QueryOptions() @@ -175,7 +175,7 @@ public void Should_UseSerialConsistencyLevel_From_QueryOptions( [TestCase(ConsistencyLevel.LocalQuorum)] public void Should_UseQueryOptionsCL_When_NotSetAtPreparedStatement(ConsistencyLevel consistencyLevel) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .WithQueryOptions(new QueryOptions().SetConsistencyLevel(consistencyLevel)) .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) @@ -195,7 +195,7 @@ public void Should_UseQueryOptionsCL_When_NotSetAtPreparedStatement(ConsistencyL [TestCase(ConsistencyLevel.LocalSerial)] public void Should_UseQueryOptionsSerialCL_When_NotSetAtPreparedStatement(ConsistencyLevel consistencyLevel) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .WithQueryOptions(new QueryOptions().SetSerialConsistencyLevel(consistencyLevel)) .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) @@ -221,7 +221,7 @@ public void Should_UseQueryOptionsSerialCL_When_NotSetAtPreparedStatement(Consis [TestCase(ConsistencyLevel.LocalQuorum)] public void Should_UsePreparedStatementCL_When_Set(ConsistencyLevel consistencyLevel) { - using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } )) + using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" })) using (var cluster = ClusterBuilder() .AddContactPoint(simulacronCluster.InitialContactPoint).Build()) { @@ -235,7 +235,7 @@ public void Should_UsePreparedStatementCL_When_Set(ConsistencyLevel consistencyL } } - private static void VerifyConsistency(SimulacronCluster simulacronCluster, string query, ConsistencyLevel consistency, + private static void VerifyConsistency(SimulacronCluster simulacronCluster, string query, ConsistencyLevel consistency, ConsistencyLevel? serialConsistency = null, QueryType queryType = QueryType.Query) { var executedQueries = simulacronCluster.GetQueries(query, queryType); diff --git a/src/Cassandra.IntegrationTests/Core/ControlConnectionSimulatorTests.cs b/src/Cassandra.IntegrationTests/Core/ControlConnectionSimulatorTests.cs index e3d4d43d9..7900058d3 100644 --- a/src/Cassandra.IntegrationTests/Core/ControlConnectionSimulatorTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ControlConnectionSimulatorTests.cs @@ -68,7 +68,7 @@ public void Should_Downgrade_To_Protocol_VX_With_Versions(ProtocolVersion versio } } } - + [TestCase(ProtocolVersion.V5, "4.0.0")] [TestCase(ProtocolVersion.V4, "3.11.6", "3.0.11", "2.2.9")] [TestCase(ProtocolVersion.V4, "3.0.13", "3.0.11", "2.2.9")] diff --git a/src/Cassandra.IntegrationTests/Core/ControlConnectionTests.cs b/src/Cassandra.IntegrationTests/Core/ControlConnectionTests.cs index 4d1c530ce..fd9801ffc 100644 --- a/src/Cassandra.IntegrationTests/Core/ControlConnectionTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ControlConnectionTests.cs @@ -104,9 +104,9 @@ private ControlConnection NewInstance( metadata.AddHost(new IPEndPoint(IPAddress.Parse(_testCluster.InitialContactPoint), ProtocolOptions.DefaultPort)); } var cc = new ControlConnection( - Mock.Of(), - GetEventDebouncer(config), - version, + Mock.Of(), + GetEventDebouncer(config), + version, config, metadata, new List @@ -120,8 +120,8 @@ private ControlConnection NewInstance( private IProtocolEventDebouncer GetEventDebouncer(Configuration config) { return new ProtocolEventDebouncer( - new TaskBasedTimerFactory(), - TimeSpan.FromMilliseconds(config.MetadataSyncOptions.RefreshSchemaDelayIncrement), + new TaskBasedTimerFactory(), + TimeSpan.FromMilliseconds(config.MetadataSyncOptions.RefreshSchemaDelayIncrement), TimeSpan.FromMilliseconds(config.MetadataSyncOptions.MaxTotalRefreshSchemaDelay)); } } diff --git a/src/Cassandra.IntegrationTests/Core/CustomPayloadTests.cs b/src/Cassandra.IntegrationTests/Core/CustomPayloadTests.cs index 6553a97f4..3128a7e01 100644 --- a/src/Cassandra.IntegrationTests/Core/CustomPayloadTests.cs +++ b/src/Cassandra.IntegrationTests/Core/CustomPayloadTests.cs @@ -43,7 +43,7 @@ public void SetupFixture() } //Using a mirroring handler, the server will reply providing the same payload that was sent - var jvmArgs = new [] { "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler" }; + var jvmArgs = new[] { "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler" }; var testCluster = TestClusterManager.GetTestCluster(1, 0, false, DefaultMaxClusterCreateRetries, true, true, 0, jvmArgs); Session = testCluster.Session; Session.Execute(string.Format(TestUtils.CreateKeyspaceSimpleFormat, Keyspace, 1)); @@ -96,7 +96,7 @@ public void Prepare_Payload_Test() { var outgoing = new Dictionary { - { "k1-prep", Encoding.UTF8.GetBytes("value1-prep") }, + { "k1-prep", Encoding.UTF8.GetBytes("value1-prep") }, { "k2-prep", Encoding.UTF8.GetBytes("value2-prep") } }; var prepared = Session.Prepare("SELECT key as k FROM system.local WHERE key = ?", outgoing); diff --git a/src/Cassandra.IntegrationTests/Core/EmptyColumnTests.cs b/src/Cassandra.IntegrationTests/Core/EmptyColumnTests.cs index 79141f47e..2d59c14df 100644 --- a/src/Cassandra.IntegrationTests/Core/EmptyColumnTests.cs +++ b/src/Cassandra.IntegrationTests/Core/EmptyColumnTests.cs @@ -40,9 +40,9 @@ public void Should_ReturnCorrectValue_When_EmptyColumnNameAndSchemaParserV2() simulacronCluster.PrimeSystemSchemaTablesV2( "testks", "testtable", - new[] - { - new StubTableColumn("", StubColumnKind.PartitionKey, DataType.GetDataType(typeof(string))), + new[] + { + new StubTableColumn("", StubColumnKind.PartitionKey, DataType.GetDataType(typeof(string))), new StubTableColumn(" ", StubColumnKind.ClusteringKey, DataType.GetDataType(typeof(string))) }); @@ -104,9 +104,9 @@ public void Should_ReturnCorrectValue_When_EmptyColumnNameAndSchemaParserV1() simulacronCluster.PrimeSystemSchemaTablesV1( "testks", "testtable", - new[] - { - new StubTableColumn("", StubColumnKind.PartitionKey, DataType.GetDataType(typeof(string))), + new[] + { + new StubTableColumn("", StubColumnKind.PartitionKey, DataType.GetDataType(typeof(string))), new StubTableColumn(" ", StubColumnKind.ClusteringKey, DataType.GetDataType(typeof(string))) }); diff --git a/src/Cassandra.IntegrationTests/Core/ExceptionsTests.cs b/src/Cassandra.IntegrationTests/Core/ExceptionsTests.cs index 644a9da36..98225b404 100644 --- a/src/Cassandra.IntegrationTests/Core/ExceptionsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ExceptionsTests.cs @@ -63,16 +63,16 @@ public void TearDown() public void AlreadyExistsException() { var cql = string.Format(TestUtils.CreateKeyspaceSimpleFormat, _keyspace, 1); - + _simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenAlreadyExists(_keyspace, "")); var ex = Assert.Throws(() => _session.Execute(cql)); Assert.AreEqual(ex.Keyspace, _keyspace); Assert.AreEqual(ex.Table, null); Assert.AreEqual(ex.WasTableCreation, false); - + var cqlTable = string.Format(TestUtils.CreateTableSimpleFormat, _table); - + _simulacronCluster.PrimeFluent(b => b.WhenQuery(cqlTable).ThenAlreadyExists(_keyspace, _table)); var e = Assert.Throws(() => _session.Execute(cqlTable)); Assert.AreEqual(e.Keyspace, _keyspace); @@ -88,7 +88,7 @@ public void AlreadyExistsException() public void NoHostAvailableException() { const string ipAddress = "255.255.255.255"; - var errorsHashMap = new Dictionary {{IPAddress.Parse(ipAddress), null}}; + var errorsHashMap = new Dictionary { { IPAddress.Parse(ipAddress), null } }; try { @@ -322,7 +322,7 @@ public void ReadFailureExceptionTest(ConsistencyLevel consistencyLevel, int rece _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenReadFailure( - (int) consistencyLevel, + (int)consistencyLevel, received, required, "read_failure", diff --git a/src/Cassandra.IntegrationTests/Core/HeartbeatTests.cs b/src/Cassandra.IntegrationTests/Core/HeartbeatTests.cs index 1c18b38fc..273ffb57a 100644 --- a/src/Cassandra.IntegrationTests/Core/HeartbeatTests.cs +++ b/src/Cassandra.IntegrationTests/Core/HeartbeatTests.cs @@ -34,7 +34,7 @@ public class HeartbeatTests : TestGlobals [OneTimeSetUp] public void OneTimeSetup() { - _testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "1"}); + _testCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "1" }); _testCluster.PrimeFluent(b => b.WhenQuery(HeartbeatTests.Query).ThenVoidSuccess()); } @@ -71,7 +71,7 @@ await TestHelper.RetryAssertAsync( logs = await _testCluster.GetNodes().First() .GetQueriesAsync(null, OptionsQueryType).ConfigureAwait(false); Assert.That(logs.Count, Is.GreaterThan(initialCount)); - }, + }, 500, 20).ConfigureAwait(false); } diff --git a/src/Cassandra.IntegrationTests/Core/LargeDataTests.cs b/src/Cassandra.IntegrationTests/Core/LargeDataTests.cs index 77c0f46d4..7be40d713 100644 --- a/src/Cassandra.IntegrationTests/Core/LargeDataTests.cs +++ b/src/Cassandra.IntegrationTests/Core/LargeDataTests.cs @@ -32,7 +32,7 @@ public class LargeDataTests : TestGlobals { private const int Key = 0; private const string KeyspaceNameDefault = "largedatatests"; - ISession _session = null; + ISession _session = null; [SetUp] public void SetupFixture() diff --git a/src/Cassandra.IntegrationTests/Core/MetadataTests.cs b/src/Cassandra.IntegrationTests/Core/MetadataTests.cs index 31d5d87ae..19d82ae97 100644 --- a/src/Cassandra.IntegrationTests/Core/MetadataTests.cs +++ b/src/Cassandra.IntegrationTests/Core/MetadataTests.cs @@ -47,7 +47,7 @@ public void KeyspacesMetadataUpToDateViaCassandraEvents() Assert.Greater(initialLength, 0); //GetReplicas should yield the primary replica when the Keyspace is not found - Assert.AreEqual(1, cluster.GetReplicas("ks2", new byte[] {0, 0, 0, 1}).Count); + Assert.AreEqual(1, cluster.GetReplicas("ks2", new byte[] { 0, 0, 0, 1 }).Count); const string createKeyspaceQuery = "CREATE KEYSPACE {0} WITH replication = {{ 'class' : '{1}', {2} }}"; session.Execute(string.Format(createKeyspaceQuery, "ks1", "SimpleStrategy", "'replication_factor' : 1")); @@ -64,7 +64,7 @@ public void KeyspacesMetadataUpToDateViaCassandraEvents() Assert.NotNull(ks2); Assert.AreEqual(ks2.Replication["replication_factor"], 3); //GetReplicas should yield the 2 replicas (rf=3 but cluster=2) when the Keyspace is found - Assert.AreEqual(2, cluster.GetReplicas("ks2", new byte[] {0, 0, 0, 1}).Count); + Assert.AreEqual(2, cluster.GetReplicas("ks2", new byte[] { 0, 0, 0, 1 }).Count); var ks3 = cluster.Metadata.GetKeyspace("ks3"); Assert.NotNull(ks3); Assert.AreEqual(ks3.Replication["dc1"], 1); @@ -291,7 +291,7 @@ public void CheckNetworkTopologyStrategyKeyspace() string strategyClass = ReplicationStrategies.NetworkTopologyStrategy; int dataCentersCount = Randomm.Instance.Next(1, 11); - datacentersReplicationFactors = new Dictionary((int) dataCentersCount); + datacentersReplicationFactors = new Dictionary((int)dataCentersCount); for (int i = 0; i < dataCentersCount; i++) datacentersReplicationFactors.Add("dc" + i, Randomm.Instance.Next(1, 21)); session.CreateKeyspace(keyspaceName, @@ -481,7 +481,7 @@ public void TableMetadata_With_Compact_Storage() CollectionAssert.AreEqual(new[] { "id1" }, table.PartitionKeys.Select(c => c.Name)); CollectionAssert.AreEqual(new[] { "id2" }, table.ClusteringKeys.Select(c => c.Item1.Name)); CollectionAssert.AreEqual(new[] { SortOrder.Ascending }, table.ClusteringKeys.Select(c => c.Item2)); - + table = cluster.Metadata .GetKeyspace("ks_meta_compac") .GetTableMetadata("tbl6"); @@ -570,7 +570,7 @@ public void GetMaterializedView_Should_Retrieve_View_Metadata() { session.Execute(q); } - + var ks = cluster.Metadata.GetKeyspace("ks_view_meta"); Assert.NotNull(ks); var view = ks.GetMaterializedViewMetadata("dailyhigh"); @@ -586,13 +586,13 @@ public void GetMaterializedView_Should_Retrieve_View_Metadata() view.WhereClause); Assert.AreEqual(6, view.TableColumns.Length); - Assert.AreEqual(new[] { "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta" }, + Assert.AreEqual(new[] { "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta", "ks_view_meta" }, view.TableColumns.Select(c => c.Keyspace)); Assert.AreEqual(new[] { "dailyhigh", "dailyhigh", "dailyhigh", "dailyhigh", "dailyhigh", "dailyhigh" }, view.TableColumns.Select(c => c.Table)); Assert.AreEqual(new[] { "day", "game", "month", "score", "user", "year" }, view.TableColumns.Select(c => c.Name)); - Assert.AreEqual(new[] { ColumnTypeCode.Int, ColumnTypeCode.Varchar, ColumnTypeCode.Int, ColumnTypeCode.Int, ColumnTypeCode.Varchar, + Assert.AreEqual(new[] { ColumnTypeCode.Int, ColumnTypeCode.Varchar, ColumnTypeCode.Int, ColumnTypeCode.Int, ColumnTypeCode.Varchar, ColumnTypeCode.Int }, view.TableColumns.Select(c => c.TypeCode)); Assert.AreEqual(new[] { "game", "year", "month", "day" }, view.PartitionKeys.Select(c => c.Name)); Assert.AreEqual(new[] { "score", "user" }, view.ClusteringKeys.Select(c => c.Item1.Name)); diff --git a/src/Cassandra.IntegrationTests/Core/MultiThreadingTests.cs b/src/Cassandra.IntegrationTests/Core/MultiThreadingTests.cs index e2afeaee7..75421467c 100644 --- a/src/Cassandra.IntegrationTests/Core/MultiThreadingTests.cs +++ b/src/Cassandra.IntegrationTests/Core/MultiThreadingTests.cs @@ -105,8 +105,8 @@ public void ParallelInsertTest() ar[i] = localSession.BeginExecute(string.Format(@" INSERT INTO {0} (tweet_id, author, isok, body) - VALUES ({1},'test{2}',{3},'body{2}');", - tableName, Guid.NewGuid(), i, i%2 == 0 ? "false" : "true"), ConsistencyLevel.One, null, null); + VALUES ({1},'test{2}',{3},'body{2}');", + tableName, Guid.NewGuid(), i, i % 2 == 0 ? "false" : "true"), ConsistencyLevel.One, null, null); Interlocked.MemoryBarrier(); } catch @@ -196,7 +196,7 @@ public void InsertFireAndForget() var taskList = new List>(); for (var i = 0; i < rowLength; i++) { - taskList.Add(localSession.ExecuteAsync(insertStatement.Bind(Guid.NewGuid(), new byte[1024*rnd.Next(10)]))); + taskList.Add(localSession.ExecuteAsync(insertStatement.Bind(Guid.NewGuid(), new byte[1024 * rnd.Next(10)]))); } var taskArray = taskList.ToArray(); @@ -234,7 +234,7 @@ public void MassiveAsyncTest() localSession.ChangeKeyspace(keyspaceName); string tableName = "table" + Randomm.RandomAlphaNum(8); - + localSession.Execute(string.Format(@"CREATE TABLE {0}( tweet_id uuid, author text, @@ -254,7 +254,7 @@ public void MassiveAsyncTest() author, isok, body) - VALUES ({1},'test{2}',{3},'body{2}');", tableName, Guid.NewGuid(), i, i%2 == 0 ? "false" : "true") + VALUES ({1},'test{2}',{3},'body{2}');", tableName, Guid.NewGuid(), i, i % 2 == 0 ? "false" : "true") , ConsistencyLevel.One, _ => { ar[tmpi] = true; @@ -321,8 +321,8 @@ public void ShutdownAsyncTest() int tmpi = i; try { - var query = string.Format(@"INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", - tableName, Guid.NewGuid(), i, i%2 == 0 ? "false" : "true"); + var query = string.Format(@"INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", + tableName, Guid.NewGuid(), i, i % 2 == 0 ? "false" : "true"); localSession.BeginExecute(query, ConsistencyLevel.Quorum, arx => { try diff --git a/src/Cassandra.IntegrationTests/Core/PagingTests.cs b/src/Cassandra.IntegrationTests/Core/PagingTests.cs index 2bdf05a8e..ef02680e3 100644 --- a/src/Cassandra.IntegrationTests/Core/PagingTests.cs +++ b/src/Cassandra.IntegrationTests/Core/PagingTests.cs @@ -162,16 +162,16 @@ public void Should_PagingOnBoundStatement_When_NewResultMetadataIsSet() Assert.AreNotSame(previousResultMetadata, ps.ResultMetadata); Assert.AreNotEqual(previousResultMetadata.ResultMetadataId, ps.ResultMetadata.ResultMetadataId); Assert.AreEqual(3, ps.ResultMetadata.RowSetMetadata.Columns.Length); - + rs = Session.Execute(boundStatementManualPaging.SetPagingState(rs.PagingState)); var thirdPage = rs.ToList(); - + var allRowsAfterAlter = Session.Execute(ps.Bind()).ToList(); Assert.AreEqual(totalRowLength, allRowsAfterAlter.Count); Assert.AreEqual(pageSize, firstPage.Count); Assert.AreEqual(pageSize, secondPage.Count); - Assert.AreEqual(totalRowLength-(pageSize*2), thirdPage.Count); + Assert.AreEqual(totalRowLength - (pageSize * 2), thirdPage.Count); Assert.IsTrue(firstPage.All(r => !r.ContainsColumn("new_column"))); Assert.IsTrue(secondPage.All(r => r.ContainsColumn("new_column") && r.GetValue("new_column") == null)); diff --git a/src/Cassandra.IntegrationTests/Core/ParameterizedStatementsTests.cs b/src/Cassandra.IntegrationTests/Core/ParameterizedStatementsTests.cs index bf767ddd4..630f3b3f1 100644 --- a/src/Cassandra.IntegrationTests/Core/ParameterizedStatementsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ParameterizedStatementsTests.cs @@ -295,7 +295,7 @@ public void SimpleStatementNamedValuesCaseInsensitivity() Session.Execute( new SimpleStatement( insertQuery, - new { my_INt = 1, my_TEXT = "WAT1", my_id = id})); + new { my_INt = 1, my_TEXT = "WAT1", my_id = id })); var row = Session.Execute(string.Format("SELECT * FROM {0} WHERE id = {1:D}", AllTypesTableName, id)).First(); Assert.AreEqual(1, row.GetValue("int_sample")); @@ -310,7 +310,7 @@ public void SimpleStatementNamedValuesNotSpecified() Assert.Throws(() => Session.Execute( new SimpleStatement(insertQuery, - new {id = Guid.NewGuid(), my_bigint = 1L }))); + new { id = Guid.NewGuid(), my_bigint = 1L }))); } [Test] @@ -341,7 +341,7 @@ public void SimpleStatementTinyIntTests() foreach (var v in values) { var insert = new SimpleStatement("INSERT INTO tbl_tinyint_param (id, v, m) VALUES (?, ?, ?)", - Convert.ToInt32(v), v, new SortedDictionary { { v, v.ToString()} }); + Convert.ToInt32(v), v, new SortedDictionary { { v, v.ToString() } }); var select = new SimpleStatement("SELECT * FROM tbl_tinyint_param WHERE id = ?", Convert.ToInt32(v)); Session.Execute(insert); var rs = Session.Execute(select).ToList(); @@ -535,7 +535,7 @@ public void SimpleStatement_With_Keyspace_Defined_On_Protocol_Greater_Than_4() } [Test] - [TestBothServersVersion(4, 0, 5,1, Comparison.LessThan)] + [TestBothServersVersion(4, 0, 5, 1, Comparison.LessThan)] public void SimpleStatement_With_Keyspace_Defined_On_Lower_Protocol_Versions() { // It should fail as the keyspace from the session will be used diff --git a/src/Cassandra.IntegrationTests/Core/PoolShortTests.cs b/src/Cassandra.IntegrationTests/Core/PoolShortTests.cs index 4b3d5d2d8..bf423c916 100644 --- a/src/Cassandra.IntegrationTests/Core/PoolShortTests.cs +++ b/src/Cassandra.IntegrationTests/Core/PoolShortTests.cs @@ -308,7 +308,7 @@ public async Task Should_Create_Core_Connections_To_Hosts_In_Local_Dc_When_Warmu } } } - + [Test] public async Task ControlConnection_Should_Reconnect_To_Up_Host() { @@ -654,9 +654,9 @@ await TestHelper.RetryAssertAsync(async () => connections = await simulacronNode.GetConnectionsAsync().ConfigureAwait(false); Assert.AreEqual(1, connections.Count); }, 100, 200).ConfigureAwait(false); - + await testCluster.DropConnection(connections[0]).ConfigureAwait(false); - + await TestHelper.RetryAssertAsync(async () => { connections = await simulacronNode.GetConnectionsAsync().ConfigureAwait(false); diff --git a/src/Cassandra.IntegrationTests/Core/PoolTests.cs b/src/Cassandra.IntegrationTests/Core/PoolTests.cs index fd50c0ffd..83972765e 100644 --- a/src/Cassandra.IntegrationTests/Core/PoolTests.cs +++ b/src/Cassandra.IntegrationTests/Core/PoolTests.cs @@ -281,7 +281,7 @@ public void AddressTranslatorIsCalledPerEachPeer() Thread.Sleep(30000); //Should be down Assert.False(cluster.AllHosts().First(h => TestHelper.GetLastAddressByte(h) == 3).IsUp); - + //Should have been translated Assert.AreEqual(3, invokedEndPoints.Count); //The recently translated should be the host #3 diff --git a/src/Cassandra.IntegrationTests/Core/PrepareSimulatorTests.cs b/src/Cassandra.IntegrationTests/Core/PrepareSimulatorTests.cs index cdd74864b..8de7eb24b 100644 --- a/src/Cassandra.IntegrationTests/Core/PrepareSimulatorTests.cs +++ b/src/Cassandra.IntegrationTests/Core/PrepareSimulatorTests.cs @@ -34,7 +34,7 @@ public class PrepareSimulatorTests : TestGlobals { private const string Keyspace = "ks1"; private static readonly string Query = $"SELECT * FROM {PrepareSimulatorTests.Keyspace}.prepare_table1"; - + private static readonly string QueryWithoutKeyspace = $"SELECT * FROM prepare_table1"; private static IPrimeRequest QueryPrime(int delay = 0) @@ -46,7 +46,7 @@ private static IPrimeRequest QueryPrime(int delay = 0) .WithDelayInMs(delay) .BuildRequest(); } - + private static IPrimeRequest QueryWithoutKeyspacePrime(int delay = 0) { return SimulacronBase @@ -221,7 +221,7 @@ public async Task Should_Reprepare_On_Up_Node() Assert.AreEqual(2, node.GetQueries(Query, QueryType.Prepare).Count); } } - + [Test] public async Task Should_ReprepareOnUpNodeAfterSetKeyspace_With_SessionKeyspace() { @@ -250,7 +250,7 @@ public async Task Should_ReprepareOnUpNodeAfterSetKeyspace_With_SessionKeyspace( await node.Stop().ConfigureAwait(false); await TestHelper.WaitUntilAsync(() => cluster.AllHosts().Any(h => !h.IsUp)).ConfigureAwait(false); Assert.AreEqual(1, cluster.AllHosts().Count(h => !h.IsUp)); - + // still only 1 USE and Prepare requests Assert.AreEqual(1, node.GetQueries($"USE \"{PrepareSimulatorTests.Keyspace}\"").Count); Assert.AreEqual(1, node.GetQueries(PrepareSimulatorTests.QueryWithoutKeyspace, QueryType.Prepare).Count); @@ -264,10 +264,10 @@ public async Task Should_ReprepareOnUpNodeAfterSetKeyspace_With_SessionKeyspace( Assert.AreEqual(0, cluster.AllHosts().Count(h => !h.IsUp)); // wait until driver reprepares the statement - TestHelper.WaitUntil(() => + TestHelper.WaitUntil(() => node.GetQueries(PrepareSimulatorTests.QueryWithoutKeyspace, QueryType.Prepare).Count == 2 && node.GetQueries(PrepareSimulatorTests.Query, QueryType.Prepare).Count == 2); - + // It should be prepared 2 times Assert.AreEqual(2, node.GetQueries(PrepareSimulatorTests.QueryWithoutKeyspace, QueryType.Prepare).Count); Assert.AreEqual(2, node.GetQueries(PrepareSimulatorTests.Query, QueryType.Prepare).Count); @@ -284,11 +284,11 @@ public async Task Should_ReprepareOnUpNodeAfterSetKeyspace_With_SessionKeyspace( Assert.AreEqual(PrepareSimulatorTests.Query, relevantQueries[2].Query); Assert.AreEqual($"USE \"{PrepareSimulatorTests.Keyspace}\"", relevantQueries[3].Query); CollectionAssert.AreEquivalent( - new [] + new[] { PrepareSimulatorTests.QueryWithoutKeyspace, PrepareSimulatorTests.Query - }, + }, relevantQueries.Skip(4).Select(q => q.Query)); } } diff --git a/src/Cassandra.IntegrationTests/Core/PreparedStatementsTests.cs b/src/Cassandra.IntegrationTests/Core/PreparedStatementsTests.cs index 5d03c2e5d..f871b679d 100644 --- a/src/Cassandra.IntegrationTests/Core/PreparedStatementsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/PreparedStatementsTests.cs @@ -75,7 +75,7 @@ public override void OneTimeSetUp() Session.Execute(string.Format(TestUtils.CreateTableAllTypes, AllTypesTableName)); CreateTable(_tableName); } - + [Test] public void Bound_AllSingleTypesDifferentValues() { @@ -86,21 +86,21 @@ INSERT INTO {0} VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", AllTypesTableName); var preparedStatement = Session.Prepare(insertQuery); - CollectionAssert.AreEqual(new[] {0}, preparedStatement.RoutingIndexes); - - var firstRowValues = new object[] - { - Guid.NewGuid(), "first", 10, Int64.MaxValue - 1, 1.999F, 32.002D, 1.101010M, + CollectionAssert.AreEqual(new[] { 0 }, preparedStatement.RoutingIndexes); + + var firstRowValues = new object[] + { + Guid.NewGuid(), "first", 10, Int64.MaxValue - 1, 1.999F, 32.002D, 1.101010M, new byte[] {255, 255}, true, new DateTimeOffset(new DateTime(2005, 8, 5)), new IPAddress(new byte[] {192, 168, 0, 100}) }; - var secondRowValues = new object[] - { - Guid.NewGuid(), "second", 0, 0L, 0F, 0D, 0M, + var secondRowValues = new object[] + { + Guid.NewGuid(), "second", 0, 0L, 0F, 0D, 0M, new byte[] {0, 0}, true, new DateTimeOffset(new DateTime(1970, 9, 18)), new IPAddress(new byte[] {0, 0, 0, 0}) }; - var thirdRowValues = new object[] - { - Guid.NewGuid(), "third", -100, Int64.MinValue + 1, -150.111F, -5.12342D, -8.101010M, + var thirdRowValues = new object[] + { + Guid.NewGuid(), "third", -100, Int64.MinValue + 1, -150.111F, -5.12342D, -8.101010M, new byte[] {1, 1}, true, new DateTimeOffset(new DateTime(1543, 5, 24)), new IPAddress(new byte[] {255, 128, 12, 1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}) }; @@ -116,7 +116,7 @@ INSERT INTO {0} var rowList = Session.Execute(selectQuery).ToList(); //Check that they were inserted and retrieved Assert.AreEqual(3, rowList.Count); - + //Create a dictionary with the inserted values to compare with the retrieved values var insertedValues = new Dictionary() { @@ -128,7 +128,7 @@ INSERT INTO {0} foreach (var retrievedRow in rowList) { var inserted = insertedValues[retrievedRow.GetValue("id")]; - for (var i = 0; i < inserted.Length; i++ ) + for (var i = 0; i < inserted.Length; i++) { var insertedValue = inserted[i]; var retrievedValue = retrievedRow[i]; @@ -149,8 +149,8 @@ INSERT INTO {0} var preparedStatement = Session.Prepare(insertQuery); Assert.AreEqual(columns, String.Join(", ", preparedStatement.Variables.Columns.Select(c => c.Name))); - var nullRowValues = new object[] - { + var nullRowValues = new object[] + { Guid.NewGuid(), null, null, null, null, null, null, null, null, null, null }; @@ -174,8 +174,8 @@ INSERT INTO {0} var preparedStatement = Session.Prepare(insertQuery); Assert.AreEqual(columns, String.Join(", ", preparedStatement.Variables.Columns.Select(c => c.Name))); - var nullRowValues = new object[] - { + var nullRowValues = new object[] + { Guid.NewGuid(), "" }; @@ -335,22 +335,22 @@ public void Bound_Unset_Values_Tests() // initial condition Session.Execute(insert.Bind(0, 0, 0)); - Check_Expected(select, new object[] {0, 0, 0}); + Check_Expected(select, new object[] { 0, 0, 0 }); // explicit unset Session.Execute(insert.Bind(0, 1, Unset.Value)); - Check_Expected(select, new object[] {0, 1, 0}); + Check_Expected(select, new object[] { 0, 1, 0 }); Session.Execute(insert.Bind(0, Unset.Value, 2)); - Check_Expected(select, new object[] {0, 1, 2}); - - Session.Execute(insert.Bind(new {k = 0, v0 = 3, v1 = Unset.Value})); - Check_Expected(select, new object[] {0, 3, 2}); - Session.Execute(insert.Bind(new {k = 0, v0 = Unset.Value, v1 = 4})); - Check_Expected(select, new object[] {0, 3, 4}); + Check_Expected(select, new object[] { 0, 1, 2 }); + + Session.Execute(insert.Bind(new { k = 0, v0 = 3, v1 = Unset.Value })); + Check_Expected(select, new object[] { 0, 3, 2 }); + Session.Execute(insert.Bind(new { k = 0, v0 = Unset.Value, v1 = 4 })); + Check_Expected(select, new object[] { 0, 3, 4 }); // nulls still work Session.Execute(insert.Bind(0, null, null)); - Check_Expected(select, new object[] {0, null, null}); + Check_Expected(select, new object[] { 0, null, null }); // PKs cannot be UNSET Assert.Throws(Is.InstanceOf(), () => Session.Execute(insert.Bind(Unset.Value, 0, 0))); @@ -369,23 +369,23 @@ INSERT INTO {0} var preparedStatement = Session.Prepare(insertQuery); CollectionAssert.AreEqual(new[] { 0 }, preparedStatement.RoutingIndexes); - var firstRowValues = new object[] - { - Guid.NewGuid(), + var firstRowValues = new object[] + { + Guid.NewGuid(), new Dictionary {{"key1", "value1"}, {"key2", "value2"}}, new List (new [] {"one", "two", "three", "four", "five"}), new List (new [] {"set_1one", "set_2two", "set_3three", "set_4four", "set_5five"}) }; - var secondRowValues = new object[] - { - Guid.NewGuid(), + var secondRowValues = new object[] + { + Guid.NewGuid(), new Dictionary(), new List(), new List() }; - var thirdRowValues = new object[] - { - Guid.NewGuid(), + var thirdRowValues = new object[] + { + Guid.NewGuid(), null, null, null @@ -426,7 +426,7 @@ INSERT INTO {0} } if (insertedValue != null) { - Assert.AreEqual(((ICollection) insertedValue).Count, ((ICollection) retrievedValue).Count); + Assert.AreEqual(((ICollection)insertedValue).Count, ((ICollection)retrievedValue).Count); } Assert.AreEqual(insertedValue, retrievedValue); } @@ -465,7 +465,7 @@ public void Bound_NamedParamsOrder() if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 2), Comparison.LessThan)) { //For older versions, there is no way to determine that my_id is actually id column - Assert.Null(preparedStatement.RoutingIndexes); + Assert.Null(preparedStatement.RoutingIndexes); } Assert.AreEqual(preparedStatement.Variables.Columns.Length, 4); Assert.AreEqual("my_text, my_int, my_bigint, my_id", String.Join(", ", preparedStatement.Variables.Columns.Select(c => c.Name))); @@ -477,7 +477,7 @@ public void Bound_NamedParameters() { var insertQuery = string.Format("INSERT INTO {0} (text_sample, int_sample, bigint_sample, id) VALUES (:my_text, :my_int, :my_bigint, :id)", AllTypesTableName); var preparedStatement = Session.Prepare(insertQuery); - CollectionAssert.AreEqual(new [] {3}, preparedStatement.RoutingIndexes); + CollectionAssert.AreEqual(new[] { 3 }, preparedStatement.RoutingIndexes); Assert.AreEqual(preparedStatement.Variables.Columns.Length, 4); Assert.AreEqual("my_text, my_int, my_bigint, id", String.Join(", ", preparedStatement.Variables.Columns.Select(c => c.Name))); @@ -503,7 +503,7 @@ public void Bound_NamedParameters_Nulls() var id = Guid.NewGuid(); Session.Execute( preparedStatement.Bind( - new {my_bigint = (long?)null, my_int = 100, my_id = id})); + new { my_bigint = (long?)null, my_int = 100, my_id = id })); var row = Session.Execute(string.Format("SELECT int_sample, bigint_sample, text_sample FROM {0} WHERE id = {1:D}", AllTypesTableName, id)).First(); @@ -755,10 +755,10 @@ public void Bound_With_Named_Parameters_Routing_Key() var ps = Session.Prepare("SELECT * FROM tbl_ps_multiple_pk_named WHERE a = :a AND b = :b AND c = :ce"); //Parameters at position 1 and 0 are part of the routing key CollectionAssert.AreEqual(new[] { 0, 1 }, ps.RoutingIndexes); - var anon = new {ce = "hello ce2", a = "aValue1", b = "bValue1"}; + var anon = new { ce = "hello ce2", a = "aValue1", b = "bValue1" }; var statement = ps.Bind(anon); Assert.NotNull(statement.RoutingKey); - CollectionAssert.AreEqual(calculateKey(anon.a, anon.b), statement.RoutingKey.RawRoutingKey); + CollectionAssert.AreEqual(calculateKey(anon.a, anon.b), statement.RoutingKey.RawRoutingKey); //Now with another parameters anon = new { ce = "hello ce2", a = "aValue2", b = "bValue2" }; statement = ps.Bind(anon); @@ -854,7 +854,7 @@ public void Bound_TinyInt_Tests() [TestCase(true)] [TestCase(false)] - [TestBothServersVersion(4,0,5,1)] + [TestBothServersVersion(4, 0, 5, 1)] public void Session_Prepare_With_Keyspace_Defined_On_Protocol_Greater_Than_4(bool usePayload) { if (Session.Cluster.Metadata.ControlConnection.Serializer.CurrentProtocolVersion < ProtocolVersion.V5) @@ -872,7 +872,7 @@ public void Session_Prepare_With_Keyspace_Defined_On_Protocol_Greater_Than_4(boo else { ps = Session.Prepare("SELECT key FROM local", "system", - new Dictionary {{"a", new byte[] {0, 0, 0, 1}}}); + new Dictionary { { "a", new byte[] { 0, 0, 0, 1 } } }); } Assert.AreEqual("system", ps.Keyspace); @@ -887,7 +887,7 @@ public void Session_Prepare_With_Keyspace_Defined_On_Protocol_Greater_Than_4(boo [TestCase(true)] [TestCase(false)] - [TestBothServersVersion(4,0,5,1)] + [TestBothServersVersion(4, 0, 5, 1)] public async Task Session_PrepareAsync_With_Keyspace_Defined_On_Protocol_Greater_Than_4(bool usePayload) { if (Session.Cluster.Metadata.ControlConnection.Serializer.CurrentProtocolVersion < ProtocolVersion.V5) @@ -905,7 +905,7 @@ public async Task Session_PrepareAsync_With_Keyspace_Defined_On_Protocol_Greater else { ps = await Session.PrepareAsync("SELECT key FROM local", "system", - new Dictionary {{"a", new byte[] {0, 0, 0, 1}}}).ConfigureAwait(false); + new Dictionary { { "a", new byte[] { 0, 0, 0, 1 } } }).ConfigureAwait(false); } Assert.AreEqual("system", ps.Keyspace); @@ -920,14 +920,14 @@ await TestHelper.TimesLimit(async () => } [Test] - [TestBothServersVersion(4,0,5,1)] + [TestBothServersVersion(4, 0, 5, 1)] public void Session_Prepare_With_Keyspace_Defined_On_Protocol_V4() { TestKeyspaceInPrepareNotSupported(true); } [Test] - [TestBothServersVersion(4, 0, 5,1, Comparison.LessThan)] + [TestBothServersVersion(4, 0, 5, 1, Comparison.LessThan)] public void Session_Prepare_With_Keyspace_Defined_On_Previuos_Cassandra_Versions() { TestKeyspaceInPrepareNotSupported(false); @@ -935,12 +935,13 @@ public void Session_Prepare_With_Keyspace_Defined_On_Previuos_Cassandra_Versions private void TestKeyspaceInPrepareNotSupported(bool specifyProtocol) { - using (var cluster = GetNewTemporaryCluster(builder => { - if (specifyProtocol) - { - builder.WithMaxProtocolVersion(ProtocolVersion.V4); - } - })) + using (var cluster = GetNewTemporaryCluster(builder => + { + if (specifyProtocol) + { + builder.WithMaxProtocolVersion(ProtocolVersion.V4); + } + })) { var session = cluster.Connect(KeyspaceName); @@ -1082,7 +1083,7 @@ public void Batch_PreparedStatement_With_Unprepared_Flow() Assert.AreEqual(Enumerable.Range(1, 4).Select(i => new object[] { i, $"label{i}_u" }), result); } } - + [Test] [TestCassandraVersion(2, 0, Comparison.Equal)] public void Batch_PreparedStatements_FlagsNotSupportedInC2_0() @@ -1113,7 +1114,7 @@ public void Batch_PreparedStatements_NotSupportedInC1_2() } [Test] - [TestBothServersVersion(4,0,5,1)] + [TestBothServersVersion(4, 0, 5, 1)] public void BatchStatement_With_Keyspace_Defined_On_Protocol_Greater_Than_4() { using (var cluster = ClusterBuilder().AddContactPoint(TestClusterManager.InitialContactPoint).Build()) @@ -1139,7 +1140,7 @@ public void BatchStatement_With_Keyspace_Defined_On_Protocol_Greater_Than_4() } [Test] - [TestBothServersVersion(4, 0, 5,1, Comparison.LessThan)] + [TestBothServersVersion(4, 0, 5, 1, Comparison.LessThan)] public void BatchStatement_With_Keyspace_Defined_On_Lower_Protocol_Versions() { using (var cluster = GetNewTemporaryCluster()) @@ -1162,10 +1163,11 @@ public void BatchStatement_With_Keyspace_Defined_On_Lower_Protocol_Versions() [Test] public void Should_FailFast_When_PreparedStatementIdChangesOnReprepare() { - if (TestClusterManager.CheckCassandraVersion(false, new Version(3, 0, 0), Comparison.GreaterThanOrEqualsTo) && + if (TestClusterManager.CheckCassandraVersion(false, new Version(3, 0, 0), Comparison.GreaterThanOrEqualsTo) && TestClusterManager.CheckCassandraVersion(false, new Version(3, 11, 0), Comparison.LessThan)) { - if (TestClusterManager.CheckCassandraVersion(false, new Version(3, 0, 26), Comparison.GreaterThanOrEqualsTo)) { + if (TestClusterManager.CheckCassandraVersion(false, new Version(3, 0, 26), Comparison.GreaterThanOrEqualsTo)) + { Assert.Ignore("This test relies on a bug that is fixed in this server version."); return; } @@ -1209,10 +1211,10 @@ public void InsertingSingleValuePrepared(Type tp, object value = null) var toInsert = new List(1); object val = Randomm.RandomVal(tp); - if (tp == typeof (string)) + if (tp == typeof(string)) val = "'" + val.ToString().Replace("'", "''") + "'"; - var row1 = new [] {Guid.NewGuid(), val}; + var row1 = new[] { Guid.NewGuid(), val }; toInsert.Add(row1); @@ -1221,11 +1223,11 @@ public void InsertingSingleValuePrepared(Type tp, object value = null) toInsert[0][0])); if (value == null) { - QueryTools.ExecutePreparedQuery(Session, prep, new [] { toInsert[0][1] }); + QueryTools.ExecutePreparedQuery(Session, prep, new[] { toInsert[0][1] }); } else { - QueryTools.ExecutePreparedQuery(Session, prep, new [] {value}); + QueryTools.ExecutePreparedQuery(Session, prep, new[] { value }); } QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert); diff --git a/src/Cassandra.IntegrationTests/Core/ReconnectionTests.cs b/src/Cassandra.IntegrationTests/Core/ReconnectionTests.cs index e3f6b138e..9a11e8667 100644 --- a/src/Cassandra.IntegrationTests/Core/ReconnectionTests.cs +++ b/src/Cassandra.IntegrationTests/Core/ReconnectionTests.cs @@ -46,7 +46,7 @@ public void TearDown() { TestClusterManager.TryRemove(); _realCluster = new Lazy( - () => TestClusterManagement.TestClusterManager.CreateNew(2, new TestClusterOptions { UseVNodes = true})); + () => TestClusterManagement.TestClusterManager.CreateNew(2, new TestClusterOptions { UseVNodes = true })); } } @@ -100,7 +100,7 @@ public void Reconnection_Attempted_Multiple_Times() }; Assert.True(host.IsUp); Trace.TraceInformation("Stopping node"); - var node = _testCluster.GetNodes().First(); + var node = _testCluster.GetNodes().First(); node.Stop().GetAwaiter().GetResult(); // Make sure the node is considered down TestHelper.RetryAssert(() => @@ -185,7 +185,7 @@ public void Reconnection_Attempted_Multiple_Times_On_Multiple_Nodes() }, 100, 100); Trace.TraceInformation("Stopping node #2"); nodes[1].Stop().GetAwaiter().GetResult(); - + TestHelper.RetryAssert(() => { Assert.Throws(() => TestHelper.Invoke(() => session.Execute("SELECT * FROM system.local"), 6)); @@ -293,7 +293,7 @@ public void Executions_After_Reconnection_Resizes_Pool() public void Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain() { var testCluster = _realCluster.Value; - using (var cluster = + using (var cluster = ClusterBuilder() .AddContactPoint(testCluster.InitialContactPoint) .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(22000).SetConnectTimeoutMillis(60000)) @@ -323,7 +323,7 @@ public void Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain set.Add(rs.Info.QueriedHost); } Assert.AreEqual(2, set.Count); - + // Decommission node if (!TestClusterManager.SupportsDecommissionForcefully()) { @@ -334,7 +334,7 @@ public void Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain testCluster.DecommissionNodeForcefully(1); } testCluster.Stop(1); - + // Assert that only one host is used in queries set.Clear(); foreach (var i in Enumerable.Range(1, 100)) @@ -348,13 +348,13 @@ public void Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain // Bring back the decommissioned node testCluster.Start(1, "--jvm_arg=\"-Dcassandra.override_decommission=true\""); - + // Assert that there are 2 hosts TestHelper.RetryAssert(() => { Assert.AreEqual(2, cluster.AllHosts().Count); }, 1000, 180); - + // Assert that queries use both hosts again set.Clear(); var idx = 1; @@ -364,7 +364,7 @@ public void Should_UseNewHostInQueryPlans_When_HostIsDecommissionedAndJoinsAgain set.Add(rs.Info.QueriedHost); Assert.AreEqual(2, set.Count); }, 500, 240); - + TestHelper.RetryAssert(() => { pool2 = session.GetExistingPool(removedHost.Address); @@ -388,7 +388,7 @@ public void Should_UpdateHosts_When_HostIpChanges() $"{_realCluster.Value.ClusterIpPrefix}2", oldIp }; - + var newAddresses = new[] { $"{_realCluster.Value.ClusterIpPrefix}1", @@ -414,8 +414,8 @@ public void Should_UpdateHosts_When_HostIpChanges() _realCluster.Value.Stop(3); _realCluster.Value.UpdateConfig( - 3, - $"listen_address: {_realCluster.Value.ClusterIpPrefix}4", + 3, + $"listen_address: {_realCluster.Value.ClusterIpPrefix}4", $"rpc_address: {_realCluster.Value.ClusterIpPrefix}4"); _realCluster.Value.Start(3, "--skip-wait-other-notice", "127.0.0.4"); @@ -431,7 +431,7 @@ public void Should_UpdateHosts_When_HostIpChanges() }, 500, 100); - + var newTokenMap = session.Cluster.Metadata.TokenToReplicasMap; var newHostTokens = newTokenMap.GetByKeyspace("ks1") .Where(kvp => diff --git a/src/Cassandra.IntegrationTests/Core/SchemaMetadataTests.cs b/src/Cassandra.IntegrationTests/Core/SchemaMetadataTests.cs index 89accff5f..c03e94ba0 100644 --- a/src/Cassandra.IntegrationTests/Core/SchemaMetadataTests.cs +++ b/src/Cassandra.IntegrationTests/Core/SchemaMetadataTests.cs @@ -148,7 +148,7 @@ public void Custom_MetadataTest(bool metadataSync) const string typeName2 = "org.apache.cassandra.db.marshal.CompositeType(" + "org.apache.cassandra.db.marshal.UTF8Type," + "org.apache.cassandra.db.marshal.Int32Type)"; - + const string typeName3 = "org.apache.cassandra.db.marshal.DynamicCompositeType(" + "i=>org.apache.cassandra.db.marshal.Int32Type," + "s=>org.apache.cassandra.db.marshal.UTF8Type)"; @@ -319,7 +319,7 @@ PRIMARY KEY ((a, b), c, d) Assert.NotNull(table); Assert.AreEqual(7, table.TableColumns.Length); CollectionAssert.AreEqual(new[] { "a", "b" }, table.PartitionKeys.Select(p => p.Name)); - CollectionAssert.AreEqual(new [] { "a", "b"}, table.TableColumns + CollectionAssert.AreEqual(new[] { "a", "b" }, table.TableColumns .Where(c => c.KeyType == KeyType.Partition) .Select(c => c.Name)); CollectionAssert.AreEqual(new[] { "c", "d" }, table.ClusteringKeys.Select(c => c.Item1.Name)); @@ -539,11 +539,11 @@ public void MaterializedView_Base_Table_Column_Addition(bool metadataSync) Assert.NotNull(cluster2.Metadata.GetKeyspace("ks_view_meta4")?.GetTableMetadata("scores").ColumnsByName[colName]); alltimeView = cluster2.Metadata.GetMaterializedView("ks_view_meta4", "alltimehigh"); Assert.IsNotNull(alltimeView); - foulMeta = alltimeView.ColumnsByName[colName]; + foulMeta = alltimeView.ColumnsByName[colName]; Assert.NotNull(foulMeta); }, 200, 55); - + Assert.AreEqual(ColumnTypeCode.Int, foulMeta.TypeCode); dailyView = cluster2.Metadata.GetMaterializedView("ks_view_meta4", "dailyhigh"); Assert.IsFalse(dailyView.TableColumns.Contains(foulMeta)); @@ -661,7 +661,7 @@ public void RaiseErrorOnInvalidMultipleSecondaryIndexTest(bool metadataSync) [Test, TestCase(true), TestCase(false), TestCassandraVersion(3, 0)] public void ColumnClusteringOrderReversedTest(bool metadataSync) { - if (TestClusterManager.CheckCassandraVersion(true, new Version(4, 0), Comparison.GreaterThanOrEqualsTo) || + if (TestClusterManager.CheckCassandraVersion(true, new Version(4, 0), Comparison.GreaterThanOrEqualsTo) || (TestClusterManager.IsDse && TestClusterManager.CheckDseVersion(new Version(6, 0), Comparison.GreaterThanOrEqualsTo))) { Assert.Ignore("COMPACT STORAGE is not supported by DSE 6.0 / C* 4.0"); @@ -768,7 +768,7 @@ public void Virtual_Table_Metadata_Test(bool metadataSync) public void Virtual_Keyspaces_Are_Included(bool metadataSync) { var cluster = GetNewTemporaryCluster(builder => builder.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(metadataSync))); - var defaultVirtualKeyspaces = new[] {"system_views", "system_virtual_schema"}; + var defaultVirtualKeyspaces = new[] { "system_views", "system_virtual_schema" }; CollectionAssert.IsSubsetOf(defaultVirtualKeyspaces, cluster.Metadata.GetKeyspaces()); foreach (var keyspaceName in defaultVirtualKeyspaces) diff --git a/src/Cassandra.IntegrationTests/Core/SessionExecuteAsyncTests.cs b/src/Cassandra.IntegrationTests/Core/SessionExecuteAsyncTests.cs index f1867b39b..c3ec89d84 100644 --- a/src/Cassandra.IntegrationTests/Core/SessionExecuteAsyncTests.cs +++ b/src/Cassandra.IntegrationTests/Core/SessionExecuteAsyncTests.cs @@ -37,9 +37,9 @@ public void SessionExecuteAsyncPreparedToSync() { TestCluster.PrimeFluent( b => b.WhenQuery( - "SELECT key FROM system.local WHERE key = ?", + "SELECT key FROM system.local WHERE key = ?", when => when.WithParam("local")) - .ThenRowsSuccess(new[] {"key"}, r => r.WithRow("local"))); + .ThenRowsSuccess(new[] { "key" }, r => r.WithRow("local"))); var statement = Session.Prepare("SELECT key FROM system.local WHERE key = ?"); var task = Session.ExecuteAsync(statement.Bind("local")); diff --git a/src/Cassandra.IntegrationTests/Core/SessionTests.cs b/src/Cassandra.IntegrationTests/Core/SessionTests.cs index 685bd5470..5b7f60f49 100644 --- a/src/Cassandra.IntegrationTests/Core/SessionTests.cs +++ b/src/Cassandra.IntegrationTests/Core/SessionTests.cs @@ -94,7 +94,7 @@ public void Session_Keyspace_Does_Not_Exist_On_Change_Throws() var ex = Assert.Throws(() => localSession.ChangeKeyspace("THIS_KEYSPACE_DOES_NOT_EXIST_EITHER")); Assert.True(ex.Message.ToLower().Contains("keyspace")); } - + [Test] public void ChangeKeyspace_SetsKeyspace() { @@ -267,7 +267,7 @@ public async Task Session_With_Host_Changing_Distance() stopWatch.Restart(); } } - var poolHasBeenReset = wasReset == 1 && + var poolHasBeenReset = wasReset == 1 && pool1.OpenConnections == 3 && pool2.OpenConnections == 3 && stopWatch.ElapsedMilliseconds > 2000; diff --git a/src/Cassandra.IntegrationTests/Core/SpeculativeExecutionShortTests.cs b/src/Cassandra.IntegrationTests/Core/SpeculativeExecutionShortTests.cs index bd5a7cd90..9b383e384 100644 --- a/src/Cassandra.IntegrationTests/Core/SpeculativeExecutionShortTests.cs +++ b/src/Cassandra.IntegrationTests/Core/SpeculativeExecutionShortTests.cs @@ -70,7 +70,7 @@ private ISession GetSession( public SpeculativeExecutionShortTests() : base(false, new SimulacronOptions { Nodes = "2" }, false) { } - + public override void SetUp() { base.SetUp(); @@ -114,7 +114,7 @@ public async Task SpeculativeExecution_Should_Not_Execute_On_Next_Node_When_Not_ TestCluster.GetNode(1).PrimeFluent( b => b.WhenQuery(QueryLocal) - .ThenRowsSuccess(new[] {"key"}, r => r.WithRow("local")).WithDelayInMs(1000)); + .ThenRowsSuccess(new[] { "key" }, r => r.WithRow("local")).WithDelayInMs(1000)); var rs = await session.ExecuteAsync(new SimpleStatement(QueryLocal).SetIdempotence(false)).ConfigureAwait(false); diff --git a/src/Cassandra.IntegrationTests/Core/StressTests.cs b/src/Cassandra.IntegrationTests/Core/StressTests.cs index bcb79b6e6..ef54778b7 100644 --- a/src/Cassandra.IntegrationTests/Core/StressTests.cs +++ b/src/Cassandra.IntegrationTests/Core/StressTests.cs @@ -75,9 +75,9 @@ public void Parallel_Insert_And_Select_Sync() for (var i = 0; i < 10; i++) { //Add 10 actions to execute - actions.AddRange(new[] {actionInsert, actionSelect, actionInsertPrepared}); - actions.AddRange(new[] {actionSelect, actionInsert, actionInsertPrepared, actionInsert}); - actions.AddRange(new[] {actionInsertPrepared, actionInsertPrepared, actionSelect}); + actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared }); + actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert }); + actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect }); } //Execute in parallel the 100 actions TestHelper.ParallelInvoke(actions.ToArray()); diff --git a/src/Cassandra.IntegrationTests/Core/TimeUuidSerializationTests.cs b/src/Cassandra.IntegrationTests/Core/TimeUuidSerializationTests.cs index e8660d370..892e81f10 100644 --- a/src/Cassandra.IntegrationTests/Core/TimeUuidSerializationTests.cs +++ b/src/Cassandra.IntegrationTests/Core/TimeUuidSerializationTests.cs @@ -50,7 +50,7 @@ private static string GetToDateFunction() return "dateOf"; } } - + public override void OneTimeSetUp() { base.OneTimeSetUp(); @@ -87,7 +87,7 @@ public void DeserializationTests() // the timestamp retrieved by the cql function has lower precision than timeuuid const long precision = 10000L; Assert.AreEqual( - timeUuid.GetDate().Ticks / precision, + timeUuid.GetDate().Ticks / precision, row.GetValue("timeuuid_date_value").Ticks / precision); } //Still defaults to Guid @@ -140,7 +140,7 @@ public void ComparisonTest() var dt1 = new DateTime(2016, 1, 1, 4, 55, 00); var dt2 = new DateTime(2016, 1, 1, 5, 55, 00); var ctimes = dt1.CompareTo(dt2); - + //base check Assert.That(ctimes < 0); diff --git a/src/Cassandra.IntegrationTests/Core/TimestampTests.cs b/src/Cassandra.IntegrationTests/Core/TimestampTests.cs index a9fe3fd6f..7359b8b4c 100644 --- a/src/Cassandra.IntegrationTests/Core/TimestampTests.cs +++ b/src/Cassandra.IntegrationTests/Core/TimestampTests.cs @@ -28,7 +28,7 @@ public class TimestampTests : SharedClusterTest { public TimestampTests() : base(1, false) { - + } [Test] diff --git a/src/Cassandra.IntegrationTests/Core/TypeSerializersTests.cs b/src/Cassandra.IntegrationTests/Core/TypeSerializersTests.cs index 2210b101a..564e65b27 100644 --- a/src/Cassandra.IntegrationTests/Core/TypeSerializersTests.cs +++ b/src/Cassandra.IntegrationTests/Core/TypeSerializersTests.cs @@ -43,7 +43,7 @@ public class TypeSerializersTests : SharedClusterTest private const string CustomTypeName = "org.apache.cassandra.db.marshal.DynamicCompositeType(" + "s=>org.apache.cassandra.db.marshal.UTF8Type," + "i=>org.apache.cassandra.db.marshal.Int32Type)"; - + private const string CustomTypeName2 = "org.apache.cassandra.db.marshal.DynamicCompositeType(" + "i=>org.apache.cassandra.db.marshal.Int32Type," + "s=>org.apache.cassandra.db.marshal.UTF8Type)"; @@ -235,7 +235,7 @@ public void Should_Use_Custom_TypeSerializers() } } - [Test, TestBothServersVersion(4, 0, 5,1, Comparison.LessThan)] + [Test, TestBothServersVersion(4, 0, 5, 1, Comparison.LessThan)] public void DynamicCompositeTypeTest() { string uniqueTableName = TestUtils.GetUniqueTableName(); @@ -331,7 +331,7 @@ private static IEnumerable VectorTestCaseData() new TestCaseData("uuid", (Func)(Guid.NewGuid), defaultAssert), new TestCaseData("timeuuid", (Func)(TimeUuid.NewId), defaultAssert), - + new TestCaseData("boolean", (Func)(()=>r.Next()%2==0), defaultAssert), new TestCaseData("duration", (Func)(()=>Duration.FromTimeSpan(new TimeSpan(DateTime.UtcNow.Ticks))), defaultAssert), new TestCaseData("inet", (Func)(()=> IPAddress.Parse($"{(r.Next()%255) + 1}.{r.Next()%255}.{r.Next()%255}.{(r.Next()%255) + 1}")), defaultAssert), @@ -357,7 +357,7 @@ private static IEnumerable VectorTestCaseData() new TestCaseData("vector", (Func>)(()=>new CqlVector(Enumerable.Range(0, 2).Select(i => r.Next()).ToArray())), listVectorAssert), new TestCaseData("vector", (Func>)(()=>new CqlVector(r.Next(), r.Next())), listVectorAssert), new TestCaseData("vector", (Func>)(()=>new CqlVector(Enumerable.Range(0, 2).Select(i => new BigInteger((long)r.NextDouble())).ToArray())), listVectorAssert), - + new TestCaseData("tuple", (Func>)(()=>new Tuple(r.Next(), r.Next())), defaultAssert), new TestCaseData("tuple", (Func>)(()=>new Tuple(r.Next(), new BigInteger((long)r.NextDouble()))), defaultAssert), new TestCaseData("tuple", (Func>)(()=>new Tuple(new BigInteger((long)r.NextDouble()), r.Next())), defaultAssert), @@ -415,17 +415,17 @@ public void VectorSimpleStatementTestComplex(string cqlSubType, Func eleme }; vectorSimpleStmtTestFn((i, v) => new SimpleStatement( - $"INSERT INTO {tableNameComplex} (i, k, l) VALUES (?, ?, ?)", - i, - new CqlVector>(v[0], v[1], v[2]), + $"INSERT INTO {tableNameComplex} (i, k, l) VALUES (?, ?, ?)", + i, + new CqlVector>(v[0], v[1], v[2]), new CqlVector>>(new List> { v[0] }, new List> { v[1] }, new List> { v[2] }))); vectorSimpleStmtTestFn((i, v) => new SimpleStatement( new Dictionary { - { "idx", i }, - { "vec", new CqlVector>(v[0], v[1], v[2]) }, + { "idx", i }, + { "vec", new CqlVector>(v[0], v[1], v[2]) }, { "vecc", new CqlVector>>(new List> { v[0] }, new List> { v[1] }, new List> { v[2] }) } - }, + }, $"INSERT INTO {tableNameComplex} (i, k, l) VALUES (:idx, :vec, :vecc)")); } @@ -602,20 +602,20 @@ public void VectorFloatTest() { var tableName = TestUtils.GetUniqueTableName(); Session.Execute($"CREATE TABLE {tableName} (i int PRIMARY KEY, j vector)"); - + var vector = new CqlVector(1.1f, 2.2f, 3.3f); - + // Simple insert and select Session.Execute(new SimpleStatement($"INSERT INTO {tableName} (i, j) VALUES (1, ?)", vector)); var rs = Session.Execute($"SELECT * FROM {tableName} WHERE i = 1"); AssertSimpleVectorTest(vector, rs, Assert.AreEqual); - + // Prepared insert and select var ps = Session.Prepare($"INSERT INTO {tableName} (i, j) VALUES (?, ?)"); Session.Execute(ps.Bind(2, vector)); rs = Session.Execute($"SELECT * FROM {tableName} WHERE i = 2"); AssertSimpleVectorTest(vector, rs, Assert.AreEqual); - + // throw when length is not 3 Assert.Throws(() => { @@ -623,7 +623,7 @@ public void VectorFloatTest() Session.Execute(new SimpleStatement($"INSERT INTO {tableName} (i, j) VALUES (3, ?)", shortVector)); }); } - + private void AssertSimpleVectorTest(CqlVector expected, RowSet rs, Action assertFn) { var rowList = rs.ToList(); @@ -675,9 +675,9 @@ private void AssertComplexVectorTest(List> vectorList, RowSet rs } private void AssertComplexVectorEquals( - List> vectorList, - IEnumerable> actual1, - IEnumerable>> actual2, + List> vectorList, + IEnumerable> actual1, + IEnumerable>> actual2, Action assertFn) { var retrievedVector1 = actual1.ToList(); diff --git a/src/Cassandra.IntegrationTests/Core/UdfTests.cs b/src/Cassandra.IntegrationTests/Core/UdfTests.cs index 867a812e7..28bde633a 100644 --- a/src/Cassandra.IntegrationTests/Core/UdfTests.cs +++ b/src/Cassandra.IntegrationTests/Core/UdfTests.cs @@ -122,20 +122,20 @@ public void GetFunction_Should_Retrieve_Metadata_Of_Cql_Function(bool metadataSy var cluster = GetCluster(metadataSync); var ks = cluster.Metadata.GetKeyspace("ks_udf"); Assert.NotNull(ks); - var func = ks.GetFunction("plus", new [] {"int", "int"}); + var func = ks.GetFunction("plus", new[] { "int", "int" }); if (metadataSync) { //it is the same as retrieving from Metadata, it gets cached - Assert.AreEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new [] {"int", "int"})); + Assert.AreEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new[] { "int", "int" })); } else { - Assert.AreNotEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new [] {"int", "int"})); + Assert.AreNotEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new[] { "int", "int" })); } Assert.NotNull(func); Assert.AreEqual("plus", func.Name); Assert.AreEqual("ks_udf", func.KeyspaceName); - CollectionAssert.AreEqual(new [] {"s", "v"}, func.ArgumentNames); + CollectionAssert.AreEqual(new[] { "s", "v" }, func.ArgumentNames); Assert.AreEqual(2, func.ArgumentTypes.Length); Assert.AreEqual(ColumnTypeCode.Int, func.ArgumentTypes[0].TypeCode); Assert.AreEqual(ColumnTypeCode.Int, func.ArgumentTypes[1].TypeCode); @@ -309,7 +309,7 @@ public void GetAggregate_Should_Return_Most_Up_To_Date_Metadata_Via_Events(bool .GetAggregate("sum2", new[] { "int" }); var ks = cluster.Metadata.GetKeyspace("ks_udf"); Assert.NotNull(ks); - var aggregate = cluster.Metadata.GetAggregate("ks_udf", "sum2", new[] {"int"}); + var aggregate = cluster.Metadata.GetAggregate("ks_udf", "sum2", new[] { "int" }); Assert.AreEqual("0", aggregate.InitialCondition); session.Execute("CREATE OR REPLACE AGGREGATE ks_udf.sum2(int) SFUNC plus STYPE int INITCOND 200"); TestUtils.WaitForSchemaAgreement(cluster); @@ -339,7 +339,7 @@ public void GetAggregate_Should_Return_Most_Up_To_Date_Metadata_Via_Events(bool public void GetAggregate_Should_Retrieve_Metadata_Of_A_Determinitic_Cql_Aggregate(bool metadataSync) { var cluster = GetCluster(metadataSync); - var aggregate = cluster.Metadata.GetAggregate("ks_udf", "deta", new[] {"int"}); + var aggregate = cluster.Metadata.GetAggregate("ks_udf", "deta", new[] { "int" }); Assert.AreEqual("plus", aggregate.StateFunction); Assert.True(aggregate.Deterministic); } @@ -349,10 +349,10 @@ public void GetAggregate_Should_Retrieve_Metadata_Of_A_Determinitic_Cql_Aggregat public void GetFunction_Should_Retrieve_Metadata_Of_A_Determinitic_And_Monotonic_Cql_Function(bool metadataSync) { var cluster = GetCluster(metadataSync); - var fn = cluster.Metadata.GetFunction("ks_udf", "md", new[] {"int", "int"}); + var fn = cluster.Metadata.GetFunction("ks_udf", "md", new[] { "int", "int" }); Assert.True(fn.Deterministic); Assert.True(fn.Monotonic); - Assert.AreEqual(new []{ "dividend", "divisor"}, fn.MonotonicOn); + Assert.AreEqual(new[] { "dividend", "divisor" }, fn.MonotonicOn); } [Test, TestCase(true), TestCase(false)] @@ -360,10 +360,10 @@ public void GetFunction_Should_Retrieve_Metadata_Of_A_Determinitic_And_Monotonic public void GetFunction_Should_Retrieve_Metadata_Of_Partially_Monotonic_Cql_Function(bool metadataSync) { var cluster = GetCluster(metadataSync); - var fn = cluster.Metadata.GetFunction("ks_udf", "monotonic_on", new[] {"int", "int"}); + var fn = cluster.Metadata.GetFunction("ks_udf", "monotonic_on", new[] { "int", "int" }); Assert.False(fn.Deterministic); Assert.False(fn.Monotonic); - Assert.AreEqual(new []{ "dividend"}, fn.MonotonicOn); + Assert.AreEqual(new[] { "dividend" }, fn.MonotonicOn); } } } diff --git a/src/Cassandra.IntegrationTests/Core/UdtMappingsTests.cs b/src/Cassandra.IntegrationTests/Core/UdtMappingsTests.cs index 1aa64dd40..36bbdbdfd 100644 --- a/src/Cassandra.IntegrationTests/Core/UdtMappingsTests.cs +++ b/src/Cassandra.IntegrationTests/Core/UdtMappingsTests.cs @@ -93,7 +93,7 @@ await localSession.UserDefinedTypes.DefineAsync( Assert.AreEqual("123", value.Number); Assert.AreEqual(34, value.CountryCode); } - + [Test] public async Task MappingDifferentKeyspaceSingleExplicitAsync_AsParameter() { @@ -156,7 +156,7 @@ public void MappingDifferentKeyspaceWithoutSpecifyingIt() var session = cluster.Connect(); session.CreateKeyspaceIfNotExists(newKeyspace); session.ChangeKeyspace(newKeyspace); - + session.Execute(cqlType1); session.Execute(cqlTable1); @@ -265,14 +265,14 @@ public void MappingNestedTypeTest() { new Contact { - FirstName = "Jules", LastName = "Winnfield", + FirstName = "Jules", LastName = "Winnfield", Birth = new DateTimeOffset(1950, 2, 3, 4, 5, 0, 0, TimeSpan.Zero), NullableLong = null, Phones = new HashSet{ new Phone { Alias = "home", Number = "123456" }} }, new Contact { - FirstName = "Mia", LastName = "Wallace", + FirstName = "Mia", LastName = "Wallace", Birth = null, NullableLong = 2, Phones = new HashSet @@ -350,7 +350,7 @@ public void MappingEncodingSingleTest() ); const string insertQuery = "INSERT INTO users (id, main_phone) values (?, ?)"; - + //All of the fields null var id = 201; var phone = new Phone(); @@ -360,14 +360,14 @@ public void MappingEncodingSingleTest() //Some fields null and others with value id = 202; - phone = new Phone() {Alias = "Home phone"}; + phone = new Phone() { Alias = "Home phone" }; localSession.Execute(new SimpleStatement(insertQuery, id, phone)); rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id)); Assert.AreEqual(phone, rs.First().GetValue("main_phone")); //All fields filled in id = 203; - phone = new Phone() { Alias = "Mobile phone", CountryCode = 54, Number = "1234567"}; + phone = new Phone() { Alias = "Mobile phone", CountryCode = 54, Number = "1234567" }; localSession.Execute(new SimpleStatement(insertQuery, id, phone)); rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id)); Assert.AreEqual(phone, rs.First().GetValue("main_phone")); @@ -392,8 +392,8 @@ public void MappingEncodingNestedTest() { new Contact { - FirstName = "Vincent", - LastName = "Vega", + FirstName = "Vincent", + LastName = "Vega", Phones = new HashSet { new Phone {Alias = "Wat", Number = "0000000000121220000"}, @@ -470,7 +470,7 @@ void AssertAreEqualPhone(Phone v) var value = row.GetValue("main_phone"); Assert.NotNull(value); AssertAreEqualPhone(value); - + var valueChild = row.GetValue("main_phone"); Assert.NotNull(valueChild); AssertAreEqualPhone(valueChild); @@ -479,7 +479,7 @@ void AssertAreEqualPhone(Phone v) var valueInsideList = valueList.Single(); Assert.NotNull(valueInsideList); AssertAreEqualPhone(valueInsideList); - + var valueListChild = row.GetValue>("phones"); var valueInsideListChild = valueListChild.Single(); Assert.NotNull(valueInsideListChild); @@ -580,7 +580,7 @@ public void Should_ThrowException_When_UdtWithCollectionsWithNullValues() Assert.Throws(() => localSession.Execute(insert)); insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 2222, udtList[0], null); Assert.Throws(() => localSession.Execute(insert)); - insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 3333, null, new List {null}); + insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 3333, null, new List { null }); Assert.Throws(() => localSession.Execute(insert)); } @@ -593,13 +593,13 @@ public void MappingOnLowerProtocolVersionTest() .Build()) { var localSession = cluster.Connect(KeyspaceName); - Assert.Throws(() => localSession.UserDefinedTypes.Define(UdtMap.For())); + Assert.Throws(() => localSession.UserDefinedTypes.Define(UdtMap.For())); } } private class DummyClass { - + } } } diff --git a/src/Cassandra.IntegrationTests/CqlFunctions/Tests/MaxTimeUuid.cs b/src/Cassandra.IntegrationTests/CqlFunctions/Tests/MaxTimeUuid.cs index 3558775a5..0158512d0 100644 --- a/src/Cassandra.IntegrationTests/CqlFunctions/Tests/MaxTimeUuid.cs +++ b/src/Cassandra.IntegrationTests/CqlFunctions/Tests/MaxTimeUuid.cs @@ -250,6 +250,6 @@ public void MaxTimeUuid_LessThanOrEqualTo_NullableTimeUuidComparison() } - + } diff --git a/src/Cassandra.IntegrationTests/CqlFunctions/Tests/Token.cs b/src/Cassandra.IntegrationTests/CqlFunctions/Tests/Token.cs index ea18f34d7..a9a8e8822 100644 --- a/src/Cassandra.IntegrationTests/CqlFunctions/Tests/Token.cs +++ b/src/Cassandra.IntegrationTests/CqlFunctions/Tests/Token.cs @@ -45,19 +45,19 @@ public override void OneTimeSetUp() // Create necessary tables MappingConfiguration config1 = new MappingConfiguration(); - config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithTimeUuid), - () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithTimeUuid))); + config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithTimeUuid), + () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithTimeUuid))); _tableEntityWithTimeUuid = new Table(_session, config1); _tableEntityWithTimeUuid.Create(); MappingConfiguration config2 = new MappingConfiguration(); - config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithNullableTimeUuid), - () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithNullableTimeUuid))); + config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithNullableTimeUuid), + () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithNullableTimeUuid))); _tableEntityWithNullableTimeUuid = new Table(_session, config2); _tableEntityWithNullableTimeUuid.Create(); _expectedTimeUuidObjectList = EntityWithTimeUuid.GetDefaultObjectList(); - for (int i=0; i<_expectedTimeUuidObjectList.Count; i++) + for (int i = 0; i < _expectedTimeUuidObjectList.Count; i++) { _expectedTimeUuidObjectList[i].StringType = i.ToString(); } @@ -83,7 +83,7 @@ public void Token_EqualTo_String() } // change to query that returns nothing - var whereQueryReturnsNothing =_tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) == CqlFunction.Token(Guid.NewGuid().ToString())); + var whereQueryReturnsNothing = _tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) == CqlFunction.Token(Guid.NewGuid().ToString())); List objectsReturned2 = whereQueryReturnsNothing.ExecuteAsync().Result.ToList(); Assert.AreEqual(0, objectsReturned2.Count); } diff --git a/src/Cassandra.IntegrationTests/DataStax/Auth/ProxyAuthenticationTests.cs b/src/Cassandra.IntegrationTests/DataStax/Auth/ProxyAuthenticationTests.cs index 76f1dbb26..f98048f4d 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Auth/ProxyAuthenticationTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Auth/ProxyAuthenticationTests.cs @@ -38,7 +38,7 @@ public void OneTimeSetUp() "authenticator: com.datastax.bdp.cassandra.auth.DseAuthenticator", "authorizer:com.datastax.bdp.cassandra.auth.DseAuthorizer" }, - DseYaml = new [] + DseYaml = new[] { "authentication_options.default_scheme: internal", "authorization_options.enabled:true", diff --git a/src/Cassandra.IntegrationTests/DataStax/Auth/SspiClientTests.cs b/src/Cassandra.IntegrationTests/DataStax/Auth/SspiClientTests.cs index 18e57841e..d5ffe6f3c 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Auth/SspiClientTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Auth/SspiClientTests.cs @@ -27,13 +27,13 @@ public class SspiClientTests : BaseIntegrationTest [Test] public void Test_First_Step() { -// var sspi = new SspiClient(); -// //For the server principal: "dse/cassandra1.datastax.com@DATASTAX.COM" -// //the expected Uri is: "dse/cassandra1.datastax.com" -// //sspi.Init("dse", "172.16.56.1"); -// //sspi.Init("host", "jorge-win.datastaxrealm.com"); -// sspi.Init("krbtgt", "DATASTAXREALM.COM"); -// sspi.EvaluateChallenge(null); + // var sspi = new SspiClient(); + // //For the server principal: "dse/cassandra1.datastax.com@DATASTAX.COM" + // //the expected Uri is: "dse/cassandra1.datastax.com" + // //sspi.Init("dse", "172.16.56.1"); + // //sspi.Init("host", "jorge-win.datastaxrealm.com"); + // sspi.Init("krbtgt", "DATASTAXREALM.COM"); + // sspi.EvaluateChallenge(null); } } } diff --git a/src/Cassandra.IntegrationTests/DataStax/Cloud/CloudIntegrationTests.cs b/src/Cassandra.IntegrationTests/DataStax/Cloud/CloudIntegrationTests.cs index 54e412af7..b85fa99c1 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Cloud/CloudIntegrationTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Cloud/CloudIntegrationTests.cs @@ -48,9 +48,9 @@ public void Should_ThrowNoHostAvailable_When_MetadataServiceIsUnreachable() { var ex = Assert.ThrowsAsync( () => CreateSessionAsync( - "creds-v1-unreachable.zip", - retries: 1, - act: + "creds-v1-unreachable.zip", + retries: 1, + act: b => b .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(5000).SetConnectTimeoutMillis(10000)) .WithQueryTimeout(5000))); @@ -122,7 +122,7 @@ public async Task Should_ContinueQuerying_When_ANodeGoesDown() { await session.ExecuteAsync(new SimpleStatement("SELECT key FROM system.local")).ConfigureAwait(false); } - catch (QueryTimeoutException){} + catch (QueryTimeoutException) { } } })); } @@ -141,13 +141,13 @@ public void Should_ThrowException_When_BundleDoesNotExist() .WithCloudSecureConnectionBundle("does-not-exist.zip") .WithCredentials("user1", "user1").Build()); } - + [Test] public void Should_FailFast_When_ConfigJsonDoesNotHaveCredentialsAndUserDoesNotProvideCredentials() { var ex = Assert.Throws(() => CreateTemporaryCluster("creds-v1-wo-creds.zip", withCredentials: false)); Assert.AreEqual( - ex.Message, + ex.Message, "No credentials were provided. When using the secure connection bundle, " + "your cluster's credentials must be provided via the Builder.WithCredentials() method."); } @@ -348,7 +348,7 @@ public async Task Should_UseCorrectConsistencyLevelDefaults_When_Dbaas() Assert.AreEqual(ConsistencyLevel.LocalQuorum, rs.Info.AchievedConsistency); Assert.AreEqual("auth", row["authorid"].ToString()); } - catch (QueryTimeoutException) {} + catch (QueryTimeoutException) { } }, 1000, 10); } diff --git a/src/Cassandra.IntegrationTests/DataStax/Graph/CoreGraphTests.cs b/src/Cassandra.IntegrationTests/DataStax/Graph/CoreGraphTests.cs index 6905dd930..c351c953b 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Graph/CoreGraphTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Graph/CoreGraphTests.cs @@ -847,7 +847,7 @@ public void Should_Support_BulkSet() CollectionAssert.AreEquivalent(expectedMap, node.To>()); } } - + [Test] public void Should_Support_Udts() { @@ -869,8 +869,8 @@ public void Should_Support_Udts() { new Contact { - FirstName = "Walter", - LastName = "White", + FirstName = "Walter", + LastName = "White", Phones = new HashSet { new Phone {Alias = "Wat2", Number = "2414817", PhoneType = PhoneType.Mobile}, @@ -883,7 +883,7 @@ public void Should_Support_Udts() "g.addV('users_contacts')" + ".property('id', 305)" + ".property('contacts', contacts)", new { contacts })); - + var rs = session.ExecuteGraph(new SimpleGraphStatement( "g.with('allow-filtering').V().hasLabel('users_contacts').has('id', 305).properties('contacts')")); var resultArray = rs.ToArray(); @@ -898,10 +898,10 @@ public void Should_Support_Udts() Assert.AreEqual(expectedContact.Emails, dbC["emails"].To>()); CollectionAssert.AreEquivalent(expectedContact.Phones, dbC["phones"].To>()); CollectionAssert.AreEquivalent(expectedContact.Phones, dbC["phones"].To>().Select(g => g.To())); - CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Alias), dbC["phones"].To>>().Select(dict => (string) dict["alias"])); + CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Alias), dbC["phones"].To>>().Select(dict => (string)dict["alias"])); } } - + [Test] public void Should_Support_InnerUdt() { @@ -919,14 +919,14 @@ public void Should_Support_InnerUdt() .Map(c => c.NullableInt, "nullable_int") .Map(c => c.Phone, "phone"), UdtMap.For(keyspace: CoreGraphTests.GraphName)); - var testudt = new TestUdt { NullableInt = 1, Name = "123", Phone = new Phone { Alias = "123" }}; + var testudt = new TestUdt { NullableInt = 1, Name = "123", Phone = new Phone { Alias = "123" } }; session.ExecuteGraph(new SimpleGraphStatement( "schema.vertexLabel('test_udts').partitionBy('id', Int).property('test_udt', typeOf('testudt')).create()")); session.ExecuteGraph(new SimpleGraphStatement( "g.addV('test_udts')" + ".property('id', 305)" + ".property('test_udt', testudtparam)", new { testudtparam = testudt })); - + var rs = session.ExecuteGraph(new SimpleGraphStatement( "g.with('allow-filtering').V().hasLabel('test_udts').has('id', 305).properties('test_udt')")); var resultArray = rs.ToArray(); @@ -937,7 +937,7 @@ public void Should_Support_InnerUdt() Assert.AreEqual(dbTestUdt.Phone, testudt.Phone); } } - + [Test] public void Should_Support_DeserializingUnmappedUdts() { @@ -951,8 +951,8 @@ public void Should_Support_DeserializingUnmappedUdts() { new Contact { - FirstName = "Jimmy", - LastName = "McGill", + FirstName = "Jimmy", + LastName = "McGill", Phones = new HashSet { new Phone {Alias = "alias123123", Number = "21791274", PhoneType = PhoneType.Work}, @@ -971,33 +971,33 @@ public void Should_Support_DeserializingUnmappedUdts() var dbC = contactsDict.Single(); Assert.AreEqual(expectedContact.Emails, dbC["emails"].To>()); var phones = dbC["phones"].To>>().ToList(); - CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Alias), phones.Select(dict => (string) dict["alias"])); + CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Alias), phones.Select(dict => (string)dict["alias"])); CollectionAssert.AreEquivalent( - expectedContact.Phones.Select(p => p.PhoneType), + expectedContact.Phones.Select(p => p.PhoneType), phones.Select(dict => dict["phone_type"] == null ? default(PhoneType) : Enum.Parse(typeof(PhoneType), (string)dict["phone_type"]))); - CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Number), phones.Select(dict => (string) dict["number"])); - + CollectionAssert.AreEquivalent(expectedContact.Phones.Select(p => p.Number), phones.Select(dict => (string)dict["number"])); + var ex = Assert.Throws(() => session.ExecuteGraph(new SimpleGraphStatement( "g.addV('users_contacts')" + ".property('id', 1923)" + ".property('contacts', contacts)", new { contacts }))); - Assert.IsTrue(ex.Message.Contains("Wrong property type provided for property 'contacts'") + Assert.IsTrue(ex.Message.Contains("Wrong property type provided for property 'contacts'") && ex.Message.Contains("Provided type 'LinkedHashMap' is not compatible with expected type 'UDTValue'"), ex.Message); - + ex = Assert.Throws(() => session.ExecuteGraph(new SimpleGraphStatement( "g.addV('users_contacts')" + ".property('id', 1923)" + ".property('contacts', contactsDict)", new { contactsDict }))); - Assert.IsTrue(ex.Message.Contains("Wrong property type provided for property 'contacts'") + Assert.IsTrue(ex.Message.Contains("Wrong property type provided for property 'contacts'") && ex.Message.Contains("Provided type 'LinkedHashMap' is not compatible with expected type 'UDTValue'"), ex.Message); } } - + [Test] public void Should_Support_Tuples() { @@ -1013,7 +1013,7 @@ public void Should_Support_Tuples() var phone = new Phone { Alias = "Wat2", Number = "2414817", PhoneType = PhoneType.Home }; var tuple = new Tuple, ISet, IDictionary>( phone, - new DateTimeOffset(2020, 1, 29, 1, 1, 43, 953, TimeSpan.Zero), + new DateTimeOffset(2020, 1, 29, 1, 1, 43, 953, TimeSpan.Zero), Guid.NewGuid(), new[] { "123", "234" }, new HashSet { 1, 2, 3 }, diff --git a/src/Cassandra.IntegrationTests/DataStax/Graph/GraphMultiNodeTests.cs b/src/Cassandra.IntegrationTests/DataStax/Graph/GraphMultiNodeTests.cs index 20d3c9c6c..d480845d4 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Graph/GraphMultiNodeTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Graph/GraphMultiNodeTests.cs @@ -64,7 +64,7 @@ private void PrepareForSparkTest(ITestCluster testCluster) Trace.TraceInformation("GraphMultiNodeTests: Bootstrapping node 2"); testCluster.BootstrapNode(2, false); Trace.TraceInformation("GraphMultiNodeTests: Setting workload"); - testCluster.SetNodeWorkloads(2, new[] {"graph", "spark"}); + testCluster.SetNodeWorkloads(2, new[] { "graph", "spark" }); Trace.TraceInformation("GraphMultiNodeTests: Starting node 2"); testCluster.Start(2); Trace.TraceInformation("Waiting additional time for new node to be ready"); @@ -73,13 +73,13 @@ private void PrepareForSparkTest(ITestCluster testCluster) Trace.TraceInformation("GraphMultiNodeTests: Creating graph"); session.ExecuteGraph(new SimpleGraphStatement( - "system.graph(name)" + + "system.graph(name)" + ".option('graph.replication_config').set(replicationConfig)" + ".option('graph.system_replication_config').set(replicationConfig)" + - ".ifNotExists()" + + ".ifNotExists()" + (!TestClusterManager.SupportsNextGenGraph() ? string.Empty : ".engine(Classic)") + - ".create()", - new {name = GraphMultiNodeTests.GraphName, replicationConfig = replicationConfigStr})); + ".create()", + new { name = GraphMultiNodeTests.GraphName, replicationConfig = replicationConfigStr })); Trace.TraceInformation("GraphMultiNodeTests: Created graph"); var graphStatements = new StringBuilder(); @@ -146,7 +146,7 @@ public string FindSparkPrimary() return sparkHost; } } - + [Test, TestDseVersion(5, 0)] public void Should_Contact_Spark_Primary_Directly() { @@ -173,8 +173,8 @@ public void Should_Contact_Spark_Primary_Directly() public void Should_Parse_Dse_Workload() { TestUtils.VerifyCurrentClusterWorkloads(TestClusterManager.CheckDseVersion(Version.Parse("5.1"), Comparison.GreaterThanOrEqualsTo) - ? new[] {"Analytics", "Cassandra", "Graph"} - : new[] {"Analytics"}); + ? new[] { "Analytics", "Cassandra", "Graph" } + : new[] { "Analytics" }); } } } diff --git a/src/Cassandra.IntegrationTests/DataStax/Graph/GraphTests.cs b/src/Cassandra.IntegrationTests/DataStax/Graph/GraphTests.cs index 94425b19c..f4572db5a 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Graph/GraphTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Graph/GraphTests.cs @@ -41,11 +41,11 @@ public class GraphTests : BaseIntegrationTest private int _idGenerator; private ICluster _cluster; private ISession _session; - + [OneTimeSetUp] public void OneTimeSetUp() { - TestClusterManager.CreateNew(1, new TestClusterOptions {Workloads = new[] {"graph"}}); + TestClusterManager.CreateNew(1, new TestClusterOptions { Workloads = new[] { "graph" } }); CreateClassicGraph(TestClusterManager.InitialContactPoint, GraphTests.GraphName); _cluster = ClusterBuilder() .AddContactPoint(TestClusterManager.InitialContactPoint) @@ -66,7 +66,7 @@ public void Should_Parse_Dse_Workload() { TestUtils.VerifyCurrentClusterWorkloads(TestClusterManager.CheckDseVersion(Version.Parse("5.1"), Comparison.GreaterThanOrEqualsTo) ? new[] { "Cassandra", "Graph" } - : new[] { "Cassandra"}); + : new[] { "Cassandra" }); } [Test] @@ -153,7 +153,7 @@ public void Should_Retrieve_Graph_Multiple_Properties() var starWarsVertex = resultArray[0].ToVertex(); Assert.AreEqual("Star Wars", starWarsVertex.GetProperty("title").Value.ToString()); var tags = starWarsVertex.GetProperties("tags").Select(p => p.Value.ToString()); - var expectedTags = new List() {"science-fiction", "adventure"}; + var expectedTags = new List() { "science-fiction", "adventure" }; CollectionAssert.AreEquivalent(expectedTags, tags); } } @@ -258,18 +258,18 @@ public void Should_Support_Object_As_Parameter(GraphProtocol protocol) "m.citizenship.each { c -> " + " Vertex country = graph.addVertex(label, 'country', 'country_name', c);" + " scientist.addEdge('had_citizenship', country);" + - "};", new {m = new {name, year_born = year, citizenship, field}})); + "};", new { m = new { name, year_born = year, citizenship, field } })); var rs = session.ExecuteGraph( - new SimpleGraphStatement("g.V().hasLabel('scientist').has('scientist_name', name)", new {name})); + new SimpleGraphStatement("g.V().hasLabel('scientist').has('scientist_name', name)", new { name })); Assert.AreEqual(protocol, rs.GraphProtocol); Vertex einstein = rs.FirstOrDefault(); Assert.NotNull(einstein); Assert.AreEqual("scientist", einstein.Label); // Vertices contain an array of values per each property - Assert.AreEqual(new[] {true, true, true}, - new[] {"scientist_name", "year_born", "field"}.Select(propName => + Assert.AreEqual(new[] { true, true, true }, + new[] { "scientist_name", "year_born", "field" }.Select(propName => einstein.Properties[propName].IsArray)); Assert.AreEqual(name, einstein.GetProperty("scientist_name").Value.ToString()); Assert.AreEqual(year, einstein.GetProperty("year_born").Value.To()); @@ -277,7 +277,7 @@ public void Should_Support_Object_As_Parameter(GraphProtocol protocol) var citizenships = session.ExecuteGraph(new SimpleGraphStatement( "g.V().hasLabel('scientist').has('scientist_name', name)" + - ".outE('had_citizenship').inV().values('country_name')", new {name})); + ".outE('had_citizenship').inV().values('country_name')", new { name })); var citizenshipArray = citizenships.ToArray(); Assert.AreEqual(citizenship.Length, citizenshipArray.Length); @@ -651,7 +651,7 @@ public static IEnumerable Should_Support_Types_TestCases new TestCaseData("Text()", "The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy dog", null) }; } - } + } [TestCaseSource(typeof(GraphTests), nameof(GraphTests.Should_Support_Types_TestCases))] [Test] @@ -689,15 +689,15 @@ private IVertex IncludeAndQueryVertex( var schemaQuery = $"schema.propertyKey(propertyName).{type}.ifNotExists().create();\n" + "schema.vertexLabel(vertexLabel).properties(propertyName).ifNotExists().create();"; - session.ExecuteGraph(new SimpleGraphStatement(schemaQuery, new {vertexLabel, propertyName })); + session.ExecuteGraph(new SimpleGraphStatement(schemaQuery, new { vertexLabel, propertyName })); - var parameters = new {vertexLabel, propertyName, val = value }; + var parameters = new { vertexLabel, propertyName, val = value }; session.ExecuteGraph(new SimpleGraphStatement("g.addV(vertexLabel).property(propertyName, val)", parameters)); var rs = session.ExecuteGraph( new SimpleGraphStatement("g.V().hasLabel(vertexLabel).has(propertyName, val).next()", parameters)); - + if (protocol != null) { Assert.AreEqual(protocol.Value, rs.GraphProtocol); @@ -721,11 +721,11 @@ private void TestInsertSelectProperty(string type, T value, bool verifyToStri var propertyName1 = "prop" + id1; var vertexLabel2 = "vertex" + id2; var propertyName2 = "prop" + id2; - + var vertex = IncludeAndQueryVertex(vertexLabel1, propertyName1, type, value, value.ToString(), verifyToString, GraphProtocol.GraphSON1); var propObject = vertex.GetProperty(propertyName1).Value.To(); Assert.AreEqual(value, propObject); - + vertex = IncludeAndQueryVertex(vertexLabel2, propertyName2, type, value, value.ToString(), verifyToString, GraphProtocol.GraphSON2); propObject = vertex.GetProperty(propertyName2).Value.To(); Assert.AreEqual(value, propObject); @@ -878,7 +878,7 @@ public void ExecuteGraph_Should_Throw_ArgumentOutOfRange_When_Duration_Is_Out_Of foreach (var value in values) { - var parameters = new {vertexLabel = "v1", propertyName = "prop1", val = value}; + var parameters = new { vertexLabel = "v1", propertyName = "prop1", val = value }; var stmt = new SimpleGraphStatement("g.addV(vertexLabel).property(propertyName, val)", parameters); Assert.Throws(() => session.ExecuteGraph(stmt)); } @@ -985,7 +985,7 @@ public async Task With_GraphSON2_It_Should_Parse_Bulked_Results() " [\"has\", \"name\", \"marko\"], [\"outE\"], [\"label\"]]}}"); statement.SetGraphLanguage(GraphTests.BytecodeJson); var rs = await _session.ExecuteGraphAsync(statement).ConfigureAwait(false); - Assert.That(rs.To(), Is.EqualTo(new [] {"created", "knows", "knows"})); + Assert.That(rs.To(), Is.EqualTo(new[] { "created", "knows", "knows" })); Assert.AreEqual(GraphProtocol.GraphSON2, rs.GraphProtocol); } @@ -994,9 +994,9 @@ public async Task With_GraphSON1_It_Should_Parse_Bulked_Results() { var statement = new SimpleGraphStatement("g.V().hasLabel('person').has('name', 'marko').outE().label()"); var rs = await _session.ExecuteGraphAsync(statement).ConfigureAwait(false); - Assert.That(rs.To(), Is.EqualTo(new [] {"created", "knows", "knows"})); + Assert.That(rs.To(), Is.EqualTo(new[] { "created", "knows", "knows" })); } - + [Test] public async Task Should_UseGraphSON1_When_ClassicGraphEngineAndGremlinGroovy() { @@ -1015,7 +1015,7 @@ public async Task Should_UseGraphSON2_When_ClassicGraphEngineAndBytecode() var rs = await _session.ExecuteGraphAsync(statement).ConfigureAwait(false); Assert.AreEqual(GraphProtocol.GraphSON2, rs.GraphProtocol); } - + [TestCase(GraphProtocol.GraphSON1)] [TestCase(GraphProtocol.GraphSON2)] [Test] diff --git a/src/Cassandra.IntegrationTests/DataStax/Insights/InsightsIntegrationTests.cs b/src/Cassandra.IntegrationTests/DataStax/Insights/InsightsIntegrationTests.cs index fad2cc682..2cec4a54b 100644 --- a/src/Cassandra.IntegrationTests/DataStax/Insights/InsightsIntegrationTests.cs +++ b/src/Cassandra.IntegrationTests/DataStax/Insights/InsightsIntegrationTests.cs @@ -112,7 +112,7 @@ public void Should_InvokeInsightsRpcCall_When_SessionIsCreated() } } } - + [Test] [TestInsightsVersion] public void Should_InvokeInsightsRpcCallPeriodically_When_SessionIsCreatedAndEventDelayPasses() @@ -123,7 +123,7 @@ public void Should_InvokeInsightsRpcCallPeriodically_When_SessionIsCreatedAndEve using (var cluster = BuildCluster(simulacronCluster, 50)) { Assert.AreEqual(0, simulacronCluster.GetQueries("CALL InsightsRpc.reportInsight(?)").Count); - var session = (IInternalSession) cluster.Connect(); + var session = (IInternalSession)cluster.Connect(); IList queries = null; TestHelper.RetryAssert( () => @@ -134,15 +134,15 @@ public void Should_InvokeInsightsRpcCallPeriodically_When_SessionIsCreatedAndEve }, 250, 40); - - + + string json = string.Empty; Insight message = null; try { json = Encoding.UTF8.GetString( Convert.FromBase64String( - (string) queries[1].Frame.GetQueryMessage().Options.PositionalValues[0])); + (string)queries[1].Frame.GetQueryMessage().Options.PositionalValues[0])); message = JsonConvert.DeserializeObject>(json); } catch (JsonReaderException ex) diff --git a/src/Cassandra.IntegrationTests/DurationTests.cs b/src/Cassandra.IntegrationTests/DurationTests.cs index 4fd12c0b6..19ed8f4a3 100644 --- a/src/Cassandra.IntegrationTests/DurationTests.cs +++ b/src/Cassandra.IntegrationTests/DurationTests.cs @@ -27,7 +27,7 @@ namespace Cassandra.IntegrationTests [TestBothServersVersion(4, 0, 5, 1)] public class DurationTests : SharedClusterTest { - public static readonly string[] Values = + public static readonly string[] Values = { "1y2mo", "-1y2mo", @@ -73,7 +73,7 @@ protected override string[] SetupQueries { get { - return new [] + return new[] { "CREATE TABLE tbl_duration (pk uuid PRIMARY KEY, c1 duration)", "CREATE TYPE IF NOT EXISTS test_duration_udt (i int, c1 duration)", @@ -161,7 +161,7 @@ public void Should_Allow_Duration_In_Collections() Assert.AreEqual(id, row.GetValue("k")); Assert.AreEqual(list, row.GetValue>("l")); } - + } [Test] diff --git a/src/Cassandra.IntegrationTests/ExecutionProfiles/LinqExecutionProfileTests.cs b/src/Cassandra.IntegrationTests/ExecutionProfiles/LinqExecutionProfileTests.cs index f92521130..924b2a9bc 100644 --- a/src/Cassandra.IntegrationTests/ExecutionProfiles/LinqExecutionProfileTests.cs +++ b/src/Cassandra.IntegrationTests/ExecutionProfiles/LinqExecutionProfileTests.cs @@ -201,10 +201,10 @@ public async Task Should_ExecuteUpdateIfExistsWithProvidedExecutionProfile_When_ Assert.AreEqual(queries.Count + 1, newQueries.Count); Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two)); } - + private object[] CreatePrimeObject(AllDataTypesEntity allData) { - return new object [] { allData.StringType, allData.GuidType, allData.IntType }; + return new object[] { allData.StringType, allData.GuidType, allData.IntType }; } private IThenFluent CreateThenForPrimeSelect(IWhenFluent when, IEnumerable allData) @@ -217,9 +217,9 @@ private IThenFluent CreateThenForPrimeSelect(IWhenFluent when, IEnumerable allData, ConsistencyLevel consistencyLevel, string query) { - var primeQuery = + var primeQuery = CreateThenForPrimeSelect( - SimulacronBase.PrimeBuilder().WhenQuery(query, when => when.WithConsistency(consistencyLevel)), + SimulacronBase.PrimeBuilder().WhenQuery(query, when => when.WithConsistency(consistencyLevel)), allData) .BuildRequest(); _simulacronCluster.Prime(primeQuery); @@ -235,9 +235,9 @@ public async Task Should_ExecuteFetchWithProvidedExecutionProfile_When_Execution var queries = _simulacronCluster.GetQueries(cql, QueryType.Execute); var selectQuery = _table .Select(m => new AllDataTypesEntity { IntType = m.IntType }); - - var result = async - ? (await selectQuery.ExecuteAsync("testProfile").ConfigureAwait(false)).ToList() + + var result = async + ? (await selectQuery.ExecuteAsync("testProfile").ConfigureAwait(false)).ToList() : selectQuery.Execute("testProfile").ToList(); var newQueries = _simulacronCluster.GetQueries(cql, QueryType.Execute); @@ -261,8 +261,8 @@ public async Task Should_ExecuteFetchPagedWithProvidedExecutionProfile_When_Exec var queries = _simulacronCluster.GetQueries(cql, QueryType.Execute); var selectQuery = _table.Select(m => new AllDataTypesEntity { IntType = m.IntType }); - var result = async - ? (await selectQuery.ExecutePagedAsync("testProfile").ConfigureAwait(false)).ToList() + var result = async + ? (await selectQuery.ExecutePagedAsync("testProfile").ConfigureAwait(false)).ToList() : selectQuery.ExecutePaged("testProfile").ToList(); var newQueries = _simulacronCluster.GetQueries(cql, QueryType.Execute); @@ -275,7 +275,7 @@ public async Task Should_ExecuteFetchPagedWithProvidedExecutionProfile_When_Exec Assert.AreEqual(_entityList[i].IntType, result[i].IntType); } } - + [Test] [TestCase(true)] [TestCase(false)] @@ -302,7 +302,7 @@ public async Task Should_ExecuteScalarWithProvidedExecutionProfile_When_Executio Assert.AreEqual(queries.Count + 1, newQueries.Count); Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two)); } - + [Test] [TestCase(true)] [TestCase(false)] diff --git a/src/Cassandra.IntegrationTests/ExecutionProfiles/MapperExecutionProfileTests.cs b/src/Cassandra.IntegrationTests/ExecutionProfiles/MapperExecutionProfileTests.cs index 40c61b899..12e0b00c6 100644 --- a/src/Cassandra.IntegrationTests/ExecutionProfiles/MapperExecutionProfileTests.cs +++ b/src/Cassandra.IntegrationTests/ExecutionProfiles/MapperExecutionProfileTests.cs @@ -203,7 +203,7 @@ public void Should_ExecuteSingleOrDefaultWithExecutionProfile_When_ExecutionProf Assert.IsNotNull(movie); Assert.IsTrue(new MovieComparer().Compare(_movieList.Skip(2).First(), movie) == 0); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -394,7 +394,7 @@ await _mapper.UpdateIfAsync( Assert.AreEqual(queries.Count + 1, newQueries.Count); Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two)); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -424,7 +424,7 @@ public async Task Should_ExecuteBatchWithExecutionProfile_When_ExecutionProfileI Assert.AreEqual(queries.Count + 1, newQueries.Count); Assert.AreEqual(ConsistencyLevel.Two, newQueries.Last().Frame.GetBatchMessage().ConsistencyLevel); } - + [Test] [TestCase(true)] [TestCase(false)] diff --git a/src/Cassandra.IntegrationTests/FoundBugs/FoundBugTests.cs b/src/Cassandra.IntegrationTests/FoundBugs/FoundBugTests.cs index c66812d69..b6a13c64c 100644 --- a/src/Cassandra.IntegrationTests/FoundBugs/FoundBugTests.cs +++ b/src/Cassandra.IntegrationTests/FoundBugs/FoundBugTests.cs @@ -84,7 +84,7 @@ public void Jira_CSHARP_40() } catch (Exception e) { - if (e.GetType() == typeof (NoHostAvailableException)) + if (e.GetType() == typeof(NoHostAvailableException)) { noHostAvailableExceptionWasCaught = true; } @@ -109,7 +109,7 @@ public void Jira_CSHARP_40() } catch (Exception e) { - if (e.GetType() == typeof (NoHostAvailableException)) + if (e.GetType() == typeof(NoHostAvailableException)) { Trace.TraceInformation("Host still not up yet, waiting another one second ... "); Thread.Sleep(1000); diff --git a/src/Cassandra.IntegrationTests/Geometry/GeometryTests.cs b/src/Cassandra.IntegrationTests/Geometry/GeometryTests.cs index d148b4dfc..95294f607 100644 --- a/src/Cassandra.IntegrationTests/Geometry/GeometryTests.cs +++ b/src/Cassandra.IntegrationTests/Geometry/GeometryTests.cs @@ -66,8 +66,8 @@ private void SerializeDeserializeTest(bool prepared) foreach (var value in Values) { var id = prefix + value; - var statement = prepared ? - (IStatement) insertPs.Bind(id, value) : + var statement = prepared ? + (IStatement)insertPs.Bind(id, value) : new SimpleStatement(InsertGeoQuery, id, value); Session.Execute(statement); @@ -129,7 +129,7 @@ public void Serialize_Deserialize_Set_Test(bool prepared) [TestCase(false)] public void Serialize_Deserialize_Map_Test(bool prepared) { - SerializeDeserializeCollectionsTest(prepared, "tbl_map", + SerializeDeserializeCollectionsTest(prepared, "tbl_map", new Dictionary { {"a1", Values[0] } diff --git a/src/Cassandra.IntegrationTests/Linq/CqlOperatorTests/Prepend.cs b/src/Cassandra.IntegrationTests/Linq/CqlOperatorTests/Prepend.cs index 7f3eb211f..7cca54af6 100644 --- a/src/Cassandra.IntegrationTests/Linq/CqlOperatorTests/Prepend.cs +++ b/src/Cassandra.IntegrationTests/Linq/CqlOperatorTests/Prepend.cs @@ -49,7 +49,7 @@ public void Prepend_ToList() table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.Prepend(listToAdd) }) .Update().Execute(); - + VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ? + ListType WHERE Id = ?", 1, @@ -78,7 +78,7 @@ public void Prepend_ToList_StartsOutEmpty() table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.Prepend(listToAdd) }) .Update().Execute(); - + VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ? + ListType WHERE Id = ?", 1, @@ -98,7 +98,7 @@ public void Prepend_ToList_PrependEmptyList() table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.Prepend(listToAdd) }) .Update().Execute(); - + VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ? + ListType WHERE Id = ?", 1, @@ -117,8 +117,8 @@ public void Prepend_ToArray() var arrToAdd = new string[] { - "random_" + Randomm.RandomAlphaNum(10), - "random_" + Randomm.RandomAlphaNum(10), + "random_" + Randomm.RandomAlphaNum(10), + "random_" + Randomm.RandomAlphaNum(10), "random_" + Randomm.RandomAlphaNum(10), }; var singleEntity = expectedEntities.First(); @@ -144,8 +144,8 @@ public void Prepend_ToArray_QueryUsingCql() var arrToAdd = new string[] { - "random_" + Randomm.RandomAlphaNum(10), - "random_" + Randomm.RandomAlphaNum(10), + "random_" + Randomm.RandomAlphaNum(10), + "random_" + Randomm.RandomAlphaNum(10), "random_" + Randomm.RandomAlphaNum(10), }; var listReversed = arrToAdd.ToList(); @@ -163,7 +163,7 @@ public void Prepend_ToArray_QueryUsingCql() table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.Prepend(arrToAdd) }) .Update().Execute(); - + VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ? + ArrayType WHERE Id = ?", 1, @@ -189,7 +189,7 @@ public void Prepend_ToArray_AppendEmptyArray_QueryUsingCql() table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.Prepend(arrToAdd) }) .Update().Execute(); - + VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ? + ArrayType WHERE Id = ?", 1, diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Counter.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Counter.cs index 67ac0011a..0ce79c7c3 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Counter.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Counter.cs @@ -51,8 +51,8 @@ private RowsResult AddRows(IEnumerable counters } private void PrimeLinqCounterRangeQuery( - IEnumerable counters, - string tableName = "CounterEntityWithLinqAttributes", + IEnumerable counters, + string tableName = "CounterEntityWithLinqAttributes", bool caseSensitive = true) { var cql = caseSensitive diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Delete.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Delete.cs index 6e08b00eb..0d454911f 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Delete.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Delete.cs @@ -40,7 +40,7 @@ public override void SetUp() _entityList = AllDataTypesEntity.GetDefaultAllDataTypesList(); _table = new Table(Session, new MappingConfiguration()); } - + [TestCase(true)] [TestCase(false)] [Test] @@ -68,7 +68,7 @@ public void Delete_DeleteOneEquals(bool async) VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?", 1, entityToDelete.StringType); - + TestCluster.PrimeDelete(); AllDataTypesEntity.PrimeCountQuery(TestCluster, _entityList.Count - 1); @@ -77,7 +77,7 @@ public void Delete_DeleteOneEquals(bool async) TestCluster.PrimeFluent(b => entityToDelete.When(TestCluster, b).ThenVoidSuccess()); Assert.AreEqual(0, selectQuery.Execute().ToList().Count); } - + [TestCase(true)] [TestCase(false)] [Test] @@ -104,7 +104,7 @@ public void Delete_DeleteMultipleContains(bool async) public void Delete_MissingKey_Sync() { var table = new Table(Session, new MappingConfiguration()); - + TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"boolean_type\" = ?", when => when.WithParam(true)) @@ -132,7 +132,7 @@ public void Delete_NoSuchRecord() Assert.AreEqual(1, listOfExecutionParameters.Count); var parameter = Convert.FromBase64String((string)listOfExecutionParameters.Single().Single()); - var actualParameter = (string) Session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer().Deserialize(parameter, 0, parameter.Length, ColumnTypeCode.Text, null); + var actualParameter = (string)Session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer().Deserialize(parameter, 0, parameter.Length, ColumnTypeCode.Text, null); Assert.AreNotEqual(entityToDelete.StringType, actualParameter); Assert.IsTrue(actualParameter.StartsWith(entityToDelete.StringType)); Assert.IsTrue(actualParameter.Length > entityToDelete.StringType.Length); @@ -181,9 +181,9 @@ public void Delete_IfExists() deleteQuery.Execute(); VerifyBoundStatement( - $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", - 1, - entityToDelete.StringType, + $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", + 1, + entityToDelete.StringType, entityToDelete.GuidType); } @@ -200,20 +200,20 @@ public void Delete_IfExists_RowDoesntExist() var deleteQuery = selectQuery.Delete().IfExists(); deleteQuery.Execute(); - + VerifyBoundStatement( - $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", - 1, - entityToDelete.StringType, + $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", + 1, + entityToDelete.StringType, entityToDelete.GuidType); // Executing again should not fail, should just be a no-op deleteQuery.Execute(); - + VerifyBoundStatement( - $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", - 2, - entityToDelete.StringType, + $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", + 2, + entityToDelete.StringType, entityToDelete.GuidType); } @@ -225,7 +225,7 @@ public void Delete_IfExists_ClusteringKeyOmitted() { var table = new Table(Session, new MappingConfiguration()); AllDataTypesEntity entityToDelete = _entityList[0]; - + TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? IF EXISTS", when => when.WithParam(entityToDelete.StringType)) @@ -258,13 +258,13 @@ public void Delete_BatchType(BatchType batchType) batch.Execute(); VerifyBatchStatement( - 1, - new [] + 1, + new[] { $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?", $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?" }, - new[] { new object [] { entityToDelete.StringType }, new object [] { entityToDelete2.StringType }}); + new[] { new object[] { entityToDelete.StringType }, new object[] { entityToDelete2.StringType } }); } } } \ No newline at end of file diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/DeleteIf.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/DeleteIf.cs index 8ccd46a86..35e6f74d2 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/DeleteIf.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/DeleteIf.cs @@ -80,7 +80,7 @@ public void DeleteIf_ConditionBasedOnKey() var table = new Table(Session, new MappingConfiguration()); var entityToDelete = _entityList[0]; var expectedErrMsg = "PRIMARY KEY column 'string_type' cannot have IF conditions"; - + TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? IF \"string_type\" = ?", when => when.WithParams(entityToDelete.StringType, entityToDelete.StringType)) @@ -105,7 +105,7 @@ public void DeleteIf_NotAllKeysRestricted_ClusteringKeyOmitted() var random = ConstantReturningHelper.FromObj(Randomm.RandomAlphaNum(10)); var table = new Table(Session, new MappingConfiguration()); var entityToDelete = _entityList[0]; - + TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? IF \"int_type\" = ?", when => when.WithParams(entityToDelete.StringType + random.Get(), entityToDelete.IntType)) @@ -147,11 +147,11 @@ public void DeleteIf_NoMatchingRecord() TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF \"int_type\" = ?", when => when.WithParams(entityToDelete.StringType + random.Get(), randomGuid.Get(), entityToDelete.IntType)) - .ThenRowsSuccess(new [] { "[applied]" }, rows => rows.WithRow(false))); + .ThenRowsSuccess(new[] { "[applied]" }, rows => rows.WithRow(false))); // Test var selectQuery = table.Select(m => m) - .Where(m => m.StringType == entityToDelete.StringType + random.Get() + .Where(m => m.StringType == entityToDelete.StringType + random.Get() && m.GuidType == randomGuid.Get()); var deleteIfQuery = selectQuery.DeleteIf(m => m.IntType == entityToDelete.IntType); diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/First.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/First.cs index f88f3fe00..aa53079ff 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/First.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/First.cs @@ -40,7 +40,7 @@ public class First : SimulacronTest public override void SetUp() { base.SetUp(); - + MappingConfiguration movieMappingConfig = new MappingConfiguration(); movieMappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(Movie), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(Movie))); @@ -72,7 +72,7 @@ public void First_ExecuteAsync(bool async) { Assert.Fail( string.Join(",", typeof(Movie).GetFields().Select(f => f.Name) - .Union(typeof(Movie).GetProperties().Select(p => p.Name))) + + .Union(typeof(Movie).GetProperties().Select(p => p.Name))) + ex + Environment.NewLine + JsonConvert.SerializeObject(TestCluster.GetLogs())); } } @@ -91,7 +91,7 @@ public void First_NoSuchRecord() Movie foundMovie = _movieTable.First(m => m.Title == existingMovie.Title && m.MovieMaker == randomStr).Execute(); Assert.Null(foundMovie); - + VerifyBoundStatement( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " + $"FROM \"{Movie.TableName}\" WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? LIMIT ? ALLOW FILTERING", @@ -123,7 +123,7 @@ public void First_NoPartitionKey() .ThenServerError(ServerError.Invalid, "msg")); var ex = Assert.Throws(() => _movieTable.First(m => m.Year == 100).Execute()); Assert.AreEqual("msg", ex.Message); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " + diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/FirstOrDefault.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/FirstOrDefault.cs index 47f161ca8..6734fc9f5 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/FirstOrDefault.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/FirstOrDefault.cs @@ -30,11 +30,11 @@ public class FirstOrDefault : SimulacronTest { private readonly List _movieList = Movie.GetDefaultMovieList(); private Table _movieTable; - + public override void SetUp() { base.SetUp(); - + MappingConfiguration movieMappingConfig = new MappingConfiguration(); movieMappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(Movie), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(Movie))); @@ -47,7 +47,7 @@ public override void SetUp() public void LinqFirstOrDefault(bool async) { var expectedMovie = _movieList.First(); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " + @@ -63,7 +63,7 @@ public void LinqFirstOrDefault(bool async) Assert.IsNotNull(first); Assert.AreEqual(expectedMovie.MovieMaker, first.MovieMaker); } - + [TestCase(true)] [TestCase(false)] [Test] diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Select.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Select.cs index 01afe7820..c09b165ae 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Select.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Select.cs @@ -53,9 +53,9 @@ public void LinqSelect_SelectAll_Sync(bool async) var table = _table; AllDataTypesEntity.PrimeRangeSelect(TestCluster, _entityList); - List allEntities = - async - ? table.Select(m => m).ExecuteAsync().GetAwaiter().GetResult().ToList() + List allEntities = + async + ? table.Select(m => m).ExecuteAsync().GetAwaiter().GetResult().ToList() : table.Select(m => m).Execute().ToList(); Assert.AreEqual(_entityList.Count, allEntities.Count); foreach (var entity in allEntities) @@ -74,8 +74,8 @@ public void LinqSelect_BooleanType_Sync() TestCluster.PrimeFluent( b => b.WhenQuery("SELECT \"boolean_type\" FROM \"allDataTypes\" ALLOW FILTERING") .ThenRowsSuccess( - new [] { "boolean_type" }, - rows => rows.WithRows(_entityList.Select(e => new object [] { e.BooleanType }).ToArray()))); + new[] { "boolean_type" }, + rows => rows.WithRows(_entityList.Select(e => new object[] { e.BooleanType }).ToArray()))); List actualEntities = _table.Select(e => new AllDataTypesEntity { BooleanType = e.BooleanType }).Execute().ToList(); Assert.AreEqual(_entityList.Count, actualEntities.Count); foreach (var entity in _entityList) @@ -307,7 +307,7 @@ public void LinqSelect_IntType_Sync() AllDataTypesEntityUtil.AssertListContains(actualEntities, expectedEntity); } } - + [Test] public void LinqSelect_ListOfGuidsType_Sync() { @@ -495,7 +495,7 @@ public void LinqSelect_Project_To_New_Type_With_Conflict_Properties() .ThenRowsSuccess( new[] { "Col1", "Col2" }, rows => rows.WithRow(value1, value2))); - + var a = (from row in table where row.Id == pk select new TestClassDefaultCtor { S1 = row.Col1, S2 = row.Col2 }).Execute().First(); Assert.AreEqual(value1, a.S1); diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Take.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Take.cs index b737d5dd0..fd0b3b208 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Take.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Take.cs @@ -59,8 +59,8 @@ public void LinqTable_Take_Zero_Sync(bool async) .ThenRowsSuccess(Movie.CreateRowsResult(_movieList))); // Without where clause - List actualMovieList = async - ? _movieTable.Take(0).ExecuteAsync().GetAwaiter().GetResult().ToList() + List actualMovieList = async + ? _movieTable.Take(0).ExecuteAsync().GetAwaiter().GetResult().ToList() : _movieTable.Take(0).Execute().ToList(); Assert.AreEqual(5, actualMovieList.Count()); } @@ -124,7 +124,7 @@ public void LinqTable_Take_UsingWhereClause_Sync(bool async) var actualMovieQuery = _movieTable .Where(m => m.Director == expectedMovie.Director && m.Title == expectedMovie.Title && m.MovieMaker == expectedMovie.MovieMaker) .Take(1); - + var actualMovie = async ? actualMovieQuery.ExecuteAsync().GetAwaiter().GetResult().ToList().First() : actualMovieQuery.Execute().ToList().First(); Movie.AssertEquals(expectedMovie, actualMovie); } diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/UpdateIfTests.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/UpdateIfTests.cs index f3e0ef18a..846292223 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/UpdateIfTests.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/UpdateIfTests.cs @@ -46,7 +46,7 @@ public void LinqTable_UpdateIf_AppliedInfo_Test() Director = "Peter Weir", MovieMaker = "Touchstone" }; - + TestCluster.PrimeFluent( b => b.WhenQuery( $"UPDATE \"{Movie.TableName}\" " + @@ -71,7 +71,7 @@ public void LinqTable_UpdateIf_AppliedInfo_Test() Director = "Peter Weir", MovieMaker = "Touchstone" }; - + TestCluster.PrimeFluent( b => b.WhenQuery( $"UPDATE \"{Movie.TableName}\" " + @@ -79,7 +79,7 @@ public void LinqTable_UpdateIf_AppliedInfo_Test() "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ? IF \"yearMade\" = ?", when => when.WithParams("WHOEVER", movie.Title, movie.MovieMaker, movie.Director, 1500)) .ThenRowsSuccess(existingMovie.CreateAppliedInfoRowsResult())); - + //Should not update as the if clause is not satisfied var updateIf = movieTable .Where(m => m.Title == "Dead Poets Society" && m.MovieMaker == "Touchstone" && m.Director == "Peter Weir") diff --git a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Where.cs b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Where.cs index 5b950d551..4ffe21750 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqMethods/Where.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqMethods/Where.cs @@ -65,7 +65,7 @@ public override void SetUp() public void LinqWhere_Execute(bool async) { var expectedMovie = _movieList.First(); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " + @@ -81,13 +81,13 @@ public void LinqWhere_Execute(bool async) var actualMovie = movies.First(); Movie.AssertEquals(expectedMovie, actualMovie); } - + [Test] public void LinqWhere_NoSuchRecord() { var existingMovie = _movieList.Last(); var randomStr = "somethingrandom_" + Randomm.RandomAlphaNum(10); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " + @@ -132,7 +132,7 @@ public void LinqWhere_Exception() "ALLOW FILTERING", rows => rows.WithParams(100)) .ThenServerError(ServerError.Invalid, "msg")); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", " + @@ -142,7 +142,7 @@ public void LinqWhere_Exception() "ALLOW FILTERING", rows => rows.WithParams("13")) .ThenServerError(ServerError.Invalid, "msg")); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", " + @@ -178,7 +178,7 @@ public void LinqWhere_NoPartitionKey() "ALLOW FILTERING", rows => rows.WithParams(100)) .ThenServerError(ServerError.Invalid, "msg")); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", " + @@ -244,36 +244,36 @@ public void LinqWhere_AppendMultipleTimes() new TestTable { UserId = 1, Date = 2, TimeColumn = 4 }, new TestTable { UserId = 1, Date = 2, TimeColumn = 5 } }; - + TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? ALLOW FILTERING", rows => rows.WithParams(userId, date)) .ThenRowsSuccess( - new [] { "date", "time", "user" }, + new[] { "date", "time", "user" }, rows => rows.WithRows(data.Select( - t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); - + t => new object[] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); + TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? AND \"time\" >= ? ORDER BY \"time\" ALLOW FILTERING", rows => rows.WithParams(userId, date, time)) .ThenRowsSuccess( - new [] { "date", "time", "user" }, + new[] { "date", "time", "user" }, rows => rows.WithRows(data.Where(t => t.TimeColumn >= time).OrderBy(t => t.TimeColumn).Select( - t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); - + t => new object[] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); + TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? AND \"time\" <= ? ORDER BY \"time\" DESC ALLOW FILTERING", rows => rows.WithParams(userId, date, time)) .ThenRowsSuccess( - new [] { "date", "time", "user" }, + new[] { "date", "time", "user" }, rows => rows.WithRows(data.Where(t => t.TimeColumn <= time).OrderByDescending(t => t.TimeColumn).Select( - t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); + t => new object[] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); var query1Actual = table.Where(i => i.UserId == userId && i.Date == date); @@ -321,16 +321,16 @@ public void LinqWhere_TupleWithClusteringKeys() TimeColumn = 1 }; var localList = new List { 0, 2 }; - + TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT date, id, time FROM {tableName} " + "WHERE id = ? AND date IN ?", rows => rows.WithParams(1, localList)) .ThenRowsSuccess( - ("date", DataType.GetDataType(typeof(int))), - ("id",DataType.GetDataType(typeof(int))), - ("time",DataType.GetDataType(typeof(long))))); + ("date", DataType.GetDataType(typeof(int))), + ("id", DataType.GetDataType(typeof(int))), + ("time", DataType.GetDataType(typeof(long))))); var emptyResults = table.Where(t => t.UserId == 1 && localList.Contains(t.Date)).Execute(); Assert.NotNull(emptyResults); @@ -345,7 +345,7 @@ public void LinqWhere_TupleWithClusteringKeys() "WHERE id = ? AND date IN ?", rows => rows.WithParams(1, localList)) .ThenRowsSuccess( - new [] { "date", "id", "time" }, + new[] { "date", "id", "time" }, rows => rows.WithRow(data.Date, data.UserId, data.TimeColumn))); var tCreateResults = table.Where(t => t.UserId == 1 && localList.Contains(t.Date)).Execute(); @@ -378,21 +378,21 @@ public void LinqWhere_TupleWithCompositeKeys() var table = new Table(Session, new MappingConfiguration().Define(map)); var localList = new List> { Tuple.Create(0, 0L), Tuple.Create(0, 2L) }; - + TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT date, id, time FROM {tableName} " + "WHERE id = ? AND (date, time) IN ?", rows => rows.WithParams(1, localList)) .ThenRowsSuccess( - ("date", DataType.GetDataType(typeof(int))), - ("id",DataType.GetDataType(typeof(int))), - ("time",DataType.GetDataType(typeof(long))))); + ("date", DataType.GetDataType(typeof(int))), + ("id", DataType.GetDataType(typeof(int))), + ("time", DataType.GetDataType(typeof(long))))); var emptyResults = table.Where(t => t.UserId == 1 && localList.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute(); Assert.NotNull(emptyResults); Assert.AreEqual(0, emptyResults.ToArray().Length); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -400,16 +400,16 @@ public void LinqWhere_TupleWithCompositeKeys() "WHERE id = ? AND (date, time) IN ?", rows => rows.WithParams(1, new List>())) .ThenRowsSuccess( - ("date", DataType.GetDataType(typeof(int))), - ("id",DataType.GetDataType(typeof(int))), - ("time",DataType.GetDataType(typeof(long))))); + ("date", DataType.GetDataType(typeof(int))), + ("id", DataType.GetDataType(typeof(int))), + ("time", DataType.GetDataType(typeof(long))))); emptyResults = table.Where(t => t.UserId == 1 && new List>().Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute(); Assert.NotNull(emptyResults); Assert.AreEqual(0, emptyResults.ToArray().Length); localList.Add(Tuple.Create(1, 1L)); //adding to list existent tuple - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -458,7 +458,7 @@ public void LinqWhere_TupleWithCompositeKeys_Scopes() var listInsideObjResults = table.Where(t => t.UserId == 1 && anomObj.list.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute(); Assert.NotNull(listInsideObjResults); Assert.AreEqual(1, listInsideObjResults.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -470,7 +470,7 @@ public void LinqWhere_TupleWithCompositeKeys_Scopes() var listOuterScopeResults = table.Where(t => t.UserId == 1 && _tupleList.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute(); Assert.NotNull(listOuterScopeResults); Assert.AreEqual(1, listOuterScopeResults.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -531,7 +531,7 @@ public void LinqWhere_Boolean() "ALLOW FILTERING", p => p.WithParams(true)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.BooleanType).Execute(); @@ -563,7 +563,7 @@ public void LinqWhere_BooleanScopes() var rs = _manyDataTypesEntitiesTable.Where(m => m.BooleanType == all).Execute(); Assert.NotNull(rs); Assert.AreEqual(0, rs.Count()); - + //get all records TestCluster.PrimeDelete(); TestCluster.PrimeFluent( @@ -612,7 +612,7 @@ public void LinqWhere_ShortScopes() //Get poco using constant short const short expectedShortValue = 11; - + TestCluster.PrimeFluent( b => b.WhenQuery( cqlSelect + @@ -620,14 +620,14 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (int)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); var rs = _manyDataTypesEntitiesTable .Where(m => m.StringType == pk && m.IntType == expectedShortValue).AllowFiltering().Execute(); Assert.NotNull(rs); Assert.AreEqual(1, rs.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -636,14 +636,14 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (int)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && m.IntType == ExpectedShortValue) .AllowFiltering().Execute(); Assert.NotNull(rs); Assert.AreEqual(1, rs.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -652,13 +652,13 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (int)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && ExpectedShortValue == m.IntType) .AllowFiltering().Execute(); Assert.NotNull(rs); Assert.AreEqual(1, rs.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -667,7 +667,7 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (int)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && expectedShortValue == m.IntType) .AllowFiltering().Execute(); @@ -682,13 +682,13 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (long)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && m.Int64Type == expectedShortValue) .AllowFiltering().Execute(); Assert.NotNull(rs); Assert.AreEqual(1, rs.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -697,13 +697,13 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (long)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && expectedShortValue == m.Int64Type) .AllowFiltering().Execute(); Assert.NotNull(rs); Assert.AreEqual(1, rs.Count()); - + TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -712,7 +712,7 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (long)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && m.Int64Type == ExpectedShortValue) .AllowFiltering().Execute(); @@ -727,7 +727,7 @@ public void LinqWhere_ShortScopes() "ALLOW FILTERING", p => p.WithParams(pk, (long)expectedShortValue)) .ThenRowsSuccess( - ManyDataTypesEntity.GetColumnsWithTypes(), + ManyDataTypesEntity.GetColumnsWithTypes(), r => r.WithRow(data.GetColumnValues()))); rs = _manyDataTypesEntitiesTable.Where(m => m.StringType == pk && ExpectedShortValue == m.Int64Type) .AllowFiltering().Execute(); @@ -740,7 +740,7 @@ public void LinqWhere_Recovers_From_Invalid_Query_Exception() { var table = new Table(Session, new MappingConfiguration().Define( new Map().TableName("tbl_recovers_invalid_test").PartitionKey(x => x.Title))); - + TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT Artist, Id, ReleaseDate, Title FROM tbl_recovers_invalid_test" + @@ -757,9 +757,9 @@ public void LinqWhere_Recovers_From_Invalid_Query_Exception() " WHERE Title = ?", p => p.WithParams("Do I Wanna Know")) .ThenRowsSuccess( - ("Artist", DataType.GetDataType(typeof(string))), - ("Id", DataType.GetDataType(typeof(Guid))), - ("ReleaseDate", DataType.GetDataType(typeof(DateTimeOffset))), + ("Artist", DataType.GetDataType(typeof(string))), + ("Id", DataType.GetDataType(typeof(Guid))), + ("ReleaseDate", DataType.GetDataType(typeof(DateTimeOffset))), ("Title", DataType.GetDataType(typeof(string))))); Assert.AreEqual(0, table.Where(x => x.Title == "Do I Wanna Know").Execute().Count()); diff --git a/src/Cassandra.IntegrationTests/Linq/LinqRealClusterTests.cs b/src/Cassandra.IntegrationTests/Linq/LinqRealClusterTests.cs index 264202b7a..8b9ac8aca 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqRealClusterTests.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqRealClusterTests.cs @@ -74,7 +74,7 @@ public override void OneTimeSetUp() var movieMappingConfig = new MappingConfiguration(); _movieTable = new Table(_session, movieMappingConfig); _movieTable.Create(); - + //Insert some data foreach (var movie in _movieList) _movieTable.Insert(movie).Execute(); @@ -261,7 +261,7 @@ public void LinqUdt_Select() Assert.AreEqual("Bob Marley", song.Artist); } - [Test, TestCassandraVersion(2,1,0)] + [Test, TestCassandraVersion(2, 1, 0)] public void LinqUdt_Insert() { // Avoid interfering with other tests @@ -299,7 +299,7 @@ public void LinqUdt_Insert() Assert.NotNull(songs.FirstOrDefault(s => s.Title == "Communication Breakdown")); } - [Test, TestCassandraVersion(2,1,0)] + [Test, TestCassandraVersion(2, 1, 0)] public void LinqUdt_Where_Contains() { var songRecordsName = "song_records"; @@ -312,7 +312,7 @@ public void LinqUdt_Where_Contains() Artist = "Led Zeppelin", Title = "Good Times Bad Times" }; - var songs = new List {song, new Song2 {Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Whola Lotta Love"}}; + var songs = new List { song, new Song2 { Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Whola Lotta Love" } }; var id = Guid.NewGuid(); var songRecord = new SongRecords() { diff --git a/src/Cassandra.IntegrationTests/Linq/LinqTable/CreateTable.cs b/src/Cassandra.IntegrationTests/Linq/LinqTable/CreateTable.cs index 7307f4f5b..63e4a471e 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqTable/CreateTable.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqTable/CreateTable.cs @@ -73,7 +73,7 @@ public class CreateTable : SimulacronTest "NullableTimeUuidType timeuuid, " + "StringType text, " + "TimeUuidType timeuuid"; - + private const string CreateCqlDefaultColumnsCaseSensitive = "\"BooleanType\" boolean, " + "\"DateTimeOffsetType\" timestamp, " + @@ -98,14 +98,14 @@ public class CreateTable : SimulacronTest $"CREATE TABLE \"{AllDataTypesEntity.TableName}\" (" + CreateTable.CreateCqlColumns + ", " + "PRIMARY KEY (\"string_type\", \"guid_type\"))"; - + private static readonly string CreateCqlFormatStr = "CREATE TABLE {0} (" + CreateTable.CreateCqlColumns + ", " + "PRIMARY KEY (\"string_type\", \"guid_type\"))"; private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant(); - + /// /// Create a table using the method CreateIfNotExists /// @@ -138,7 +138,7 @@ public void TableCreate_Create() table.Create(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } - + [Test, TestCassandraVersion(4, 0, Comparison.LessThan)] public void Should_CreateTable_WhenClusteringOrderAndCompactOptionsAreSet() { @@ -150,9 +150,9 @@ public void Should_CreateTable_WhenClusteringOrderAndCompactOptionsAreSet() var table = new Table(Session, config); table.Create(); VerifyStatement( - QueryType.Query, + QueryType.Query, "CREATE TABLE Tweet (AuthorId text, Body text, TweetId uuid, PRIMARY KEY (TweetId, AuthorId)) " + - "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", + "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", 1); } @@ -163,7 +163,7 @@ public void TableCreateAsync_Create() table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement(QueryType.Query, CreateTable.CreateCql, 1); } - + [Test, TestCassandraVersion(4, 0, Comparison.LessThan)] public void Should_CreateTableAsync_WhenClusteringOrderAndCompactOptionsAreSet() { @@ -175,9 +175,9 @@ public void Should_CreateTableAsync_WhenClusteringOrderAndCompactOptionsAreSet() var table = new Table(Session, config); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( - QueryType.Query, + QueryType.Query, "CREATE TABLE Tweet (AuthorId text, Body text, TweetId uuid, PRIMARY KEY (TweetId, AuthorId)) " + - "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", + "WITH CLUSTERING ORDER BY (AuthorId DESC) AND COMPACT STORAGE", 1); } @@ -193,8 +193,8 @@ public void TableCreate_Create_NameOverride() Assert.AreEqual(uniqueTableName, table.Name); table.Create(); VerifyStatement( - QueryType.Query, - CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), + QueryType.Query, + CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), 1); } @@ -206,8 +206,8 @@ public void TableCreateAsync_Create_NameOverride() Assert.AreEqual(uniqueTableName, table.Name); table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( - QueryType.Query, - CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), + QueryType.Query, + CreateTable.CreateCql.Replace($"\"{AllDataTypesEntity.TableName}\"", $"\"{uniqueTableName}\""), 1); } @@ -224,8 +224,8 @@ public void TableCreate_CreateTable_AlreadyExists() table.Create(); VerifyStatement( - QueryType.Query, - $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", + QueryType.Query, + $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", 1); TestCluster.PrimeFluent( @@ -249,8 +249,8 @@ public void TableCreateAsync_CreateTable_AlreadyExists() table.CreateAsync().GetAwaiter().GetResult(); VerifyStatement( - QueryType.Query, - $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", + QueryType.Query, + $"CREATE TABLE {tableName} ({CreateTable.CreateCqlDefaultColumns}, PRIMARY KEY (TimeUuidType))", 1); TestCluster.PrimeFluent( @@ -309,7 +309,7 @@ public void TableCreate_CreateTable_SameNameDifferentTypeAlreadyExists_TableName var mappingConfig = new MappingConfiguration().Define(new Map().TableName(staticTableName).CaseSensitive().PartitionKey(c => c.StringType)); var allDataTypesTable = new Table(Session, mappingConfig); allDataTypesTable.Create(); - + VerifyStatement( QueryType.Query, $"CREATE TABLE \"{staticTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))", @@ -351,7 +351,7 @@ public void TableCreate_Create_KeyspaceOverride_NoSuchKeyspace() } var table = new Table(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); - if(!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) + if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { Assert.Throws(() => table.Create()); } @@ -380,7 +380,7 @@ public void TableCreateAsync_Create_KeyspaceOverride_NoSuchKeyspace() } var table = new Table(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName); - if(!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) + if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException()) { Assert.ThrowsAsync(() => table.CreateAsync()); } @@ -399,7 +399,7 @@ public void TableCreate_CreateIfNotExists_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); - + TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); @@ -413,7 +413,7 @@ public void TableCreateAsync_CreateIfNotExists_KeyspaceOverride_NoSuchKeyspace() { var uniqueTableName = TestUtils.GetUniqueTableName(); var uniqueKsName = TestUtils.GetUniqueKeyspaceName(); - + TestCluster.PrimeFluent( b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\"")) .ThenServerError(ServerError.ConfigError, "msg")); @@ -531,16 +531,16 @@ public void CreateTable_With_Frozen_Tuple() .ExplicitColumns()); var table = new Table(Session, config); table.Create(); - + VerifyStatement( QueryType.Query, "CREATE TABLE tbl_frozen_tuple (Id1 uuid, t frozen>, PRIMARY KEY (Id1))", 1); - + PrimeSystemSchemaTables( - _uniqueKsName, + _uniqueKsName, "tbl_frozen_tuple", - new [] + new[] { new StubTableColumn("Id1", StubColumnKind.PartitionKey, DataType.Uuid), new StubTableColumn("t", StubColumnKind.Regular, DataType.Frozen(DataType.Tuple(DataType.BigInt, DataType.BigInt, DataType.Text))) @@ -571,7 +571,7 @@ public void CreateTable_With_Counter_Static() .AsCounter())); var table = new Table(Session, config); table.Create(); - + VerifyStatement( QueryType.Query, "CREATE TABLE tbl_with_counter_static (" + @@ -580,13 +580,13 @@ public void CreateTable_With_Counter_Static() 1); PrimeSystemSchemaTables( - _uniqueKsName, + _uniqueKsName, "tbl_with_counter_static", - new [] + new[] { new StubTableColumn("counter_col1", StubColumnKind.Regular, DataType.Counter), - new StubTableColumn("counter_col2", StubColumnKind.Regular, DataType.Counter), - new StubTableColumn("id1", StubColumnKind.PartitionKey, DataType.Uuid), + new StubTableColumn("counter_col2", StubColumnKind.Regular, DataType.Counter), + new StubTableColumn("id1", StubColumnKind.PartitionKey, DataType.Uuid), new StubTableColumn("id2", StubColumnKind.ClusteringKey, DataType.Text) }); @@ -604,7 +604,7 @@ public void TableCreate_CreateWithPropertyName() { var table = new Table(Session, MappingConfiguration.Global); table.CreateIfNotExists(); - + VerifyStatement( QueryType.Query, "CREATE TABLE \"test_empty_clustering_column_name\" (" + @@ -636,13 +636,13 @@ private void WriteReadValidateUsingTableMethods(Table table) VerifyStatement( QueryType.Query, string.Format( - AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, + AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, ksAndTable), 1, expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()); // select record - + TestCluster.PrimeFluent( b => b.WhenQuery( string.Format(AllDataTypesEntity.SelectCqlDefaultColumnsFormatStr, ksAndTable), @@ -652,7 +652,7 @@ private void WriteReadValidateUsingTableMethods(Table table) r => r.WithRow(expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()))); - var listOfAllDataTypesObjects = + var listOfAllDataTypesObjects = (from x in table where x.StringType.Equals(uniqueKey) select x) .Execute().ToList(); Assert.NotNull(listOfAllDataTypesObjects); @@ -676,10 +676,10 @@ private void WriteReadValidateUsingSessionBatch(Table table) VerifyBatchStatement( 1, - new [] { string.Format( - AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, + new[] { string.Format( + AllDataTypesEntity.InsertCqlDefaultColumnsFormatStr, ksAndTable) }, - new [] { expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns() }); + new[] { expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns() }); TestCluster.PrimeFluent( b => b.WhenQuery( @@ -689,9 +689,9 @@ private void WriteReadValidateUsingSessionBatch(Table table) AllDataTypesEntity.GetDefaultColumns(), r => r.WithRow(expectedDataTypesEntityRow.GetColumnValuesForDefaultColumns()))); - var listOfAllDataTypesObjects = - (from x in table - where x.StringType.Equals(uniqueKey) + var listOfAllDataTypesObjects = + (from x in table + where x.StringType.Equals(uniqueKey) select x) .Execute().ToList(); Assert.NotNull(listOfAllDataTypesObjects); @@ -710,10 +710,10 @@ private void WriteReadValidate(Table table) private class PrivateClassMissingPartitionKey { //Is never used, but don't mind - #pragma warning disable 414, 169 +#pragma warning disable 414, 169 // ReSharper disable once InconsistentNaming private string StringValue = "someStringValue"; - #pragma warning restore 414, 169 +#pragma warning restore 414, 169 } private class PrivateEmptyClass @@ -734,7 +734,7 @@ private class TestEmptyClusteringColumnName // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local public string cluster { get; set; } - + [Column] // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local diff --git a/src/Cassandra.IntegrationTests/Linq/LinqTable/GetTable.cs b/src/Cassandra.IntegrationTests/Linq/LinqTable/GetTable.cs index ec40bfbac..bb105fda6 100644 --- a/src/Cassandra.IntegrationTests/Linq/LinqTable/GetTable.cs +++ b/src/Cassandra.IntegrationTests/Linq/LinqTable/GetTable.cs @@ -28,23 +28,23 @@ namespace Cassandra.IntegrationTests.Linq.LinqTable /// public class GetTable : SimulacronTest { - private const string InsertCql = + private const string InsertCql = "INSERT INTO \"allDataTypes\" (\"boolean_type\", \"date_time_offset_type\", " + "\"date_time_type\", \"decimal_type\", \"double_type\", \"float_type\", " + "\"guid_type\", \"int64_type\", \"int_type\", \"list_of_guids_type\", " + "\"list_of_strings_type\", \"map_type_string_long_type\", \"map_type_string_string_type\", " + "\"nullable_date_time_type\", \"nullable_int_type\", \"nullable_time_uuid_type\", " + - "\"string_type\", \"time_uuid_type\") " + - "VALUES " + + "\"string_type\", \"time_uuid_type\") " + + "VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - private const string SelectCql = - "SELECT \"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " + - "\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\", \"int64_type\", " + - "\"int_type\", \"list_of_guids_type\", \"list_of_strings_type\", \"map_type_string_long_type\"," + - " \"map_type_string_string_type\", \"nullable_date_time_type\", \"nullable_int_type\", " + - "\"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\" FROM \"allDataTypes\" " + - "WHERE \"string_type\" = ? " + + private const string SelectCql = + "SELECT \"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " + + "\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\", \"int64_type\", " + + "\"int_type\", \"list_of_guids_type\", \"list_of_strings_type\", \"map_type_string_long_type\"," + + " \"map_type_string_string_type\", \"nullable_date_time_type\", \"nullable_int_type\", " + + "\"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\" FROM \"allDataTypes\" " + + "WHERE \"string_type\" = ? " + "ALLOW FILTERING"; /// diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntity.cs b/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntity.cs index 79a1fc425..d6b77e273 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntity.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntity.cs @@ -194,7 +194,7 @@ private IWhenQueryBuilder WithParams(IWhenQueryBuilder when, params string[] col return columns.Aggregate(when, (current, c) => current.WithParam(AllDataTypesEntity.ColumnMappings[c](this))); } - public const string SelectCql = + public const string SelectCql = "SELECT \"boolean_type\", \"date_time_offset_type\", \"date_time_type\", " + "\"decimal_type\", \"double_type\", \"float_type\", \"guid_type\", \"int64_type\", " + "\"int_type\", \"list_of_guids_type\", \"list_of_strings_type\", \"map_type_string_long_type\"," + @@ -202,8 +202,8 @@ private IWhenQueryBuilder WithParams(IWhenQueryBuilder when, params string[] col "\"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\" FROM \"allDataTypes\" " + "WHERE \"string_type\" = ? " + "ALLOW FILTERING"; - - public const string SelectCqlDefaultColumnsFormatStr = + + public const string SelectCqlDefaultColumnsFormatStr = "SELECT \"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " + "\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"DoubleType\", " + "\"FloatType\", \"GuidType\", \"Int64Type\", \"IntType\", \"ListOfGuidsType\", " + @@ -225,14 +225,14 @@ public void PrimeSelect(SimulacronCluster testCluster) { testCluster.PrimeFluent(b => When(testCluster, b).ThenRowsSuccess(CreateRowsResult())); } - + public IWhenFluent When(SimulacronCluster testCluster, IPrimeRequestBuilder builder) { return builder.WhenQuery( AllDataTypesEntity.SelectCql, when => WithParams(when, "string_type")); } - + public const string InsertCqlDefaultColumnsFormatStr = "INSERT INTO {0} (" + "\"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " + @@ -260,17 +260,17 @@ public IWhenFluent When(SimulacronCluster testCluster, IPrimeRequestBuilder buil " \"nullable_int_type\", \"nullable_time_uuid_type\", \"string_type\", \"time_uuid_type\") " + "VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - + public void PrimeQuery(SimulacronCluster testCluster, string cql, params string[] paramNames) { testCluster.PrimeFluent( b => b.WhenQuery(cql, when => WithParams(when, paramNames)) .ThenRowsSuccess(CreateRowsResult())); } - + public RowsResult AddRow(RowsResult result) { - return (RowsResult) result.WithRow(GetColumnValues()); + return (RowsResult)result.WithRow(GetColumnValues()); } public object[] GetColumnValues() @@ -280,7 +280,7 @@ public object[] GetColumnValues() public static (string, DataType)[] GetDefaultColumns() { - return new [] + return new[] { (nameof(AllDataTypesEntity.BooleanType), DataType.GetDataType(typeof(bool))), (nameof(AllDataTypesEntity.DateTimeOffsetType), DataType.GetDataType(typeof(DateTimeOffset))), @@ -302,7 +302,7 @@ public static (string, DataType)[] GetDefaultColumns() (nameof(AllDataTypesEntity.TimeUuidType), DataType.GetDataType(typeof(TimeUuid))) }; } - + public object[] GetColumnValuesForDefaultColumns() { return new object[] @@ -337,7 +337,7 @@ public static void PrimeCountQuery(SimulacronCluster testCluster, long count) { testCluster.PrimeFluent( b => b.WhenQuery("SELECT count(*) FROM \"allDataTypes\" ALLOW FILTERING") - .ThenRowsSuccess(new [] { "count" }, rows => rows.WithRow(count))); + .ThenRowsSuccess(new[] { "count" }, rows => rows.WithRow(count))); } public static void PrimeRangeSelect(SimulacronCluster testCluster, IEnumerable data) diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntityUtil.cs b/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntityUtil.cs index be0f45c71..8667e2f8d 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntityUtil.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/AllDataTypesEntityUtil.cs @@ -42,15 +42,15 @@ public static IAllDataTypesEntity Randomize(IAllDataTypesEntity entity) entity.StringType = "StringType_val_" + Randomm.RandomAlphaNum(10); entity.GuidType = Guid.NewGuid(); entity.DateTimeType = DateTime.Now.ToUniversalTime(); - entity.NullableDateTimeType = Randomm.RandomInt() % 2 == 0 ? (DateTime?) null : DateTime.UtcNow; + entity.NullableDateTimeType = Randomm.RandomInt() % 2 == 0 ? (DateTime?)null : DateTime.UtcNow; entity.DateTimeOffsetType = new DateTimeOffset(); entity.BooleanType = false; - entity.DecimalType = (decimal) 98765432.0; - entity.DoubleType = (double) 9876543; - entity.FloatType = (float) 987654; + entity.DecimalType = (decimal)98765432.0; + entity.DoubleType = (double)9876543; + entity.FloatType = (float)987654; entity.NullableIntType = null; entity.IntType = 98765; - entity.Int64Type = (Int64) 9876; + entity.Int64Type = (Int64)9876; entity.TimeUuidType = TimeUuid.NewId(); entity.NullableTimeUuidType = null; entity.DictionaryStringLongType = dictionaryStringLong; diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/EmptyClusteringColumnName.cs b/src/Cassandra.IntegrationTests/Linq/Structures/EmptyClusteringColumnName.cs index ea0cf3f23..e51c4f50b 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/EmptyClusteringColumnName.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/EmptyClusteringColumnName.cs @@ -38,7 +38,7 @@ class EmptyClusteringColumnName // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local public string cluster { get; set; } - + [Mapping::Attributes.Column] // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithAllCollectionTypes.cs b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithAllCollectionTypes.cs index edbc7a803..c5c32ca8f 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithAllCollectionTypes.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithAllCollectionTypes.cs @@ -38,7 +38,7 @@ public static EntityWithAllCollectionTypes GetRandomInstance(int seed = 1) cte.Id = Guid.NewGuid().ToString(); cte.ListType = new List() { seed }; cte.ArrayType = new string[] { seed.ToString() }; - cte.DictionaryType = new Dictionary() { {"key_" + seed, "val_" + seed} }; + cte.DictionaryType = new Dictionary() { { "key_" + seed, "val_" + seed } }; return cte; } diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithArrayType.cs b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithArrayType.cs index 80993a79e..639a7c55f 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithArrayType.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithArrayType.cs @@ -46,7 +46,7 @@ public static Tuple, List> Setup return new Tuple, List>(table, entityList); } - + public static Tuple, List> GetDefaultTable( ISession session, string tableName) { diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithDictionaryType.cs b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithDictionaryType.cs index f0ec3429b..29e7371bf 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithDictionaryType.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithDictionaryType.cs @@ -46,7 +46,7 @@ public static Tuple, List, List>(table, entityList); } - + public static Tuple, List> GetDefaultTable( ISession session, string tableName) { @@ -77,7 +77,7 @@ public static EntityWithDictionaryType GetRandomInstance(int seed = 1) var entity = new EntityWithDictionaryType { Id = Guid.NewGuid().ToString(), - DictionaryType = new Dictionary() {{"key_" + seed, "val_" + seed}} + DictionaryType = new Dictionary() { { "key_" + seed, "val_" + seed } } }; return entity; } diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithListType.cs b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithListType.cs index b1f09a026..9825ada21 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithListType.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/EntityWithListType.cs @@ -28,7 +28,7 @@ class EntityWithListType private const int DefaultListLength = 5; public string Id { get; set; } public List ListType { get; set; } - + public static Tuple, List> GetDefaultTable( ISession session, string tableName) { diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/ManyDataTypesEntity.cs b/src/Cassandra.IntegrationTests/Linq/Structures/ManyDataTypesEntity.cs index 7f1c7f1bb..00308163a 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/ManyDataTypesEntity.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/ManyDataTypesEntity.cs @@ -159,7 +159,7 @@ public static void AssertListEqualsList(List expectedEntiti foreach (var expectedEntity in expectedEntities) Assert.IsTrue(ListContains(actualEntities, expectedEntity)); } - + private static readonly IDictionary> ColumnMappings = new Dictionary> { @@ -179,7 +179,7 @@ public static void AssertListEqualsList(List expectedEntiti { "NullableIntType", entity => entity.NullableIntType }, { "StringType", entity => entity.StringType } }; - + private static readonly IDictionary ColumnsToTypes = new Dictionary { diff --git a/src/Cassandra.IntegrationTests/Linq/Structures/Movie.cs b/src/Cassandra.IntegrationTests/Linq/Structures/Movie.cs index 60576c5e6..afe2b079e 100644 --- a/src/Cassandra.IntegrationTests/Linq/Structures/Movie.cs +++ b/src/Cassandra.IntegrationTests/Linq/Structures/Movie.cs @@ -126,7 +126,7 @@ public static List GetDefaultMovieList() movieList.Add(new Movie("title4", "actor2", "director4", "maker4", 1988)); return movieList; } - + private static readonly IDictionary> ColumnMappings = new Dictionary> { @@ -154,7 +154,7 @@ public static RowsResult GetEmptyRowsResult() { return new RowsResult(Movie.ColumnMappings.Keys.ToArray()); } - + public static RowsResult GetEmptyAppliedInfoRowsResult() { return new RowsResult(ColumnToDataTypes.Select(kvp => (kvp.Key, kvp.Value)).ToArray()); @@ -163,22 +163,22 @@ public static RowsResult GetEmptyAppliedInfoRowsResult() public static RowsResult CreateAppliedInfoRowsResultWithoutMovie(bool applied) { var result = new RowsResult("[applied]"); - return (RowsResult) result.WithRow(applied); + return (RowsResult)result.WithRow(applied); } public RowsResult CreateAppliedInfoRowsResult() { return AddAppliedInfoRow(Movie.GetEmptyAppliedInfoRowsResult()); } - + public RowsResult CreateRowsResult() { return AddRow(Movie.GetEmptyRowsResult()); } - + public RowsResult AddRow(RowsResult result) { - return (RowsResult) result.WithRow(GetParameters()); + return (RowsResult)result.WithRow(GetParameters()); } public static (string, DataType)[] GetColumns() @@ -212,11 +212,11 @@ public static RowsResult CreateRowsResult(IEnumerable data) { return data.Aggregate(Movie.GetEmptyRowsResult(), (current, c) => c.AddRow(current)); } - + public RowsResult AddAppliedInfoRow(RowsResult result) { - return (RowsResult) result.WithRow( - Movie.ColumnMappings.Values.Select(func => func(this)).Concat(new object [] { false }).ToArray()); + return (RowsResult)result.WithRow( + Movie.ColumnMappings.Values.Select(func => func(this)).Concat(new object[] { false }).ToArray()); } } } diff --git a/src/Cassandra.IntegrationTests/Mapping/Structures/Author.cs b/src/Cassandra.IntegrationTests/Mapping/Structures/Author.cs index b3928d4c0..5b03bb807 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Structures/Author.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Structures/Author.cs @@ -81,7 +81,7 @@ public static void AssertListContains(List actualAuthors, Author expecte public static List GetRandomList(int count) { List authors = new List(); - for(int i=0; i< count; i++) + for (int i = 0; i < count; i++) { Author author = Author.GetRandom(i + "_"); authors.Add(author); diff --git a/src/Cassandra.IntegrationTests/Mapping/Structures/ManyDataTypesPoco.cs b/src/Cassandra.IntegrationTests/Mapping/Structures/ManyDataTypesPoco.cs index 613e08649..54d40a30c 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Structures/ManyDataTypesPoco.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Structures/ManyDataTypesPoco.cs @@ -177,7 +177,7 @@ public static void KeepTryingSelectAndAssert(IMapper mapper, string selectStatem AssertListEqualsList(expectedInstanceList, instancesQueried); } - public static readonly IDictionary> Columns = + public static readonly IDictionary> Columns = new Dictionary> { { "BooleanType", entity => entity.BooleanType }, @@ -220,7 +220,7 @@ public static void KeepTryingSelectAndAssert(IMapper mapper, string selectStatem { "StringType", DataType.Text }, { "TimeUuidType", DataType.GetDataType(typeof(TimeUuid)) } }; - + public object[] GetParameters() { return ManyDataTypesPoco.Columns.Values.Select(func => func(this)).ToArray(); diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/Attributes.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/Attributes.cs index 45ea13e12..b19032583 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/Attributes.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/Attributes.cs @@ -754,7 +754,7 @@ public void Attributes_Column_NoCustomLabel() var defaultInstance = new SimplePocoWithColumnAttribute(); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); mapper.Insert(defaultInstance); - + VerifyBoundStatement( "INSERT INTO SimplePocoWithColumnAttribute (SomeColumn, SomePartitionKey) VALUES (?, ?)", 1, diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/Counter.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/Counter.cs index ed623b230..fb2cc11ed 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/Counter.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/Counter.cs @@ -63,13 +63,13 @@ public void Counter_Success() TestCluster.PrimeFluent( b => b.WhenQuery("SELECT Counter, KeyPart1, KeyPart2 FROM PocoWithCounterAttribute") - .ThenRowsSuccess(new[] + .ThenRowsSuccess(new[] { ("Counter", DataType.Counter), ("KeyPart1", DataType.Uuid), ("KeyPart2", DataType.Decimal) }, - r => r.WithRows(counterPocos.Select(c => new object [] { c.Counter, c.KeyPart1, c.KeyPart2 }).ToArray()))); + r => r.WithRows(counterPocos.Select(c => new object[] { c.Counter, c.KeyPart1, c.KeyPart2 }).ToArray()))); var countersQueried = cqlClient.Fetch().ToList(); foreach (var pocoWithCounterExpected in counterPocos) @@ -113,8 +113,8 @@ public void Counter_LinqAttributes_AttemptInsert() b => b.WhenQuery( "INSERT INTO PocoWithCounterAttribute (Counter, KeyPart1, KeyPart2) VALUES (?, ?, ?)", when => when.WithParams( - pocoAndLinqAttributesPocos.Counter, - pocoAndLinqAttributesPocos.KeyPart1, + pocoAndLinqAttributesPocos.Counter, + pocoAndLinqAttributesPocos.KeyPart1, pocoAndLinqAttributesPocos.KeyPart2)) .ThenServerError(ServerError.Invalid, expectedErrMsg)); diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/CqlClientConfig.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/CqlClientConfig.cs index de366d0e4..2cf3d846f 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/CqlClientConfig.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/CqlClientConfig.cs @@ -141,7 +141,7 @@ public void CqlClientConfiguration_UseIndividualMappings_MappingDefinedDuringRun var instancesQueried = mapper.Fetch(cqlSelect).ToList(); ManyDataTypesPoco.AssertListEqualsList(new List { manyTypesInstance }, instancesQueried); } - + /// /// Successfully insert a Poco instance /// diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/Fetch.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/Fetch.cs index e9ccede03..248da7c0e 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/Fetch.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/Fetch.cs @@ -83,7 +83,7 @@ public void FetchAsync_Using_Select_Cql_And_PageSize() table.Create(); var mapper = new Mapper(_session, new MappingConfiguration().Define(new FluentUserMapping())); - var ids = new[] {Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}; + var ids = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; mapper.Insert(new Author { AuthorId = ids[0] }); mapper.Insert(new Author { AuthorId = ids[1] }); @@ -93,7 +93,7 @@ public void FetchAsync_Using_Select_Cql_And_PageSize() { authors = t.Result.ToList(); }).Wait(); - Assert.AreEqual(2, authors.Count);; + Assert.AreEqual(2, authors.Count); ; CollectionAssert.AreEquivalent(ids, authors.Select(a => a.AuthorId)); } @@ -513,7 +513,7 @@ public void Fetch_Guid_HashSet_Key() public void Fetch_Poco_With_Enum_Collections_Test() { _session.Execute(string.Format(PocoWithEnumCollections.DefaultCreateTableCql, "tbl_with_enum_collections")); - var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; + var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary { { HairColor.Brown, TimeUuid.NewId() }, @@ -521,7 +521,7 @@ public void Fetch_Poco_With_Enum_Collections_Test() }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = - new SortedDictionary(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); + new SortedDictionary(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value)); const string insertQuery = "INSERT INTO tbl_with_enum_collections (id, list1, list2, array1, set1, set2, set3, map1, map2, map3)" + @@ -536,7 +536,7 @@ public void Fetch_Poco_With_Enum_Collections_Test() new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections")); var mapper = new Mapper(_session, config); - + var result = mapper.Fetch("WHERE id = ?", 2000L); Assert.NotNull(result); var rows = result.ToArray(); diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/First.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/First.cs index e53ffdea3..8369b6d13 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/First.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/First.cs @@ -43,7 +43,7 @@ public override void OneTimeSetUp() _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); - + Session.Execute(string.Format(PocoWithEnumCollections.DefaultCreateTableCql, "tbl_with_enum_collections")); // drop table if exists, re-create @@ -99,7 +99,7 @@ public void First_Async_NoSuchRecord() [Test] public void First_With_Enum_Collections() { - var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; + var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary { { HairColor.Brown, TimeUuid.NewId() }, @@ -107,7 +107,7 @@ public void First_With_Enum_Collections() }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = - new SortedDictionary(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); + new SortedDictionary(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value)); const string insertQuery = "INSERT INTO tbl_with_enum_collections (id, list1, list2, array1, set1, set2, set3, map1, map2, map3)" + @@ -117,7 +117,7 @@ public void First_With_Enum_Collections() mapValues)); Session.Execute(new SimpleStatement(insertQuery, 2001L, null, null, null, null, null, null, null, null, null)); - + var config = new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections")); @@ -135,7 +135,7 @@ public void First_With_Enum_Collections() Assert.AreEqual(expectedMap, result.Dictionary1); Assert.AreEqual(expectedMap, result.Dictionary2); Assert.AreEqual(expectedMap, result.Dictionary3); - + result = mapper .First("SELECT * FROM tbl_with_enum_collections WHERE id = ?", 2001L); Assert.NotNull(result); @@ -159,7 +159,7 @@ public void First_With_Enum_Collections() public void First_InvalidCql() { string cqlToFindNothing = _selectAllDefaultCql + " where this is invalid cql"; - Assert.Throws(() =>_mapper.First(cqlToFindNothing)); + Assert.Throws(() => _mapper.First(cqlToFindNothing)); } [Test] diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/InsertTests.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/InsertTests.cs index c69279284..e51ea989f 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/InsertTests.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/InsertTests.cs @@ -74,7 +74,7 @@ public void Insert_Sync() lowercaseclassnamepklowercase defaultInstance = new lowercaseclassnamepklowercase(); Assert.AreEqual(defaultInstance.somepartitionkey, instancesQueried[0].somepartitionkey); } - + /// /// Successfully insert a new record into a table that was created with fluent mapping, inserting asynchronously /// @@ -119,7 +119,7 @@ public void Insert_WithConsistency_Success() var mapper = new Mapper(_session, mappingConfig); // Insert the data - var consistencyLevels = new [] + var consistencyLevels = new[] { ConsistencyLevel.All, ConsistencyLevel.Any, @@ -185,7 +185,7 @@ public void Insert_WithConsistencyLevel_Fail() table.Create(); // Insert the data - var consistencyLevels = new [] + var consistencyLevels = new[] { ConsistencyLevel.Three, ConsistencyLevel.Two @@ -223,8 +223,8 @@ public void Insert_WithMapperInsert_TwoPartitionKeys_OnlyOne() { // Setup var mappingConfig = new MappingConfiguration().Define(new Map() - .TableName(typeof (ClassWithTwoPartitionKeys).Name).CaseSensitive() - .PartitionKey(new string[] {"PartitionKey1", "PartitionKey2" }).CaseSensitive() + .TableName(typeof(ClassWithTwoPartitionKeys).Name).CaseSensitive() + .PartitionKey(new string[] { "PartitionKey1", "PartitionKey2" }).CaseSensitive() ); var table = new Table(_session, mappingConfig); table.Create(); @@ -267,7 +267,7 @@ public void Insert_WithMapperInsert_TwoPartitionKeys_OnlyOne() /// Successfully insert a new record into a table that was created with fluent mapping, /// using Session.Execute to insert an Insert object created with table.Insert() /// - [Test, TestCassandraVersion(2,0)] + [Test, TestCassandraVersion(2, 0)] public void Insert_WithSessionExecuteTableInsert() { // Setup @@ -323,7 +323,7 @@ public void Insert_ClassAndPartitionKeyAreCamelCase() lowercaseclassnamepklowercase defaultInstance = new lowercaseclassnamepklowercase(); Assert.AreEqual(defaultInstance.somepartitionkey, instancesQueried[0].somepartitionkey); - Assert.Throws(() => TestUtils.TableExists(_session, _uniqueKsName, typeof (PrivateClassWithClassNameCamelCase).Name, true)); + Assert.Throws(() => TestUtils.TableExists(_session, _uniqueKsName, typeof(PrivateClassWithClassNameCamelCase).Name, true)); Assert.IsTrue(TestUtils.TableExists(_session, _uniqueKsName, typeof(PrivateClassWithClassNameCamelCase).Name.ToLower(), true)); } @@ -349,7 +349,7 @@ public void Insert_TableNameLowerCase_PartitionKeyCamelCase() Assert.AreEqual(defaultPocoInstance.SomePartitionKey, instancesQueried[0].SomePartitionKey); // Attempt to select from Camel Case partition key - string cqlCamelCasePartitionKey = "SELECT * from " + typeof (lowercaseclassnamepkcamelcase).Name + " where \"SomePartitionKey\" = 'doesntmatter'"; + string cqlCamelCasePartitionKey = "SELECT * from " + typeof(lowercaseclassnamepkcamelcase).Name + " where \"SomePartitionKey\" = 'doesntmatter'"; var ex = Assert.Throws(() => _session.Execute(cqlCamelCasePartitionKey)); var expectedMessageCassandra = "Undefined name SomePartitionKey in where clause"; var expectedMessageScylla = "Unrecognized name SomePartitionKey"; @@ -399,7 +399,7 @@ public void InsertIfNotExists_Applied_Test() //Use linq to create the table new Table(_session, config).Create(); var mapper = new Mapper(_session, config); - var song = new Song {Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Good Times Bad Times"}; + var song = new Song { Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Good Times Bad Times" }; //It is the first song there, it should apply it var appliedInfo = mapper.InsertIfNotExists(song); Assert.True(appliedInfo.Applied); @@ -420,18 +420,18 @@ public void Insert_Without_Nulls_Test() //Use linq to create the table new Table(_session, config).CreateIfNotExists(); var mapper = new Mapper(_session, config); - var song = new Song - { - Id = Guid.NewGuid(), - Artist = "The Who", - Title = "Substitute", + var song = new Song + { + Id = Guid.NewGuid(), + Artist = "The Who", + Title = "Substitute", ReleaseDate = DateTimeOffset.UtcNow }; mapper.Insert(song); var storedSong = mapper.First("WHERE id = ?", song.Id); Assert.AreEqual(song.Artist, storedSong.Artist); //do NOT insert nulls - mapper.Insert(new Song { Id = song.Id, Artist = null, Title = "Substitute 2", ReleaseDate = DateTimeOffset.UtcNow}, false); + mapper.Insert(new Song { Id = song.Id, Artist = null, Title = "Substitute 2", ReleaseDate = DateTimeOffset.UtcNow }, false); //it should have the new title but the artist should still be the same (not null) storedSong = mapper.First("WHERE id = ?", song.Id); Assert.NotNull(storedSong.Artist); @@ -488,7 +488,7 @@ public void CqlClient_Timestamp() { var config = new MappingConfiguration() .Define(new Map().PartitionKey(s => s.Id).TableName("song_insert")); - + //Use linq to create the table var table = new Table(_session, config); table.CreateIfNotExists(); @@ -613,14 +613,14 @@ public void Insert_Poco_With_Enum_Collections_Test() Session.Execute(string.Format(PocoWithEnumCollections.DefaultCreateTableCql, "tbl_with_enum_collections")); var mapper = new Mapper(Session, new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections"))); - var collectionValues = new[]{ HairColor.Blonde, HairColor.Gray, HairColor.Red }; + var collectionValues = new[] { HairColor.Blonde, HairColor.Gray, HairColor.Red }; var mapValues = new SortedDictionary { { HairColor.Brown, TimeUuid.NewId() }, { HairColor.Red, TimeUuid.NewId() } }; - var expectedCollection = collectionValues.Select(x => (int) x).ToArray(); - var expectedMap = mapValues.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value); + var expectedCollection = collectionValues.Select(x => (int)x).ToArray(); + var expectedMap = mapValues.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value); var poco = new PocoWithEnumCollections { Id = 1000L, @@ -649,7 +649,7 @@ public void Insert_Poco_With_Enum_Collections_Test() Assert.AreEqual(expectedMap, row.GetValue>("map1")); Assert.AreEqual(expectedMap, row.GetValue>("map2")); Assert.AreEqual(expectedMap, row.GetValue>("map3")); - + // BONUS: Attempt insert with null values Assert.DoesNotThrow(() => mapper.Insert(new PocoWithEnumCollections { Id = 1001L })); } diff --git a/src/Cassandra.IntegrationTests/Mapping/Tests/Update.cs b/src/Cassandra.IntegrationTests/Mapping/Tests/Update.cs index e73fb38b6..bd3d11602 100644 --- a/src/Cassandra.IntegrationTests/Mapping/Tests/Update.cs +++ b/src/Cassandra.IntegrationTests/Mapping/Tests/Update.cs @@ -105,7 +105,7 @@ public void UpdateIf_Applied_Test() //Use linq to create the table new Table(_session, config).Create(); var mapper = new Mapper(_session, config); - var song = new Song { Id = Guid.NewGuid(), Artist = "Cream", Title = "Crossroad", ReleaseDate = DateTimeOffset.Parse("1970/1/1")}; + var song = new Song { Id = Guid.NewGuid(), Artist = "Cream", Title = "Crossroad", ReleaseDate = DateTimeOffset.Parse("1970/1/1") }; //It is the first song there, it should apply it mapper.Insert(song); const string query = "SET artist = ?, title = ? WHERE id = ? IF releasedate = ?"; @@ -141,7 +141,7 @@ public void Update_PartitionKeyOmitted() [Test] public void Update_Poco_With_Enum_Collections_Test() { - var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; + var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary { { HairColor.Brown, TimeUuid.NewId() }, @@ -149,13 +149,13 @@ public void Update_Poco_With_Enum_Collections_Test() }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = - new SortedDictionary(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); + new SortedDictionary(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value)); var pocoToUpdate = new PocoWithEnumCollections { Id = 3000L, - Dictionary1 = expectedMap.ToDictionary(x => x.Key, x=> x.Value), - Dictionary2 = expectedMap.ToDictionary(x => x.Key, x=> x.Value), + Dictionary1 = expectedMap.ToDictionary(x => x.Key, x => x.Value), + Dictionary2 = expectedMap.ToDictionary(x => x.Key, x => x.Value), Dictionary3 = expectedMap, List1 = expectedCollection.ToList(), List2 = expectedCollection.ToList(), @@ -163,7 +163,7 @@ public void Update_Poco_With_Enum_Collections_Test() Set2 = new SortedSet(expectedCollection), Set3 = new HashSet(expectedCollection) }; - pocoToUpdate.Array1 = new[]{ HairColor.Blonde, HairColor.Red, HairColor.Black }; + pocoToUpdate.Array1 = new[] { HairColor.Blonde, HairColor.Red, HairColor.Black }; pocoToUpdate.Dictionary1.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.Dictionary2.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.List1.Add(HairColor.Black); @@ -176,14 +176,14 @@ public void Update_Poco_With_Enum_Collections_Test() _session.Execute(new SimpleStatement(insertQuery, pocoToUpdate.Id, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, mapValues, mapValues, mapValues)); - + var config = new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections")); var mapper = new Mapper(_session, config); mapper.Update(pocoToUpdate); var statement = new SimpleStatement("SELECT * FROM tbl_with_enum_collections WHERE id = ?", pocoToUpdate.Id); - + var row = _session.Execute(statement).First(); Assert.AreEqual(pocoToUpdate.Id, row.GetValue("id")); CollectionAssert.AreEquivalent(pocoToUpdate.List1.Select(x => (int)x).ToList(), row.GetValue>("list1")); @@ -192,11 +192,11 @@ public void Update_Poco_With_Enum_Collections_Test() CollectionAssert.AreEquivalent(pocoToUpdate.Set1.Select(x => (int)x), row.GetValue>("set1")); CollectionAssert.AreEquivalent(pocoToUpdate.Set2.Select(x => (int)x), row.GetValue>("set2")); CollectionAssert.AreEquivalent(pocoToUpdate.Set3.Select(x => (int)x), row.GetValue>("set3")); - CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary1.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), + CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary1.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue>("map1")); - CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary2.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), + CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary2.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue>("map2")); - CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary3.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), + CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary3.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue>("map3")); } diff --git a/src/Cassandra.IntegrationTests/MetadataTests/TokenMapTopologyChangeTests.cs b/src/Cassandra.IntegrationTests/MetadataTests/TokenMapTopologyChangeTests.cs index 92760652d..db22f287e 100644 --- a/src/Cassandra.IntegrationTests/MetadataTests/TokenMapTopologyChangeTests.cs +++ b/src/Cassandra.IntegrationTests/MetadataTests/TokenMapTopologyChangeTests.cs @@ -86,7 +86,7 @@ public void TokenMap_Should_RebuildTokenMap_When_NodeIsDecommissioned() var oldTokenMapNotSync = ClusterObjNotSync.Metadata.TokenToReplicasMap; var oldTokenMapSync = ClusterObjSync.Metadata.TokenToReplicasMap; - + if (TestClusterManager.SupportsDecommissionForcefully()) { this.TestCluster.DecommissionNodeForcefully(1); diff --git a/src/Cassandra.IntegrationTests/Metrics/MetricsTests.cs b/src/Cassandra.IntegrationTests/Metrics/MetricsTests.cs index db43baa4f..def0f7692 100644 --- a/src/Cassandra.IntegrationTests/Metrics/MetricsTests.cs +++ b/src/Cassandra.IntegrationTests/Metrics/MetricsTests.cs @@ -90,7 +90,7 @@ public void Teardown() _metricsRoot = null; } } - + [Category(TestCategory.RealClusterLong)] [Test] public void Should_RemoveNodeMetricsAndDisposeMetricsContext_When_HostIsRemoved() @@ -163,7 +163,7 @@ public void Should_RemoveNodeMetricsAndDisposeMetricsContext_When_HostIsRemoved( Assert.True(context.IsNotEmpty()); Assert.AreEqual(2, context.Gauges.Count()); } - + [Category(TestCategory.RealCluster)] [Test] public void Should_AllMetricsHaveValidValues_When_AllNodesAreUp() @@ -223,7 +223,7 @@ public void Should_AllMetricsHaveValidValues_When_AllNodesAreUp() Assert.Greater(metrics.GetSessionMeter(SessionMetric.Meters.BytesReceived).GetValue().Count, 0); Assert.AreEqual(3, metrics.GetSessionGauge(SessionMetric.Gauges.ConnectedNodes).GetValue()); } - + [Category(TestCategory.RealCluster)] [Test] public void Should_DefaultMetricsHaveValidValuesAndTimersDisabled() @@ -270,7 +270,7 @@ public void Should_DefaultMetricsHaveValidValuesAndTimersDisabled() Assert.Greater(metrics.GetSessionMeter(SessionMetric.Meters.BytesReceived).GetValue().Count, 0); Assert.AreEqual(3, metrics.GetSessionGauge(SessionMetric.Gauges.ConnectedNodes).GetValue()); } - + [Category(TestCategory.RealCluster)] [Test] public void Should_AllMetricsHaveValidValues_When_NodeIsDown() diff --git a/src/Cassandra.IntegrationTests/OpenTelemetry/OpenTelemetryTests.cs b/src/Cassandra.IntegrationTests/OpenTelemetry/OpenTelemetryTests.cs index 60463673c..dcf89b274 100644 --- a/src/Cassandra.IntegrationTests/OpenTelemetry/OpenTelemetryTests.cs +++ b/src/Cassandra.IntegrationTests/OpenTelemetry/OpenTelemetryTests.cs @@ -47,7 +47,7 @@ public class OpenTelemetryTests : SharedClusterTest private readonly CopyOnReadList _exportedActivities = new CopyOnReadList(); private readonly ActivitySource _internalActivitySource = new ActivitySource("testeActivitySource"); - + private DateTime _testStartDateTime; private TracerProvider _sdk; @@ -91,7 +91,7 @@ public void AddOpenTelemetry_WithKeyspaceAvailable_DbOperationAndDbNameAreInclud RetryUntilActivities(_testStartDateTime, expectedActivityName, 1); - var activity = GetActivities(_testStartDateTime).First(x => x.DisplayName == expectedActivityName); + var activity = GetActivities(_testStartDateTime).First(x => x.DisplayName == expectedActivityName); ValidateSessionActivityAttributes(activity, typeof(SimpleStatement)); @@ -319,7 +319,7 @@ public void AddOpenTelemetry_Linq_SessionRequestIsParentOfNodeRequest() table.Insert(song).Execute(); RetryUntilActivities(_testStartDateTime, $"{SessionActivityName}({nameof(BoundStatement)}) {keyspace}", 1); - RetryUntilActivities(_testStartDateTime, $"{NodeActivityName}({nameof(BoundStatement)}) {keyspace}", 1); + RetryUntilActivities(_testStartDateTime, $"{NodeActivityName}({nameof(BoundStatement)}) {keyspace}", 1); var syncActivities = GetActivities(_testStartDateTime); var syncSessionActivity = syncActivities.First(x => x.DisplayName == $"{SessionActivityName}({nameof(BoundStatement)}) {keyspace}"); @@ -686,7 +686,7 @@ public async Task AddOpenTelemetry_Mapper_ExpectedPrepareActivities(bool prepare ValidateNodeActivityAttributes(boundStmtNodeActivity, typeof(BoundStatement)); Assert.Contains(new KeyValuePair("db.query.text", expectedStatement), boundStmtNodeActivity.Tags.ToArray()); } - + foreach (var prepareStmtSessionActivity in prepareStmtSessionActivities) { ValidateSessionActivityAttributes(prepareStmtSessionActivity, typeof(PrepareRequest)); @@ -874,9 +874,9 @@ private static void ValidateSessionActivityAttributes(Activity activity, Type st }; Assert.AreEqual(activity.Kind, expectedActivityKind); - + var tags = activity.Tags; - + foreach (var pair in expectedTags) { Assert.AreEqual(tags.FirstOrDefault(x => x.Key == pair.Key).Value, expectedTags[pair.Key]); diff --git a/src/Cassandra.IntegrationTests/Policies/Tests/ColumnEncryptionPolicyTests.cs b/src/Cassandra.IntegrationTests/Policies/Tests/ColumnEncryptionPolicyTests.cs index 7afe18a64..3d1c61000 100644 --- a/src/Cassandra.IntegrationTests/Policies/Tests/ColumnEncryptionPolicyTests.cs +++ b/src/Cassandra.IntegrationTests/Policies/Tests/ColumnEncryptionPolicyTests.cs @@ -116,7 +116,7 @@ public async Task Should_InsertAndSelectEncryptedColumnsPartitionKeyOnly_Prepare var clusterNoEncryption = GetNewTemporaryCluster(); var sessionNoEncryption = await clusterNoEncryption.ConnectAsync(KeyspaceName).ConfigureAwait(false); var insertQuery = - _withVector ? + _withVector ? $"INSERT INTO {tableName} (id, name, surname, age, public_notes, vv) VALUES (?, ?, ?, ?, ?, ?)" : $"INSERT INTO {tableName} (id, name, surname, age, public_notes) VALUES (?, ?, ?, ?, ?)"; var selectQuery = $"SELECT * FROM {tableName} WHERE id = ?"; @@ -143,8 +143,8 @@ public async Task Should_InsertAndSelectEncryptedColumnsPartitionKeyOnly_Prepare newUser.Vv = null; } - var boundInsert = _withVector ? - preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes, newUser.Vv) : + var boundInsert = _withVector ? + preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes, newUser.Vv) : preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes); var boundSelect = preparedSelect.Bind(newUser.Id); await session.ExecuteAsync(boundInsert).ConfigureAwait(false); @@ -214,10 +214,10 @@ public async Task Should_InsertAndSelectEncryptedColumns_PreparedStatements(bool } var boundInsert = _withVector ? - preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes, newUser.Vv) : + preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes, newUser.Vv) : preparedInsert.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.PublicNotes); - var boundSelect = _withVector ? - preparedSelect.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.Vv) : + var boundSelect = _withVector ? + preparedSelect.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age, newUser.Vv) : preparedSelect.Bind(newUser.Id, newUser.Name, newUser.Surname, newUser.Age); await session.ExecuteAsync(boundInsert).ConfigureAwait(false); var rs = await session.ExecuteAsync(boundSelect).ConfigureAwait(false); diff --git a/src/Cassandra.IntegrationTests/Policies/Tests/ConsistencyTests.cs b/src/Cassandra.IntegrationTests/Policies/Tests/ConsistencyTests.cs index 3224e1d12..d19acfd0a 100644 --- a/src/Cassandra.IntegrationTests/Policies/Tests/ConsistencyTests.cs +++ b/src/Cassandra.IntegrationTests/Policies/Tests/ConsistencyTests.cs @@ -65,7 +65,7 @@ public void ReplicationFactorOne_TokenAware() testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord + ":" + DefaultCassandraPort, testCluster.Cluster, 30); - var acceptedList = new List + var acceptedList = new List { ConsistencyLevel.Any }; @@ -467,7 +467,7 @@ public void ReplicationFactorOne_DowngradingConsistencyRetryPolicy() testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30); - var acceptedList = new List {ConsistencyLevel.Any}; + var acceptedList = new List { ConsistencyLevel.Any }; var failList = new List { @@ -737,7 +737,7 @@ public void ReplicationFactorThree_TwoDCs_DowngradingConsistencyRetryPolicy() Assert.IsTrue(_policyTestTools.Coordinators.Count() >= 4, "The minimum number of hosts queried was not met!"); int totalQueriesForAllHosts = _policyTestTools.Coordinators.Sum(c => c.Value); - Assert.AreEqual(queriesCompleted, totalQueriesForAllHosts, + Assert.AreEqual(queriesCompleted, totalQueriesForAllHosts, "The sum of queries for all hosts should equal the number of queries recorded by the calling test!"); _policyTestTools.ResetCoordinators(); diff --git a/src/Cassandra.IntegrationTests/Policies/Tests/LoadBalancingPolicyShortTests.cs b/src/Cassandra.IntegrationTests/Policies/Tests/LoadBalancingPolicyShortTests.cs index fe8e8da30..71d9e0e01 100644 --- a/src/Cassandra.IntegrationTests/Policies/Tests/LoadBalancingPolicyShortTests.cs +++ b/src/Cassandra.IntegrationTests/Policies/Tests/LoadBalancingPolicyShortTests.cs @@ -35,7 +35,7 @@ public class LoadBalancingPolicyShortTests : SharedClusterTest public LoadBalancingPolicyShortTests() : base(3, false, new TestClusterOptions { UseVNodes = true }) { } - + /// /// Validate that two sessions connected to the same DC use separate Policy instances /// @@ -47,8 +47,8 @@ public void TwoSessionsConnectedToSameDcUseSeparatePolicyInstances() using (var cluster1 = builder.WithConnectionString($"Contact Points={TestCluster.ClusterIpPrefix}1").Build()) using (var cluster2 = builder.WithConnectionString($"Contact Points={TestCluster.ClusterIpPrefix}2").Build()) { - var session1 = (Session) cluster1.Connect(); - var session2 = (Session) cluster2.Connect(); + var session1 = (Session)cluster1.Connect(); + var session2 = (Session)cluster2.Connect(); Assert.AreNotSame(session1.Policies.LoadBalancingPolicy, session2.Policies.LoadBalancingPolicy, "Load balancing policy instances should be different"); Assert.AreNotSame(session1.Policies.ReconnectionPolicy, session2.Policies.ReconnectionPolicy, "Reconnection policy instances should be different"); Assert.AreNotSame(session1.Policies.RetryPolicy, session2.Policies.RetryPolicy, "Retry policy instances should be different"); @@ -337,7 +337,7 @@ public void TokenAware_VNodes_Test(bool metadataSync) var rs = session.Execute(bound); traces.Add(rs.Info.QueryTrace); } - + //Check that there weren't any hops foreach (var t in traces) { diff --git a/src/Cassandra.IntegrationTests/Policies/Tests/ReconnectionPolicyTests.cs b/src/Cassandra.IntegrationTests/Policies/Tests/ReconnectionPolicyTests.cs index acee9061c..814f60db0 100644 --- a/src/Cassandra.IntegrationTests/Policies/Tests/ReconnectionPolicyTests.cs +++ b/src/Cassandra.IntegrationTests/Policies/Tests/ReconnectionPolicyTests.cs @@ -44,7 +44,7 @@ public void SetupTest() [Test] public void ExponentialReconnectionPolicyTest() { - var builder = ClusterBuilder().WithReconnectionPolicy(new ExponentialReconnectionPolicy(2*1000, 5*60*1000)); + var builder = ClusterBuilder().WithReconnectionPolicy(new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000)); // Ensure that ExponentialReconnectionPolicy is what we should be testing if (!(builder.GetConfiguration().Policies.ReconnectionPolicy is ExponentialReconnectionPolicy)) @@ -53,9 +53,9 @@ public void ExponentialReconnectionPolicyTest() } // Test basic getters - ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) builder.GetConfiguration().Policies.ReconnectionPolicy; - Assert.True(reconnectionPolicy.BaseDelayMs == 2*1000); - Assert.True(reconnectionPolicy.MaxDelayMs == 5*60*1000); + ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy)builder.GetConfiguration().Policies.ReconnectionPolicy; + Assert.True(reconnectionPolicy.BaseDelayMs == 2 * 1000); + Assert.True(reconnectionPolicy.MaxDelayMs == 5 * 60 * 1000); // Test erroneous instantiations try @@ -63,32 +63,32 @@ public void ExponentialReconnectionPolicyTest() new ExponentialReconnectionPolicy(-1, 1); Assert.Fail(); } - catch (ArgumentException){} + catch (ArgumentException) { } try { new ExponentialReconnectionPolicy(1, -1); Assert.Fail(); } - catch (ArgumentException){} + catch (ArgumentException) { } try { new ExponentialReconnectionPolicy(-1, -1); Assert.Fail(); } - catch (ArgumentException){} + catch (ArgumentException) { } try { new ExponentialReconnectionPolicy(2, 1); Assert.Fail(); } - catch (ArgumentException){} + catch (ArgumentException) { } // Test nextDelays() - var schedule = new ExponentialReconnectionPolicy(2*1000, 5*60*1000).NewSchedule(); + var schedule = new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000).NewSchedule(); Assert.True(schedule.NextDelayMs() == 2000); Assert.True(schedule.NextDelayMs() == 4000); Assert.True(schedule.NextDelayMs() == 8000); @@ -113,7 +113,7 @@ public void ExponentialReconnectionPolicyTest() [Test] public void ConstantReconnectionPolicyTest() { - Builder builder = ClusterBuilder().WithReconnectionPolicy(new ConstantReconnectionPolicy(25*1000)); + Builder builder = ClusterBuilder().WithReconnectionPolicy(new ConstantReconnectionPolicy(25 * 1000)); // Ensure that ConstantReconnectionPolicy is what we should be testing if (!(builder.GetConfiguration().Policies.ReconnectionPolicy is ConstantReconnectionPolicy)) @@ -122,8 +122,8 @@ public void ConstantReconnectionPolicyTest() } // Test basic getters - ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) builder.GetConfiguration().Policies.ReconnectionPolicy; - Assert.True(reconnectionPolicy.ConstantDelayMs == 25*1000); + ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy)builder.GetConfiguration().Policies.ReconnectionPolicy; + Assert.True(reconnectionPolicy.ConstantDelayMs == 25 * 1000); // Test erroneous instantiations try @@ -136,7 +136,7 @@ public void ConstantReconnectionPolicyTest() } // Test nextDelays() - var schedule = new ConstantReconnectionPolicy(10*1000).NewSchedule(); + var schedule = new ConstantReconnectionPolicy(10 * 1000).NewSchedule(); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); @@ -173,14 +173,14 @@ public void ReconnectionPolicyTest(Builder builder, long restartTime, long retry _policyTestTools.Query(testCluster, 12); Assert.Fail("Test race condition where node has not shut off quickly enough."); } - catch (NoHostAvailableException){} + catch (NoHostAvailableException) { } long elapsedSeconds; bool restarted = false; while (true) { //thisTime = System.nanoTime() / 1000000000; - elapsedSeconds = startTime.ElapsedMilliseconds/1000; + elapsedSeconds = startTime.ElapsedMilliseconds / 1000; // Restart node at restartTime if (!restarted && elapsedSeconds > restartTime) @@ -205,7 +205,7 @@ public void ReconnectionPolicyTest(Builder builder, long restartTime, long retry continue; } - Thread.Sleep((int) (breakTime*1000)); + Thread.Sleep((int)(breakTime * 1000)); // The same query once more, just to be sure _policyTestTools.Query(testCluster, 12); @@ -233,7 +233,7 @@ public void ReconnectionPolicyTest(Builder builder, long restartTime, long retry while (true) { //elapsedSeconds = System.nanoTime() / 1000000000; - elapsedSeconds = startTime.ElapsedMilliseconds/1000; + elapsedSeconds = startTime.ElapsedMilliseconds / 1000; // Restart node at restartTime if (!restarted && elapsedSeconds > restartTime) diff --git a/src/Cassandra.IntegrationTests/Policies/Util/PolicyTestTools.cs b/src/Cassandra.IntegrationTests/Policies/Util/PolicyTestTools.cs index 25a0a5b47..bfbe9f430 100644 --- a/src/Cassandra.IntegrationTests/Policies/Util/PolicyTestTools.cs +++ b/src/Cassandra.IntegrationTests/Policies/Util/PolicyTestTools.cs @@ -114,7 +114,7 @@ public void ResetCoordinators() public void AssertQueried(string host, int expectedHostQueryCount) { // if the host is not found, that's the same as it being queried zero times - int actualHostQueryCount = 0; + int actualHostQueryCount = 0; if (Coordinators.ContainsKey(host)) actualHostQueryCount = Coordinators[host]; Assert.AreEqual(expectedHostQueryCount, actualHostQueryCount, "For " + host); @@ -129,7 +129,7 @@ public void AssertQueriedSet(String[] hosts, int n) int queriedInSet = 0; foreach (var host in hosts) { - queriedInSet += Coordinators.ContainsKey(host) ? (int) Coordinators[host] : 0; + queriedInSet += Coordinators.ContainsKey(host) ? (int)Coordinators[host] : 0; } Assert.AreEqual(queriedInSet, n, string.Format("For [{0}]", String.Join(", ", hosts))); } @@ -139,7 +139,7 @@ public void AssertQueriedAtLeast(string host, int n) var queried = 0; if (Coordinators.ContainsKey(host)) { - queried = Coordinators[host]; + queried = Coordinators[host]; } Assert.GreaterOrEqual(queried, n); } @@ -176,7 +176,7 @@ public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsT // Also note that we don't use tracing because this would trigger requests that screw up the test for (int i = 0; i < numberOfInsertsToMake; ++i) if (batch) - // BUG: WriteType == SIMPLE + // BUG: WriteType == SIMPLE { var bth = new StringBuilder(); bth.AppendLine("BEGIN BATCH"); @@ -233,7 +233,7 @@ public void Query(ITestCluster testCluster, int numberOfQueriesToExecute, bool u else { var routingKey = new RoutingKey(); - routingKey.RawRoutingKey = Enumerable.Repeat((byte) 0x00, 4).ToArray(); + routingKey.RawRoutingKey = Enumerable.Repeat((byte)0x00, 4).ToArray(); for (int i = 0; i < numberOfQueriesToExecute; ++i) { string hostQueried; diff --git a/src/Cassandra.IntegrationTests/SharedCloudClusterTest.cs b/src/Cassandra.IntegrationTests/SharedCloudClusterTest.cs index 1b6cbf727..466044180 100644 --- a/src/Cassandra.IntegrationTests/SharedCloudClusterTest.cs +++ b/src/Cassandra.IntegrationTests/SharedCloudClusterTest.cs @@ -65,7 +65,7 @@ protected override void CreateCommonSession() } catch (Exception ex) { - last = ex; + last = ex; Task.Delay(1000).GetAwaiter().GetResult(); if (Cluster != null) { @@ -104,7 +104,7 @@ protected ICluster CreateTemporaryCluster(string creds = "creds-v1.zip", Action< ClusterInstances.Add(cluster); return cluster; } - + protected async Task CreateSessionAsync( string creds = "creds-v1.zip", int retries = SharedCloudClusterTest.MaxRetries, Action act = null) { diff --git a/src/Cassandra.IntegrationTests/SharedClusterTest.cs b/src/Cassandra.IntegrationTests/SharedClusterTest.cs index df53ab8bb..7c61465b7 100644 --- a/src/Cassandra.IntegrationTests/SharedClusterTest.cs +++ b/src/Cassandra.IntegrationTests/SharedClusterTest.cs @@ -91,7 +91,7 @@ protected virtual ITestCluster CreateNew(int nodeLength, TestClusterOptions opti { return TestClusterManager.CreateNew(nodeLength, options, startCluster); } - + [OneTimeSetUp] public virtual void OneTimeSetUp() { @@ -105,7 +105,7 @@ public virtual void OneTimeSetUp() } } } - + protected virtual void CreateCommonSession() { var builder = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint) @@ -139,12 +139,12 @@ public virtual void OneTimeTearDown() } ClusterInstances.Clear(); } - + protected ISession GetNewTemporarySession(string keyspace = null) { return GetNewTemporaryCluster().Connect(keyspace); } - + [TearDown] public virtual void TearDown() { @@ -164,7 +164,7 @@ public virtual void TearDown() protected virtual ICluster GetNewTemporaryCluster(Action build = null) { - var builder = + var builder = ClusterBuilder() .AddContactPoint(TestCluster.InitialContactPoint) .WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(30000).SetReadTimeoutMillis(22000)); diff --git a/src/Cassandra.IntegrationTests/SharedSimulacronTests.cs b/src/Cassandra.IntegrationTests/SharedSimulacronTests.cs index 3c77fa1b2..bbdf994e0 100644 --- a/src/Cassandra.IntegrationTests/SharedSimulacronTests.cs +++ b/src/Cassandra.IntegrationTests/SharedSimulacronTests.cs @@ -27,7 +27,7 @@ public abstract class SharedSimulacronTests : TestGlobals { private readonly List _clusterInstances = new List(); private readonly List _simulacronClusters = new List(); - + /// /// Gets the amount of nodes in the test cluster /// @@ -57,7 +57,7 @@ public abstract class SharedSimulacronTests : TestGlobals /// Gets or sets the name of the default keyspace used for this instance /// protected string KeyspaceName { get; set; } - + protected SimulacronOptions Options { get; set; } public SharedSimulacronTests() : this(1, true) @@ -87,7 +87,7 @@ protected virtual SimulacronCluster CreateNew(SimulacronOptions options) _simulacronClusters.Add(c); return c; } - + protected virtual SimulacronCluster CreateNew(int nodeLength) { Options = new SimulacronOptions { Nodes = nodeLength.ToString() }; @@ -107,7 +107,7 @@ public virtual void OneTimeSetUp() .WithQueryTimeout(60000) .WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(30000)) .Build(); - Session = (Session) Cluster.Connect(); + Session = (Session)Cluster.Connect(); Session.CreateKeyspace(KeyspaceName, null, false); Session.ChangeKeyspace(KeyspaceName); } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/DataType.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/DataType.cs index b34aaee63..13cdeff86 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/DataType.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/DataType.cs @@ -127,7 +127,7 @@ private DataType(string value, DataTypeEnum dataTypeEnum, params DataType[] inne InnerTypes = innerTypes; _dataTypeEnum = dataTypeEnum; } - + public static readonly DataType Text = new DataType("text"); public static readonly DataType Ascii = new DataType("ascii"); @@ -163,7 +163,7 @@ private DataType(string value, DataTypeEnum dataTypeEnum, params DataType[] inne public static readonly DataType Date = new DataType("date"); public static readonly DataType Time = new DataType("time"); - + public static readonly DataType Empty = new DataType("empty"); public static readonly DataType SmallInt = new DataType("smallint"); @@ -171,7 +171,7 @@ private DataType(string value, DataTypeEnum dataTypeEnum, params DataType[] inne public static readonly DataType TinyInt = new DataType("tinyint"); public static readonly DataType Duration = new DataType("duration"); // v5+ - + public static DataType Udt(string name) { return new DataType(name); @@ -201,12 +201,12 @@ public static DataType Map(DataType dataTypeKey, DataType dataTypeValue) { return new DataType($"map<{dataTypeKey.Value}, {dataTypeValue.Value}>", DataTypeEnum.Map, dataTypeKey, dataTypeValue); } - + public static DataType Tuple(params DataType[] dataTypes) { return new DataType($"tuple<{string.Join(", ", dataTypes.Select(d => d.Value))}>", DataTypeEnum.Tuple, dataTypes); } - + private static readonly Dictionary CqlTypeNames = new Dictionary { {typeof (Int32), DataType.Int}, @@ -259,7 +259,7 @@ public static DataType GetDataType(Type type) { return DataType.GetDataType(type.GetGenericArguments()[0]); } - + if (type.Name.StartsWith("Tuple")) { return DataType.Tuple(type.GetGenericArguments().Select(DataType.GetDataType).ToArray()); @@ -290,7 +290,7 @@ public static DataType GetDataType(Type type) throw new ArgumentException("no type found for dotnet type " + type.Name); } - + internal static readonly DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); public static string ByteArrayToString(byte[] ba) @@ -337,7 +337,7 @@ public static long GetTimestamp(DateTimeOffset dt) { return DataType.GetMicroSecondsTimestamp(dt) / 1000; } - + public static long GetMicroSecondsTimestamp(DateTimeOffset dt) { var ticks = (dt - UnixStart).Ticks; @@ -368,7 +368,7 @@ public override int GetHashCode() hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(Value); return hashCode; } - + public DataType AdaptForSimulacron() { if (Value == DataType.Text.Value) diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/ConsistencyLevelEnumConverter.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/ConsistencyLevelEnumConverter.cs index 922cd43b5..dfe459a02 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/ConsistencyLevelEnumConverter.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/ConsistencyLevelEnumConverter.cs @@ -23,7 +23,7 @@ namespace Cassandra.IntegrationTests.SimulacronAPI.Models.Converters { public class ConsistencyLevelEnumConverter : JsonConverter { - private static readonly IDictionary Map = + private static readonly IDictionary Map = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "ONE", ConsistencyLevel.One }, diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/QueryTypeEnumConverter.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/QueryTypeEnumConverter.cs index 76b9b2838..c6c7964f8 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/QueryTypeEnumConverter.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Converters/QueryTypeEnumConverter.cs @@ -24,7 +24,7 @@ namespace Cassandra.IntegrationTests.SimulacronAPI.Models.Converters { public class QueryTypeEnumConverter : JsonConverter { - private static readonly IDictionary Map = + private static readonly IDictionary Map = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "EXECUTE", QueryType.Execute }, diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BaseMessage.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BaseMessage.cs index 8821015c7..844cf0440 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BaseMessage.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BaseMessage.cs @@ -22,7 +22,7 @@ public class BaseMessage { [JsonProperty("opcode")] public int OpCode { get; set; } - + [JsonProperty("is_response")] public bool IsResponse { get; set; } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BatchMessage.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BatchMessage.cs index be66fa87c..80c872a34 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BatchMessage.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/BatchMessage.cs @@ -24,10 +24,10 @@ public class BatchMessage : BaseMessage { [JsonProperty("queries_or_ids")] public List QueriesOrIds { get; set; } - + [JsonProperty("values")] public List> Values { get; set; } - + [JsonProperty("consistency")] [JsonConverter(typeof(ConsistencyLevelEnumConverter))] public ConsistencyLevel ConsistencyLevel { get; set; } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/Frame.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/Frame.cs index b07aeb8bd..31aa34225 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/Frame.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/Frame.cs @@ -24,22 +24,22 @@ public class Frame { [JsonProperty("protocol_version")] public int ProtocolVersion { get; set; } - + [JsonProperty("beta")] public bool Beta { get; set; } [JsonProperty("stream_id")] public int StreamId { get; set; } - + [JsonProperty("tracing_id")] public Guid? TracingId { get; set; } - + [JsonProperty("custom_payload")] public Dictionary CustomPayload { get; set; } - + [JsonProperty("warnings")] public List Warnings { get; set; } - + [JsonProperty("message")] public object Message { @@ -64,7 +64,7 @@ public QueryMessage GetQueryMessage() { return GetTypedMessage(); } - + public BatchMessage GetBatchMessage() { return GetTypedMessage(); diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessage.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessage.cs index 539489e7e..4826b808b 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessage.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessage.cs @@ -22,7 +22,7 @@ public class QueryMessage : BaseMessage { [JsonProperty("query")] public string Query { get; set; } - + [JsonProperty("options")] public QueryMessageOptions Options { get; set; } } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessageOptions.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessageOptions.cs index b6da0b93c..f3b2cb83d 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessageOptions.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/QueryMessageOptions.cs @@ -25,29 +25,29 @@ public class QueryMessageOptions [JsonProperty("consistency")] [JsonConverter(typeof(ConsistencyLevelEnumConverter))] public ConsistencyLevel ConsistencyLevel { get; set; } - + [JsonProperty("serial_consistency")] [JsonConverter(typeof(ConsistencyLevelEnumConverter))] public ConsistencyLevel? SerialConsistencyLevel { get; set; } - + [JsonProperty("positional_values")] public List PositionalValues { get; set; } - + [JsonProperty("named_values")] public Dictionary NamedValues { get; set; } - + [JsonProperty("skip_metadata")] public bool? SkipMetadata { get; set; } - + [JsonProperty("page_size")] public int? PageSize { get; set; } - + [JsonProperty("paging_state")] public string PagingState { get; set; } - + [JsonProperty("default_timestamp")] public long DefaultTimestamp { get; set; } - + [JsonProperty("keyspace")] public string Keyspace { get; set; } } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/RequestLog.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/RequestLog.cs index 0ee025517..a014aca4d 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/RequestLog.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/Models/Logs/RequestLog.cs @@ -23,11 +23,11 @@ public class RequestLog { [JsonProperty("query")] public string Query { get; set; } - + [JsonProperty("consistency_level")] [JsonConverter(typeof(ConsistencyLevelEnumConverter))] public ConsistencyLevel? ConsistencyLevel { get; set; } - + [JsonProperty("serial_consistency_level")] [JsonConverter(typeof(ConsistencyLevelEnumConverter))] public ConsistencyLevel? SerialConsistencyLevel { get; set; } @@ -37,17 +37,17 @@ public class RequestLog [JsonProperty("received_timestamp")] public long ReceivedTimestamp { get; set; } - + [JsonProperty("client_timestamp")] public long ClientTimestamp { get; set; } - + [JsonProperty("primed")] public bool Primed { get; set; } - + [JsonProperty("type")] [JsonConverter(typeof(QueryTypeEnumConverter))] public QueryType? Type { get; set; } - + [JsonProperty("frame")] public Frame Frame { get; set; } } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/IWhenFluent.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/IWhenFluent.cs index 04a32e813..ff21fcffc 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/IWhenFluent.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/IWhenFluent.cs @@ -31,7 +31,7 @@ public interface IWhenFluent IThenFluent ThenRowsSuccess(params (string, DataType)[] columnNamesToTypes); IThenFluent ThenRowsSuccess(string[] columnNames, Action rowsBuilder); - + IThenFluent ThenRowsSuccess(RowsResult result); IThenFluent ThenAlreadyExists(string keyspace, string table); @@ -53,11 +53,11 @@ IThenFluent ThenWriteFailure( string writeType); IThenFluent ThenReadFailure( - int consistencyLevel, - int received, - int blockFor, - string message, - IDictionary failureReasons, + int consistencyLevel, + int received, + int blockFor, + string message, + IDictionary failureReasons, bool dataPresent); IThenFluent ThenFunctionFailure(string keyspace, string function, string[] argTypes, string detail); diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/PrimeRequestBuilder.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/PrimeRequestBuilder.cs index 50105d337..eb07343a5 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/PrimeRequestBuilder.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/PrimeRequestBuilder.cs @@ -47,7 +47,7 @@ public IThenFluent ThenRowsSuccess((string, DataType)[] columnNamesToTypes, Acti _then = new ThenRowsSuccess(rows); return this; } - + public IThenFluent ThenRowsSuccess(string[] columnNames, Action rowsBuilder) { var rows = new RowsResult(columnNames); diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ServerError.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ServerError.cs index 4baa20000..344696d5a 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ServerError.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ServerError.cs @@ -25,11 +25,11 @@ private ServerError(string value) public string Value { get; } public static ServerError IsBootstrapping { get; } = new ServerError("is_bootstrapping"); - + public static ServerError Overloaded { get; } = new ServerError("overloaded"); - + public static ServerError Invalid { get; } = new ServerError("invalid"); - + public static ServerError ConfigError { get; } = new ServerError("config_error"); } } \ No newline at end of file diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenAlreadyExists.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenAlreadyExists.cs index 2110b3e38..b90500467 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenAlreadyExists.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenAlreadyExists.cs @@ -19,7 +19,7 @@ public class ThenAlreadyExists : BaseThen { private readonly string _keyspace; private readonly string _table; - + public ThenAlreadyExists(string keyspace, string table) { _keyspace = keyspace; diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenReadFailure.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenReadFailure.cs index 729214cc6..2ffd682b1 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenReadFailure.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenReadFailure.cs @@ -27,11 +27,11 @@ public class ThenReadFailure : BaseThen private readonly bool _dataPresent; public ThenReadFailure( - int consistencyLevel, - int received, - int blockFor, - string message, - IDictionary failureReasons, + int consistencyLevel, + int received, + int blockFor, + string message, + IDictionary failureReasons, bool dataPresent) { _consistencyLevel = consistencyLevel; diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenWriteFailure.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenWriteFailure.cs index ad5e0338b..6a6ac6938 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenWriteFailure.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/Then/ThenWriteFailure.cs @@ -27,11 +27,11 @@ public class ThenWriteFailure : BaseThen private readonly string _writeType; public ThenWriteFailure( - int consistencyLevel, - int received, - int blockFor, - string message, - IDictionary failureReasons, + int consistencyLevel, + int received, + int blockFor, + string message, + IDictionary failureReasons, string writeType) { _consistencyLevel = consistencyLevel; diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/IWhenQueryBuilder.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/IWhenQueryBuilder.cs index 287f055f9..b2e3034e8 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/IWhenQueryBuilder.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/IWhenQueryBuilder.cs @@ -18,11 +18,11 @@ namespace Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.When public interface IWhenQueryBuilder { IWhenQueryBuilder WithNamedParam(string name, DataType type, object value); - + IWhenQueryBuilder WithParam(DataType type, object value); - + IWhenQueryBuilder WithParam(object value); - + IWhenQueryBuilder WithParams(params object[] values); IWhenQueryBuilder WithParams(params (DataType, object)[] values); diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenBatchBuilder.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenBatchBuilder.cs index 6638d28ff..1bcabebc5 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenBatchBuilder.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenBatchBuilder.cs @@ -23,9 +23,9 @@ namespace Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.When public class WhenBatchBuilder : IWhen, IWhenBatchBuilder { private readonly List _queriesOrIds = new List(); - + private readonly List _allowedCls = new List(); - + public object Render() { var dictionary = new Dictionary diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenQueryBuilder.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenQueryBuilder.cs index f661131c0..a77da4de1 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenQueryBuilder.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/PrimeBuilder/When/WhenQueryBuilder.cs @@ -30,22 +30,22 @@ public WhenQueryBuilder(string query) { this._query = query; } - + public IWhenQueryBuilder WithNamedParam(string name, DataType type, object value) { _namesToTypes.Add((name, type.Value)); _values.Add(value); return this; } - - + + public IWhenQueryBuilder WithParam(DataType type, object value) { _namesToTypes.Add(($"column{_namesToTypes.Count}", type.Value)); _values.Add(value); return this; } - + public IWhenQueryBuilder WithParam(object value) { return WithParam(DataType.GetDataType(value), value); @@ -89,7 +89,7 @@ public object Render() if (_namesToTypes != null && _values != null) { - var parameters = + var parameters = _namesToTypes .Zip(_values, (tuple, value) => (tuple.Item1, value)) .ToDictionary(kvp => kvp.Item1, kvp => kvp.value); @@ -102,7 +102,7 @@ public object Render() { dictionary.Add("consistency_level", _consistency); } - + return dictionary; } } diff --git a/src/Cassandra.IntegrationTests/SimulacronAPI/SystemTables/StubTableColumn.cs b/src/Cassandra.IntegrationTests/SimulacronAPI/SystemTables/StubTableColumn.cs index 95641a367..24bd9eb48 100644 --- a/src/Cassandra.IntegrationTests/SimulacronAPI/SystemTables/StubTableColumn.cs +++ b/src/Cassandra.IntegrationTests/SimulacronAPI/SystemTables/StubTableColumn.cs @@ -27,14 +27,14 @@ public StubTableColumn(string name, StubColumnKind kind, DataType type, StubClus } public DataType Type { get; set; } - + public string Name { get; set; } - + public StubColumnKind Kind { get; set; } public StubClusteringOrder ClusteringOrder { get; set; } } - + public class StubUdtField { public StubUdtField(string name, DataType type) @@ -44,7 +44,7 @@ public StubUdtField(string name, DataType type) } public DataType Type { get; set; } - + public string Name { get; set; } } diff --git a/src/Cassandra.IntegrationTests/SimulacronTest.cs b/src/Cassandra.IntegrationTests/SimulacronTest.cs index dd10fdc0f..1e1318f47 100644 --- a/src/Cassandra.IntegrationTests/SimulacronTest.cs +++ b/src/Cassandra.IntegrationTests/SimulacronTest.cs @@ -42,9 +42,9 @@ protected SimulacronTest() : this(false, null, true, null, null) } protected SimulacronTest( - bool shared = false, - SimulacronOptions options = null, - bool connect = true, + bool shared = false, + SimulacronOptions options = null, + bool connect = true, string keyspace = null, SimulacronManager simulacronManager = null) { @@ -54,10 +54,10 @@ protected SimulacronTest( _keyspace = keyspace; _simulacronManager = simulacronManager; } - + protected ISession Session { get; private set; } - internal IInternalSession InternalSession => (IInternalSession) Session; + internal IInternalSession InternalSession => (IInternalSession)Session; protected ICluster SessionCluster => Session?.Cluster; @@ -74,7 +74,7 @@ protected string SerializeParameter(object parameter) var serializer = Session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer(); return Convert.ToBase64String(serializer.Serialize(parameter)); } - + protected void VerifyBoundStatement(string cql, int count, params object[] positionalParameters) { VerifyStatement(QueryType.Execute, cql, count, positionalParameters); @@ -123,9 +123,9 @@ protected void VerifyBatchStatement(int count, string[] queries, Func obj.Select(o => o == null ? null : Convert.ToBase64String(serializer.Serialize(o)))).ToArray(); - var filteredQueries = logs.Where(q => + var filteredQueries = logs.Where(q => q.Frame.GetBatchMessage().Values.SelectMany(l => l).SequenceEqual(paramBytes) - && q.Frame.GetBatchMessage().QueriesOrIds.SequenceEqual(queries) + && q.Frame.GetBatchMessage().QueriesOrIds.SequenceEqual(queries) && func(q.Frame.GetBatchMessage())); Assert.AreEqual(count, filteredQueries.Count()); } @@ -230,7 +230,7 @@ protected void SetupNewTestCluster() TestCluster = null; Init(); } - + protected void SetupNewSession(Func builderConfig = null) { var builder = ClusterBuilder(); diff --git a/src/Cassandra.IntegrationTests/TestBase/QueryTools.cs b/src/Cassandra.IntegrationTests/TestBase/QueryTools.cs index 5020a7631..c5e3e6d7b 100644 --- a/src/Cassandra.IntegrationTests/TestBase/QueryTools.cs +++ b/src/Cassandra.IntegrationTests/TestBase/QueryTools.cs @@ -31,7 +31,7 @@ private static string CellEncoder(object col) internal static void ExecuteSyncQuery(ISession session, string query, ConsistencyLevel consistency, List expectedValues = null, string messageInstead = null) - { + { var ret = session.Execute(query, consistency); if (expectedValues != null) { @@ -49,7 +49,7 @@ internal static void valueComparator(RowSet rawrowset, List insertedRo int i = 0; foreach (Row row in rowset) { - if (row.Any(col => col.GetType() == typeof (byte[]))) + if (row.Any(col => col.GetType() == typeof(byte[]))) for (int j = 0; j < row.Length; j++) { Assert.AreEqual(insertedRows[i][j], row[j]); diff --git a/src/Cassandra.IntegrationTests/TestBase/Randomm.cs b/src/Cassandra.IntegrationTests/TestBase/Randomm.cs index 826a7a87c..48f433f85 100644 --- a/src/Cassandra.IntegrationTests/TestBase/Randomm.cs +++ b/src/Cassandra.IntegrationTests/TestBase/Randomm.cs @@ -39,7 +39,7 @@ private Randomm(int seed) internal static object RandomVal(Type tp) { if (tp != null) - return Randomm.Instance.GetType().GetTypeInfo().GetMethod("Next" + tp.Name).Invoke(Randomm.Instance, new object[] {}); + return Randomm.Instance.GetType().GetTypeInfo().GetMethod("Next" + tp.Name).Invoke(Randomm.Instance, new object[] { }); return ""; } @@ -68,12 +68,12 @@ public float NextSingle() double numb = _r.NextDouble(); numb -= 0.5; numb *= 2; - return float.MaxValue*(float) numb; + return float.MaxValue * (float)numb; } public UInt16 NextUInt16() { - return (ushort) _r.Next(0, 65535); + return (ushort)_r.Next(0, 65535); } public static int NextInt32() @@ -83,14 +83,14 @@ public static int NextInt32() public Int64 NextInt64() { - var buffer = new byte[sizeof (Int64)]; + var buffer = new byte[sizeof(Int64)]; _r.NextBytes(buffer); return BitConverter.ToInt64(buffer, 0); } public decimal NextDecimal() { - var scale = (byte) _r.Next(29); + var scale = (byte)_r.Next(29); bool sign = _r.Next(2) == 1; return new decimal(Randomm.NextInt32(), @@ -102,7 +102,7 @@ public decimal NextDecimal() public BigInteger NextBigInteger() { - return new BigInteger(Int64.MaxValue)*10; + return new BigInteger(Int64.MaxValue) * 10; } public string NextString() @@ -117,7 +117,7 @@ public string NextChar() if (i == 34 || i == 39) continue; else - asciiString += (char) i; + asciiString += (char)i; return asciiString; } @@ -142,7 +142,7 @@ public void NextBytes(byte[] buffer) public System.Net.IPAddress NextIPAddress() { - byte[] btarr = new byte[]{(byte)this.Next(0, 128), (byte)this._r.Next(0, 128), (byte)this._r.Next(0, 128), (byte)this._r.Next(0, 128)}; + byte[] btarr = new byte[] { (byte)this.Next(0, 128), (byte)this._r.Next(0, 128), (byte)this._r.Next(0, 128), (byte)this._r.Next(0, 128) }; return new System.Net.IPAddress(btarr); } diff --git a/src/Cassandra.IntegrationTests/TestBase/TestHttpClient.cs b/src/Cassandra.IntegrationTests/TestBase/TestHttpClient.cs index 2945ce327..225769f33 100644 --- a/src/Cassandra.IntegrationTests/TestBase/TestHttpClient.cs +++ b/src/Cassandra.IntegrationTests/TestBase/TestHttpClient.cs @@ -43,7 +43,7 @@ public TestHttpClient(Uri baseAddress) { _baseAddress = baseAddress; } - + public Task SendAsync(string method, string url) { #if NETCOREAPP diff --git a/src/Cassandra.IntegrationTests/TestBase/TestInfrastructureException.cs b/src/Cassandra.IntegrationTests/TestBase/TestInfrastructureException.cs index 03d8a85ae..94d527a1d 100644 --- a/src/Cassandra.IntegrationTests/TestBase/TestInfrastructureException.cs +++ b/src/Cassandra.IntegrationTests/TestBase/TestInfrastructureException.cs @@ -21,7 +21,7 @@ namespace Cassandra.IntegrationTests.TestBase /// /// Represents an error on the infrastructure setup /// - public class TestInfrastructureException: Exception + public class TestInfrastructureException : Exception { public TestInfrastructureException() { diff --git a/src/Cassandra.IntegrationTests/TestBase/TestUtils.cs b/src/Cassandra.IntegrationTests/TestBase/TestUtils.cs index c4ce8ac73..2593a5392 100644 --- a/src/Cassandra.IntegrationTests/TestBase/TestUtils.cs +++ b/src/Cassandra.IntegrationTests/TestBase/TestUtils.cs @@ -106,9 +106,9 @@ public static void TryToDeleteKeyspace(ISession session, string keyspaceName) session.DeleteKeyspaceIfExists(keyspaceName); } - public static bool TableExists(ISession session, string keyspaceName, string tableName, bool caseSensitive=false) + public static bool TableExists(ISession session, string keyspaceName, string tableName, bool caseSensitive = false) { - var cql = caseSensitive ? string.Format(@"SELECT * FROM ""{0}"".""{1}"" LIMIT 1", keyspaceName, tableName) + var cql = caseSensitive ? string.Format(@"SELECT * FROM ""{0}"".""{1}"" LIMIT 1", keyspaceName, tableName) : string.Format("SELECT * FROM {0}.{1} LIMIT 1", keyspaceName, tableName); //it will throw a InvalidQueryException if the table/keyspace does not exist session.Execute(cql); @@ -128,10 +128,10 @@ public static Builder NewBuilder() } return TestClusterManager.ShouldEnableBetaProtocolVersion() ? builder.WithBetaProtocolVersions() : builder; } - + public static byte[] GetBytes(string str) { - byte[] bytes = new byte[str.Length*sizeof (char)]; + byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } @@ -280,7 +280,7 @@ public static void WaitForDownWithWait(String node, Cluster cluster, int waitTim private static void WaitFor(string node, Cluster cluster, int maxTry, bool waitForDead, bool waitForOut) { - TestUtils.WaitForMeta(node, cluster, maxTry, !waitForDead); + TestUtils.WaitForMeta(node, cluster, maxTry, !waitForDead); } /// @@ -617,7 +617,7 @@ public static bool IsNodeReachable(IPAddress ip, int port = 9042) } } } - + public static void WaitForSchemaAgreement( ICluster cluster, bool ignoreDownNodes = true, bool throwOnMaxRetries = false, int maxRetries = 20) { diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmBridge.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmBridge.cs index b8475c126..0030470da 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmBridge.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmBridge.cs @@ -80,7 +80,7 @@ public void Create(bool useSsl) ExecuteCcm(string.Format( "create {0} --dse -v {1} {2}", Name, Version, sslParams)); } - else if(TestClusterManager.CurrentBackendType == TestClusterManager.BackendType.Hcd) + else if (TestClusterManager.CurrentBackendType == TestClusterManager.BackendType.Hcd) { ExecuteCcm(string.Format( "create {0} --hcd -v {1} {2}", Name, Version, sslParams)); @@ -287,7 +287,7 @@ public ProcessOutput BootstrapNode(int n, string dc, bool start = true) } else if (TestClusterManager.IsScylla) { - cmd += " --scylla"; + cmd += " --scylla"; } var output = ExecuteCcm(string.Format(cmd, n, IpPrefix, n, 7000 + 100 * n, dc != null ? "-d " + dc : null)); diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmCluster.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmCluster.cs index 73baf9749..558047ea7 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmCluster.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmCluster.cs @@ -68,7 +68,7 @@ public void Create(int nodeLength, TestClusterOptions options = null) if (TestClusterManager.Executor is WslCcmProcessExecuter) { - _ccm.UpdateConfig(new [] + _ccm.UpdateConfig(new[] { "read_request_timeout_in_ms: 20000", "counter_write_request_timeout_in_ms: 20000", @@ -101,14 +101,14 @@ public void InitClient() Cluster?.Shutdown(); if (Builder == null) { - Builder = TestUtils.NewBuilder(); + Builder = TestUtils.NewBuilder(); } Cluster = Builder.AddContactPoint(InitialContactPoint).Build(); Session = Cluster.Connect(); if (DefaultKeyspace != null) { Session.CreateKeyspaceIfNotExists(DefaultKeyspace); - Session.ChangeKeyspace(DefaultKeyspace); + Session.ChangeKeyspace(DefaultKeyspace); } } @@ -215,7 +215,7 @@ public void BootstrapNode(int nodeIdToStart, string dataCenterName, bool start = _ccm.CheckNativePortOpen(output, TestClusterManager.IpPrefix + nodeIdToStart); } } - + public void UpdateDseConfig(params string[] yamlChanges) { _ccm.UpdateDseConfig(yamlChanges); diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmProcessExecuter.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmProcessExecuter.cs index 78af02294..2373518ca 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/CcmProcessExecuter.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/CcmProcessExecuter.cs @@ -133,7 +133,7 @@ private static async Task ReadStreamAsync( while (!endProcessToken.IsCancellationRequested) { var read = await Task.Run( - () => stream.ReadAsync(buf, 0, bufLength), + () => stream.ReadAsync(buf, 0, bufLength), timeoutToken).ConfigureAwait(false); if (read <= 0) { @@ -154,7 +154,7 @@ private static async Task ReadStreamAsync( try { var readEnd = await Task.Run( - stream.ReadToEndAsync, + stream.ReadToEndAsync, timeoutToken).ConfigureAwait(false); stringBuilder.Append(readEnd); } diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/CloudCluster.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/CloudCluster.cs index 08cd9ac5d..bc56e251f 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/CloudCluster.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/CloudCluster.cs @@ -106,8 +106,8 @@ public void Create(int nodeLength, TestClusterOptions options = null) sniPath = @"powershell"; args = "-executionpolicy unrestricted \"& '" + oldSniPath + "'" + args + "\""; } - - if (envVars.ContainsKey("REQUIRE_CLIENT_CERTIFICATE")) + + if (envVars.ContainsKey("REQUIRE_CLIENT_CERTIFICATE")) { args = @"-c ""export REQUIRE_CLIENT_CERTIFICATE=true && " + sniPath + "\""; sniPath = "bash"; @@ -222,7 +222,7 @@ private static void ExecCcmCommand(string ccmCmd) } } - private static ProcessOutput ExecCommand(bool throwOnProcessError, string executable, string args, int timeOut = 20*60*1000, IReadOnlyDictionary envVars = null, string workDir = null, bool killOnTimeout = false) + private static ProcessOutput ExecCommand(bool throwOnProcessError, string executable, string args, int timeOut = 20 * 60 * 1000, IReadOnlyDictionary envVars = null, string workDir = null, bool killOnTimeout = false) { Trace.TraceInformation($"{executable} {args}"); var output = ExecuteProcess(executable, args, timeOut, envVariables: envVars, workDir: workDir, killOnTimeout: killOnTimeout); @@ -251,15 +251,15 @@ public static void DockerKill() ExecCommand(true, "bash", @"-c ""docker kill $(docker ps -a -q --filter ancestor=single_endpoint)"""); } } - + /// /// Spawns a new process (platform independent) /// private static ProcessOutput ExecuteProcess( - string processName, - string args, - int timeout, - IReadOnlyDictionary envVariables = null, + string processName, + string args, + int timeout, + IReadOnlyDictionary envVariables = null, string workDir = null, bool killOnTimeout = false) { @@ -327,7 +327,7 @@ private static ProcessOutput ExecuteProcess( output.OutputText.AppendLine(e.Data); } }; - + try { process.Start(); diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/ITestCluster.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/ITestCluster.cs index f59f4b2f0..1598237a6 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/ITestCluster.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/ITestCluster.cs @@ -70,7 +70,7 @@ public interface ITestCluster /// Starts the cluster /// void Start(string[] jvmArgs = null); - + /// /// Updates the dse yaml config /// @@ -80,7 +80,7 @@ public interface ITestCluster /// Updates the yaml config /// void UpdateConfig(params string[] yamlChanges); - + /// /// Updates the yaml config of a specific node /// diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/LocalCcmProcessExecuter.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/LocalCcmProcessExecuter.cs index 443f61663..9ee75f79f 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/LocalCcmProcessExecuter.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/LocalCcmProcessExecuter.cs @@ -25,7 +25,7 @@ public class LocalCcmProcessExecuter : CcmProcessExecuter private LocalCcmProcessExecuter() { - + } protected override string GetExecutable(ref string args) diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/RemoteCcmProcessExecuter.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/RemoteCcmProcessExecuter.cs index 10647f1ed..4e207cf94 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/RemoteCcmProcessExecuter.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/RemoteCcmProcessExecuter.cs @@ -103,7 +103,7 @@ protected override string GetExecutable(ref string args) ~RemoteCcmProcessExecuter() { - if (_sshClient != null && _sshClient.IsConnected) + if (_sshClient != null && _sshClient.IsConnected) _sshClient.Disconnect(); } } diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronCluster.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronCluster.cs index bff57cbf9..0423eb741 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronCluster.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronCluster.cs @@ -70,7 +70,7 @@ private IPEndPoint GetTupleFromContactPoint(string contact) public SimulacronCluster(string id, SimulacronManager simulacronManager) : base(id, simulacronManager) { } - + public static Task CreateNewAsync(int nodeLength) { return SimulacronManager.DefaultInstance.CreateNewAsync(nodeLength); @@ -83,7 +83,7 @@ public static SimulacronCluster CreateNew(int nodeLength) { return SimulacronManager.DefaultInstance.CreateNew(nodeLength); } - + public static Task CreateNewAsync(SimulacronOptions options) { return SimulacronManager.DefaultInstance.CreateNewAsync(options); @@ -116,13 +116,13 @@ public async Task> GetConnectedPortsAsync() { var result = new List(); var response = await GetConnectionsAsync().ConfigureAwait(false); - var dcs = (JArray) response["data_centers"]; + var dcs = (JArray)response["data_centers"]; foreach (var dc in dcs) { - var nodes = (JArray) dc["nodes"]; + var nodes = (JArray)dc["nodes"]; foreach (var nodeJObject in nodes) { - var connections = (JArray) nodeJObject["connections"]; + var connections = (JArray)nodeJObject["connections"]; foreach (var conn in connections) { result.Add(GetTupleFromContactPoint(conn.ToString())); diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronDataCenter.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronDataCenter.cs index ee563e36d..7ba3bb25d 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronDataCenter.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronDataCenter.cs @@ -22,7 +22,7 @@ public class SimulacronDataCenter : SimulacronBase { public List Nodes { get; set; } - public SimulacronDataCenter(string id, SimulacronManager simulacronManager): base(id, simulacronManager) + public SimulacronDataCenter(string id, SimulacronManager simulacronManager) : base(id, simulacronManager) { } } diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronNode.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronNode.cs index 9ee4381e6..cba1b1cf8 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronNode.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/Simulacron/SimulacronNode.cs @@ -61,7 +61,7 @@ public Task Start() { return PutAsync($"/listener/{Id}", null); } - + /// /// Gets the list of established connections to a node. /// diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/TestCloudClusterManager.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/TestCloudClusterManager.cs index 90f9fe4c5..4a1a80dda 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/TestCloudClusterManager.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/TestCloudClusterManager.cs @@ -41,7 +41,7 @@ public static ITestCluster CreateNew(bool enableCert) TestCloudClusterManager.Created = true; TryRemove(); var testCluster = new CloudCluster( - TestUtils.GetTestClusterNameBasedOnRandomString(), + TestUtils.GetTestClusterNameBasedOnRandomString(), VersionString, enableCert); testCluster.Create(3, null); @@ -63,7 +63,7 @@ public static void TryRemove() { if (Diagnostics.CassandraTraceSwitch.Level == TraceLevel.Verbose) { - Trace.TraceError("cloud test cluster could not be removed: {0}", ex); + Trace.TraceError("cloud test cluster could not be removed: {0}", ex); } } } diff --git a/src/Cassandra.IntegrationTests/TestClusterManagement/TestClusterManager.cs b/src/Cassandra.IntegrationTests/TestClusterManagement/TestClusterManager.cs index e467b0304..ec4804f5c 100644 --- a/src/Cassandra.IntegrationTests/TestClusterManagement/TestClusterManager.cs +++ b/src/Cassandra.IntegrationTests/TestClusterManagement/TestClusterManager.cs @@ -118,7 +118,7 @@ public static BackendType CurrentBackendType { get { - if ( Environment.GetEnvironmentVariable("DSE_VERSION") != null ) + if (Environment.GetEnvironmentVariable("DSE_VERSION") != null) { return BackendType.Dse; } diff --git a/src/Cassandra.IntegrationTests/TestDataTypes/Contact.cs b/src/Cassandra.IntegrationTests/TestDataTypes/Contact.cs index cd12252d2..1c394da5e 100644 --- a/src/Cassandra.IntegrationTests/TestDataTypes/Contact.cs +++ b/src/Cassandra.IntegrationTests/TestDataTypes/Contact.cs @@ -23,9 +23,9 @@ namespace Cassandra.IntegrationTests.TestDataTypes { internal class Contact : IEquatable { - public const string CreateUdtCql = + public const string CreateUdtCql = "CREATE TYPE contact (first_name text, last_name text, birth_date timestamp, phones set>, emails set, nullable_long bigint)"; - + public string FirstName { get; set; } public string LastName { get; set; } diff --git a/src/Cassandra.IntegrationTests/TestDataTypes/Phone.cs b/src/Cassandra.IntegrationTests/TestDataTypes/Phone.cs index e45e02b1d..061633030 100644 --- a/src/Cassandra.IntegrationTests/TestDataTypes/Phone.cs +++ b/src/Cassandra.IntegrationTests/TestDataTypes/Phone.cs @@ -22,7 +22,7 @@ internal class Phone : IEquatable { public const string CreateUdtCql = "CREATE TYPE phone (alias text, number text, country_code int, verified_at timestamp, phone_type text)"; - + public string Alias { get; set; } public string Number { get; set; } diff --git a/src/Cassandra.IntegrationTests/TestDataTypes/UserFeedback.cs b/src/Cassandra.IntegrationTests/TestDataTypes/UserFeedback.cs index 89c64f55a..4e8a9989a 100644 --- a/src/Cassandra.IntegrationTests/TestDataTypes/UserFeedback.cs +++ b/src/Cassandra.IntegrationTests/TestDataTypes/UserFeedback.cs @@ -20,7 +20,7 @@ namespace Cassandra.IntegrationTests.TestDataTypes internal class UserFeedback { public DateTimeOffset? SubmittedAt { get; set; } - + public int? Rating { get; set; } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/AbstractResponseTest.cs b/src/Cassandra.Tests/AbstractResponseTest.cs index f39327846..ea00d59ad 100644 --- a/src/Cassandra.Tests/AbstractResponseTest.cs +++ b/src/Cassandra.Tests/AbstractResponseTest.cs @@ -51,8 +51,8 @@ public void Ctor_NoFlags_BodyStreamPositionIsZero() { // Arrange var frame = new Frame( - new FrameHeader(), - new MemoryStream(new byte[] { 1 }), + new FrameHeader(), + new MemoryStream(new byte[] { 1 }), new SerializerManager(ProtocolVersion.V4).GetCurrentSerializer(), null); @@ -67,7 +67,7 @@ public void Ctor_NoFlags_BodyStreamPositionIsZero() public void Ctor_TraceFlagSet_TraceIdIsSet() { // Arrange - var header = new FrameHeader {Flags = HeaderFlags.Tracing}; + var header = new FrameHeader { Flags = HeaderFlags.Tracing }; var rnd = new Random(); var buffer = new byte[16]; rnd.NextBytes(buffer); diff --git a/src/Cassandra.Tests/AdoUnitTests.cs b/src/Cassandra.Tests/AdoUnitTests.cs index 939793404..98bd1b618 100644 --- a/src/Cassandra.Tests/AdoUnitTests.cs +++ b/src/Cassandra.Tests/AdoUnitTests.cs @@ -38,7 +38,7 @@ public void CommandExecuteReaderUsesSyncExecute() .Verifiable(); connection.ManagedConnection = sessionMock.Object; - var cmd = (CqlCommand) connection.CreateCommand(); + var cmd = (CqlCommand)connection.CreateCommand(); cmd.CommandText = "INSERT INTO dummy_cf (a,b) VALUES (1,2)"; var reader = cmd.ExecuteReader(); reader.Dispose(); diff --git a/src/Cassandra.Tests/ApiTests.cs b/src/Cassandra.Tests/ApiTests.cs index f7222140c..ffce789f3 100644 --- a/src/Cassandra.Tests/ApiTests.cs +++ b/src/Cassandra.Tests/ApiTests.cs @@ -83,7 +83,7 @@ private static IEnumerable GetTypesInNamespace(string nameSpace, bool recu { isMatch = n => n == nameSpace; } - var assembly = typeof (ISession).GetTypeInfo().Assembly; + var assembly = typeof(ISession).GetTypeInfo().Assembly; return assembly.GetTypes().Where(t => t.GetTypeInfo().IsPublic && isMatch(t.Namespace)); } } diff --git a/src/Cassandra.Tests/AppMetricsExtension/HistogramTests.cs b/src/Cassandra.Tests/AppMetricsExtension/HistogramTests.cs index 03c6c4d5a..1f929080b 100644 --- a/src/Cassandra.Tests/AppMetricsExtension/HistogramTests.cs +++ b/src/Cassandra.Tests/AppMetricsExtension/HistogramTests.cs @@ -122,7 +122,7 @@ public async Task Should_ReturnEmptyHistogram_When_ResetIsCalled() await Task.WhenAll(tasks).ConfigureAwait(false); } } - + [Test] public void Should_EmptySnapshotBeThreadSafe() { diff --git a/src/Cassandra.Tests/BuilderTests.cs b/src/Cassandra.Tests/BuilderTests.cs index 4235a0857..b6e6826f9 100644 --- a/src/Cassandra.Tests/BuilderTests.cs +++ b/src/Cassandra.Tests/BuilderTests.cs @@ -95,22 +95,22 @@ public void WithCredentials() Cluster.Builder().AddContactPoints(contactPoints).WithCredentials(null, null)); Assert.That(ex.Message, Contains.Substring("username")); } - + [Test] public void Should_SetResolvedContactPoints_When_ClusterIsBuilt() { const string host1 = "127.0.0.1"; const string host2 = "127.0.0.2"; const string host3 = "localhost"; - + var builder = Cluster.Builder().AddContactPoints(host1, host2, host3); var cluster = builder.Build(); Assert.AreEqual(3, cluster.InternalRef.GetResolvedEndpoints().Count); CollectionAssert.AreEqual( - new[] { new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse(host1), ProtocolOptions.DefaultPort), cluster.Configuration.ServerNameResolver, null) }, + new[] { new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse(host1), ProtocolOptions.DefaultPort), cluster.Configuration.ServerNameResolver, null) }, cluster.InternalRef.GetResolvedEndpoints().Single(kvp => kvp.Key.StringRepresentation == host1).Value); CollectionAssert.AreEqual( - new[] { new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse(host2), ProtocolOptions.DefaultPort), cluster.Configuration.ServerNameResolver, null) }, + new[] { new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse(host2), ProtocolOptions.DefaultPort), cluster.Configuration.ServerNameResolver, null) }, cluster.InternalRef.GetResolvedEndpoints().Single(kvp => kvp.Key.StringRepresentation == host2).Value); var localhostAddress = new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ProtocolOptions.DefaultPort), cluster.Configuration.ServerNameResolver, null); @@ -279,21 +279,21 @@ public void Should_ThrowException_When_ContactPointAndBundleAreProvided() var ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .AddContactPoint(IPAddress.Parse("192.168.1.10")) .WithCloudSecureConnectionBundle("bundle"); ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .AddContactPoint(new IPEndPoint(IPAddress.Parse("192.168.1.10"), 9042)) .WithCloudSecureConnectionBundle("bundle"); ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .AddContactPoints(new IPEndPoint(IPAddress.Parse("192.168.1.10"), 9042)) .WithCloudSecureConnectionBundle("bundle"); @@ -311,11 +311,11 @@ public void Should_ThrowException_When_ContactPointAndBundleAreProvided() builder = Cluster.Builder() .WithCloudSecureConnectionBundle("bundle") .AddContactPoint(IPAddress.Parse("192.168.1.10")); - + ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); } - + [Test] public void Should_ThrowException_When_SslOptionsAndBundleAreProvided() { @@ -326,21 +326,21 @@ public void Should_ThrowException_When_SslOptionsAndBundleAreProvided() var ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .WithSSL() .WithCloudSecureConnectionBundle("bundle"); ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .WithSSL() .WithCloudSecureConnectionBundle("bundle"); ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .WithSSL() .WithCloudSecureConnectionBundle("bundle"); @@ -358,11 +358,11 @@ public void Should_ThrowException_When_SslOptionsAndBundleAreProvided() builder = Cluster.Builder() .WithCloudSecureConnectionBundle("bundle") .WithSSL(); - + ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); } - + [Test] public void Should_ThrowException_When_CredentialsAreNotProvidedWithBundle() { @@ -385,7 +385,7 @@ public void Should_ThrowException_When_SslOptionsAndContactPointAndBundleAreProv var ex = Assert.Throws(() => builder.Build()); Assert.AreEqual(exceptionMsg, ex.Message); - + builder = Cluster.Builder() .WithSSL() .AddContactPoints("127.0.0.1") diff --git a/src/Cassandra.Tests/ClusterTests.cs b/src/Cassandra.Tests/ClusterTests.cs index fe6ecaed8..ef4e33f94 100644 --- a/src/Cassandra.Tests/ClusterTests.cs +++ b/src/Cassandra.Tests/ClusterTests.cs @@ -205,17 +205,17 @@ public void Should_OnlyDisposePoliciesOnce_When_NoProfileIsProvided( ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbps[0], - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbps[0], + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null), ExecutionProfiles = lbps.Skip(1).Select( - (lbp, idx) => new - { - idx, - a = new ExecutionProfile(null, null, null, lbp, null, null, null) + (lbp, idx) => new + { + idx, + a = new ExecutionProfile(null, null, null, lbp, null, null, null) as IExecutionProfile }).ToDictionary(obj => obj.idx.ToString(), obj => obj.a) }.Build(); @@ -226,7 +226,7 @@ as IExecutionProfile Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); cluster.Dispose(); diff --git a/src/Cassandra.Tests/CollectionTests.cs b/src/Cassandra.Tests/CollectionTests.cs index aaa5d2a4e..5a63c18e1 100644 --- a/src/Cassandra.Tests/CollectionTests.cs +++ b/src/Cassandra.Tests/CollectionTests.cs @@ -50,7 +50,7 @@ public void CopyOnWriteList_Should_AddRange_And_Count() [Test] public void CopyOnWriteList_Should_Add_And_Remove() { - var list = new CopyOnWriteList {"one", "two", "three", "four", "five"}; + var list = new CopyOnWriteList { "one", "two", "three", "four", "five" }; Assert.AreEqual(5, list.Count); list.Remove("three"); CollectionAssert.AreEqual(new[] { "one", "two", "four", "five" }, list); diff --git a/src/Cassandra.Tests/ConnectionTests.cs b/src/Cassandra.Tests/ConnectionTests.cs index 3dc3dd2d8..a6c0963e4 100644 --- a/src/Cassandra.Tests/ConnectionTests.cs +++ b/src/Cassandra.Tests/ConnectionTests.cs @@ -41,10 +41,10 @@ private static Mock GetConnectionMock(Configuration config = null, I { config = config ?? new Configuration(); return new Mock( - MockBehavior.Loose, - serializer?.GetCurrentSerializer() ?? new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), - new ConnectionEndPoint(ConnectionTests.Address, config.ServerNameResolver, null), - config, + MockBehavior.Loose, + serializer?.GetCurrentSerializer() ?? new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), + new ConnectionEndPoint(ConnectionTests.Address, config.ServerNameResolver, null), + config, new StartupRequestFactory(config.StartupOptionsFactory), NullConnectionObserver.Instance); } @@ -70,7 +70,7 @@ public void ReadParse_Handles_Complete_Frames_In_Different_Buffers() CollectionAssert.AreEqual(new short[] { 127, 126, 125 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); Assert.AreEqual(3, responses.Count); - CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse) r).Kind)); + CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse)r).Kind)); } [Test] @@ -200,7 +200,7 @@ public void ReadParse_Handles_UnComplete_Body_In_Multiple_Messages() //2 more bytes, but not enough var buffer = originalBuffer.Skip(firstSlice).Take(2).ToArray(); connection.ReadParse(buffer, buffer.Length); - CollectionAssert.AreEqual(new short[] { 127, 126}, streamIds); + CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); //the last byte buffer = originalBuffer.Skip(firstSlice + 2).ToArray(); connection.ReadParse(buffer, buffer.Length); @@ -283,7 +283,7 @@ public async Task ReadParse_While_Disposing_Faults_Tasks_But_Never_Throws() var connectionMock = GetConnectionMock(); var responses = new ConcurrentBag(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny())) - .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add((object) ex ?? r))); + .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add((object)ex ?? r))); var connection = connectionMock.Object; var bufferBuilder = Enumerable.Empty(); const int totalFrames = 63; @@ -298,7 +298,7 @@ public async Task ReadParse_While_Disposing_Faults_Tasks_But_Never_Throws() { var index = i; tasks.Add( - Task.Factory.StartNew(() => connection.ReadParse(buffer.Skip(index).ToArray(), 1), + Task.Factory.StartNew(() => connection.ReadParse(buffer.Skip(index).ToArray(), 1), CancellationToken.None, TaskCreationOptions.None, schedulerPair.ExclusiveScheduler)); } var random = new Random(); @@ -310,7 +310,7 @@ public async Task ReadParse_While_Disposing_Faults_Tasks_But_Never_Throws() await TestHelper.WaitUntilAsync(() => totalFrames == responses.Count, 100, 30).ConfigureAwait(false); Assert.AreEqual(totalFrames, responses.Count); } - + [Test] public void Should_HandleDifferentProtocolVersionsInDifferentConnections_When_OneConnectionResponseVersionIsDifferentThanSerializer() { diff --git a/src/Cassandra.Tests/Connections/Control/ControlConnectionTests.cs b/src/Cassandra.Tests/Connections/Control/ControlConnectionTests.cs index 1e2ca9b28..02fb8c691 100644 --- a/src/Cassandra.Tests/Connections/Control/ControlConnectionTests.cs +++ b/src/Cassandra.Tests/Connections/Control/ControlConnectionTests.cs @@ -44,8 +44,8 @@ public class ControlConnectionTests private IProtocolEventDebouncer GetEventDebouncer(Configuration config) { return new ProtocolEventDebouncer( - new TaskBasedTimerFactory(), - TimeSpan.FromMilliseconds(config.MetadataSyncOptions.RefreshSchemaDelayIncrement), + new TaskBasedTimerFactory(), + TimeSpan.FromMilliseconds(config.MetadataSyncOptions.RefreshSchemaDelayIncrement), TimeSpan.FromMilliseconds(config.MetadataSyncOptions.MaxTotalRefreshSchemaDelay)); } @@ -64,9 +64,9 @@ private ControlConnectionCreateResult NewInstance( new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042), TestHelper.CreateRow(new Dictionary { - { "cluster_name", "ut-cluster" }, - { "data_center", "ut-dc" }, - { "rack", "ut-rack" }, + { "cluster_name", "ut-cluster" }, + { "data_center", "ut-dc" }, + { "rack", "ut-rack" }, { "tokens", null }, { "release_version", "2.2.1-SNAPSHOT" } }) @@ -95,7 +95,7 @@ private ControlConnectionCreateResult NewInstance( configBuilderAct?.Invoke(builder); config = builder.Build(); } - + if (metadata == null) { metadata = new Metadata(config); @@ -161,7 +161,7 @@ public void Should_NotAttemptDownOrIgnoredHosts() if (!connectionOpenEnabled) { Mock.Get(connection).Setup(c => c.Open()) - .ThrowsAsync(new SocketException((int) SocketError.ConnectionRefused)); + .ThrowsAsync(new SocketException((int)SocketError.ConnectionRefused)); } return connection; @@ -377,7 +377,7 @@ private class ControlConnectionCreateResult public Configuration Config { get; set; } public FakeConnectionFactory ConnectionFactory { get; set; } - + public IInternalCluster Cluster { get; set; } } @@ -394,7 +394,7 @@ public TestContactPoint(IEnumerable endPoints) public bool Equals(IContactPoint other) { - return Equals((object) other); + return Equals((object)other); } public override bool Equals(object obj) diff --git a/src/Cassandra.Tests/Connections/Control/HostnameContactPointTests.cs b/src/Cassandra.Tests/Connections/Control/HostnameContactPointTests.cs index f5e894647..ff3cbc974 100644 --- a/src/Cassandra.Tests/Connections/Control/HostnameContactPointTests.cs +++ b/src/Cassandra.Tests/Connections/Control/HostnameContactPointTests.cs @@ -30,7 +30,7 @@ public class HostnameContactPointTests private readonly IPEndPoint _localhostIpEndPoint2 = new IPEndPoint(IPAddress.Parse("127.0.0.2"), HostnameContactPointTests.Port); private IDnsResolver _dnsResolver; private const int Port = 100; - + [Test] public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameHostname() { @@ -85,12 +85,12 @@ public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameHostn Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); Mock.Get(_dnsResolver).Setup(m => m.GetHostEntryAsync("cp1")) - .ReturnsAsync(new IPHostEntry { AddressList = new[] { IPAddress.Parse("127.0.0.2") }}); - + .ReturnsAsync(new IPHostEntry { AddressList = new[] { IPAddress.Parse("127.0.0.2") } }); + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); - + await target2.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); @@ -106,7 +106,7 @@ public async Task Should_DnsResolve_When_HostnameIsProvided(bool refreshCache) Mock.Get(_dnsResolver).Verify(x => x.GetHostEntryAsync("cp1"), Times.Once); } - + [Test] public async Task Should_DnsResolveAgain_When_RefreshCacheIsTrue() { @@ -114,12 +114,12 @@ public async Task Should_DnsResolveAgain_When_RefreshCacheIsTrue() await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(_dnsResolver).Verify(x => x.GetHostEntryAsync("cp1"), Times.Once); - + await target.GetConnectionEndPointsAsync(true).ConfigureAwait(false); Mock.Get(_dnsResolver).Verify(x => x.GetHostEntryAsync("cp1"), Times.Exactly(2)); } - + [Test] public async Task Should_NotDnsResolveAgain_When_RefreshCacheIsFalse() { @@ -127,18 +127,18 @@ public async Task Should_NotDnsResolveAgain_When_RefreshCacheIsFalse() await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(_dnsResolver).Verify(x => x.GetHostEntryAsync("cp1"), Times.Once); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(_dnsResolver).Verify(x => x.GetHostEntryAsync("cp1"), Times.Once); } - + [Test] public async Task Should_BuildEndPointCorrectly_When_HostnameIsProvided() { var target = Create("cp1", "127.0.0.2"); var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); - + Assert.AreEqual(1, resolved.Count); Assert.AreEqual(_localhostIpEndPoint2, resolved[0].GetHostIpEndPointWithFallback()); Assert.AreEqual(_localhostIpEndPoint2, resolved[0].SocketIpEndPoint); @@ -152,11 +152,11 @@ public async Task Should_GetCorrectServerName_When_HostnameIsProvided() { var target = Create("cp1", "127.0.0.2"); var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); - + Assert.AreEqual(1, resolved.Count); Assert.AreEqual("127.0.0.2", await resolved[0].GetServerNameAsync().ConfigureAwait(false)); } - + [Test] public async Task Should_NotLogMultipleAddressesWarning_When_SingleAddressIsResolved() { @@ -178,7 +178,7 @@ public async Task Should_NotLogMultipleAddressesWarning_When_SingleAddressIsReso Trace.Listeners.Remove(testListener); } } - + [Test] public async Task Should_LogMultipleAddressesWarning_When_TwoAddressesAreResolved() { diff --git a/src/Cassandra.Tests/Connections/Control/ResolvedContactPointTests.cs b/src/Cassandra.Tests/Connections/Control/ResolvedContactPointTests.cs index a59d790e5..a167c9813 100644 --- a/src/Cassandra.Tests/Connections/Control/ResolvedContactPointTests.cs +++ b/src/Cassandra.Tests/Connections/Control/ResolvedContactPointTests.cs @@ -77,7 +77,7 @@ public async Task Should_GetCorrectServerName_When_IpEndPointIsProvided() Assert.AreEqual(1, resolved.Count); Assert.AreEqual("127.0.0.1", await resolved[0].GetServerNameAsync().ConfigureAwait(false)); } - + [Test] public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameIPAddress() { @@ -86,11 +86,11 @@ public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameIPAdd Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); - + await target2.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); @@ -104,16 +104,16 @@ public async Task Should_EqualsReturnFalse_When_BothContactPointsReferToDifferen Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); - + await target2.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); } - + [Test] public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameIPEndPoint() { @@ -122,11 +122,11 @@ public async Task Should_EqualsReturnTrue_When_BothContactPointsReferToSameIPEnd Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); - + await target2.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreEqual(target, target2); Assert.AreEqual(target.GetHashCode(), target2.GetHashCode()); @@ -149,7 +149,7 @@ public async Task Should_EqualsReturnFalse_When_BothContactPointsReferToSameIPAd Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); } - + [Test] public async Task Should_EqualsReturnFalse_When_BothContactPointsReferToSamePortButDifferentIPAddresses() { @@ -158,11 +158,11 @@ public async Task Should_EqualsReturnFalse_When_BothContactPointsReferToSamePort Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); - + await target2.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Assert.AreNotEqual(target, target2); Assert.AreNotEqual(target.GetHashCode(), target2.GetHashCode()); diff --git a/src/Cassandra.Tests/Connections/Control/TopologyRefresherTests.cs b/src/Cassandra.Tests/Connections/Control/TopologyRefresherTests.cs index 3ab724963..4563bc969 100644 --- a/src/Cassandra.Tests/Connections/Control/TopologyRefresherTests.cs +++ b/src/Cassandra.Tests/Connections/Control/TopologyRefresherTests.cs @@ -47,10 +47,10 @@ private FakeMetadataRequestHandler CreateFakeMetadataRequestHandler( { var row = localRow ?? TestHelper.CreateRow(new Dictionary { - { "cluster_name", "ut-cluster" }, - { "data_center", "ut-dc" }, - { "rack", "ut-rack" }, - {"tokens", null}, + { "cluster_name", "ut-cluster" }, + { "data_center", "ut-dc" }, + { "rack", "ut-rack" }, + {"tokens", null}, {"release_version", "2.2.1-SNAPSHOT"}, {"partitioner", "Murmur3Partitioner" } }); @@ -61,16 +61,16 @@ private FakeMetadataRequestHandler CreateFakeMetadataRequestHandler( { new Dictionary { - {"rpc_address", IPAddress.Parse("127.0.0.2")}, - {"peer", null}, - { "data_center", "ut-dc3" }, - { "rack", "ut-rack3" }, - {"tokens", null}, + {"rpc_address", IPAddress.Parse("127.0.0.2")}, + {"peer", null}, + { "data_center", "ut-dc3" }, + { "rack", "ut-rack3" }, + {"tokens", null}, {"release_version", "2.1.5"} } }); } - + IEnumerable peersV2Rows = null; if (withPeersV2) { @@ -118,11 +118,11 @@ public async Task Should_SendSystemLocalAndPeersV1AndPeersV2Queries() _metadata = new Metadata(config); var topologyRefresher = new TopologyRefresher(_metadata, config); var connection = Mock.Of(); - + await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); @@ -130,7 +130,7 @@ await topologyRefresher Assert.AreEqual(TopologyRefresherTests.PeersV2Query, fakeRequestHandler.Requests.ElementAt(1).CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersQuery, fakeRequestHandler.Requests.Last().CqlQuery); } - + [Test] public async Task Should_SendSystemLocalAndPeersV2Queries() { @@ -145,14 +145,14 @@ public async Task Should_SendSystemLocalAndPeersV2Queries() await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); Assert.AreEqual(TopologyRefresherTests.LocalQuery, fakeRequestHandler.Requests.First().CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersV2Query, fakeRequestHandler.Requests.Last().CqlQuery); } - + [Test] public async Task Should_KeepSendingSystemPeersV2Queries_When_ItDoesNotFail() { @@ -167,20 +167,20 @@ public async Task Should_KeepSendingSystemPeersV2Queries_When_ItDoesNotFail() await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); Assert.AreEqual(2, fakeRequestHandler.Requests.Count); Assert.AreEqual(TopologyRefresherTests.LocalQuery, fakeRequestHandler.Requests.First().CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersV2Query, fakeRequestHandler.Requests.ElementAt(1).CqlQuery); - + await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); - + Assert.AreEqual(4, fakeRequestHandler.Requests.Count); Assert.AreEqual(TopologyRefresherTests.LocalQuery, fakeRequestHandler.Requests.ElementAt(2).CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersV2Query, fakeRequestHandler.Requests.ElementAt(3).CqlQuery); @@ -194,24 +194,24 @@ public async Task Should_SendPeersV1OnlyAfterPeersV2Fails() _metadata = new Metadata(config); var topologyRefresher = new TopologyRefresher(_metadata, config); var connection = Mock.Of(); - + await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); - + Assert.AreEqual(3, fakeRequestHandler.Requests.Count); Assert.AreEqual(TopologyRefresherTests.LocalQuery, fakeRequestHandler.Requests.First().CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersV2Query, fakeRequestHandler.Requests.ElementAt(1).CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersQuery, fakeRequestHandler.Requests.ElementAt(2).CqlQuery); - + await topologyRefresher .RefreshNodeListAsync( - new FakeConnectionEndPoint("127.0.0.1", 9042), - connection, + new FakeConnectionEndPoint("127.0.0.1", 9042), + connection, _serializer).ConfigureAwait(false); - + Assert.AreEqual(5, fakeRequestHandler.Requests.Count); Assert.AreEqual(TopologyRefresherTests.LocalQuery, fakeRequestHandler.Requests.ElementAt(3).CqlQuery); Assert.AreEqual(TopologyRefresherTests.PeersQuery, fakeRequestHandler.Requests.ElementAt(4).CqlQuery); @@ -300,7 +300,7 @@ await topologyRefresher.RefreshNodeListAsync( Assert.AreEqual(2, _metadata.AllHosts().Count); Assert.AreEqual(1, _metadata.AllHosts().Count(h => h.Address.Address.ToString() == "127.0.0.9")); } - + [Test] public async Task Should_UseListenAddressWhenSystemLocalAndRpcIsBindAllAndBroadcastIsNull() { diff --git a/src/Cassandra.Tests/Connections/HostConnectionPoolTests.cs b/src/Cassandra.Tests/Connections/HostConnectionPoolTests.cs index 578859551..d34c42f23 100644 --- a/src/Cassandra.Tests/Connections/HostConnectionPoolTests.cs +++ b/src/Cassandra.Tests/Connections/HostConnectionPoolTests.cs @@ -113,8 +113,8 @@ private IHostConnectionPool CreatePool(IEndPointResolver res = null) }.Build(); var pool = new HostConnectionPool( - _host, - config, + _host, + config, SerializerManager.Default, new MetricsObserverFactory(new MetricsManager(new NullDriverMetricsProvider(), new DriverMetricsOptions(), false, "s1")) ); diff --git a/src/Cassandra.Tests/Connections/SniContactPointAndResolverTests.cs b/src/Cassandra.Tests/Connections/SniContactPointAndResolverTests.cs index 31fbec403..e3ad7d8c9 100644 --- a/src/Cassandra.Tests/Connections/SniContactPointAndResolverTests.cs +++ b/src/Cassandra.Tests/Connections/SniContactPointAndResolverTests.cs @@ -47,7 +47,7 @@ public async Task Should_NotDnsResolveProxy_When_ProxyIpAddressIsProvided() Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny()), Times.Never); } - + [Test] public async Task Should_DnsResolveProxy_When_ProxyNameIsProvided() { @@ -59,37 +59,37 @@ public async Task Should_DnsResolveProxy_When_ProxyNameIsProvided() Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny()), Times.Once); } - + [Test] public async Task Should_BuildEndPointCorrectly_When_ProxyIpAddressIsProvided() { - var result = Create(_proxyEndPoint.Address, serverNames: new [] { "host1" }); + var result = Create(_proxyEndPoint.Address, serverNames: new[] { "host1" }); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); - + Assert.AreEqual(1, resolved.Count); Assert.AreEqual(_proxyEndPoint, resolved[0].GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyEndPoint, resolved[0].SocketIpEndPoint); Assert.AreEqual($"{_proxyEndPoint} (host1)", resolved[0].EndpointFriendlyName); Assert.AreEqual(_proxyEndPoint, resolved[0].GetHostIpEndPointWithFallback()); } - + [Test] public async Task Should_BuildEndPointCorrectly_When_ProxyNameIsProvided() { - var result = Create(name: "proxy", serverNames: new [] { "host1" }); + var result = Create(name: "proxy", serverNames: new[] { "host1" }); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); - + Assert.AreEqual(1, resolved.Count); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].SocketIpEndPoint); Assert.AreEqual($"{_proxyResolvedEndPoint} (host1)", resolved[0].EndpointFriendlyName); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].GetHostIpEndPointWithFallback()); } - + [Test] public async Task Should_DnsResolveProxyTwice_When_RefreshIsTrue() { @@ -100,12 +100,12 @@ public async Task Should_DnsResolveProxyTwice_When_RefreshIsTrue() await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); - + await target.GetConnectionEndPointsAsync(true).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Exactly(2)); } - + [Test] public async Task Should_NotDnsResolveProxyTwice_When_RefreshIsFalse() { @@ -116,12 +116,12 @@ public async Task Should_NotDnsResolveProxyTwice_When_RefreshIsFalse() await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); - + await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); } - + [Test] public async Task Should_EndPointResolver_DnsResolveProxyTwice_When_RefreshIsTrue() { @@ -133,12 +133,12 @@ public async Task Should_EndPointResolver_DnsResolveProxyTwice_When_RefreshIsTru await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); - + await target.GetConnectionEndPointAsync(host, true).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Exactly(2)); } - + [Test] public async Task Should_EndPointResolver_NotDnsResolveProxyTwice_When_RefreshIsFalse() { @@ -150,16 +150,16 @@ public async Task Should_EndPointResolver_NotDnsResolveProxyTwice_When_RefreshIs await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); - + await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); } - + [Test] public async Task Should_ReturnNewResolvedAddress_When_RefreshIsTrue() { - var result = Create(name: "proxy", serverNames: new [] { "cp1" }); + var result = Create(name: "proxy", serverNames: new[] { "cp1" }); var target = result.SniContactPoint; var oldResolvedResults = await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); @@ -170,14 +170,14 @@ public async Task Should_ReturnNewResolvedAddress_When_RefreshIsTrue() Assert.AreNotEqual(IPAddress.Parse("123.10.10.10"), oldResolvedResults.Single().SocketIpEndPoint.Address); Assert.AreEqual(IPAddress.Parse("123.10.10.10"), newResolvedResults.Single().SocketIpEndPoint.Address); } - + [Test] public async Task Should_GetCorrectServerName() { var result = Create(_proxyEndPoint.Address); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); - + Assert.AreEqual(_serverNames.Count(), resolved.Count); var tasks = resolved.Select(r => r.GetServerNameAsync()).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); @@ -196,10 +196,10 @@ public async Task Should_NotDnsResolve_When_ResolvingHostButProxyIsIpAddress() var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); - + Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny()), Times.Never); } - + [Test] public async Task Should_BuildEndPointCorrectly_When_ResolvingHostButProxyIsIpAddress() { @@ -208,12 +208,12 @@ public async Task Should_BuildEndPointCorrectly_When_ResolvingHostButProxyIsIpAd var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolved = await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); - + Assert.AreEqual(host.HostId.ToString("D"), await resolved.GetServerNameAsync().ConfigureAwait(false)); Assert.AreEqual(host.Address, resolved.GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyEndPoint, resolved.SocketIpEndPoint); } - + [Test] public async Task Should_BuildEndPointCorrectly_When_ResolvingHostAndProxyIsHostname() { @@ -222,12 +222,12 @@ public async Task Should_BuildEndPointCorrectly_When_ResolvingHostAndProxyIsHost var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolved = await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); - + Assert.AreEqual(host.HostId.ToString("D"), await resolved.GetServerNameAsync().ConfigureAwait(false)); Assert.AreEqual(host.Address, resolved.GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyResolvedEndPoint, resolved.SocketIpEndPoint); } - + [Test] public async Task Should_CycleThroughResolvedAddresses_When_ResolvingHostAndProxyResolutionReturnsMultipleAddresses() { @@ -261,7 +261,7 @@ async Task AssertResolved(IConnectionEndPoint endPoint, string proxyAddress) await AssertResolved(resolvedSecond[0], "127.0.0.6").ConfigureAwait(false); await AssertResolved(resolvedSecond[1], "127.0.0.6").ConfigureAwait(false); } - + [Test] public async Task Should_NotCallDnsResolve_When_CyclingThroughResolvedProxyAddresses() { @@ -277,7 +277,7 @@ public async Task Should_NotCallDnsResolve_When_CyclingThroughResolvedProxyAddre Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny()), Times.Once); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxyMultiple"), Times.Once); } - + [Test] public async Task Should_UseNewResolution_When_ResolveSucceeds() { @@ -387,7 +387,7 @@ public async Task Should_CycleThroughAddressesCorrectly_When_ConcurrentCalls() Assert.AreEqual(500, resolvedFirst); Assert.AreEqual(500, resolvedSecond); } - + [Test] public async Task Should_CycleThroughAddressesCorrectly_When_ConcurrentCallsWithRefresh() { @@ -397,14 +397,14 @@ public async Task Should_CycleThroughAddressesCorrectly_When_ConcurrentCallsWith var resolvedCollection = new ConcurrentQueue(); - var tasks = + var tasks = Enumerable.Range(0, 16) .Select(i => Task.Run(async () => { foreach (var j in Enumerable.Range(0, 10000)) { resolvedCollection.Enqueue( - await target.GetConnectionEndPointAsync(host, (i+j) % 2 == 0).ConfigureAwait(false)); + await target.GetConnectionEndPointAsync(host, (i + j) % 2 == 0).ConfigureAwait(false)); } })).ToList(); @@ -451,7 +451,7 @@ private CreateResult Create(IPAddress ip = null, string name = null, IEnumerable var sniResolver = new SniEndPointResolver( sniOptionsProvider, dnsResolver, - randValue == null ? (IRandom) new DefaultRandom() : new FixedRandom(randValue.Value)); + randValue == null ? (IRandom)new DefaultRandom() : new FixedRandom(randValue.Value)); return new CreateResult { DnsResolver = dnsResolver, diff --git a/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionEndPoint.cs b/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionEndPoint.cs index e6c4395b6..05b3fa298 100644 --- a/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionEndPoint.cs +++ b/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionEndPoint.cs @@ -36,7 +36,7 @@ public bool Equals(IConnectionEndPoint other) public IContactPoint ContactPoint => null; public IPEndPoint SocketIpEndPoint { get; private set; } - + public bool HasHostIpEndPoint { get; private set; } public string EndpointFriendlyName => SocketIpEndPoint.ToString(); diff --git a/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionFactory.cs b/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionFactory.cs index 9a479b9f0..998315059 100644 --- a/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionFactory.cs +++ b/src/Cassandra.Tests/Connections/TestHelpers/FakeConnectionFactory.cs @@ -31,11 +31,11 @@ internal class FakeConnectionFactory : IConnectionFactory public event Action OnCreate; public ConcurrentDictionary> CreatedConnections { get; } = new ConcurrentDictionary>(); - + public FakeConnectionFactory() : this((Func)null) { } - + public FakeConnectionFactory(Func func) { _func = endpoint => func(); @@ -56,7 +56,7 @@ public FakeConnectionFactory(Func func) _func = func; } - + public FakeConnectionFactory(Func func) { _func = endpoint => func(endpoint.SocketIpEndPoint); diff --git a/src/Cassandra.Tests/Connections/TestHelpers/FakeMetadataRequestHandler.cs b/src/Cassandra.Tests/Connections/TestHelpers/FakeMetadataRequestHandler.cs index 153d4606d..386b36b3e 100644 --- a/src/Cassandra.Tests/Connections/TestHelpers/FakeMetadataRequestHandler.cs +++ b/src/Cassandra.Tests/Connections/TestHelpers/FakeMetadataRequestHandler.cs @@ -31,7 +31,7 @@ internal class FakeMetadataRequestHandler : IMetadataRequestHandler internal ConcurrentQueue Requests { get; } = new ConcurrentQueue(); - + public FakeMetadataRequestHandler(IDictionary> rows) { _rows = rows; @@ -42,8 +42,8 @@ private async Task Send( { Requests.Enqueue(new MetadataRequest { - Serializer = serializer, - CqlQuery = cqlQuery, + Serializer = serializer, + CqlQuery = cqlQuery, QueryProtocolOptions = queryProtocolOptions }); @@ -51,8 +51,8 @@ private async Task Send( ThrowErrorIfNullRows(cqlQuery); var response = new FakeResultResponse(ResultResponse.ResultResponseKind.Rows); - _responsesByCql.AddOrUpdate(response, _ => cqlQuery, (_,__) => cqlQuery); - return (Response) response; + _responsesByCql.AddOrUpdate(response, _ => cqlQuery, (_, __) => cqlQuery); + return (Response)response; } private void ThrowErrorIfNullRows(string cqlQuery) diff --git a/src/Cassandra.Tests/CustomTypeSerializerTests.cs b/src/Cassandra.Tests/CustomTypeSerializerTests.cs index 386bf321e..3e7feab5f 100644 --- a/src/Cassandra.Tests/CustomTypeSerializerTests.cs +++ b/src/Cassandra.Tests/CustomTypeSerializerTests.cs @@ -35,7 +35,7 @@ public void Should_Allow_Custom_Primitive_Serializers() CollectionAssert.AreEqual(new byte[] { 0, 0, 0, 5, 1 }, buffer); var deserializedValue = serializer.Deserialize(buffer, ColumnTypeCode.Decimal, null); Assert.IsInstanceOf(deserializedValue); - var deserializedDecimal = (BigDecimal) deserializedValue; + var deserializedDecimal = (BigDecimal)deserializedValue; Assert.AreEqual("0.00001", deserializedDecimal.ToString()); Assert.AreEqual(value.Scale, deserializedDecimal.Scale); Assert.AreEqual(value.UnscaledValue, deserializedDecimal.UnscaledValue); diff --git a/src/Cassandra.Tests/DataStax/Auth/DsePlainTextAuthProviderTests.cs b/src/Cassandra.Tests/DataStax/Auth/DsePlainTextAuthProviderTests.cs index 812a34ec5..cb8095476 100644 --- a/src/Cassandra.Tests/DataStax/Auth/DsePlainTextAuthProviderTests.cs +++ b/src/Cassandra.Tests/DataStax/Auth/DsePlainTextAuthProviderTests.cs @@ -40,7 +40,7 @@ public void Authenticator_InitialResponse_With_Other_Authenticator_Should_Return authProvider.SetName("org.other.authenticator"); var authenticator = authProvider.NewAuthenticator(null); CollectionAssert.AreEqual( - new byte[] { 0, Encoding.UTF8.GetBytes("u")[0], 0, Encoding.UTF8.GetBytes("p")[0] }, + new byte[] { 0, Encoding.UTF8.GetBytes("u")[0], 0, Encoding.UTF8.GetBytes("p")[0] }, authenticator.InitialResponse()); } @@ -50,7 +50,7 @@ public void Should_CreatePlainTextAuthProvider_When_WithCredentialsIsCalled() var cluster = Cluster.Builder().AddContactPoint("127.0.0.1").WithCredentials("cassandra", "cassandra").Build(); Assert.AreEqual(typeof(PlainTextAuthProvider), cluster.Configuration.AuthProvider.GetType()); } - + [Test] public void Should_SetDsePlainTextAuthProvider_When_WithAuthProviderIsCalled() { diff --git a/src/Cassandra.Tests/DataStax/Cloud/CloudConfigurationParserTests.cs b/src/Cassandra.Tests/DataStax/Cloud/CloudConfigurationParserTests.cs index a9c416be7..60adcccbc 100644 --- a/src/Cassandra.Tests/DataStax/Cloud/CloudConfigurationParserTests.cs +++ b/src/Cassandra.Tests/DataStax/Cloud/CloudConfigurationParserTests.cs @@ -33,9 +33,9 @@ public void Should_ParseCorrectly_When_AllPropertiesAreThereAndMore() var randomString3 = Guid.NewGuid().ToString().Replace("-", ""); var randomString4 = Guid.NewGuid().ToString().Replace("-", ""); var randomString5 = Guid.NewGuid().ToString().Replace("-", ""); - var a = + var a = "{" + - $"\"username\": \"{randomString}\"," + + $"\"username\": \"{randomString}\"," + $"\"password\": \"{randomString2}\"," + "\"host\": \"ea20d9d5-f69e-46ad-8eb1-f32f33a7472e.us-east-1.dse.datastax.com\"," + "\"port\": 30443," + @@ -52,17 +52,17 @@ public void Should_ParseCorrectly_When_AllPropertiesAreThereAndMore() "}"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var config = target.ParseConfig(stream); - + Assert.AreEqual(30443, config.Port); Assert.AreEqual("ea20d9d5-f69e-46ad-8eb1-f32f33a7472e.us-east-1.dse.datastax.com", config.Host); } - + [Test] public void Should_ParseCorrectly_When_OnlyRequiredPropertiesAreThere() { - var a = + var a = @"{ ""host"": ""ea20d9d5-f69e-46ad-8eb1-f32f33a7472e.us-east-1.dse.datastax.com"", ""port"": 30443, @@ -70,20 +70,20 @@ public void Should_ParseCorrectly_When_OnlyRequiredPropertiesAreThere() }"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var config = target.ParseConfig(stream); - + Assert.AreEqual(30443, config.Port); Assert.AreEqual("ea20d9d5-f69e-46ad-8eb1-f32f33a7472e.us-east-1.dse.datastax.com", config.Host); } - + [Test] public void Should_ParseCorrectly_When_AllPropertiesAreThere() { var randomString = Guid.NewGuid().ToString().Replace("-", ""); var randomString2 = Guid.NewGuid().ToString().Replace("-", ""); var randomString3 = Guid.NewGuid().ToString().Replace("-", ""); - var a = + var a = @"{" + $"\"username\": \"{randomString}\"," + $"\"password\": \"{randomString2}\"," + @@ -94,20 +94,20 @@ public void Should_ParseCorrectly_When_AllPropertiesAreThere() "}"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var config = target.ParseConfig(stream); - + Assert.AreEqual(30443, config.Port); Assert.AreEqual("ea20d9d5-f69e-46ad-8eb1-f32f33a7472e.us-east-1.dse.datastax.com", config.Host); } - + [Test] public void Should_ThrowException_When_HostIsNotThere() { var randomString = Guid.NewGuid().ToString().Replace("-", ""); var randomString2 = Guid.NewGuid().ToString().Replace("-", ""); var randomString3 = Guid.NewGuid().ToString().Replace("-", ""); - var a = + var a = "{" + $"\"username\": \"{randomString}\"," + $"\"password\": \"{randomString2}\"," + @@ -117,19 +117,19 @@ public void Should_ThrowException_When_HostIsNotThere() "}"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var ex = Assert.Throws(() => target.ParseConfig(stream)); - + Assert.IsTrue(ex.Message.Contains("Could not parse the \"host\""), ex.Message); } - + [Test] public void Should_ThrowException_When_PortIsNotThere() { var randomString = Guid.NewGuid().ToString().Replace("-", ""); var randomString2 = Guid.NewGuid().ToString().Replace("-", ""); var randomString3 = Guid.NewGuid().ToString().Replace("-", ""); - var a = + var a = "{" + $"\"username\": \"{randomString}\"," + $"\"password\": \"{randomString2}\"," + @@ -139,33 +139,33 @@ public void Should_ThrowException_When_PortIsNotThere() "}"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var ex = Assert.Throws(() => target.ParseConfig(stream)); - + Assert.IsTrue(ex.Message.Contains("Could not parse the \"port\""), ex.Message); } - + [Test] public void Should_ThrowException_When_ConfigIsEmpty() { var a = @""; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var ex = Assert.Throws(() => target.ParseConfig(stream)); - + Assert.IsTrue(ex.Message.Contains("Config file is empty"), ex.Message); } - + [Test] public void Should_ThrowException_When_ConfigDoesntHaveAnyRelevantProperty() { var a = @"{""keyStoreLocation"": ""./identity.jks""}"; var stream = new MemoryStream(Encoding.Default.GetBytes(a)); var target = new CloudConfigurationParser(); - + var ex = Assert.Throws(() => target.ParseConfig(stream)); - + Assert.IsTrue(ex.Message.Contains("Could not parse"), ex.Message); } } diff --git a/src/Cassandra.Tests/DataStax/Cloud/CloudMetadataServiceTests.cs b/src/Cassandra.Tests/DataStax/Cloud/CloudMetadataServiceTests.cs index 29693c334..ff6e02756 100644 --- a/src/Cassandra.Tests/DataStax/Cloud/CloudMetadataServiceTests.cs +++ b/src/Cassandra.Tests/DataStax/Cloud/CloudMetadataServiceTests.cs @@ -28,7 +28,7 @@ public class CloudMetadataServiceTests [CloudSupported(Supported = false)] public void Should_ThrowNotSupported_When_NetCore20() { - Assert.Throws(() => + Assert.Throws(() => new CloudMetadataService().GetClusterMetadataAsync(null, null, null).GetAwaiter().GetResult()); } } diff --git a/src/Cassandra.Tests/DataStax/Cloud/CustomCaCertificateValidatorTests.cs b/src/Cassandra.Tests/DataStax/Cloud/CustomCaCertificateValidatorTests.cs index 238c96cfc..765f440ba 100644 --- a/src/Cassandra.Tests/DataStax/Cloud/CustomCaCertificateValidatorTests.cs +++ b/src/Cassandra.Tests/DataStax/Cloud/CustomCaCertificateValidatorTests.cs @@ -86,7 +86,7 @@ public void TestCertificateWithWildcardAndNoRootCaInChain() "9Awg4x6WQmtMoredcpRSAOGn9hX+IMenRF4OEI8ltG17zVGaMThZ7/OHzFIvgX5ynql9sRBXG0AjNsBG2QiP+0Xia9BGvvj" + "kqAfxwp44CWacVsbbWFrc+reYmOfmoy8b1Flm/gXVP2DbjMYwHX5RKvPt2SQ7L2iXgaa1a4+g9ZJx/U3RFHKeFbwpRLFH70" + "3FA1W20139MimrSfinHiQSy+WEDs7P41w=="; - + var ca = new X509Certificate2(Convert.FromBase64String(rawDataCa)); var cert = new X509Certificate2(Convert.FromBase64String(rawData)); var chain = new X509Chain(); diff --git a/src/Cassandra.Tests/DataStax/Graph/ExecuteGraphTests.cs b/src/Cassandra.Tests/DataStax/Graph/ExecuteGraphTests.cs index 9f9f367a5..af0904b12 100644 --- a/src/Cassandra.Tests/DataStax/Graph/ExecuteGraphTests.cs +++ b/src/Cassandra.Tests/DataStax/Graph/ExecuteGraphTests.cs @@ -151,7 +151,7 @@ public void ExecuteGraph_Should_Wrap_RowSet() }; var rsMock = new Mock(); rsMock.Setup(r => r.GetEnumerator()).Returns(() => rows.GetEnumerator()); - + _cluster = ExecuteGraphTests.GetCluster(stmt => { }, null, rsMock.Object); var session = _cluster.Connect(); var rsGraph = session.ExecuteGraph(new SimpleGraphStatement("g.V()")); @@ -181,7 +181,7 @@ public void ExecuteGraph_Should_Build_Payload_With_GraphOptions() { SimpleStatement coreStatement = null; _cluster = ExecuteGraphTests.GetCluster( - stmt => coreStatement = stmt, + stmt => coreStatement = stmt, new GraphOptions() .SetName("name1") .SetSource("My source!") @@ -208,7 +208,7 @@ public void ExecuteGraph_Should_Build_Payload_With_Statement_Properties() { SimpleStatement coreStatement = null; _cluster = ExecuteGraphTests.GetCluster( - stmt => coreStatement = stmt, + stmt => coreStatement = stmt, new GraphOptions() .SetName("name1") .SetSource("My source!") @@ -373,7 +373,7 @@ private static ICluster GetCluster( { return ExecuteGraphTests.GetCluster(executeCallback, graphOptions, stmt => rs ?? new RowSet()); } - + private static ICluster GetCluster( Action executeCallback, GraphOptions graphOptions, Func rs) { @@ -387,12 +387,12 @@ private static ICluster GetCluster( return Cluster.BuildFrom( new FakeInitializer( - config, + config, new List { new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042), new IPEndPoint(IPAddress.Parse("1.2.3.4"), 9042) - }), + }), new List()); } diff --git a/src/Cassandra.Tests/DataStax/Graph/GraphNodeGraphSON1Tests.cs b/src/Cassandra.Tests/DataStax/Graph/GraphNodeGraphSON1Tests.cs index eab26f3df..98209b434 100644 --- a/src/Cassandra.Tests/DataStax/Graph/GraphNodeGraphSON1Tests.cs +++ b/src/Cassandra.Tests/DataStax/Graph/GraphNodeGraphSON1Tests.cs @@ -113,7 +113,7 @@ public void To_T_Should_Allow_Serializable_Types() GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", BigInteger.Parse("22")); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", "22"); GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); - GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", (Guid?) Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); + GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", (Guid?)Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", (TimeUuid)Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); } @@ -121,7 +121,7 @@ public void To_T_Should_Allow_Serializable_Types() public void To_Should_Throw_For_Not_Supported_Types() { const string json = "{\"result\": \"123\"}"; - var types = new [] { typeof(UIntPtr), typeof(IntPtr), typeof(StringBuilder) }; + var types = new[] { typeof(UIntPtr), typeof(IntPtr), typeof(StringBuilder) }; foreach (var t in types) { Assert.Throws(() => new GraphNode(json).To(t)); @@ -184,7 +184,7 @@ public void Should_Allow_Nested_Properties_For_Object_Trees() "}}"); Assert.AreEqual(1, result.something.inTheAir); IEnumerable values = result.everything.isAwesome; - CollectionAssert.AreEqual(new [] { "1", "2", "zeta" }, values.Select(x => x.ToString())); + CollectionAssert.AreEqual(new[] { "1", "2", "zeta" }, values.Select(x => x.ToString())); Assert.AreEqual(0.6D, result.a.b.c); } @@ -290,10 +290,10 @@ public void ToVertex_Should_Convert_To_Vertex() dynamic nameProp = vertex.Properties["name"].ToArray(); Assert.NotNull(nameProp); Assert.NotNull(nameProp[0].id); - + // Validate properties var properties = vertex.GetProperties(); - CollectionAssert.AreEquivalent(new[] {"name", "age"}, properties.Select(p => p.Name)); + CollectionAssert.AreEquivalent(new[] { "name", "age" }, properties.Select(p => p.Name)); var nameProperty = vertex.GetProperty("name"); Assert.NotNull(nameProperty); Assert.AreEqual("j", nameProperty.Value.ToString()); @@ -302,7 +302,7 @@ public void ToVertex_Should_Convert_To_Vertex() Assert.NotNull(ageProperty); Assert.AreEqual(34, ageProperty.Value.To()); Assert.AreEqual(0, ageProperty.GetProperties().Count()); - + //Is convertible Assert.NotNull((Vertex)result); //Any enumeration of graph result can be casted to vertex @@ -377,7 +377,7 @@ public void ToEdge_Should_Convert() var result = new GraphNode("{" + "\"result\":{" + "\"id\":{" + - "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"label\":\"knows\"," + "\"type\":\"edge\"," + @@ -401,9 +401,9 @@ public void ToEdge_Should_Convert() Assert.NotNull(property); Assert.AreEqual("weight", property.Name); Assert.AreEqual(1.5D, property.Value.To()); - + Assert.Null(edge.GetProperty("nonExistentProperty")); - + //Is convertible Assert.NotNull((Edge)result); //Any enumeration of graph result can be casted to edge @@ -427,7 +427,7 @@ public void ToEdge_Should_Not_Throw_When_The_Properties_Is_Not_Present() { var edge = GraphNodeGraphSON1Tests.GetGraphNode("{" + "\"id\":{" + - "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"label\":\"knows\"," + "\"type\":\"edge\"," + @@ -448,11 +448,11 @@ public void ToEdge_Should_Throw_When_Required_Attributes_Are_Not_Present() "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"" + "}").ToEdge()); - + Assert.Throws(() => GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"id\":{" + - "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"" + @@ -462,7 +462,7 @@ public void ToEdge_Should_Throw_When_Required_Attributes_Are_Not_Present() [Test] public void ToPath_Should_Convert() { - const string pathJson = "{\"result\":" + + const string pathJson = "{\"result\":" + "{" + " \"labels\": [" + " [\"a\"]," + @@ -564,15 +564,15 @@ public void ToPath_Should_Convert() Assert.AreEqual("person", path.Objects.First().ToVertex().Label); Assert.AreEqual("knows", path.Objects.Skip(1).First().ToEdge().Label); //Verify implicit result - var path2 = (Path) result; + var path2 = (Path)result; CollectionAssert.AreEqual(path.Labels, path2.Labels); Assert.AreEqual(path.Objects.Count, path2.Objects.Count); - var path3 = (IPath) path; + var path3 = (IPath)path; Assert.AreEqual(path.Objects.Count, path3.Objects.Count); var path4 = result.To(); Assert.AreEqual(path.Objects.Count, path4.Objects.Count); } - + [Test] public void Should_Be_Serializable() { diff --git a/src/Cassandra.Tests/DataStax/Insights/InsightTypeConverterTests.cs b/src/Cassandra.Tests/DataStax/Insights/InsightTypeConverterTests.cs index 0beac1537..4cd414c1a 100644 --- a/src/Cassandra.Tests/DataStax/Insights/InsightTypeConverterTests.cs +++ b/src/Cassandra.Tests/DataStax/Insights/InsightTypeConverterTests.cs @@ -34,7 +34,7 @@ public void Should_WriteNull_When_NullObjectIsProvided() sut.WriteJson(mockWriter, null, new JsonSerializer()); Mock.Get(mockWriter).Verify(mock => mock.WriteNull(), Times.Once); } - + [Test] public void Should_WriteEvent_When_EventEnumIsProvided() { @@ -43,7 +43,7 @@ public void Should_WriteEvent_When_EventEnumIsProvided() sut.WriteJson(mockWriter, InsightType.Event, new JsonSerializer()); Mock.Get(mockWriter).Verify(mock => mock.WriteValue((object)"EVENT"), Times.Once); } - + [Test] public void Should_ReturnTrue_When_InsightTypeEnumIsProvided() { diff --git a/src/Cassandra.Tests/DataStax/Insights/InsightsClientTests.cs b/src/Cassandra.Tests/DataStax/Insights/InsightsClientTests.cs index c623f069f..1d4f68cfb 100644 --- a/src/Cassandra.Tests/DataStax/Insights/InsightsClientTests.cs +++ b/src/Cassandra.Tests/DataStax/Insights/InsightsClientTests.cs @@ -74,7 +74,7 @@ public void Should_LogFiveTimes_When_ThereAreMoreThanFiveErrorsOnStartupMessageS cc => cc.UnsafeSendQueryRequestAsync( "CALL InsightsRpc.reportInsight(?)", It.IsAny()); - Mock.Get(cluster.Metadata.ControlConnection).Setup(mockExpression).ReturnsAsync((Response) null); + Mock.Get(cluster.Metadata.ControlConnection).Setup(mockExpression).ReturnsAsync((Response)null); target.Init(); @@ -113,12 +113,12 @@ public void Should_ResetErrorCounterForLogging_When_ThereSendMessageIsSuccessful It.IsAny()); Mock.Get(cluster.Metadata.ControlConnection) .SetupSequence(mockExpression) - .ReturnsAsync((Response) null) + .ReturnsAsync((Response)null) .ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void)) - .ReturnsAsync((Response) null) - .ReturnsAsync((Response) null) + .ReturnsAsync((Response)null) + .ReturnsAsync((Response)null) .ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void)) - .ReturnsAsync((Response) null); + .ReturnsAsync((Response)null); target.Init(); @@ -540,13 +540,13 @@ private IInternalCluster GetCluster(bool withProfiles, int eventDelayMillisecond var hostIp2 = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042); metadata.SetResolvedContactPoints(new Dictionary> { - { + { new HostnameContactPoint( - config.DnsResolver, - config.ProtocolOptions, - config.ServerNameResolver, - config.KeepContactPointsUnresolved, - "localhost"), + config.DnsResolver, + config.ProtocolOptions, + config.ServerNameResolver, + config.KeepContactPointsUnresolved, + "localhost"), new[] { new ConnectionEndPoint(hostIp, config.ServerNameResolver, null) } } }); metadata.AddHost(hostIp); @@ -575,7 +575,7 @@ private Configuration GetConfig(int eventDelayMilliseconds, bool withProfiles) null, null), ProtocolOptions = new ProtocolOptions().SetCompression(CompressionType.Snappy), - PoolingOptions = new PoolingOptions() + PoolingOptions = new PoolingOptions() .SetCoreConnectionsPerHost(HostDistance.Remote, 5) .SetCoreConnectionsPerHost(HostDistance.Local, 1) .SetHeartBeatInterval(10000), @@ -583,7 +583,7 @@ private Configuration GetConfig(int eventDelayMilliseconds, bool withProfiles) QueryOptions = new QueryOptions() .SetConsistencyLevel(ConsistencyLevel.All) .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial), - ExecutionProfiles = withProfiles + ExecutionProfiles = withProfiles ? new Dictionary { { diff --git a/src/Cassandra.Tests/DataStax/Insights/InsightsSupportVerifierTests.cs b/src/Cassandra.Tests/DataStax/Insights/InsightsSupportVerifierTests.cs index 322e88e28..6d321805f 100644 --- a/src/Cassandra.Tests/DataStax/Insights/InsightsSupportVerifierTests.cs +++ b/src/Cassandra.Tests/DataStax/Insights/InsightsSupportVerifierTests.cs @@ -47,7 +47,7 @@ public void Should_ReturnFalse_When_OneNode_6_0_5_AndOneNode_6_0_4() Assert.IsFalse(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnTrue_When_OneNode_6_1_0_AndOneNode_6_0_5() { @@ -58,7 +58,7 @@ public void Should_ReturnTrue_When_OneNode_6_1_0_AndOneNode_6_0_5() Assert.IsTrue(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnTrue_When_TwoNodes_6_0_5() { @@ -69,7 +69,7 @@ public void Should_ReturnTrue_When_TwoNodes_6_0_5() Assert.IsTrue(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnFalse_When_TwoNodes_6_0_4() { @@ -91,7 +91,7 @@ public void Should_ReturnFalse_When_OneNode5_1_12() Assert.IsFalse(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnTrue_When_OneNode5_1_13() { @@ -102,7 +102,7 @@ public void Should_ReturnTrue_When_OneNode5_1_13() Assert.IsTrue(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnTrue_When_OneNode5_2_0() { @@ -124,7 +124,7 @@ public void Should_ReturnTrue_When_OneNode6_0_5() Assert.IsTrue(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnTrue_When_OneNode6_0_5_alpha() { @@ -135,7 +135,7 @@ public void Should_ReturnTrue_When_OneNode6_0_5_alpha() Assert.IsTrue(target.SupportsInsights(cluster)); } - + [Test] public void Should_ReturnFalse_When_OneNode6_0_4() { diff --git a/src/Cassandra.Tests/DataStax/Insights/MessageFactories/InsightsMessageFactoryTests.cs b/src/Cassandra.Tests/DataStax/Insights/MessageFactories/InsightsMessageFactoryTests.cs index 2cda828e7..4a1fc9d62 100644 --- a/src/Cassandra.Tests/DataStax/Insights/MessageFactories/InsightsMessageFactoryTests.cs +++ b/src/Cassandra.Tests/DataStax/Insights/MessageFactories/InsightsMessageFactoryTests.cs @@ -232,10 +232,10 @@ private IInternalCluster GetCluster() ControlConnection = Mock.Of() }; var contactPoint = new HostnameContactPoint( - config.DnsResolver, - config.ProtocolOptions, - config.ServerNameResolver, - config.KeepContactPointsUnresolved, + config.DnsResolver, + config.ProtocolOptions, + config.ServerNameResolver, + config.KeepContactPointsUnresolved, "localhost"); var connectionEndPoint = new ConnectionEndPoint( new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9011), config.ServerNameResolver, contactPoint); diff --git a/src/Cassandra.Tests/DataStax/Search/DateRangeSerializerTests.cs b/src/Cassandra.Tests/DataStax/Search/DateRangeSerializerTests.cs index 6ed001122..a5a257f4b 100644 --- a/src/Cassandra.Tests/DataStax/Search/DateRangeSerializerTests.cs +++ b/src/Cassandra.Tests/DataStax/Search/DateRangeSerializerTests.cs @@ -32,7 +32,7 @@ public void Serialize_Deserialize_Test() { var serialized = serializer.Serialize(4, value); // Use a buffer at a different index than 0 - var buffer = DateRangeSerializerTests.JoinBuffers(new[] {new byte[10], serialized}, serialized.Length + 10); + var buffer = DateRangeSerializerTests.JoinBuffers(new[] { new byte[10], serialized }, serialized.Length + 10); var deserialized = serializer.Deserialize(4, buffer, 10, serialized.Length, serializer.TypeInfo); Assert.AreEqual(value, deserialized); } diff --git a/src/Cassandra.Tests/DataStax/Search/DateRangeTests.cs b/src/Cassandra.Tests/DataStax/Search/DateRangeTests.cs index 34a7ebdb9..ba782b2b8 100644 --- a/src/Cassandra.Tests/DataStax/Search/DateRangeTests.cs +++ b/src/Cassandra.Tests/DataStax/Search/DateRangeTests.cs @@ -24,24 +24,24 @@ namespace Cassandra.Tests.DataStax.Search public class DateRangeTests : BaseUnitTest { internal static readonly Tuple[] Values = { - Tuple.Create("[2010 TO 2011-12]", (string)null, + Tuple.Create("[2010 TO 2011-12]", (string)null, DateRangeTests.GetRange(DateRangeTests.UtcDate(2010), Precision.Year, DateRangeTests.UtcDate(2011, 12, 31, 23, 59, 59, 999), Precision.Month)), - Tuple.Create("[* TO 2011-8]", "[* TO 2011-08]", + Tuple.Create("[* TO 2011-8]", "[* TO 2011-08]", DateRangeTests.GetRange(null, null, DateRangeTests.UtcDate(2011, 8, 31, 23, 59, 59, 999), Precision.Month)), - Tuple.Create("[2015-01 TO *]", (string)null, + Tuple.Create("[2015-01 TO *]", (string)null, new DateRange(new DateRangeBound(DateRangeTests.UtcDate(2015), Precision.Month), DateRangeBound.Unbounded)), - Tuple.Create("[2017-01 TO 2017-02]", "[2017-01 TO 2017-02]", + Tuple.Create("[2017-01 TO 2017-02]", "[2017-01 TO 2017-02]", DateRangeTests.GetRange(DateRangeTests.UtcDate(2017), Precision.Month, DateRangeTests.UtcDate(2017, 2, 28, 23, 59, 59, 999), Precision.Month)), - Tuple.Create("[2016-1 TO 2016-02]", "[2016-01 TO 2016-02]", + Tuple.Create("[2016-1 TO 2016-02]", "[2016-01 TO 2016-02]", DateRangeTests.GetRange(DateRangeTests.UtcDate(2016), Precision.Month, DateRangeTests.UtcDate(2016, 2, 29, 23, 59, 59, 999), Precision.Month)), Tuple.Create("2012-1-2", "2012-01-02", DateRangeTests.GetRange(DateRangeTests.UtcDate(2012, 1, 2), Precision.Day)), Tuple.Create("2012-1-2T", "2012-01-02", DateRangeTests.GetRange(DateRangeTests.UtcDate(2012, 1, 2), Precision.Day)), - Tuple.Create("1-2-3T23:5:7", "0001-02-03T23:05:07", + Tuple.Create("1-2-3T23:5:7", "0001-02-03T23:05:07", DateRangeTests.GetRange(DateRangeTests.UtcDate(1, 2, 3, 23, 5, 7), Precision.Second)), Tuple.Create("2015-01T03", "2015-01-01T03", DateRangeTests.GetRange(DateRangeTests.UtcDate(2015, 1, 1, 3), Precision.Hour)), - Tuple.Create("2015-04T03:02", "2015-04-01T03:02", + Tuple.Create("2015-04T03:02", "2015-04-01T03:02", DateRangeTests.GetRange(DateRangeTests.UtcDate(2015, 4, 1, 3, 2), Precision.Minute)), - Tuple.Create("2015-04T03:02:01.081", "2015-04-01T03:02:01.081Z", + Tuple.Create("2015-04T03:02:01.081", "2015-04-01T03:02:01.081Z", DateRangeTests.GetRange(DateRangeTests.UtcDate(2015, 4, 1, 3, 2, 1, 81), Precision.Millisecond)), Tuple.Create("*", (string)null, new DateRange(DateRangeBound.Unbounded)), Tuple.Create("[* TO *]", (string)null, new DateRange(DateRangeBound.Unbounded, DateRangeBound.Unbounded)), @@ -116,7 +116,7 @@ public void Compare_Should_Be_Based_By_Byte_Order() foreach (var other in valuesToCompare) { Assert.AreEqual( - Math.Sign(value.Item2.CompareTo(other.Item2)), + Math.Sign(value.Item2.CompareTo(other.Item2)), Math.Sign(DateRange.Parse(value.Item1).CompareTo(DateRange.Parse(other.Item1))), "Comparison failed for {0} vs {1}", value.Item1, other.Item1); } diff --git a/src/Cassandra.Tests/DataTypeParserTests.cs b/src/Cassandra.Tests/DataTypeParserTests.cs index cb585c59a..af6226da2 100644 --- a/src/Cassandra.Tests/DataTypeParserTests.cs +++ b/src/Cassandra.Tests/DataTypeParserTests.cs @@ -88,23 +88,23 @@ public void Parse_DataType_Name_Multiple_Test() var dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)"); Assert.AreEqual(ColumnTypeCode.List, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Int, ((ListColumnInfo) dataType.TypeInfo).ValueTypeCode); + Assert.AreEqual(ColumnTypeCode.Int, ((ListColumnInfo)dataType.TypeInfo).ValueTypeCode); dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UUIDType)"); Assert.AreEqual(ColumnTypeCode.Set, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Uuid, ((SetColumnInfo) dataType.TypeInfo).KeyTypeCode); + Assert.AreEqual(ColumnTypeCode.Uuid, ((SetColumnInfo)dataType.TypeInfo).KeyTypeCode); dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.TimeUUIDType)"); Assert.AreEqual(ColumnTypeCode.Set, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Timeuuid, ((SetColumnInfo) dataType.TypeInfo).KeyTypeCode); + Assert.AreEqual(ColumnTypeCode.Timeuuid, ((SetColumnInfo)dataType.TypeInfo).KeyTypeCode); dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.LongType)"); Assert.AreEqual(ColumnTypeCode.Map, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo) dataType.TypeInfo).KeyTypeCode); - Assert.AreEqual(ColumnTypeCode.Bigint, ((MapColumnInfo) dataType.TypeInfo).ValueTypeCode); + Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo)dataType.TypeInfo).KeyTypeCode); + Assert.AreEqual(ColumnTypeCode.Bigint, ((MapColumnInfo)dataType.TypeInfo).ValueTypeCode); } [Test] @@ -129,7 +129,7 @@ void AssertFn(string str) void AssertComplexFn(string str) { - var dataType = DataTypeParser.ParseFqTypeName(str); + var dataType = DataTypeParser.ParseFqTypeName(str); Assert.AreEqual(ColumnTypeCode.Custom, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); Assert.AreEqual(ColumnTypeCode.List, ((VectorColumnInfo)dataType.TypeInfo).ValueTypeCode); @@ -154,14 +154,14 @@ public void Parse_DataType_Name_Frozen_Test() var dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.TimeUUIDType))"); Assert.AreEqual(ColumnTypeCode.List, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Timeuuid, ((ListColumnInfo) dataType.TypeInfo).ValueTypeCode); + Assert.AreEqual(ColumnTypeCode.Timeuuid, ((ListColumnInfo)dataType.TypeInfo).ValueTypeCode); dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))"); Assert.AreEqual(ColumnTypeCode.Map, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); - Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo) dataType.TypeInfo).KeyTypeCode); - Assert.AreEqual(ColumnTypeCode.List, ((MapColumnInfo) dataType.TypeInfo).ValueTypeCode); - var subType = (ListColumnInfo)(((MapColumnInfo) dataType.TypeInfo).ValueTypeInfo); + Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo)dataType.TypeInfo).KeyTypeCode); + Assert.AreEqual(ColumnTypeCode.List, ((MapColumnInfo)dataType.TypeInfo).ValueTypeCode); + var subType = (ListColumnInfo)(((MapColumnInfo)dataType.TypeInfo).ValueTypeInfo); Assert.AreEqual(ColumnTypeCode.Int, subType.ValueTypeCode); } @@ -177,7 +177,7 @@ public void Parse_DataType_Name_Udt_Test() //Udt name Assert.AreEqual("phone", dataType.Name); Assert.IsInstanceOf(dataType.TypeInfo); - var subTypes = ((UdtColumnInfo) dataType.TypeInfo).Fields; + var subTypes = ((UdtColumnInfo)dataType.TypeInfo).Fields; Assert.AreEqual(2, subTypes.Count); Assert.AreEqual("alias", subTypes[0].Name); Assert.AreEqual(ColumnTypeCode.Varchar, subTypes[0].TypeCode); @@ -205,8 +205,8 @@ public void Parse_DataType_Name_Udt_Nested_Test() Assert.AreEqual(ColumnTypeCode.Udt, dataType.TypeCode); Assert.IsInstanceOf(dataType.TypeInfo); Assert.AreEqual("address", dataType.Name); - Assert.AreEqual("tester.address", ((UdtColumnInfo) dataType.TypeInfo).Name); - var subTypes = ((UdtColumnInfo) dataType.TypeInfo).Fields; + Assert.AreEqual("tester.address", ((UdtColumnInfo)dataType.TypeInfo).Name); + var subTypes = ((UdtColumnInfo)dataType.TypeInfo).Fields; Assert.AreEqual(3, subTypes.Count); Assert.AreEqual("street,ZIP,phones", String.Join(",", subTypes.Select(s => s.Name))); Assert.AreEqual(ColumnTypeCode.Varchar, subTypes[0].TypeCode); diff --git a/src/Cassandra.Tests/DurationTests.cs b/src/Cassandra.Tests/DurationTests.cs index eceedc537..41f0cea84 100644 --- a/src/Cassandra.Tests/DurationTests.cs +++ b/src/Cassandra.Tests/DurationTests.cs @@ -188,7 +188,7 @@ public void ToTimeSpan_Should_Throw_For_Month_Not_Equals_To_Zero() [Test] public void ToTimeSpan_FromTimeSpan_Test() { - var values = Values.Select(t => t.Item1).Where(d => d.Months == 0L && d.Nanoseconds%100L == 0L); + var values = Values.Select(t => t.Item1).Where(d => d.Months == 0L && d.Nanoseconds % 100L == 0L); foreach (var value in values) { var timespan = value.ToTimeSpan(); diff --git a/src/Cassandra.Tests/ExceptionsUnitTest.cs b/src/Cassandra.Tests/ExceptionsUnitTest.cs index 4005e8eac..2eabe2ec7 100644 --- a/src/Cassandra.Tests/ExceptionsUnitTest.cs +++ b/src/Cassandra.Tests/ExceptionsUnitTest.cs @@ -31,7 +31,7 @@ public void WriteTimeoutException_BatchLog_Message_Test() StringAssert.Contains("Server timeout during batchlog write at consistency LOCALONE", ex.Message); StringAssert.Contains(" (0 peer(s) acknowledged the write over 1 required)", ex.Message); } - + [Test] public void WriteTimeoutException_Query_Message_Test() { @@ -39,7 +39,7 @@ public void WriteTimeoutException_Query_Message_Test() StringAssert.Contains("Server timeout during write query at consistency QUORUM", ex.Message); StringAssert.Contains(" (8 peer(s) acknowledged the write over 10 required)", ex.Message); } - + [Test] public void WriteFailureException_Message_Test() { @@ -63,7 +63,7 @@ public void NoHostAvailableException_Message_Includes_First_Host() { new IPEndPoint(IPAddress.Parse("10.10.0.1"), 9042), new AuthenticationException("Bad credentials") } }); Assert.AreEqual( - "All hosts tried for query failed (tried 10.10.0.1:9042: AuthenticationException 'Bad credentials')", + "All hosts tried for query failed (tried 10.10.0.1:9042: AuthenticationException 'Bad credentials')", ex.Message); } @@ -78,7 +78,7 @@ public void NoHostAvailableException_Message_Includes_Message_To_See_Errors_Prop }); Assert.AreEqual( "All hosts tried for query failed (tried 10.10.0.1:9042: AuthenticationException 'Bad credentials';" + - " 10.10.0.2:9042: AuthenticationException 'No credentials'; ...), see Errors property for more info", + " 10.10.0.2:9042: AuthenticationException 'No credentials'; ...), see Errors property for more info", ex.Message); } @@ -92,7 +92,7 @@ public void NoHostAvailableException_Message_Can_Contain_Host_Without_Info() }); Assert.AreEqual( "All hosts tried for query failed (tried 10.10.0.1:9042; 10.10.0.2:9042: AuthenticationException " + - "'No credentials')", + "'No credentials')", ex.Message); } diff --git a/src/Cassandra.Tests/ExecutionProfiles/ClusterTests.cs b/src/Cassandra.Tests/ExecutionProfiles/ClusterTests.cs index e2e4194ff..1bd61c669 100644 --- a/src/Cassandra.Tests/ExecutionProfiles/ClusterTests.cs +++ b/src/Cassandra.Tests/ExecutionProfiles/ClusterTests.cs @@ -43,10 +43,10 @@ public void Should_OnlyInitializePoliciesOnce_When_MultiplePoliciesAreProvidedWi ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbps[0], - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - seps[0], + lbps[0], + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + seps[0], new AtomicMonotonicTimestampGenerator(), null), ExecutionProfiles = new Dictionary @@ -75,7 +75,7 @@ public void Should_OnlyInitializePoliciesOnce_When_MultiplePoliciesAreProvidedWi "profile5", new ExecutionProfile(profile1, new ExecutionProfileBuilder().Build()) }, - { + { "graphProfile1", new ExecutionProfileBuilder() .WithLoadBalancingPolicy(lbps[4]) @@ -100,16 +100,16 @@ public void Should_OnlyInitializePoliciesOnce_When_MultiplePoliciesAreProvidedWi Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); - + Assert.IsTrue(lbps.Skip(1).All(lbp => lbp.InitializeCount == 1)); Assert.IsTrue(seps.Skip(1).All(sep => sep.InitializeCount == 1)); Assert.AreEqual(0, lbps[0].InitializeCount); Assert.AreEqual(0, seps[0].InitializeCount); } - + [Test] public void Should_OnlyInitializePoliciesOnce_When_NoProfileIsProvided() { @@ -120,10 +120,10 @@ public void Should_OnlyInitializePoliciesOnce_When_NoProfileIsProvided() ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbp, - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - sep, + lbp, + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + sep, new AtomicMonotonicTimestampGenerator(), null) }.Build(); @@ -134,14 +134,14 @@ public void Should_OnlyInitializePoliciesOnce_When_NoProfileIsProvided() Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); Assert.AreEqual(1, lbp.InitializeCount); Assert.AreEqual(1, sep.InitializeCount); } - + [Test] public void Should_OnlyDisposePoliciesOnce_When_MultiplePoliciesAreProvidedWithExecutionProfiles() { @@ -158,10 +158,10 @@ public void Should_OnlyDisposePoliciesOnce_When_MultiplePoliciesAreProvidedWithE ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbps[0], - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - seps[0], + lbps[0], + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + seps[0], new AtomicMonotonicTimestampGenerator(), null), ExecutionProfiles = new Dictionary @@ -183,8 +183,8 @@ public void Should_OnlyDisposePoliciesOnce_When_MultiplePoliciesAreProvidedWithE "profile5", new ExecutionProfile(profile1, new ExecutionProfileBuilder().Build()) }, - { - "graphProfile1", + { + "graphProfile1", new ExecutionProfileBuilder() .WithSpeculativeExecutionPolicy(seps[3]) .CastToClass() @@ -205,7 +205,7 @@ public void Should_OnlyDisposePoliciesOnce_When_MultiplePoliciesAreProvidedWithE Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); cluster.Dispose(); @@ -213,7 +213,7 @@ public void Should_OnlyDisposePoliciesOnce_When_MultiplePoliciesAreProvidedWithE Assert.IsTrue(seps.Skip(1).All(sep => sep.DisposeCount == 1)); Assert.AreEqual(0, seps[0].DisposeCount); } - + [Test] public void Should_OnlyDisposePoliciesOnce_When_NoProfileIsProvided() { @@ -224,10 +224,10 @@ public void Should_OnlyDisposePoliciesOnce_When_NoProfileIsProvided() ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbp, - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - sep, + lbp, + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + sep, new AtomicMonotonicTimestampGenerator(), null) }.Build(); @@ -238,14 +238,14 @@ public void Should_OnlyDisposePoliciesOnce_When_NoProfileIsProvided() Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); cluster.Dispose(); Assert.AreEqual(1, sep.DisposeCount); } - + [Test] public void Should_OnlyDisposeRelevantPolicies_When_PoliciesAreProvidedByDefaultProfile() { @@ -258,10 +258,10 @@ public void Should_OnlyDisposeRelevantPolicies_When_PoliciesAreProvidedByDefault ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbp1, - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - sep1, + lbp1, + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + sep1, new AtomicMonotonicTimestampGenerator(), null), ExecutionProfiles = new Dictionary @@ -276,7 +276,7 @@ public void Should_OnlyDisposeRelevantPolicies_When_PoliciesAreProvidedByDefault Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); cluster.Dispose(); @@ -284,7 +284,7 @@ public void Should_OnlyDisposeRelevantPolicies_When_PoliciesAreProvidedByDefault Assert.AreEqual(0, sep1.DisposeCount); Assert.AreEqual(1, sep2.DisposeCount); } - + [Test] public void Should_OnlyInitializeRelevantPolicies_When_PoliciesAreProvidedByDefaultProfile() { @@ -297,10 +297,10 @@ public void Should_OnlyInitializeRelevantPolicies_When_PoliciesAreProvidedByDefa ControlConnectionFactory = new FakeControlConnectionFactory(), ConnectionFactory = new FakeConnectionFactory(), Policies = new Cassandra.Policies( - lbp1, - new ConstantReconnectionPolicy(50), - new DefaultRetryPolicy(), - sep1, + lbp1, + new ConstantReconnectionPolicy(50), + new DefaultRetryPolicy(), + sep1, new AtomicMonotonicTimestampGenerator(), null), ExecutionProfiles = new Dictionary @@ -315,16 +315,16 @@ public void Should_OnlyInitializeRelevantPolicies_When_PoliciesAreProvidedByDefa Mock.Get(initializerMock) .Setup(i => i.GetConfiguration()) .Returns(testConfig); - + var cluster = Cluster.BuildFrom(initializerMock, new List(), testConfig); cluster.Connect(); - + Assert.AreEqual(0, lbp1.InitializeCount); Assert.AreEqual(0, sep1.InitializeCount); Assert.AreEqual(1, lbp2.InitializeCount); Assert.AreEqual(1, sep2.InitializeCount); } - + private class FakeSpeculativeExecutionPolicy : ISpeculativeExecutionPolicy { public volatile int InitializeCount; diff --git a/src/Cassandra.Tests/ExecutionProfiles/ConfigurationTests.cs b/src/Cassandra.Tests/ExecutionProfiles/ConfigurationTests.cs index 9978e7d45..8852eae38 100644 --- a/src/Cassandra.Tests/ExecutionProfiles/ConfigurationTests.cs +++ b/src/Cassandra.Tests/ExecutionProfiles/ConfigurationTests.cs @@ -32,7 +32,7 @@ public void Should_MapProfileToOptionsCorrectly_When_AllSettingsAreProvided() var lbpGraph = new RoundRobinPolicy(); var sepGraph = new ConstantSpeculativeExecutionPolicy(2000, 1); var rpGraph = new LoggingRetryPolicy(new DefaultRetryPolicy()); - var cluster = + var cluster = Cluster .Builder() .AddContactPoint("127.0.0.1") @@ -74,7 +74,7 @@ public void Should_MapProfileToOptionsCorrectly_When_AllSettingsAreProvided() Assert.AreSame(rpGraph, graphOptions.RetryPolicy); Assert.AreSame(go, graphOptions.GraphOptions); } - + [Test] public void Should_MapDefaultProfileToDefaultOptionsCorrectly_When_AllSettingsAreProvided() { @@ -82,7 +82,7 @@ public void Should_MapDefaultProfileToDefaultOptionsCorrectly_When_AllSettingsAr var lbp = new RoundRobinPolicy(); var sep = new ConstantSpeculativeExecutionPolicy(1000, 1); var rp = new LoggingRetryPolicy(new DefaultRetryPolicy()); - var cluster = + var cluster = Cluster .Builder() .AddContactPoint("127.0.0.1") @@ -134,9 +134,9 @@ public void Should_MapProfileToOptionsWithAllSettingsFromCluster_When_NoSettingI .WithLoadBalancingPolicy(lbp) .WithSpeculativeExecutionPolicy(sep) .WithRetryPolicy(rp) - .WithExecutionProfiles(opts => - { - opts.WithProfile("test1", profile => {}); + .WithExecutionProfiles(opts => + { + opts.WithProfile("test1", profile => { }); opts.WithProfile("test1Graph", profile => { }); }) .WithQueryTimeout(30) @@ -301,7 +301,7 @@ public void Should_MapProfileToOptionsWithSomeSettingsFromBaseProfile_When_ADeri Assert.AreEqual(5, options.PageSize); Assert.AreEqual(30, options.QueryAbortTimeout); Assert.AreSame(tg, options.TimestampGenerator); - + var graphOptions = cluster.Configuration.RequestOptions["test1Graph"]; Assert.AreEqual(ConsistencyLevel.Two, graphOptions.ConsistencyLevel); Assert.AreEqual(ConsistencyLevel.Serial, graphOptions.SerialConsistencyLevel); @@ -317,7 +317,7 @@ public void Should_MapProfileToOptionsWithSomeSettingsFromBaseProfile_When_ADeri Assert.IsNotNull(cluster.Configuration.GraphOptions); Assert.AreNotSame(graphOptions.GraphOptions, cluster.Configuration.GraphOptions); } - + [Test] public void Should_MapDefaultProfileToOptionsWithAllSettingsFromCluster_When_NoSettingIsProvided() { @@ -403,7 +403,7 @@ public void Should_MapDefaultProfileToOptionsWithAllSettingsFromCluster_When_NoP Assert.AreEqual(30, options.QueryAbortTimeout); Assert.AreSame(tg, options.TimestampGenerator); } - + [Test] public void Should_MapOptionsToProfileCorrectly_When_AllSettingsAreProvided() { @@ -438,7 +438,7 @@ public void Should_MapOptionsToProfileCorrectly_When_AllSettingsAreProvided() Assert.AreSame(sep, execProfile.SpeculativeExecutionPolicy); Assert.AreSame(rp, execProfile.RetryPolicy); Assert.IsNull(execProfile.GraphOptions); - + var graphExecProfile = cluster.Configuration.ExecutionProfiles["test1Graph"]; Assert.AreEqual(ConsistencyLevel.EachQuorum, graphExecProfile.ConsistencyLevel); Assert.AreEqual(ConsistencyLevel.LocalSerial, graphExecProfile.SerialConsistencyLevel); @@ -516,7 +516,7 @@ public void Should_MapOptionsToProfileWithAllSettingsFromCluster_When_NoProfileI Assert.AreSame(rp, profile.RetryPolicy); Assert.AreSame(go, profile.GraphOptions); } - + [Test] public void Should_SetLegacyProperties_When_PoliciesAreProvidedByDefaultProfile() { @@ -538,7 +538,7 @@ public void Should_SetLegacyProperties_When_PoliciesAreProvidedByDefaultProfile( .SetConsistencyLevel(ConsistencyLevel.All) .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)) .WithExecutionProfiles(opt => opt - .WithProfile("default", profile => + .WithProfile("default", profile => profile .WithLoadBalancingPolicy(lbp2) .WithSpeculativeExecutionPolicy(sep2) diff --git a/src/Cassandra.Tests/ExecutionProfiles/ExecutionProfileBuilderTests.cs b/src/Cassandra.Tests/ExecutionProfiles/ExecutionProfileBuilderTests.cs index ae0884b02..f8bcf4fab 100644 --- a/src/Cassandra.Tests/ExecutionProfiles/ExecutionProfileBuilderTests.cs +++ b/src/Cassandra.Tests/ExecutionProfiles/ExecutionProfileBuilderTests.cs @@ -25,7 +25,7 @@ public class ExecutionProfileBuilderTests { [Test] public void Should_GetAllSettingsFromBaseProfile_When_DerivedProfileHasNoSettings() - { + { var go = new GraphOptions(); var lbp = new RoundRobinPolicy(); var sep = new ConstantSpeculativeExecutionPolicy(1000, 1); @@ -52,10 +52,10 @@ public void Should_GetAllSettingsFromBaseProfile_When_DerivedProfileHasNoSetting Assert.AreEqual(ConsistencyLevel.Quorum, profile.ConsistencyLevel); Assert.AreEqual(go, profile.GraphOptions); } - + [Test] public void Should_GetNoSettingFromBaseProfile_When_DerivedProfileHasAllSettings() - { + { var go = new GraphOptions().SetName("ee"); var goProfile = new GraphOptions().SetName("tt"); var lbp = new RoundRobinPolicy(); @@ -75,7 +75,7 @@ public void Should_GetNoSettingFromBaseProfile_When_DerivedProfileHasAllSettings .WithRetryPolicy(rp); var baseProfile = baseProfileBuilder.Build(); - + var derivedProfileBuilder = new ExecutionProfileBuilder(); derivedProfileBuilder .WithLoadBalancingPolicy(lbpProfile) @@ -87,7 +87,7 @@ public void Should_GetNoSettingFromBaseProfile_When_DerivedProfileHasAllSettings .WithRetryPolicy(rpProfile); var derivedProfile = derivedProfileBuilder.Build(); - + var profile = new ExecutionProfile(baseProfile, derivedProfile); Assert.AreSame(lbpProfile, profile.LoadBalancingPolicy); diff --git a/src/Cassandra.Tests/ExecutionProfiles/RequestHandlerTests.cs b/src/Cassandra.Tests/ExecutionProfiles/RequestHandlerTests.cs index 8438e6196..14096c86b 100644 --- a/src/Cassandra.Tests/ExecutionProfiles/RequestHandlerTests.cs +++ b/src/Cassandra.Tests/ExecutionProfiles/RequestHandlerTests.cs @@ -84,7 +84,7 @@ public async Task Should_UseStatementSettings_When_StatementSettingsAreSet(Reque profile); await mockResult.RequestHandler.SendAsync().ConfigureAwait(false); - + var results = mockResult.SendResults.ToArray(); Assert.GreaterOrEqual(results.Length, 1); var timeouts = results.Select(r => r.TimeoutMillis).ToList(); @@ -139,7 +139,7 @@ public async Task Should_NotUseAnyClusterSettings_When_ExecutionProfileIsProvide profile); await mockResult.RequestHandler.SendAsync().ConfigureAwait(false); - + var results = mockResult.SendResults.ToArray(); Assert.GreaterOrEqual(results.Length, 1); var timeouts = results.Select(r => r.TimeoutMillis).ToList(); @@ -155,7 +155,7 @@ public async Task Should_NotUseAnyClusterSettings_When_ExecutionProfileIsProvide Assert.AreEqual(0, Interlocked.Read(ref sepCluster.Count)); Assert.AreEqual(0, Interlocked.Read(ref rpCluster.Count)); } - + [Test] [TestCase(RequestTypeTestCase.Batch)] [TestCase(RequestTypeTestCase.Simple)] @@ -206,31 +206,31 @@ private IEnumerable GetConsistencyLevels(RequestTypeTestCase t switch (testCase) { case RequestTypeTestCase.Batch: - return results.Select(r => ((BatchRequest) r.Request).Consistency); + return results.Select(r => ((BatchRequest)r.Request).Consistency); case RequestTypeTestCase.Bound: - return results.Select(r => ((ExecuteRequest) r.Request).Consistency); + return results.Select(r => ((ExecuteRequest)r.Request).Consistency); case RequestTypeTestCase.Simple: - return results.Select(r => ((QueryRequest) r.Request).Consistency); + return results.Select(r => ((QueryRequest)r.Request).Consistency); default: throw new InvalidOperationException(); } } - + private IEnumerable GetSerialConsistencyLevels(RequestTypeTestCase testCase, ConnectionSendResult[] results) { switch (testCase) { case RequestTypeTestCase.Batch: - return results.Select(r => ((BatchRequest) r.Request).SerialConsistency); + return results.Select(r => ((BatchRequest)r.Request).SerialConsistency); case RequestTypeTestCase.Bound: - return results.Select(r => ((ExecuteRequest) r.Request).SerialConsistency); + return results.Select(r => ((ExecuteRequest)r.Request).SerialConsistency); case RequestTypeTestCase.Simple: - return results.Select(r => ((QueryRequest) r.Request).SerialConsistency); + return results.Select(r => ((QueryRequest)r.Request).SerialConsistency); default: throw new InvalidOperationException(); } } - + private IStatement BuildStatement(RequestTypeTestCase testCase) { switch (testCase) @@ -304,8 +304,8 @@ private RequestHandlerMockResult BuildRequestHandler( mockResult.SendResults.Enqueue(new ConnectionSendResult { Request = req, TimeoutMillis = timeout }); Task.Run(async () => { - var rp = (FakeRetryPolicy) (statement.RetryPolicy ?? options.RetryPolicy); - var sep = (FakeSpeculativeExecutionPolicy) options.SpeculativeExecutionPolicy; + var rp = (FakeRetryPolicy)(statement.RetryPolicy ?? options.RetryPolicy); + var sep = (FakeSpeculativeExecutionPolicy)options.SpeculativeExecutionPolicy; if (Interlocked.Read(ref rp.Count) > 0 && Interlocked.Read(ref sep.Count) > 0) { await Task.Delay(1, cts.Token).ConfigureAwait(false); diff --git a/src/Cassandra.Tests/Extensions/ExecutionProfileBuilderExtensions.cs b/src/Cassandra.Tests/Extensions/ExecutionProfileBuilderExtensions.cs index ffaa76633..38c2f2529 100644 --- a/src/Cassandra.Tests/Extensions/ExecutionProfileBuilderExtensions.cs +++ b/src/Cassandra.Tests/Extensions/ExecutionProfileBuilderExtensions.cs @@ -22,7 +22,7 @@ internal static class ExecutionProfileBuilderExtensions { public static ExecutionProfileBuilder CastToClass(this IExecutionProfileBuilder builder) { - return (ExecutionProfileBuilder) builder; + return (ExecutionProfileBuilder)builder; } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/Extensions/NumericTypeConstraint.cs b/src/Cassandra.Tests/Extensions/NumericTypeConstraint.cs index 726d42a4e..3f28d318d 100644 --- a/src/Cassandra.Tests/Extensions/NumericTypeConstraint.cs +++ b/src/Cassandra.Tests/Extensions/NumericTypeConstraint.cs @@ -21,7 +21,7 @@ namespace Cassandra.Tests.Extensions /// /// A NUnit constraint designed to enforce strict equality (no coersion) on numeric values. /// - public class NumericTypeConstraint : Constraint where T: struct + public class NumericTypeConstraint : Constraint where T : struct { private readonly T _expected; @@ -31,7 +31,7 @@ public NumericTypeConstraint(T expected) { _expected = expected; } - + public override ConstraintResult ApplyTo(TActual actual) { var areEqual = _expected.Equals(actual); diff --git a/src/Cassandra.Tests/Extensions/Serializers/BigDecimalSerializer.cs b/src/Cassandra.Tests/Extensions/Serializers/BigDecimalSerializer.cs index 1463b4fa5..5e4e7dd89 100644 --- a/src/Cassandra.Tests/Extensions/Serializers/BigDecimalSerializer.cs +++ b/src/Cassandra.Tests/Extensions/Serializers/BigDecimalSerializer.cs @@ -44,7 +44,7 @@ public override byte[] Serialize(ushort protocolVersion, BigDecimal value) { var scaleBuffer = BeConverter.GetBytes(value.Scale); var valueBuffer = _bigIntegerSerializer.Serialize(protocolVersion, value.UnscaledValue); - return Utils.JoinBuffers(new[] {scaleBuffer, valueBuffer}, scaleBuffer.Length + valueBuffer.Length); + return Utils.JoinBuffers(new[] { scaleBuffer, valueBuffer }, scaleBuffer.Length + valueBuffer.Length); } } @@ -65,7 +65,7 @@ public BigDecimal(int scale, BigInteger unscaledValue) public override string ToString() { var intString = UnscaledValue.ToString(); - if (Scale == 0) + if (Scale == 0) { return intString; } diff --git a/src/Cassandra.Tests/Extensions/Serializers/UdtSerializerWrapper.cs b/src/Cassandra.Tests/Extensions/Serializers/UdtSerializerWrapper.cs index dc738314e..2566c5274 100644 --- a/src/Cassandra.Tests/Extensions/Serializers/UdtSerializerWrapper.cs +++ b/src/Cassandra.Tests/Extensions/Serializers/UdtSerializerWrapper.cs @@ -36,7 +36,7 @@ public override byte[] Serialize(ushort protocolVersion, object value) SerializationCounter++; if (_fixedValue) { - return Encoding.UTF8.GetBytes("DUMMY UDT SERIALIZED"); + return Encoding.UTF8.GetBytes("DUMMY UDT SERIALIZED"); } return base.Serialize(protocolVersion, value); } @@ -46,7 +46,7 @@ public override object Deserialize(ushort protocolVersion, byte[] buffer, int of DeserializationCounter++; if (_fixedValue) { - return Utils.SliceBuffer(buffer, offset, length); + return Utils.SliceBuffer(buffer, offset, length); } return base.Deserialize(protocolVersion, buffer, offset, length, typeInfo); } diff --git a/src/Cassandra.Tests/FrameParserTests.cs b/src/Cassandra.Tests/FrameParserTests.cs index b8f30c8e9..0ea362e9e 100644 --- a/src/Cassandra.Tests/FrameParserTests.cs +++ b/src/Cassandra.Tests/FrameParserTests.cs @@ -44,7 +44,7 @@ public void Should_Parse_ErrorResponse_Of_Syntax_Error() var ex = IsErrorResponse(response); Assert.AreEqual("Test syntax error", ex.Message); } - + [Test] public void Should_Parse_ErrorResponse_With_Warnings() { @@ -61,11 +61,11 @@ public void Should_Parse_ErrorResponse_With_Warnings() public void Should_Parse_ErrorResponse_For_Read_Failure_Under_Protocol_V4() { // - var additional = new byte[] {0, (byte) ConsistencyLevel.LocalQuorum} // Consistency level - .Concat(new byte[] {0, 0, 0, 1}) // Received - .Concat(new byte[] {0, 0, 0, 3}) // Required - .Concat(new byte[] {0, 0, 0, 2}) // Failures (int) - .Concat(new byte[] {1}); // Data present + var additional = new byte[] { 0, (byte)ConsistencyLevel.LocalQuorum } // Consistency level + .Concat(new byte[] { 0, 0, 0, 1 }) // Received + .Concat(new byte[] { 0, 0, 0, 3 }) // Required + .Concat(new byte[] { 0, 0, 0, 2 }) // Failures (int) + .Concat(new byte[] { 1 }); // Data present var body = GetErrorBody(ReadFailureErrorCode, "Test error message", additional); var response = GetResponse(body, ProtocolVersion.V4); var ex = IsErrorResponse(response); @@ -81,13 +81,13 @@ public void Should_Parse_ErrorResponse_For_Read_Failure_Under_Protocol_V4() public void Should_Parse_ErrorResponse_For_Read_Failure_Under_Latest_Protocol() { // - var additional = new byte[] {0, (byte) ConsistencyLevel.LocalQuorum} // Consistency level - .Concat(new byte[] {0, 0, 0, 2}) // Received - .Concat(new byte[] {0, 0, 0, 3}) // Required - .Concat(new byte[] {0, 0, 0, 1}) // Reasons length (int) - .Concat(new byte[] {4, 10, 10, 0, 1}) // Reasons first item IP - .Concat(new byte[] {0, 5}) // Reasons first item code - .Concat(new byte[] {0}); // Data present + var additional = new byte[] { 0, (byte)ConsistencyLevel.LocalQuorum } // Consistency level + .Concat(new byte[] { 0, 0, 0, 2 }) // Received + .Concat(new byte[] { 0, 0, 0, 3 }) // Required + .Concat(new byte[] { 0, 0, 0, 1 }) // Reasons length (int) + .Concat(new byte[] { 4, 10, 10, 0, 1 }) // Reasons first item IP + .Concat(new byte[] { 0, 5 }) // Reasons first item code + .Concat(new byte[] { 0 }); // Data present var body = GetErrorBody(ReadFailureErrorCode, "Test error message", additional); var response = GetResponse(body); var ex = IsErrorResponse(response); @@ -106,11 +106,11 @@ public void Should_Parse_ErrorResponse_For_Read_Failure_Under_Latest_Protocol() public void Should_Parse_ErrorResponse_For_Write_Failure_Under_Protocol_V4() { // - var additional = new byte[] {0, (byte) ConsistencyLevel.All} // Consistency level - .Concat(new byte[] {0, 0, 0, 1}) // Received - .Concat(new byte[] {0, 0, 0, 3}) // Required - .Concat(new byte[] {0, 0, 0, 2}) // Failures (int) - .Concat(new byte[] {0, (byte) "SIMPLE".Length}) // WriteType length + var additional = new byte[] { 0, (byte)ConsistencyLevel.All } // Consistency level + .Concat(new byte[] { 0, 0, 0, 1 }) // Received + .Concat(new byte[] { 0, 0, 0, 3 }) // Required + .Concat(new byte[] { 0, 0, 0, 2 }) // Failures (int) + .Concat(new byte[] { 0, (byte)"SIMPLE".Length }) // WriteType length .Concat(Encoding.UTF8.GetBytes("SIMPLE")); // WriteType text var body = GetErrorBody(WriteFailureErrorCode, "Test error message", additional); @@ -128,13 +128,13 @@ public void Should_Parse_ErrorResponse_For_Write_Failure_Under_Protocol_V4() public void Should_Parse_ErrorResponse_For_Write_Failure_Under_Latest_Protocol() { // - var additional = new byte[] {0, (byte) ConsistencyLevel.Quorum} // Consistency level - .Concat(new byte[] {0, 0, 0, 2}) // Received - .Concat(new byte[] {0, 0, 0, 3}) // Required - .Concat(new byte[] {0, 0, 0, 1}) // Reasons length (int) - .Concat(new byte[] {4, 12, 10, 0, 1}) // Reasons first item IP - .Concat(new byte[] {0, 4}) // Reasons first item code - .Concat(new byte[] {0, (byte) "COUNTER".Length}) // WriteType length + var additional = new byte[] { 0, (byte)ConsistencyLevel.Quorum } // Consistency level + .Concat(new byte[] { 0, 0, 0, 2 }) // Received + .Concat(new byte[] { 0, 0, 0, 3 }) // Required + .Concat(new byte[] { 0, 0, 0, 1 }) // Reasons length (int) + .Concat(new byte[] { 4, 12, 10, 0, 1 }) // Reasons first item IP + .Concat(new byte[] { 0, 4 }) // Reasons first item code + .Concat(new byte[] { 0, (byte)"COUNTER".Length }) // WriteType length .Concat(Encoding.UTF8.GetBytes("COUNTER")); // WriteType text var body = GetErrorBody(WriteFailureErrorCode, "Test error message", additional); @@ -153,7 +153,7 @@ public void Should_Parse_ErrorResponse_For_Write_Failure_Under_Latest_Protocol() private static byte[] GetHeaderBuffer(int length, HeaderFlags flags = 0) { - var headerBuffer = new byte[] {0x80 | (int) Version, (byte) flags, 0, 0, ErrorResponse.OpCode} + var headerBuffer = new byte[] { 0x80 | (int)Version, (byte)flags, 0, 0, ErrorResponse.OpCode } .Concat(BeConverter.GetBytes(length)); return headerBuffer.ToArray(); } @@ -177,15 +177,15 @@ private static Response GetResponse(byte[] body, ProtocolVersion version = Versi private static byte[] GetProtocolString(string value) { var textBuffer = Encoding.UTF8.GetBytes(value); - return BeConverter.GetBytes((ushort) textBuffer.Length).Concat(textBuffer).ToArray(); + return BeConverter.GetBytes((ushort)textBuffer.Length).Concat(textBuffer).ToArray(); } private static TException IsErrorResponse(Response response) where TException : DriverException { Assert.IsInstanceOf(response); - var ex = ((ErrorResponse) response).Output.CreateException(); + var ex = ((ErrorResponse)response).Output.CreateException(); Assert.IsInstanceOf(ex); - return (TException) ex; + return (TException)ex; } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/Geometry/LineStringTests.cs b/src/Cassandra.Tests/Geometry/LineStringTests.cs index 3e2275f57..8a9f41903 100644 --- a/src/Cassandra.Tests/Geometry/LineStringTests.cs +++ b/src/Cassandra.Tests/Geometry/LineStringTests.cs @@ -33,7 +33,7 @@ public class LineStringTests : BaseUnitTest new LineString(), new LineString(new Point(-1.101, -20.2121121221211), new Point(2.01, 4.02), new Point(10.010, 14.03)) }; - + [Test] public void Should_Be_Serialized_As_GeoJson() { diff --git a/src/Cassandra.Tests/Geometry/PointTests.cs b/src/Cassandra.Tests/Geometry/PointTests.cs index c3941b1dd..cf3be478a 100644 --- a/src/Cassandra.Tests/Geometry/PointTests.cs +++ b/src/Cassandra.Tests/Geometry/PointTests.cs @@ -27,13 +27,13 @@ namespace Cassandra.Tests.Geometry { public class PointTests : BaseUnitTest { - private static readonly Point[] Values = + private static readonly Point[] Values = { new Point(1.1, 2.2), new Point(5.666, 3.1), new Point(-1.789, -900.77888) }; - + [Test] public void Should_Be_Serialized_As_GeoJson() { @@ -66,7 +66,7 @@ public class SerializationException : Exception { public SerializationException(string message) : base(message) { - + } } @@ -78,7 +78,7 @@ public void TypeSerializer_Test() { var serialized = typeSerializer.Serialize(1, item); //start from offset - serialized = new byte[] {1, 2, 3}.Concat(serialized).ToArray(); + serialized = new byte[] { 1, 2, 3 }.Concat(serialized).ToArray(); var deserialized = typeSerializer.Deserialize(1, serialized, 3, serialized.Length - 3, null); Assert.AreEqual(item, deserialized); } diff --git a/src/Cassandra.Tests/Geometry/PolygonTests.cs b/src/Cassandra.Tests/Geometry/PolygonTests.cs index 843fa304b..a74f9e248 100644 --- a/src/Cassandra.Tests/Geometry/PolygonTests.cs +++ b/src/Cassandra.Tests/Geometry/PolygonTests.cs @@ -93,7 +93,7 @@ public void ToString_Should_Retrieve_Wkt_Representation() { Assert.AreEqual("POLYGON EMPTY", new Polygon().ToString()); Assert.AreEqual( - "POLYGON ((1 3.1, 3 1, 3 6, 1 3))", + "POLYGON ((1 3.1, 3 1, 3 6, 1 3))", new Polygon(new Point(1, 3.1), new Point(3, 1), new Point(3, 6), new Point(1, 3)).ToString()); } } diff --git a/src/Cassandra.Tests/HostConnectionPoolTests.cs b/src/Cassandra.Tests/HostConnectionPoolTests.cs index db2752534..5fe87b6fa 100644 --- a/src/Cassandra.Tests/HostConnectionPoolTests.cs +++ b/src/Cassandra.Tests/HostConnectionPoolTests.cs @@ -46,7 +46,7 @@ public class HostConnectionPoolTests private static readonly Host Host1 = TestHelper.CreateHost("127.0.0.1"); private static readonly HashedWheelTimer Timer = new HashedWheelTimer(); private Mock _mock; - + [TearDown] public void TearDown() { @@ -72,10 +72,10 @@ private static IConnection CreateConnection(byte lastIpByte = 1, Configuration c config = GetConfig(); } return new Connection( - new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), - new ConnectionEndPoint(GetIpEndPoint(lastIpByte), config.ServerNameResolver, null), + new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), + new ConnectionEndPoint(GetIpEndPoint(lastIpByte), config.ServerNameResolver, null), config, - new StartupRequestFactory(config.StartupOptionsFactory), + new StartupRequestFactory(config.StartupOptionsFactory), NullConnectionObserver.Instance); } @@ -90,9 +90,9 @@ private static Mock GetPoolMock(Host host = null, Configurat config = GetConfig(); } return new Mock( - host, - config, - new SerializerManager(ProtocolVersion.MaxSupported), + host, + config, + new SerializerManager(ProtocolVersion.MaxSupported), new MetricsObserverFactory(new MetricsManager(new NullDriverMetricsProvider(), new DriverMetricsOptions(), false, "s1"))); } @@ -524,7 +524,7 @@ await Task.Run(() => { pool.Dispose(); }).ConfigureAwait(false); - + TestHelper.RetryAssert(() => { Assert.AreEqual(0, pool.OpenConnections); diff --git a/src/Cassandra.Tests/HostTests.cs b/src/Cassandra.Tests/HostTests.cs index 3d33f3da6..e0168def0 100644 --- a/src/Cassandra.Tests/HostTests.cs +++ b/src/Cassandra.Tests/HostTests.cs @@ -41,7 +41,7 @@ public void BringUpIfDown_Should_Allow_Multiple_Concurrent_Calls() //Should fire event only once Assert.AreEqual(1, counter); } - + [Test] public void Should_UseHostIdEmpty_When_HostIdIsNull() { @@ -51,7 +51,7 @@ public void Should_UseHostIdEmpty_When_HostIdIsNull() host.SetInfo(row); Assert.AreEqual(Guid.Empty, host.HostId); } - + private IRow BuildRow(Guid? hostId) { return new TestHelper.DictionaryBasedRow(new Dictionary diff --git a/src/Cassandra.Tests/IOUnitTests.cs b/src/Cassandra.Tests/IOUnitTests.cs index e3d72e23e..ca2a04485 100644 --- a/src/Cassandra.Tests/IOUnitTests.cs +++ b/src/Cassandra.Tests/IOUnitTests.cs @@ -63,7 +63,7 @@ public void OperationState_Can_Concurrently_Get_Timeout_And_Response() state.InvokeCallback(null, 0); } }; - if ((counter++)%2 == 0) + if ((counter++) % 2 == 0) { //invert order actions = actions.Reverse().ToArray(); @@ -146,7 +146,7 @@ public void BeBinaryWriter_Close_Sets_Frame_Body_Length() var buffer = new byte[frameLength]; stream.Position = i * frameLength; stream.Read(buffer, 0, frameLength); - CollectionAssert.AreEqual(new byte[] { 2, 0, 127, 8, 0, 0, 0, 2, 9, i}, buffer); + CollectionAssert.AreEqual(new byte[] { 2, 0, 127, 8, 0, 0, 0, 2, 9, i }, buffer); } } } @@ -158,7 +158,7 @@ public void RecyclableMemoryStream_GetBufferList_Handles_Multiple_Blocks() var buffer = new byte[256]; for (var i = 0; i < buffer.Length; i++) { - buffer[i] = (byte) i; + buffer[i] = (byte)i; } var bufferPool = new RecyclableMemoryStreamManager(blockSize, 1024, 1024 * 1024 * 10); using (var stream = (RecyclableMemoryStream)bufferPool.GetStream()) diff --git a/src/Cassandra.Tests/KeyspaceMetadataTests.cs b/src/Cassandra.Tests/KeyspaceMetadataTests.cs index 5d5374b15..468920e89 100644 --- a/src/Cassandra.Tests/KeyspaceMetadataTests.cs +++ b/src/Cassandra.Tests/KeyspaceMetadataTests.cs @@ -28,76 +28,76 @@ public class KeyspaceMetadataTests public void Ctor_Should_ParseNetworkTopologyStrategyClass_When_LongClassName() { var ks = new KeyspaceMetadata( - null, - "ks2", - true, - "org.apache.cassandra.locator.NetworkTopologyStrategy", + null, + "ks2", + true, + "org.apache.cassandra.locator.NetworkTopologyStrategy", new Dictionary { { "dc1", "2" }, { "dc2", "1" } }, - new ReplicationStrategyFactory(), + new ReplicationStrategyFactory(), null); Assert.IsNotNull(ks.Strategy); Assert.AreEqual(ReplicationStrategies.NetworkTopologyStrategy, ks.StrategyClass); } - + [Test] public void Ctor_Should_ParseSimpleStrategyClass_When_LongClassName() { var ks = new KeyspaceMetadata( - null, - "ks2", - true, - "org.apache.cassandra.locator.SimpleStrategy", + null, + "ks2", + true, + "org.apache.cassandra.locator.SimpleStrategy", new Dictionary { { "replication_factor", "2" } }, - new ReplicationStrategyFactory(), + new ReplicationStrategyFactory(), null); Assert.IsNotNull(ks.Strategy); Assert.AreEqual(ReplicationStrategies.SimpleStrategy, ks.StrategyClass); } - + [Test] public void Ctor_Should_ParseNetworkTopologyStrategyClass_When_ShortClassName() { var ks = new KeyspaceMetadata( - null, - "ks2", - true, - "NetworkTopologyStrategy", + null, + "ks2", + true, + "NetworkTopologyStrategy", new Dictionary { { "dc1", "2" }, { "dc2", "1" } }, - new ReplicationStrategyFactory(), + new ReplicationStrategyFactory(), null); Assert.IsNotNull(ks.Strategy); Assert.AreEqual(ReplicationStrategies.NetworkTopologyStrategy, ks.StrategyClass); } - + [Test] public void Ctor_Should_ParseSimpleStrategyClass_When_ShortClassName() { var ks = new KeyspaceMetadata( - null, - "ks2", - true, - "SimpleStrategy", + null, + "ks2", + true, + "SimpleStrategy", new Dictionary { { "replication_factor", "2" } }, - new ReplicationStrategyFactory(), + new ReplicationStrategyFactory(), null); Assert.IsNotNull(ks.Strategy); Assert.AreEqual(ReplicationStrategies.SimpleStrategy, ks.StrategyClass); } - + [Test] public void Ctor_Should_StrategyBeNull_When_UnrecognizedStrategyClass() { var ks = new KeyspaceMetadata( - null, - "ks2", - true, - "random", + null, + "ks2", + true, + "random", new Dictionary { { "replication_factor", "2" } }, - new ReplicationStrategyFactory(), + new ReplicationStrategyFactory(), null); Assert.IsNull(ks.Strategy); @@ -110,12 +110,12 @@ public void Ctor_Should_StrategyBeNull_When_UnrecognizedStrategyClass() public void Ctor_Should_InitializeStrategyWithNull_When_NullReplicationOptionsAndStrategyClassArePassed() { var sut = new KeyspaceMetadata( - null, - "name", - false, - null, null, - new ReplicationStrategyFactory(), + "name", + false, + null, + null, + new ReplicationStrategyFactory(), null, true); Assert.IsNull(sut.Strategy); @@ -166,7 +166,7 @@ public void Ctor_Should_InitializeStrategyClassWithNonNull_When_NullReplicationO null, "name", true, "SimpleStrategy", null, new ReplicationStrategyFactory(), null, true); Assert.IsNotNull(sut.StrategyClass); } - + [Test] public void Ctor_Should_InitializeStrategyWithNull_When_NonNullReplicationOptionsArePassedButNullStrategyClassIsPassed() { diff --git a/src/Cassandra.Tests/LocalDateTests.cs b/src/Cassandra.Tests/LocalDateTests.cs index 296e5d598..18d491242 100644 --- a/src/Cassandra.Tests/LocalDateTests.cs +++ b/src/Cassandra.Tests/LocalDateTests.cs @@ -23,7 +23,7 @@ namespace Cassandra.Tests [TestFixture] public class LocalDateTests { - private static readonly Tuple[] Values = + private static readonly Tuple[] Values = { Tuple.Create(new LocalDate(1970, 1, 1), 2147483648U), Tuple.Create(new LocalDate(2010, 8, 5), 2147498474U), @@ -124,7 +124,7 @@ public void Should_Support_Operators() [Test] public void ToString_Should_Return_String_Representation() { - var values = new [] + var values = new[] { Tuple.Create(2010, 4, 29, "2010-04-29"), Tuple.Create(2005, 8, 5, "2005-08-05"), diff --git a/src/Cassandra.Tests/LocalTimeTests.cs b/src/Cassandra.Tests/LocalTimeTests.cs index a26f85a5e..ed6dc61d3 100644 --- a/src/Cassandra.Tests/LocalTimeTests.cs +++ b/src/Cassandra.Tests/LocalTimeTests.cs @@ -137,7 +137,7 @@ public void LocalTime_Parse_Should_Return_A_New_Instance_Based_On_String_Represe Assert.AreEqual(new LocalTime(v.Item5), time); } } - + [Test] [TestCase("pt-PT")] [TestCase("es-ES")] diff --git a/src/Cassandra.Tests/Mapping/AttributeBasedTypeDefinitionTests.cs b/src/Cassandra.Tests/Mapping/AttributeBasedTypeDefinitionTests.cs index 18b40f4c3..3f57bd610 100644 --- a/src/Cassandra.Tests/Mapping/AttributeBasedTypeDefinitionTests.cs +++ b/src/Cassandra.Tests/Mapping/AttributeBasedTypeDefinitionTests.cs @@ -61,7 +61,7 @@ public void AttributeBased_Composite_PartitionKey_Test() Assert.False(definition.CompactStorage); Assert.False(definition.AllowFiltering); Assert.False(definition.ExplicitColumns); - CollectionAssert.AreEqual(new [] {Tuple.Create("Time", SortOrder.Unspecified)}, definition.ClusteringKeys); + CollectionAssert.AreEqual(new[] { Tuple.Create("Time", SortOrder.Unspecified) }, definition.ClusteringKeys); CollectionAssert.AreEqual(new[] { "name", "Slice" }, definition.PartitionKeys); } @@ -73,7 +73,7 @@ public void AttributeBased_Without_Name_For_Clustering_Key_Test() Assert.False(definition.CompactStorage); Assert.False(definition.AllowFiltering); Assert.False(definition.ExplicitColumns); - CollectionAssert.AreEqual(new [] {Tuple.Create("Id2", SortOrder.Unspecified)}, definition.ClusteringKeys); + CollectionAssert.AreEqual(new[] { Tuple.Create("Id2", SortOrder.Unspecified) }, definition.ClusteringKeys); CollectionAssert.AreEqual(new[] { "Id1" }, definition.PartitionKeys); } diff --git a/src/Cassandra.Tests/Mapping/CqlGeneratorTests.cs b/src/Cassandra.Tests/Mapping/CqlGeneratorTests.cs index 554ae528c..0e7ef2ae7 100644 --- a/src/Cassandra.Tests/Mapping/CqlGeneratorTests.cs +++ b/src/Cassandra.Tests/Mapping/CqlGeneratorTests.cs @@ -231,11 +231,11 @@ public void GenerateInsert_Without_Nulls_Test() .Column(u => u.UserId, cm => cm.WithName("ID"))); var pocoFactory = new PocoDataFactory(types); var cqlGenerator = new CqlGenerator(pocoFactory); - var values = new object[] {Guid.NewGuid(), null, 100}; + var values = new object[] { Guid.NewGuid(), null, 100 }; var cql = cqlGenerator.GenerateInsert(false, values, out object[] queryParameters); Assert.AreEqual(@"INSERT INTO USERS (ID, UserAge) VALUES (?, ?)", cql); CollectionAssert.AreEqual(values.Where(v => v != null), queryParameters); - + cql = cqlGenerator.GenerateInsert(false, values, out queryParameters, true); Assert.AreEqual(@"INSERT INTO USERS (ID, UserAge) VALUES (?, ?) IF NOT EXISTS", cql); CollectionAssert.AreEqual(values.Where(v => v != null), queryParameters); diff --git a/src/Cassandra.Tests/Mapping/DeleteTests.cs b/src/Cassandra.Tests/Mapping/DeleteTests.cs index fd862b041..5cb0c1545 100644 --- a/src/Cassandra.Tests/Mapping/DeleteTests.cs +++ b/src/Cassandra.Tests/Mapping/DeleteTests.cs @@ -42,13 +42,13 @@ public void Delete_Poco_Generates_Test() { string query = null; object[] parameters = null; - var session = GetSession((q, args) => - { + var session = GetSession((q, args) => + { query = q; parameters = args; }, new RowSet()); var mapper = new Mapper(session, new MappingConfiguration().Define(new Map().PartitionKey(s => s.Id))); - var song = new Song {Id = Guid.NewGuid()}; + var song = new Song { Id = Guid.NewGuid() }; mapper.Delete(song); Assert.AreEqual("DELETE FROM Song WHERE Id = ?", query); CollectionAssert.AreEqual(new object[] { song.Id }, parameters); diff --git a/src/Cassandra.Tests/Mapping/FetchTests.cs b/src/Cassandra.Tests/Mapping/FetchTests.cs index 9e79aa287..ed6239b90 100644 --- a/src/Cassandra.Tests/Mapping/FetchTests.cs +++ b/src/Cassandra.Tests/Mapping/FetchTests.cs @@ -45,7 +45,7 @@ public void FetchAsync_Pocos_WithCql_Empty() public void FetchAsync_Pocos_WithCql_Single_Column_Maps() { //just the userid - var usersExpected = TestDataHelper.GetUserList().Select(u => new PlainUser { UserId = u.UserId} ).ToList(); + var usersExpected = TestDataHelper.GetUserList().Select(u => new PlainUser { UserId = u.UserId }).ToList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mappingClient = GetMappingClient(rowset); var userTask = mappingClient.FetchAsync("SELECT * FROM users"); @@ -188,13 +188,13 @@ public void Fetch_Lazily_Pages() { const int pageSize = 10; const int totalPages = 4; - var rs = TestDataHelper.CreateMultipleValuesRowSet(new[] {"title", "artist"}, new[] {"Once in a Livetime", "Dream Theater"}, pageSize); - rs.PagingState = new byte[] {1}; + var rs = TestDataHelper.CreateMultipleValuesRowSet(new[] { "title", "artist" }, new[] { "Once in a Livetime", "Dream Theater" }, pageSize); + rs.PagingState = new byte[] { 1 }; SetFetchNextMethod(rs, state => { var pageNumber = state[0]; pageNumber++; - var nextRs = TestDataHelper.CreateMultipleValuesRowSet(new[] {"title", "artist"}, new[] {"Once in a Livetime " + pageNumber, "Dream Theater"}, pageSize); + var nextRs = TestDataHelper.CreateMultipleValuesRowSet(new[] { "title", "artist" }, new[] { "Once in a Livetime " + pageNumber, "Dream Theater" }, pageSize); if (pageNumber < totalPages) { nextRs.PagingState = new[] { pageNumber }; @@ -243,7 +243,7 @@ public void FetchPageAsync_Pocos_WithCqlAndOptions() var usersExpected = TestDataHelper.GetUserList(pageSize); var rs = TestDataHelper.GetUsersRowSet(usersExpected); rs.AutoPage = false; - rs.PagingState = new byte[] {1, 2, 3}; + rs.PagingState = new byte[] { 1, 2, 3 }; BoundStatement stmt = null; var sessionMock = new Mock(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns(null); @@ -323,7 +323,7 @@ public void Fetch_Maps_NullableDateTime_Test() new CqlColumn {Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof (DateTimeOffset), Index = 2} } }; - var values = new object[] { Guid.NewGuid(), "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0")}; + var values = new object[] { Guid.NewGuid(), "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0") }; var row = new Row(values, rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index)); rs.AddRow(row); var sessionMock = new Mock(MockBehavior.Strict); @@ -363,7 +363,7 @@ T[] FetchAnonymous(Func justHereToCreateAnonymousType) new CqlColumn {Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof (DateTimeOffset), Index = 1} } }; - var values = new object[] {"Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0")}; + var values = new object[] { "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0") }; var row = new Row(values, rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index)); rs.AddRow(row); values = new object[] { "Come Away with Me", null }; @@ -386,14 +386,14 @@ T[] FetchAnonymous(Func justHereToCreateAnonymousType) [Test] public void Fetch_Poco_With_Enum() { - var columns = new [] + var columns = new[] { new CqlColumn { Name = "id", Index = 0, Type = typeof(long), TypeCode = ColumnTypeCode.Bigint }, new CqlColumn { Name = "enum1", Index = 1, Type = typeof(int), TypeCode = ColumnTypeCode.Int } }; var rs = new RowSet { Columns = columns }; rs.AddRow( - new Row(new object[] {1L, 3}, columns, columns.ToDictionary(c => c.Name, c => c.Index))); + new Row(new object[] { 1L, 3 }, columns, columns.ToDictionary(c => c.Name, c => c.Index))); var config = new MappingConfiguration().Define(new Map() .ExplicitColumns() .Column(x => x.Id, cm => cm.WithName("id")) @@ -411,7 +411,7 @@ public void Fetch_Poco_With_Enum_Collections() { var columns = PocoWithEnumCollections.DefaultColumns; var rs = new RowSet { Columns = columns }; - var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; + var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary { { HairColor.Brown, TimeUuid.NewId() }, @@ -419,7 +419,7 @@ public void Fetch_Poco_With_Enum_Collections() }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = - new SortedDictionary(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); + new SortedDictionary(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value)); rs.AddRow( new Row( new object[] diff --git a/src/Cassandra.Tests/Mapping/FluentMappings/FluentUserMapping.cs b/src/Cassandra.Tests/Mapping/FluentMappings/FluentUserMapping.cs index 663f58c9d..711ac3054 100644 --- a/src/Cassandra.Tests/Mapping/FluentMappings/FluentUserMapping.cs +++ b/src/Cassandra.Tests/Mapping/FluentMappings/FluentUserMapping.cs @@ -30,9 +30,9 @@ public FluentUserMapping() PartitionKey(u => u.Id); Column(u => u.Id, cm => cm.WithName("userid")); Column(u => u.FavoriteColor, cm => cm.WithDbType()); - Column(u => u.TypeOfUser, cm => cm.WithDbType(typeof (string))); + Column(u => u.TypeOfUser, cm => cm.WithDbType(typeof(string))); Column(u => u.PreferredContact, cm => cm.WithName("preferredcontactmethod").WithDbType()); - Column(u => u.HairColor, cm => cm.WithDbType(typeof (int?))); + Column(u => u.HairColor, cm => cm.WithDbType(typeof(int?))); Column(u => u.SomeIgnoredProperty, cm => cm.Ignore()); } } diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqBatchStatementUnitTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqBatchStatementUnitTests.cs index f5da92bf5..2576956fe 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqBatchStatementUnitTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqBatchStatementUnitTests.cs @@ -50,7 +50,7 @@ public void DeleteBatch(BatchType? batchType) batch.Append(deleteCqls); batch.Execute(); - + Assert.NotNull(statement); Assert.AreEqual(batchType ?? BatchType.Logged, statement.BatchType); Assert.AreEqual(deleteGuids.Count, statement.Queries.Count); diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqEntryPointsTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqEntryPointsTests.cs index 8601b3729..8c1c09f1f 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqEntryPointsTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqEntryPointsTests.cs @@ -58,7 +58,7 @@ public void Deprecated_EntryPoint_Honors_Mapping_Defined() public void Deprecated_EntryPoint_Uses_Table_Provided() { MappingConfiguration.Global.Define(new Map().TableName("tbl1")); - var table = _session.GetTable( "linqTable"); + var table = _session.GetTable("linqTable"); Assert.AreEqual( @"SELECT BooleanValue, DateTimeValue, DecimalValue, DoubleValue, Int64Value, IntValue, StringValue, UuidValue FROM linqTable", table.ToString()); @@ -68,7 +68,7 @@ public void Deprecated_EntryPoint_Uses_Table_Provided() public void Deprecated_EntryPoint_Uses_Keyspace_Provided() { MappingConfiguration.Global.Define(new Map().TableName("tbl1")); - var table = _session.GetTable( "linqTable", "linqKs"); + var table = _session.GetTable("linqTable", "linqKs"); Assert.AreEqual( @"SELECT BooleanValue, DateTimeValue, DecimalValue, DoubleValue, Int64Value, IntValue, StringValue, UuidValue FROM linqKs.linqTable", table.ToString()); diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqExecutionProfileTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqExecutionProfileTests.cs index ed59b6007..95375732b 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqExecutionProfileTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqExecutionProfileTests.cs @@ -76,7 +76,7 @@ public async Task Should_ExecuteBatchCorrectlyWithExecutionProfile_When_Executio if (!batchV1) { - var batchStatement = (BatchStatement) statement; + var batchStatement = (BatchStatement)statement; foreach (var updateGuid in updateGuids) { var updateStatement = batchStatement.Queries.First(_ => _.QueryValues.Length == 2 && _.QueryValues[1] as Guid? == updateGuid) as SimpleStatement; @@ -121,7 +121,7 @@ public async Task Should_ExecuteCqlCommandWithExecutionProfile_When_ExecutionPro Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -154,7 +154,7 @@ public async Task Should_ExecuteCqlConditionalCommandWithExecutionProfile_When_E Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -187,7 +187,7 @@ public async Task Should_ExecuteCqlQueryWithExecutionProfile_When_ExecutionProfi Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -220,7 +220,7 @@ public async Task Should_ExecutePagedCqlQueryWithExecutionProfile_When_Execution Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -237,7 +237,7 @@ public async Task Should_ExecuteCqlQuerySingleElementWithExecutionProfile_When_E .TableName("tbl1"); var table = GetTable(session, map); var cqlFirst = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue }).First(); - + if (async) { await cqlFirst.ExecuteAsync("testProfile").ConfigureAwait(false); @@ -253,7 +253,7 @@ public async Task Should_ExecuteCqlQuerySingleElementWithExecutionProfile_When_E Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -270,7 +270,7 @@ public async Task Should_ExecuteCqlScalarQueryWithExecutionProfile_When_Executio .TableName("tbl1"); var table = GetTable(session, map); var cqlCount = table.Where(t => t.IntValue == 100).Select(t => new AllTypesEntity { DoubleValue = t.DoubleValue }).Count(); - + if (async) { await cqlCount.ExecuteAsync("testProfile").ConfigureAwait(false); diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqStatementPropertiesTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqStatementPropertiesTests.cs index 7abee9616..b3203a331 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqStatementPropertiesTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqStatementPropertiesTests.cs @@ -70,7 +70,7 @@ public async Task Should_ExecuteWithReadTimeoutMillis_When_SetReadTimeoutMillisI .Verify(s => s.ExecuteAsync(It.Is(statement => statement.ReadTimeoutMillis == 5000), It.IsAny()), Times.Once); } - + [Test] [TestCaseSource(typeof(TestCasesClass))] public async Task Should_ExecuteWithOutgoingPayload_When_SetOutgoingPayloadIsCalled(TestCase testCase) @@ -176,10 +176,10 @@ public Task Do(Table table, string method, object[] parameters) { var val = Func(table); var output = val.GetType().InvokeMember(method, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, val, parameters); - var executeMethod = output.GetType().GetMethod("ExecuteAsync", new Type[]{}); + var executeMethod = output.GetType().GetMethod("ExecuteAsync", new Type[] { }); if (executeMethod != null) { - return (Task) executeMethod.Invoke(output, new object[] { }); + return (Task)executeMethod.Invoke(output, new object[] { }); } // this means the method that was executed is from the Statement class and returns an IStatement so call ExecuteAsync on the previous output from the call chain diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlFunctionTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlFunctionTests.cs index 64723e95a..8aa640ccb 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlFunctionTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlFunctionTests.cs @@ -100,12 +100,12 @@ public void Token_Function_Constant_Linq_Test() var table = GetTable(session, new Map().TableName("tbl1")); var token = CqlToken.Create("abc1", 200L); - table.Where(t => CqlToken.Create(t.StringValue, t.Int64Value) > token).Select(t => new {t.IntValue}) + table.Where(t => CqlToken.Create(t.StringValue, t.Int64Value) > token).Select(t => new { t.IntValue }) .Execute(); Assert.AreEqual("SELECT IntValue FROM tbl1 WHERE token(StringValue, Int64Value) > token(?, ?)", query); Assert.AreEqual(token.Values, parameters); } - + [Test] public void WriteTime_Linq_Test() { @@ -117,7 +117,7 @@ public void WriteTime_Linq_Test() parameters = v; }); var table = GetTable(session, new Map().TableName("tbl")); - table.Select(x => new {WriteTime = CqlFunction.WriteTime(x.StringValue), x.StringValue, x.IntValue}).Execute(); + table.Select(x => new { WriteTime = CqlFunction.WriteTime(x.StringValue), x.StringValue, x.IntValue }).Execute(); Assert.AreEqual("SELECT WRITETIME(StringValue), StringValue, IntValue FROM tbl", query); } @@ -181,7 +181,7 @@ public void SubstractAssign_Operator_Linq_Test() .Update() .Execute(); Assert.AreEqual("UPDATE tbl SET Tags = Tags - ? WHERE Id = ?", query); - CollectionAssert.AreEqual(new object[] { new [] { "clock" }, 100L }, parameters); + CollectionAssert.AreEqual(new object[] { new[] { "clock" }, 100L }, parameters); } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlInsertUnitTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlInsertUnitTests.cs index 7cfe43fcb..d09f76996 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlInsertUnitTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlInsertUnitTests.cs @@ -34,62 +34,62 @@ private class InsertNullTable [Test] public void Insert_With_Nulls_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration()); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration()); var row = new InsertNullTable { Key = 101, Value = null }; var cqlInsert = table.Insert(row); var cql = cqlInsert.GetCqlAndValues(out object[] values); - TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] {"Key", "Value"}, - new object[] {row.Key, row.Value}, values); + TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] { "Key", "Value" }, + new object[] { row.Key, row.Value }, values); } [Test] public void Insert_Without_Nulls_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration()); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration()); var row = new InsertNullTable { Key = 102, Value = null }; var cqlInsert = table.Insert(row, false); var cql = cqlInsert.GetCqlAndValues(out object[] values); Assert.AreEqual("INSERT INTO InsertNullTable (Key) VALUES (?)", cql); - TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] {"Key"}, - new object[] {row.Key}, values); + TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] { "Key" }, + new object[] { row.Key }, values); } [Test] public void Insert_Without_Nulls_With_Table_And_Keyspace_Name_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration(), "tbl1", "ks100"); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration(), "tbl1", "ks100"); var row = new InsertNullTable { Key = 102, Value = null }; var cqlInsert = table.Insert(row, false); var cql = cqlInsert.GetCqlAndValues(out object[] values); - TestHelper.VerifyInsertCqlColumns("ks100.tbl1", cql, new[] {"Key"}, - new object[] {102}, values); + TestHelper.VerifyInsertCqlColumns("ks100.tbl1", cql, new[] { "Key" }, + new object[] { 102 }, values); } [Test] public void Insert_Without_Nulls_With_Table_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration(), "tbl1"); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration(), "tbl1"); var row = new InsertNullTable { Key = 110, Value = null }; var cqlInsert = table.Insert(row, false); var cql = cqlInsert.GetCqlAndValues(out object[] values); - TestHelper.VerifyInsertCqlColumns("tbl1", cql, new[] {"Key"}, - new object[]{ 110 }, values); + TestHelper.VerifyInsertCqlColumns("tbl1", cql, new[] { "Key" }, + new object[] { 110 }, values); } [Test] public void Insert_IfNotExists_Test() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var uuid = Guid.NewGuid(); - var row = new AllTypesDecorated { Int64Value = 202, UuidValue = uuid}; + var row = new AllTypesDecorated { Int64Value = 202, UuidValue = uuid }; var cqlInsert = table.Insert(row).IfNotExists(); var cql = cqlInsert.GetCql(out object[] values); @@ -100,7 +100,7 @@ public void Insert_IfNotExists_Test() [Test] public void Insert_IfNotExists_With_Ttl_And_Timestamp_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration()); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration()); var row = new InsertNullTable { Key = 103, Value = null }; var timestamp = DateTimeOffset.UtcNow; @@ -110,14 +110,14 @@ public void Insert_IfNotExists_With_Ttl_And_Timestamp_Test() cqlInsert.SetTimestamp(timestamp); var cql = cqlInsert.GetCqlAndValues(out object[] values); var expectedTimestamp = (timestamp - new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero)).Ticks / 10; - TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] {"Key", "Value"}, - new object[] {103, null, 86401, expectedTimestamp}, values, "IF NOT EXISTS USING TTL ? AND TIMESTAMP ?"); + TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] { "Key", "Value" }, + new object[] { 103, null, 86401, expectedTimestamp }, values, "IF NOT EXISTS USING TTL ? AND TIMESTAMP ?"); } [Test] public void Insert_IfNotExists_Without_Nulls_With_Timestamp_Test() { - var table = new Table(GetSession((_,__) => {}), new MappingConfiguration()); + var table = new Table(GetSession((_, __) => { }), new MappingConfiguration()); var row = new InsertNullTable { Key = 104, Value = null }; var timestamp = DateTimeOffset.UtcNow; @@ -126,8 +126,8 @@ public void Insert_IfNotExists_Without_Nulls_With_Timestamp_Test() cqlInsert.SetTimestamp(timestamp); var cql = cqlInsert.GetCqlAndValues(out object[] values); var expectedTimestamp = (timestamp - new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero)).Ticks / 10; - TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] {"Key"}, - new object[]{104, expectedTimestamp}, values, "IF NOT EXISTS USING TIMESTAMP ?"); + TestHelper.VerifyInsertCqlColumns("InsertNullTable", cql, new[] { "Key" }, + new object[] { 104, expectedTimestamp }, values, "IF NOT EXISTS USING TIMESTAMP ?"); } [Test] @@ -155,7 +155,7 @@ public void Insert_IfNotExists_With_Ttl() insert.SetTTL(ttl); insert.Execute(); var cql = insert.GetCqlAndValues(out object[] values); - TestHelper.VerifyInsertCqlColumns("Song", query, new[] {"Title", "Id", "Artist", "ReleaseDate"}, + TestHelper.VerifyInsertCqlColumns("Song", query, new[] { "Title", "Id", "Artist", "ReleaseDate" }, new object[] { song.Title, song.Id, song.Artist, song.ReleaseDate, ttl }, values, "IF NOT EXISTS USING TTL ?"); } } diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlSelectUnitTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlSelectUnitTests.cs index f9ab44beb..1c0f62576 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlSelectUnitTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlSelectUnitTests.cs @@ -80,37 +80,37 @@ public void Select_With_Boolean_Field_Test() var valueFalse = false; const string expectedQuery = "SELECT c FROM tbl1 WHERE a = ? AND b = ?"; var table = GetTable(session, map); - + // Using equality operator table.Where(x => x.UuidValue == id && x.BooleanValue == valueFalse).Select(x => x.StringValue).Execute(); Assert.AreEqual(expectedQuery, query); Assert.AreEqual(new object[] { id, false }, parameters); - + // Using equality operator, with inverted condition table.Where(x => x.UuidValue == id && valueTrue == x.BooleanValue).Select(x => x.StringValue).Execute(); Assert.AreEqual(expectedQuery, query); Assert.AreEqual(new object[] { id, true }, parameters); - + // Using equality operator, with constant condition table.Where(x => x.UuidValue == id && x.BooleanValue == false).Select(x => x.StringValue).Execute(); Assert.AreEqual(expectedQuery, query); Assert.AreEqual(new object[] { id, false }, parameters); - + // Using false expression table.Where(x => x.UuidValue == id && !x.BooleanValue).Select(x => x.StringValue).Execute(); Assert.AreEqual(expectedQuery, query); Assert.AreEqual(new object[] { id, false }, parameters); - + // Using true expresion only table.Where(x => x.BooleanValue).Select(x => x.StringValue).Execute(); Assert.AreEqual("SELECT c FROM tbl1 WHERE b = ?", query); Assert.AreEqual(new object[] { true }, parameters); - + // Using true expresion first table.Where(x => x.BooleanValue && x.UuidValue == id).Select(x => x.StringValue).Execute(); Assert.AreEqual("SELECT c FROM tbl1 WHERE b = ? AND a = ?", query); Assert.AreEqual(new object[] { true, id }, parameters); - + // Using true expresion table.Where(x => x.UuidValue == id && x.BooleanValue).Select(x => x.StringValue).Execute(); Assert.AreEqual(expectedQuery, query); @@ -154,17 +154,17 @@ public void Select_In_With_Composite_Keys() var table = GetTable(session, map); const string expectedQuery = "SELECT id1, id2, id3 FROM tbl1 WHERE id1 = ? AND (id2, id3) IN ?"; var id = Guid.NewGuid(); - var list = new List> {Tuple.Create("z", 1)}; + var list = new List> { Tuple.Create("z", 1) }; // Using Tuple.Create() table.Where(t => t.UuidValue == id && list.Contains(Tuple.Create(t.StringValue, t.IntValue))).Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, list}, statement.QueryValues); + Assert.AreEqual(new object[] { id, list }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using constructor table.Where(t => t.UuidValue == id && list.Contains(new Tuple(t.StringValue, t.IntValue))) .Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, list}, statement.QueryValues); + Assert.AreEqual(new object[] { id, list }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); } @@ -183,22 +183,22 @@ public void Select_In_Field_And_New() var table = GetTable(session, map); var id = Guid.NewGuid(); const string expectedQuery = "SELECT id1, id2 FROM tbl1 WHERE id1 = ? AND id2 IN ?"; - var values = new[] {"a", "b"}; + var values = new[] { "a", "b" }; // Using a field table.Where(t => t.UuidValue == id && values.Contains(t.StringValue)).Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, values}, statement.QueryValues); + Assert.AreEqual(new object[] { id, values }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using a new expression - table.Where(t => t.UuidValue == id && new[] {"a", "b"}.Contains(t.StringValue)).Execute(); + table.Where(t => t.UuidValue == id && new[] { "a", "b" }.Contains(t.StringValue)).Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, values}, statement.QueryValues); + Assert.AreEqual(new object[] { id, values }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using a list - var list = new List(new[] {"a", "b"}); + var list = new List(new[] { "a", "b" }); table.Where(t => t.UuidValue == id && list.Contains(t.StringValue)).Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, list}, statement.QueryValues); + Assert.AreEqual(new object[] { id, list }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); } @@ -224,7 +224,7 @@ public void Select_Contains_With_String_Throws() public void Select_Group_By_Projected_To_Constructor_With_Parameter() { string query = null; - var session = GetSession((q, v) => query = q, TestHelper.CreateRowSetFromSingle(new [] + var session = GetSession((q, v) => query = q, TestHelper.CreateRowSetFromSingle(new[] { new KeyValuePair("id", Guid.NewGuid()), new KeyValuePair("string_value", "hello"), @@ -242,7 +242,7 @@ public void Select_Group_By_Projected_To_Constructor_With_Parameter() var id = Guid.NewGuid(); var linqQuery = table .Where(e => e.UuidValue == id) - .GroupBy(e => new {e.UuidValue, e.StringValue}) + .GroupBy(e => new { e.UuidValue, e.StringValue }) .Select(eGrouped => new Song3(eGrouped.Key.UuidValue) { Title = eGrouped.Key.StringValue, @@ -306,7 +306,7 @@ public void Select_Group_By_Projected_To_Parameter_Less_Constructor() var linqQuery = table .Where(e => e.UuidValue == id) .GroupBy(e => new { e.UuidValue, e.StringValue }) - .Select(eGrouped => new + .Select(eGrouped => new { Id1 = eGrouped.Key.UuidValue, Id2 = eGrouped.Key.StringValue, @@ -359,11 +359,11 @@ public void Select_Contains_Test() .TableName("values"); var table = GetTable(session, map); - var values = new[] {1M, 2M}; + var values = new[] { 1M, 2M }; table.Where(t => values.Contains(t.DecimalValue)) - .Select(t => new AllTypesEntity { DateTimeValue = t.DateTimeValue}).Execute(); + .Select(t => new AllTypesEntity { DateTimeValue = t.DateTimeValue }).Execute(); Assert.AreEqual("SELECT d FROM values WHERE val2 IN ?", query); - CollectionAssert.AreEqual(new[] {values}, parameters); + CollectionAssert.AreEqual(new[] { values }, parameters); } [Test] @@ -431,7 +431,7 @@ public void Select_Project_To_Single_Type() var result = (from t in table where t.IntValue == parameter select t.DoubleValue).First().Execute(); Assert.AreEqual(123D, result); Assert.AreEqual("SELECT val FROM tbl1 WHERE id = ? LIMIT ?", query); - CollectionAssert.AreEqual(parameters, new object[] { parameter, 1}); + CollectionAssert.AreEqual(parameters, new object[] { parameter, 1 }); session = GetSession((q, v) => { @@ -458,7 +458,7 @@ public void Select_Project_Chained() .PartitionKey(t => t.UuidValue) .TableName("tbl1"); var session = GetSession( - TestDataHelper.CreateMultipleValuesRowSet(new [] {"val", "id"}, new object[] { -1D, 10 }), + TestDataHelper.CreateMultipleValuesRowSet(new[] { "val", "id" }, new object[] { -1D, 10 }), s => { statement = s; @@ -605,7 +605,7 @@ public void Select_With_All_Possible_Member_Expression_In_Where_Clause() .PartitionKey(t => t.Int64Value) .TableName("tbl1"); var table = GetTable(session, map); - var fieldWithProp = new AllTypesEntity {Int64Value = long.MaxValue}; + var fieldWithProp = new AllTypesEntity { Int64Value = long.MaxValue }; ClassWithPublicField.DecimalStaticField++; var fieldWithField = new ClassWithPublicField { GuidField = Guid.NewGuid() }; _instanceField++; @@ -627,7 +627,7 @@ public void Select_With_All_Possible_Member_Expression_In_Where_Clause() "SELECT c0, id FROM tbl1 " + "WHERE id = ? AND c0 = ? AND c1 = ? AND c2 = ? AND c3 = ? AND c4 = ? AND c5 = ? AND c6 = ?", query); - CollectionAssert.AreEqual(parameters, new object[] + CollectionAssert.AreEqual(parameters, new object[] { fieldWithProp.Int64Value, ClassWithPublicField.DoubleConstant, "0", _instanceField, InstanceProperty, date, fieldWithField.GuidField, @@ -675,8 +675,8 @@ public void Select_With_Numeric_Constants() var table = GetTable(session, map); table.Where(t => t.SbyteValue == sbyteValue && t.ShortValue == shortValue).Execute(); - - Assert.AreEqual(query, + + Assert.AreEqual(query, "SELECT sbyte_value, short_value FROM table1 WHERE sbyte_value = ? AND short_value = ?"); Assert.That(parameters[0], NumericTypeConstraint.Create(sbyteValue)); Assert.That(parameters[1], NumericTypeConstraint.Create(shortValue)); @@ -697,7 +697,7 @@ public void Select_Simple_Where() .Column(t => t.IntValue, cm => cm.WithName("int_value")) .Column(t => t.LongValue, cm => cm.WithName("long_value")) .TableName("table1"); - + var table = GetTable(session, map); var expectedQuery = "SELECT int_value, long_value FROM table1 WHERE int_value = ? AND long_value = ?"; @@ -765,46 +765,46 @@ public void Select_Tuple_Expressions() // Using Tuple.Create() table.Where(t => t.UuidValue == id && Tuple.Create(t.StringValue, t.IntValue) == tupleValue).Execute(); Assert.NotNull(statement); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using Tuple.Create() and Equals() table.Where(t => t.UuidValue == id && Tuple.Create(t.StringValue, t.IntValue).Equals(tupleValue)).Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using linq query expressions var q = from t in table where t.UuidValue == id && Tuple.Create(t.StringValue, t.IntValue).Equals(tupleValue) - select new {t.IntValue, t.StringValue, t.UuidValue}; + select new { t.IntValue, t.StringValue, t.UuidValue }; q.Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual("SELECT id3, id2, id1 FROM tbl1 WHERE id1 = ? AND (id2, id3) = ?", statement.PreparedStatement.Cql); // Using constructor table.Where(t => t.UuidValue == id && new Tuple(t.StringValue, t.IntValue) == tupleValue) .Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); expectedQuery = "SELECT id1, id2, id3 FROM tbl1 WHERE id1 = ? AND (id2, id3) = ?"; // yoda with equals table.Where(t => t.UuidValue == id && tupleValue.Equals(Tuple.Create(t.StringValue, t.IntValue))).Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); expectedQuery = "SELECT id1, id2, id3 FROM tbl1 WHERE id1 = ? AND (id2, id3) >= ?"; table.Where(t => t.UuidValue == id && - ((IComparable) Tuple.Create(t.StringValue, t.IntValue)).CompareTo(tupleValue) >= 0) + ((IComparable)Tuple.Create(t.StringValue, t.IntValue)).CompareTo(tupleValue) >= 0) .Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); expectedQuery = "SELECT id1, id2, id3 FROM tbl1 WHERE id1 = ? AND (id2, id3) < ?"; table.Where(t => t.UuidValue == id && - ((IComparable) tupleValue).CompareTo(Tuple.Create(t.StringValue, t.IntValue)) > 0) + ((IComparable)tupleValue).CompareTo(Tuple.Create(t.StringValue, t.IntValue)) > 0) .Execute(); - Assert.AreEqual(new object[] {id, tupleValue}, statement.QueryValues); + Assert.AreEqual(new object[] { id, tupleValue }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); } @@ -817,7 +817,7 @@ public void Select_Test_Not_Mapped() .Column(t => t.IntValue, cm => cm.WithName("int_value")) .Column(t => t.DoubleValue, cm => cm.WithName("double_value")) .TableName("table1"); - + var table = GetTable(session, map); var queries = new CqlQueryBase[] { diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUnitTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUnitTests.cs index 188f68a42..a4c156dbc 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUnitTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUnitTests.cs @@ -39,7 +39,7 @@ public class LinqToCqlUnitTests : MappingTestBase [Test] public void TestCqlFromLinq() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); Assert.AreEqual( (from ent in table select ent).ToString(), @@ -97,12 +97,12 @@ public void TestCqlFromLinq() (from ent in table where ent.pk == "x" || ent.ck2 == 1 select ent).ToString()); Assert.AreEqual( - (from ent in table where new[] {10, 30, 40}.Contains(ent.ck2) select ent).ToString(), + (from ent in table where new[] { 10, 30, 40 }.Contains(ent.ck2) select ent).ToString(), @"SELECT ""x_ck1"", ""x_ck2"", ""x_f1"", ""x_pk"" FROM ""x_t"" WHERE ""x_ck2"" IN ? ALLOW FILTERING"); Assert.AreEqual( @"SELECT ""x_ck1"", ""x_ck2"", ""x_f1"", ""x_pk"" FROM ""x_t"" WHERE ""x_ck2"" IN ? ALLOW FILTERING", - (from ent in table where new int[] {}.Contains(ent.ck2) select ent).ToString()); + (from ent in table where new int[] { }.Contains(ent.ck2) select ent).ToString()); Assert.AreEqual( (from ent in table where new int[] { 10, 30, 40 }.Contains(ent.ck2) select ent).Delete().ToString(), @@ -112,14 +112,14 @@ public void TestCqlFromLinq() @"INSERT INTO ""x_t"" (""x_ck1"", ""x_ck2"", ""x_f1"", ""x_pk"") VALUES (?, ?, ?, ?)", (table.Insert(new LinqDecoratedEntity() { ck1 = 1, ck2 = 2, f1 = 3, pk = "x" })).ToString()); - Assert.Throws(() => - (from ent in table where new int[] {10, 30, 40}.Contains(ent.ck2) select new {x = ent.pk, e = ent}).ToString()); + Assert.Throws(() => + (from ent in table where new int[] { 10, 30, 40 }.Contains(ent.ck2) select new { x = ent.pk, e = ent }).ToString()); } [Test] public void StartsWith_Test() { - var table = new Table(GetSession((_,__) => {})); + var table = new Table(GetSession((_, __) => { })); var query = table.Where(t => t.pk == "a" && t.ck1.StartsWith("foo") && t.pk == "bar"); var pocoData = MappingConfiguration.Global.MapperFactory.GetPocoData(); var visitor = new CqlExpressionVisitor(pocoData, "x_ts", null); @@ -148,7 +148,7 @@ public void PropertyAccess_Test() Property = "b" } }; - var table = new Table(GetSession((_,__) => {})); + var table = new Table(GetSession((_, __) => { })); var query = table.Where(t => t.pk == testObject.Property && t.ck1 == testObject.AnotherObjectProperty.Property); var pocoData = MappingConfiguration.Global.MapperFactory.GetPocoData(); var visitor = new CqlExpressionVisitor(pocoData, "x_ts", null); @@ -169,7 +169,7 @@ public void FieldAccess_Test() Field = "b" } }; - var table = new Table(GetSession((_,__) => { })); + var table = new Table(GetSession((_, __) => { })); var query = table.Where(t => t.pk == testObject.Field && t.ck1 == testObject.AnotherObjectField.Field); var pocoData = MappingConfiguration.Global.MapperFactory.GetPocoData(); var visitor = new CqlExpressionVisitor(pocoData, "x_ts", null); @@ -193,7 +193,7 @@ public void MixedFieldAndPropertyAccess_Test() Field = "b" } }; - var table = new Table(GetSession((_,__) => {})); + var table = new Table(GetSession((_, __) => { })); var query = table.Where(t => t.pk == testObject.AnotherObjectField.Property && t.ck1 == testObject.AnotherObjectProperty.Field); var pocoData = MappingConfiguration.Global.MapperFactory.GetPocoData(); var visitor = new CqlExpressionVisitor(pocoData, "x_ts", null); @@ -207,8 +207,8 @@ public void MixedFieldAndPropertyAccess_Test() [Test] public void Linq_Unlogged_Batch_Test() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); - var batch = SessionExtensions.CreateBatch(GetSession((_,__) => {}), BatchType.Unlogged); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); + var batch = SessionExtensions.CreateBatch(GetSession((_, __) => { }), BatchType.Unlogged); batch.Append(table.Insert(new LinqDecoratedEntity() { ck1 = 1, ck2 = 2, f1 = 3, pk = "x" })); batch.Append(table.Where(ent => new int[] { 10, 30, 40 }.Contains(ent.ck2)).Select(ent => new { f1 = 1223 }).Update()); batch.Append(table.Where(ent => new int[] { 10, 30, 40 }.Contains(ent.ck2)).Delete()); @@ -223,8 +223,8 @@ public void Linq_Unlogged_Batch_Test() [Test] public void Linq_Logged_Batch_Test() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); - var batch = SessionExtensions.CreateBatch(GetSession((_,__) => {}), BatchType.Logged); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); + var batch = SessionExtensions.CreateBatch(GetSession((_, __) => { }), BatchType.Logged); batch.Append(table.Insert(new LinqDecoratedEntity() { ck1 = 1, ck2 = 2, f1 = 3, pk = "x" })); batch.Append(table.Where(ent => new int[] { 10, 30, 40 }.Contains(ent.ck2)).Select(ent => new { f1 = 1223 }).Update()); batch.Append(table.Where(ent => new int[] { 10, 30, 40 }.Contains(ent.ck2)).Delete()); @@ -240,8 +240,8 @@ public void Linq_Logged_Batch_Test() public void Linq_Counter_Batch_Test() { //TODO: Write actual counter statements - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); - var batch = SessionExtensions.CreateBatch(GetSession((_,__) => {}), BatchType.Counter); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); + var batch = SessionExtensions.CreateBatch(GetSession((_, __) => { }), BatchType.Counter); batch.Append(table.Where(ent => ent.RowKey1 == 1 && ent.RowKey2 == 2).Select(_ => new CounterTestTable1 { Value = 1 }).Update()); batch.Append(table.Where(ent => ent.RowKey1 == 3 && ent.RowKey2 == 4).Select(_ => new CounterTestTable1 { Value = 1 }).Update()); Assert.AreEqual(batch.ToString().Replace("\r", ""), @@ -254,7 +254,7 @@ public void Linq_Counter_Batch_Test() [Test] public void LinqGeneratedUpdateStatementTest() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); string query; string expectedQuery; @@ -280,7 +280,7 @@ public void LinqGeneratedUpdateStatementTest() [Test] public void TestCqlFromLinqPaxosSupport() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); Assert.AreEqual( (table.Insert(new LinqDecoratedEntity { ck1 = 1, ck2 = 2, f1 = 3, pk = "x" })).IfNotExists().ToString(), @@ -299,7 +299,7 @@ public void TestCqlFromLinqPaxosSupport() [Test] public void TestCqlNullValuesLinqSupport() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); Assert.AreEqual( @"INSERT INTO ""x_t"" (""x_ck1"", ""x_ck2"", ""x_f1"", ""x_pk"") VALUES (?, ?, ?, ?)", @@ -343,7 +343,7 @@ public void LinqSelectWhereTest() (from ent in table where ent.DateTimeValue >= date select ent), (from ent in table where ent.IntValue == 0 select ent), (from ent in table where ent.StringValue == "Hello world" select ent) - + }; var expectedCqlQueries = new List() { @@ -403,7 +403,7 @@ private class AllowFilteringTestTable [Test] public void AllowFilteringTest() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var key1 = "x"; var cqlQuery = table .Where(item => item.ClusteringKey == key1 && item.Value == 1M) @@ -479,7 +479,7 @@ public void CreateTableCounterTest() [Test] public void VirtualPropertiesTest() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query1 = table.Where(e => e.Id == 10); Assert.AreEqual("SELECT \"Description\", \"Id\", \"Name\" FROM \"InheritedEntity\" WHERE \"Id\" = ?", query1.ToString()); var query2 = (from e in table where e.Id == 1 && e.Name == "MyName" select new { e.Id, e.Name, e.Description }); @@ -508,7 +508,7 @@ public void VirtualPropertiesTest() [Test] public void LinqGeneratedUpdateStatementForCounterTest() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query = table .Where(r => r.RowKey1 == 5 && r.RowKey2 == 6) .Select(r => new CounterTestTable1() { Value = 2 }) @@ -527,7 +527,7 @@ public void LinqGeneratedUpdateStatementForCounterTest() [Test] public void EmptyListTest() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var keys = new string[0]; var query = table.Where(item => keys.Contains(item.pk)); @@ -562,7 +562,7 @@ public override int Id [Test] public void Select_Specific_Columns() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query = table.Select(t => new LinqDecoratedEntity { f1 = t.f1, pk = t.pk }); Assert.AreEqual(@"SELECT ""x_f1"", ""x_pk"" FROM ""x_t"" ALLOW FILTERING", query.ToString()); } @@ -570,7 +570,7 @@ public void Select_Specific_Columns() [Test] public void Select_Count() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); Assert.AreEqual( (from ent in table select ent).Count().ToString(), @"SELECT count(*) FROM ""x_t"" ALLOW FILTERING"); @@ -579,7 +579,7 @@ public void Select_Count() [Test] public void Select_One_Columns() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query = table.Select(t => t.f1); Assert.AreEqual(@"SELECT ""x_f1"" FROM ""x_t"" ALLOW FILTERING", query.ToString()); } @@ -587,7 +587,7 @@ public void Select_One_Columns() [Test] public void Select_OrderBy_Columns() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query = table.OrderBy(t => t.UuidValue).OrderByDescending(t => t.DateTimeValue); Assert.AreEqual(@"SELECT ""BooleanValue"", ""DateTimeValue"", ""DecimalValue"", ""DoubleValue"", ""Int64Value"", ""IntValue"", ""StringValue"", ""UuidValue"" FROM ""AllTypesEntity"" ORDER BY ""UuidValue"", ""DateTimeValue"" DESC", query.ToString()); } @@ -595,8 +595,8 @@ public void Select_OrderBy_Columns() [Test] public void Select_Where_Contains() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); - var ids = new []{ 1, 2, 3}; + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); + var ids = new[] { 1, 2, 3 }; var query = table.Where(t => ids.Contains(t.IntValue) && t.Int64Value == 10); Assert.AreEqual( "SELECT \"boolean_VALUE\", \"datetime_VALUE\", \"decimal_VALUE\", \"double_VALUE\", \"int64_VALUE\"," + @@ -608,7 +608,7 @@ public void Select_Where_Contains() [Test] public void DeleteIf_With_Where_Clause() { - var table = SessionExtensions.GetTable(GetSession((_,__) => {})); + var table = SessionExtensions.GetTable(GetSession((_, __) => { })); var query = table .Where(t => t.Int64Value == 1) .DeleteIf(t => t.StringValue == "conditional!"); diff --git a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUpdateUnitTests.cs b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUpdateUnitTests.cs index b9a936e9b..8be370b3f 100644 --- a/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUpdateUnitTests.cs +++ b/src/Cassandra.Tests/Mapping/Linq/LinqToCqlUpdateUnitTests.cs @@ -81,8 +81,8 @@ public void Update_Multiple_Where_Test() .Select(t => new AllTypesEntity { StringValue = "Billy the Vision" }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("tbl1", query, new []{"string_val"}, - new [] {"id", "val2"}, new object[] {"Billy the Vision", id, 20M}, + TestHelper.VerifyUpdateCqlColumns("tbl1", query, new[] { "string_val" }, + new[] { "id", "val2" }, new object[] { "Billy the Vision", id, 20M }, parameters); } @@ -107,8 +107,8 @@ public void Update_Set_Enum_Int() .Select(t => new PlainUser { HairColor = HairColor.Red }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("tbl1", query, new []{"HairColor"}, - new [] {"UserId"}, new object[] { (int)HairColor.Red, id}, + TestHelper.VerifyUpdateCqlColumns("tbl1", query, new[] { "HairColor" }, + new[] { "UserId" }, new object[] { (int)HairColor.Red, id }, parameters); } @@ -133,8 +133,8 @@ public void Update_Set_Enum_String() .Select(t => new PlainUser { HairColor = HairColor.Red }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("tbl1", query, new []{"HairColor"}, - new [] {"UserId"}, new object[] { HairColor.Red.ToString(), id}, + TestHelper.VerifyUpdateCqlColumns("tbl1", query, new[] { "HairColor" }, + new[] { "UserId" }, new object[] { HairColor.Red.ToString(), id }, parameters); } @@ -144,7 +144,7 @@ public void Update_With_Query_Trace_Defined() TestQueryTrace(table => { var linqQuery = table.Where(x => x.IntValue == 1) - .Select(x => new AllTypesEntity { StringValue = "a"}) + .Select(x => new AllTypesEntity { StringValue = "a" }) .Update(); linqQuery.EnableTracing(); linqQuery.Execute(); @@ -178,8 +178,8 @@ public void Update_With_Keyspace_Defined_Test() .Select(t => new AllTypesEntity { StringValue = "Aṣa" }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("SomeKS.tbl1", query, new []{"string_val"}, - new [] {"id"}, new object[] { "Aṣa", id }, + TestHelper.VerifyUpdateCqlColumns("SomeKS.tbl1", query, new[] { "string_val" }, + new[] { "id" }, new object[] { "Aṣa", id }, parameters); } @@ -207,8 +207,8 @@ public void Update_If_Exists() .Select(t => new Song { Title = "When The Sun Goes Down" }) .UpdateIfExists() .Execute(); - TestHelper.VerifyUpdateCqlColumns("songs", query, new []{"title"}, - new [] {"id"}, new object[] { "When The Sun Goes Down", id }, + TestHelper.VerifyUpdateCqlColumns("songs", query, new[] { "title" }, + new[] { "id" }, new object[] { "When The Sun Goes Down", id }, parameters, "IF EXISTS"); } @@ -229,8 +229,8 @@ public void UpdateIf_With_Where_Clause() .Select(t => new AllTypesDecorated { StringValue = "updated value" }) .UpdateIf(t => t.IntValue == 100) .Execute(); - TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new []{@"""string_VALUE"""}, - new [] {@"""boolean_VALUE""", @"""double_VALUE"""}, new object[] {"updated value", true, 1d, 100}, + TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new[] { @"""string_VALUE""" }, + new[] { @"""boolean_VALUE""", @"""double_VALUE""" }, new object[] { "updated value", true, 1d, 100 }, parameters, "IF \"int_VALUE\" = ?"); } @@ -251,8 +251,8 @@ public void UpdateIf_Set_From_Variable_With_Where_Clause() .Select(t => new AllTypesDecorated { DateTimeValue = dateTimeValue }) .UpdateIf(t => t.IntValue == 100) .Execute(); - TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new []{@"""datetime_VALUE"""}, - new [] {@"""boolean_VALUE""", @"""double_VALUE"""}, new object[] {dateTimeValue, true, 1d, 100}, + TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new[] { @"""datetime_VALUE""" }, + new[] { @"""boolean_VALUE""", @"""double_VALUE""" }, new object[] { dateTimeValue, true, 1d, 100 }, parameters, "IF \"int_VALUE\" = ?"); } @@ -279,9 +279,9 @@ public void Update_Set_From_Variable_With_Where_Clause() }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new []{@"""datetime_VALUE""", @"""string_VALUE""", @"""int64_VALUE"""}, - new [] {@"""int_VALUE""", @"""boolean_VALUE""", @"""double_VALUE"""}, - new object[] {dateTimeValue, dateTimeValue.ToString(), anon.Prop1, 100, true, 1d}, + TestHelper.VerifyUpdateCqlColumns(@"""atd""", query, new[] { @"""datetime_VALUE""", @"""string_VALUE""", @"""int64_VALUE""" }, + new[] { @"""int_VALUE""", @"""boolean_VALUE""", @"""double_VALUE""" }, + new object[] { dateTimeValue, dateTimeValue.ToString(), anon.Prop1, 100, true, 1d }, parameters); } @@ -312,8 +312,8 @@ public void Update_Set_From_Other_Instances_With_Where_Clause() }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Title", "Artist", "ReleaseDate"}, - new [] {"Id"}, new object[] {other.Artist, other.Artist, DateTimeOffset.MinValue, Guid.Empty}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Title", "Artist", "ReleaseDate" }, + new[] { "Id" }, new object[] { other.Artist, other.Artist, DateTimeOffset.MinValue, Guid.Empty }, parameters); } @@ -337,8 +337,8 @@ public void Update_Set_From_New_Instance_Expression_With_Where_Clause() }) .Update() .Execute(); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Artist", "ReleaseDate"}, - new [] {"Id"}, new object[] {"The Rolling Stones".ToUpperInvariant(), new DateTimeOffset(new DateTime(1999, 12, 31)), Guid.Empty}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Artist", "ReleaseDate" }, + new[] { "Id" }, new object[] { "The Rolling Stones".ToUpperInvariant(), new DateTimeOffset(new DateTime(1999, 12, 31)), Guid.Empty }, parameters); } @@ -347,17 +347,18 @@ public void Update_With_Attribute_Based_Mapping() { string query = null; object[] parameters = null; - var session = GetSession((q, v) => { + var session = GetSession((q, v) => + { query = q; parameters = v; }); var table = new Table(session, new MappingConfiguration()); table.Where(x => x.PartitionKey == 1 && x.ClusteringKey0 == 10L).Select(x => new AttributeMappingClass { - DecimalValue = 10M + DecimalValue = 10M }).Update().Execute(); - TestHelper.VerifyUpdateCqlColumns("attr_mapping_class_table", query, new []{"decimal_value_col"}, - new [] {"partition_key", "clustering_key_0"}, new object[] {10M, 1, 10L}, parameters); + TestHelper.VerifyUpdateCqlColumns("attr_mapping_class_table", query, new[] { "decimal_value_col" }, + new[] { "partition_key", "clustering_key_0" }, new object[] { 10M, 1, 10L }, parameters); } [Test] @@ -379,10 +380,10 @@ public void Update_Dictionary_With_Substract_Assign() var table = GetTable(session, map); var id = 100L; table.Where(x => x.Id == id) - .Select(x => new CollectionTypesEntity { Favs = x.Favs.SubstractAssign("a", "b", "c")}) + .Select(x => new CollectionTypesEntity { Favs = x.Favs.SubstractAssign("a", "b", "c") }) .Update().Execute(); Assert.AreEqual("UPDATE tbl1 SET favs = favs - ? WHERE id = ?", query); - CollectionAssert.AreEquivalent(new object[]{ new [] { "a", "b", "c" }, id }, parameters); + CollectionAssert.AreEquivalent(new object[] { new[] { "a", "b", "c" }, id }, parameters); } [Test] @@ -404,23 +405,23 @@ public void Update_Where_In_With_Composite_Keys() const string expectedQuery = "UPDATE tbl1 SET val = ? WHERE id1 = ? AND (id2, id3) IN ?"; var id = Guid.NewGuid(); var value = 100L; - var list = new List> {Tuple.Create("z", 1)}; + var list = new List> { Tuple.Create("z", 1) }; // Using Tuple.Create() table.Where(t => t.UuidValue == id && list.Contains(Tuple.Create(t.StringValue, t.IntValue))) .Select(t => new AllTypesEntity { Int64Value = value }) .Update().Execute(); Assert.NotNull(statement); - CollectionAssert.AreEquivalent(new object[] {value, id, list }, statement.QueryValues); + CollectionAssert.AreEquivalent(new object[] { value, id, list }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); // Using constructor table.Where(t => t.UuidValue == id && list.Contains(new Tuple(t.StringValue, t.IntValue))) .Select(t => new AllTypesEntity { Int64Value = value }) .Update().Execute(); Assert.NotNull(statement); - CollectionAssert.AreEquivalent(new object[] {value, id, list}, statement.QueryValues); + CollectionAssert.AreEquivalent(new object[] { value, id, list }, statement.QueryValues); Assert.AreEqual(expectedQuery, statement.PreparedStatement.Cql); } - + private class TestObjectStaticProperty { public static string Property => "static"; diff --git a/src/Cassandra.Tests/Mapping/LinqAttributeBasedTypeDefinitionTests.cs b/src/Cassandra.Tests/Mapping/LinqAttributeBasedTypeDefinitionTests.cs index 59dc92899..3919aace6 100644 --- a/src/Cassandra.Tests/Mapping/LinqAttributeBasedTypeDefinitionTests.cs +++ b/src/Cassandra.Tests/Mapping/LinqAttributeBasedTypeDefinitionTests.cs @@ -31,7 +31,7 @@ public class LinqAttributeBasedColumnDefinitionTests public void AttributeBased_Without_Name_For_Clustering_Key_Test() { var definition = new LinqAttributeBasedTypeDefinition(typeof(SamplePocoWithoutClusteringKeyName), "t", "k"); - CollectionAssert.AreEqual(new [] {Tuple.Create("Id2", SortOrder.Ascending)}, definition.ClusteringKeys); + CollectionAssert.AreEqual(new[] { Tuple.Create("Id2", SortOrder.Ascending) }, definition.ClusteringKeys); CollectionAssert.AreEqual(new[] { "Id1" }, definition.PartitionKeys); } diff --git a/src/Cassandra.Tests/Mapping/MapperExecutionProfileTests.cs b/src/Cassandra.Tests/Mapping/MapperExecutionProfileTests.cs index 85079da69..dc15c962f 100644 --- a/src/Cassandra.Tests/Mapping/MapperExecutionProfileTests.cs +++ b/src/Cassandra.Tests/Mapping/MapperExecutionProfileTests.cs @@ -49,7 +49,7 @@ public void Should_ExecuteFetchWithExecutionProfile_When_ExecutionProfileIsProvi Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -70,7 +70,7 @@ public void Should_ExecuteFetchPagedWithExecutionProfile_When_ExecutionProfileIs Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -91,7 +91,7 @@ public void Should_ExecuteFirstOrDefaultWithExecutionProfile_When_ExecutionProfi Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -112,7 +112,7 @@ public void Should_ExecuteSingleOrDefaultWithExecutionProfile_When_ExecutionProf Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -133,7 +133,7 @@ public void Should_ExecuteFirstWithExecutionProfile_When_ExecutionProfileIsProvi Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -162,13 +162,13 @@ public void Should_ExecuteDeleteWithExecutionProfile_When_ExecutionProfileIsProv { string query = null; object[] parameters = null; - var session = GetSession((q, args) => - { + var session = GetSession((q, args) => + { query = q; parameters = args; }, new RowSet()); var mapper = new Mapper(session, new MappingConfiguration().Define(new Map().PartitionKey(s => s.Id))); - var song = new Song {Id = Guid.NewGuid()}; + var song = new Song { Id = Guid.NewGuid() }; if (async) { @@ -211,7 +211,7 @@ public void Should_ExecuteDeleteIfWithExecutionProfile_When_ExecutionProfileIsPr Mock.Get(session).Verify(s => s.Execute(It.IsAny(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny()), Times.Never); } - + [Test] [TestCase(true)] [TestCase(false)] @@ -226,7 +226,7 @@ public void Should_ExecuteInsertWithExecutionProfile_When_ExecutionProfileIsProv }); var song = new Song { Id = Guid.NewGuid() }; const int ttl = 600; - + if (async) { mapperAndSession.Mapper.InsertAsync(song, "testProfile", false, ttl).Wait(); @@ -259,7 +259,7 @@ public void Should_ExecuteInsertIfNotExistsWithExecutionProfile_When_ExecutionPr }); var song = new Song { Id = Guid.NewGuid(), Title = "t2", ReleaseDate = DateTimeOffset.Now }; const int ttl = 600; - + if (async) { mapperAndSession.Mapper.InsertIfNotExistsAsync(song, "testProfile", false, ttl).Wait(); diff --git a/src/Cassandra.Tests/Mapping/MappingTestBase.cs b/src/Cassandra.Tests/Mapping/MappingTestBase.cs index 9578f3446..582aa8c28 100644 --- a/src/Cassandra.Tests/Mapping/MappingTestBase.cs +++ b/src/Cassandra.Tests/Mapping/MappingTestBase.cs @@ -53,7 +53,7 @@ protected MapperAndSessionTuple GetMappingClientAndSession(Func> ge { return GetMappingClientAndSession(getRowSetFunc, null, config); } - + protected MapperAndSessionTuple GetMappingClientAndSession(Func> getRowSetFunc, Action queryCallback, MappingConfiguration config = null) { if (queryCallback == null) @@ -122,7 +122,7 @@ protected ISession GetSession(RowSet rs, Action callback .Setup(s => s.ExecuteAsync(It.IsAny(), It.IsAny())) .Returns(() => TaskHelper.ToTask(rs)) .Callback( - (stmt, execProfile) => + (stmt, execProfile) => callback((TStatement)stmt)) .Verifiable(); sessionMock @@ -167,7 +167,7 @@ protected void TestQueryTrace(Func, QueryTrace> queryExecu var clusterMock = new Mock(); clusterMock.Setup(c => c.Configuration).Returns(new Configuration()); - + var sessionMock = new Mock(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns(null); sessionMock.Setup(s => s.Cluster).Returns(clusterMock.Object); diff --git a/src/Cassandra.Tests/Mapping/Pocos/AttributeMappingClass.cs b/src/Cassandra.Tests/Mapping/Pocos/AttributeMappingClass.cs index fdace27e6..099f4b445 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/AttributeMappingClass.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/AttributeMappingClass.cs @@ -46,7 +46,7 @@ public class AttributeMappingClass [Column("decimal_value_col")] public decimal DecimalValue { get; set; } - + private static readonly IDictionary> ColumnMappings = new Dictionary> { @@ -58,7 +58,7 @@ public class AttributeMappingClass { "float_value_col", entity => entity.FloatValue }, { "partition_key", entity => entity.PartitionKey } }; - + public object[] GetParameters() { return AttributeMappingClass.ColumnMappings.Values.Select(func => func(this)).ToArray(); diff --git a/src/Cassandra.Tests/Mapping/Pocos/LinqDecoratedCaseInsensitiveEntity.cs b/src/Cassandra.Tests/Mapping/Pocos/LinqDecoratedCaseInsensitiveEntity.cs index ab1de197a..aa1b7875e 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/LinqDecoratedCaseInsensitiveEntity.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/LinqDecoratedCaseInsensitiveEntity.cs @@ -20,7 +20,7 @@ namespace Cassandra.Tests.Mapping.Pocos { - [Table(CaseSensitive=false, Name="tbl1")] + [Table(CaseSensitive = false, Name = "tbl1")] public class LinqDecoratedCaseInsensitiveEntity { [Column("i_id"), PartitionKey] diff --git a/src/Cassandra.Tests/Mapping/Pocos/PocoWithEnumCollections.cs b/src/Cassandra.Tests/Mapping/Pocos/PocoWithEnumCollections.cs index 71473d67f..2d77fbdd8 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/PocoWithEnumCollections.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/PocoWithEnumCollections.cs @@ -29,7 +29,7 @@ public class PocoWithEnumCollections public List List1 { get; set; } public IList List2 { get; set; } - + public HairColor[] Array1 { get; set; } public SortedSet Set1 { get; set; } @@ -41,7 +41,7 @@ public class PocoWithEnumCollections public Dictionary Dictionary1 { get; set; } public IDictionary Dictionary2 { get; set; } - + public SortedDictionary Dictionary3 { get; set; } public static Map DefaultMapping => new Map() diff --git a/src/Cassandra.Tests/Mapping/Pocos/PocoWithNumericTypes.cs b/src/Cassandra.Tests/Mapping/Pocos/PocoWithNumericTypes.cs index f108386df..175f5b814 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/PocoWithNumericTypes.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/PocoWithNumericTypes.cs @@ -23,7 +23,7 @@ public class PocoWithNumericTypes public int IntValue { get; set; } public short ShortValue { get; set; } - + public long LongValue { get; set; } public sbyte SbyteValue { get; set; } diff --git a/src/Cassandra.Tests/Mapping/Pocos/Song.cs b/src/Cassandra.Tests/Mapping/Pocos/Song.cs index d72d0fe01..6c25aaa12 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/Song.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/Song.cs @@ -50,7 +50,7 @@ public class Song3 { public Song3() { - + } public Song3(Guid id) diff --git a/src/Cassandra.Tests/Mapping/Pocos/VectorEntity.cs b/src/Cassandra.Tests/Mapping/Pocos/VectorEntity.cs index ddc188da5..8c2671156 100644 --- a/src/Cassandra.Tests/Mapping/Pocos/VectorEntity.cs +++ b/src/Cassandra.Tests/Mapping/Pocos/VectorEntity.cs @@ -39,7 +39,7 @@ public static VectorPoco Generate(Random r) Func> generator = () => new CqlVector(r.Next(), r.Next(), r.Next()); var vector = generator(); var vectorOfVectors = new CqlVector>(generator(), generator(), generator()); - return new VectorPoco { UuidValue = Guid.NewGuid(), VectorValue = vector, VectorOfVectorsValue = vectorOfVectors}; + return new VectorPoco { UuidValue = Guid.NewGuid(), VectorValue = vector, VectorOfVectorsValue = vectorOfVectors }; } public static void AssertEquals(VectorPoco one, VectorPoco two) diff --git a/src/Cassandra.Tests/Mapping/StatementFactoryTests.cs b/src/Cassandra.Tests/Mapping/StatementFactoryTests.cs index 39bea8976..0d989c53c 100644 --- a/src/Cassandra.Tests/Mapping/StatementFactoryTests.cs +++ b/src/Cassandra.Tests/Mapping/StatementFactoryTests.cs @@ -52,8 +52,8 @@ public async Task GetStatementAsync_Should_Prepare_Once_And_Cache() var concurrentTasks = 1000; var semaphore = new SemaphoreSlim(0, concurrentTasks); - - var tasks = + + var tasks = Enumerable.Range(0, concurrentTasks) .Select(_ => Task.Run( async () => @@ -68,22 +68,22 @@ public async Task GetStatementAsync_Should_Prepare_Once_And_Cache() await Task.WhenAll(tasks).ConfigureAwait(false); var boundStatementsSet = new HashSet( - tasks.Select(t => (BoundStatement)t.Result), + tasks.Select(t => (BoundStatement)t.Result), new ReferenceEqualityComparer()); - + var preparedStatementsSet = new HashSet( - tasks.Select(t => ((BoundStatement)t.Result).PreparedStatement), + tasks.Select(t => ((BoundStatement)t.Result).PreparedStatement), new ReferenceEqualityComparer()); - + var createdPreparedStatementsSet = new HashSet( - createdPreparedStatementsBag.Select(t => t.Result), + createdPreparedStatementsBag.Select(t => t.Result), new ReferenceEqualityComparer()); Assert.AreEqual(1, preparedStatementsSet.Count); Assert.AreEqual(concurrentTasks, boundStatementsSet.Count); Assert.AreEqual(1, createdPreparedStatementsSet.Count); } - + [Test] public async Task GetStatementAsync_Should_PrepareTwiceAndCache_When_FirstPrepareFails() { @@ -99,7 +99,7 @@ public async Task GetStatementAsync_Should_PrepareTwiceAndCache_When_FirstPrepar if (Interlocked.CompareExchange(ref firstTime, 0, 1) == 1) { PreparedStatement Func() => throw new Exception(exceptionMessage); - return Task.Run((Func) Func); + return Task.Run((Func)Func); } var task = Task.FromResult(GetPrepared(q)); @@ -112,8 +112,8 @@ public async Task GetStatementAsync_Should_PrepareTwiceAndCache_When_FirstPrepar var concurrentTasks = 1000; var semaphore = new SemaphoreSlim(0, concurrentTasks); - - var tasks = + + var tasks = Enumerable.Range(0, concurrentTasks) .Select(_ => Task.Run( async () => @@ -140,15 +140,15 @@ public async Task GetStatementAsync_Should_PrepareTwiceAndCache_When_FirstPrepar tasks = tasks.Where(t => !t.IsFaulted).ToArray(); var boundStatementsSet = new HashSet( - tasks.Select(t => (BoundStatement)t.Result), + tasks.Select(t => (BoundStatement)t.Result), new ReferenceEqualityComparer()); - + var preparedStatementsSet = new HashSet( - tasks.Select(t => ((BoundStatement)t.Result).PreparedStatement), + tasks.Select(t => ((BoundStatement)t.Result).PreparedStatement), new ReferenceEqualityComparer()); - + var createdPreparedStatementsSet = new HashSet( - createdPreparedStatementsBag.Select(t => t.Result), + createdPreparedStatementsBag.Select(t => t.Result), new ReferenceEqualityComparer()); Assert.AreEqual(1, preparedStatementsSet.Count); @@ -242,11 +242,11 @@ public async Task GetStatementAsync_Should_Reprepare_Each_Time_After_Failed_Atte Assert.IsInstanceOf(statement); - var ps = ((BoundStatement) statement).PreparedStatement; + var ps = ((BoundStatement)statement).PreparedStatement; for (var i = 0; i < 10; i++) { - var bound = (BoundStatement) await sf.GetStatementAsync(sessionMock.Object, cql).ConfigureAwait(false); + var bound = (BoundStatement)await sf.GetStatementAsync(sessionMock.Object, cql).ConfigureAwait(false); Assert.AreSame(ps, bound.PreparedStatement); } } @@ -254,7 +254,7 @@ public async Task GetStatementAsync_Should_Reprepare_Each_Time_After_Failed_Atte private static PreparedStatement GetPreparedStatement(Statement statement) { Assert.IsInstanceOf(statement); - return ((BoundStatement) statement).PreparedStatement; + return ((BoundStatement)statement).PreparedStatement; } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/Mapping/TestData/TestDataGenerator.cs b/src/Cassandra.Tests/Mapping/TestData/TestDataGenerator.cs index 996f423d1..fdb7e4275 100644 --- a/src/Cassandra.Tests/Mapping/TestData/TestDataGenerator.cs +++ b/src/Cassandra.Tests/Mapping/TestData/TestDataGenerator.cs @@ -41,12 +41,12 @@ public static TEnum GetEnumValue(int index) // If not a nullable enum, use index with mod to pick an available value if (isNullableEnum == false) - return (TEnum) enumValues[index % enumValues.Length]; + return (TEnum)enumValues[index % enumValues.Length]; // If a nullable enum, we want to generate null also so treat an index of length + 1 as null int idx = index % (enumValues.Length + 1); if (idx < enumValues.Length) - return (TEnum) enumValues[idx]; + return (TEnum)enumValues[idx]; return default(TEnum); } diff --git a/src/Cassandra.Tests/Mapping/TestData/TestDataHelper.cs b/src/Cassandra.Tests/Mapping/TestData/TestDataHelper.cs index ef94807d7..e18fc1bd7 100644 --- a/src/Cassandra.Tests/Mapping/TestData/TestDataHelper.cs +++ b/src/Cassandra.Tests/Mapping/TestData/TestDataHelper.cs @@ -61,7 +61,7 @@ public static RowSet GetSingleColumnRowSet(string columnName, T[] values) foreach (var v in values) { - var row = new Row(new object[] { v}, rs.Columns, columnIndexes); + var row = new Row(new object[] { v }, rs.Columns, columnIndexes); rs.AddRow(row); } return rs; @@ -72,7 +72,7 @@ public static RowSet GetSingleColumnRowSet(string columnName, T[] values) /// public static RowSet GetSingleValueRowSet(string columnName, T value) { - return GetSingleColumnRowSet(columnName, new [] { value }); + return GetSingleColumnRowSet(columnName, new[] { value }); } public static RowSet CreateMultipleValuesRowSet(string[] columnNames, T[] genericValues, int rowLength = 1) @@ -83,7 +83,7 @@ public static RowSet CreateMultipleValuesRowSet(string[] columnNames, T[] gen for (var i = 0; i < columnNames.Length; i++) { var type = typeof(T); - if (type == typeof (Object)) + if (type == typeof(Object)) { //Try to guess by value if (genericValues[i] == null) @@ -109,7 +109,7 @@ public static RowSet CreateMultipleValuesRowSet(string[] columnNames, T[] gen .Select(v => (object)v) .ToArray(); var row = new Row(values, rs.Columns, columnIndexes); - rs.AddRow(row); + rs.AddRow(row); } return rs; } diff --git a/src/Cassandra.Tests/Mapping/TypeConverterTests.cs b/src/Cassandra.Tests/Mapping/TypeConverterTests.cs index fac202183..110ffde66 100644 --- a/src/Cassandra.Tests/Mapping/TypeConverterTests.cs +++ b/src/Cassandra.Tests/Mapping/TypeConverterTests.cs @@ -121,7 +121,7 @@ public void GetFromDbConverter_Should_Convert_From_Dictionary_With_TimeUuid_Keys }; [Test] - [TestCaseSourceGeneric(nameof(ListSourceData), TypeArguments = new[] {typeof(IEnumerable), typeof(List)})] + [TestCaseSourceGeneric(nameof(ListSourceData), TypeArguments = new[] { typeof(IEnumerable), typeof(List) })] [TestCaseSourceGeneric(nameof(ListSourceData), TypeArguments = new[] { typeof(IEnumerable), typeof(IReadOnlyList) })] [TestCaseSourceGeneric(nameof(ListSourceData), TypeArguments = new[] { typeof(IEnumerable), typeof(IList) })] [TestCaseSourceGeneric(nameof(ListSourceData), TypeArguments = new[] { typeof(IEnumerable), typeof(ICollection) })] @@ -131,7 +131,7 @@ public void GetFromDbConverter_Should_Convert_From_Dictionary_With_TimeUuid_Keys [TestCaseSourceGeneric(nameof(ListSourceDataNullable), TypeArguments = new[] { typeof(IEnumerable), typeof(IList) })] [TestCaseSourceGeneric(nameof(ListSourceDataNullable), TypeArguments = new[] { typeof(IEnumerable), typeof(ICollection) })] [TestCaseSourceGeneric(nameof(ListSourceDataNullable), TypeArguments = new[] { typeof(IEnumerable), typeof(IEnumerable) })] - public void GetFromDbConverter_Should_Convert_Collections(TSource src, TResult expected) + public void GetFromDbConverter_Should_Convert_Collections(TSource src, TResult expected) where TSource : IEnumerable where TResult : IEnumerable { var result = TestGetFromDbConverter(src, false); @@ -165,7 +165,7 @@ public void GetFromDbConverter_Should_ThrowInvalidCastException_When_NullableCol private static TResult TestGetFromDbConverter(TSource value, bool compare = true) { var converter = new DefaultTypeConverter(); - var result = (Func) converter.TryGetFromDbConverter(typeof(TSource), typeof(TResult)); + var result = (Func)converter.TryGetFromDbConverter(typeof(TSource), typeof(TResult)); Assert.NotNull(result); var convertedValue = result(value); if (compare) diff --git a/src/Cassandra.Tests/Mapping/UpdateTests.cs b/src/Cassandra.Tests/Mapping/UpdateTests.cs index e8e2e5694..153d551f2 100644 --- a/src/Cassandra.Tests/Mapping/UpdateTests.cs +++ b/src/Cassandra.Tests/Mapping/UpdateTests.cs @@ -59,8 +59,8 @@ public void Update_With_Single_PartitionKey() var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map().PartitionKey(s => s.Id))); mapper.Update(song); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Title", "Artist", "ReleaseDate"}, - new [] {"Id"}, new object[] {song.Title, song.Artist, song.ReleaseDate, song.Id}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Title", "Artist", "ReleaseDate" }, + new[] { "Id" }, new object[] { song.Title, song.Artist, song.ReleaseDate, song.Id }, parameters); sessionMock.Verify(); } @@ -95,17 +95,17 @@ public void Update_With_Multiple_PartitionKeys() var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map().PartitionKey(s => s.Title, s => s.Id))); mapper.Update(song); - - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Artist", "ReleaseDate"}, - new [] {"Title", "Id"}, new object[] {song.Artist, song.ReleaseDate, song.Title, song.Id}, + + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Artist", "ReleaseDate" }, + new[] { "Title", "Id" }, new object[] { song.Artist, song.ReleaseDate, song.Title, song.Id }, parameters); - + //Different order in the partition key definitions mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map().PartitionKey(s => s.Id, s => s.Title))); mapper.Update(song); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Artist", "ReleaseDate"}, - new [] {"Id", "Title"}, new object[] {song.Artist, song.ReleaseDate, song.Id, song.Title}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Artist", "ReleaseDate" }, + new[] { "Id", "Title" }, new object[] { song.Artist, song.ReleaseDate, song.Id, song.Title }, parameters); sessionMock.Verify(); } @@ -140,8 +140,8 @@ public void Update_With_ClusteringKey() var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map().PartitionKey(s => s.Id).ClusteringKey(s => s.ReleaseDate))); mapper.Update(song); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Title", "Artist"}, - new [] {"Id", "ReleaseDate"}, new object[] {song.Title, song.Artist, song.Id, song.ReleaseDate}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "Title", "Artist" }, + new[] { "Id", "ReleaseDate" }, new object[] { song.Title, song.Artist, song.Id, song.ReleaseDate }, parameters); sessionMock.Verify(); } @@ -209,7 +209,7 @@ public void UpdateIf_AppliedInfo_True_Test() object[] parameters = null; sessionMock .Setup(s => s.ExecuteAsync(It.IsAny())) - .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]" }, new [] { true }))) + .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]" }, new[] { true }))) .Callback(b => { parameters = b.QueryValues; @@ -226,8 +226,8 @@ public void UpdateIf_AppliedInfo_True_Test() var appliedInfo = mapper.UpdateIf(Cql.New(partialQuery, "Ramble On", new DateTime(1969, 1, 1), updateGuid, "Led Zeppelin")); sessionMock.Verify(); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"title", "releasedate"}, - new [] {"id"}, new object[] {"Ramble On", new DateTime(1969, 1, 1), updateGuid, "Led Zeppelin"}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "title", "releasedate" }, + new[] { "id" }, new object[] { "Ramble On", new DateTime(1969, 1, 1), updateGuid, "Led Zeppelin" }, parameters, "IF artist = ?"); Assert.True(appliedInfo.Applied); @@ -244,7 +244,7 @@ public void UpdateIf_AppliedInfo_False_Test() sessionMock.Setup(s => s.Keyspace).Returns(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny())) - .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new [] { "[applied]", "id", "artist" }, new object[] { false, id, "Jimmy Page" }))) + .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]", "id", "artist" }, new object[] { false, id, "Jimmy Page" }))) .Callback(b => { parameters = b.QueryValues; @@ -259,8 +259,8 @@ public void UpdateIf_AppliedInfo_False_Test() const string partialQuery = "SET title = ?, releasedate = ? WHERE id = ? IF artist = ?"; var appliedInfo = mapper.UpdateIf(Cql.New(partialQuery, "Kashmir", new DateTime(1975, 1, 1), id, "Led Zeppelin")); sessionMock.Verify(); - TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"title", "releasedate"}, - new [] {"id"}, new object[] {"Kashmir", new DateTime(1975, 1, 1), id, "Led Zeppelin"}, + TestHelper.VerifyUpdateCqlColumns("Song", query, new[] { "title", "releasedate" }, + new[] { "id" }, new object[] { "Kashmir", new DateTime(1975, 1, 1), id, "Led Zeppelin" }, parameters, "IF artist = ?"); Assert.False(appliedInfo.Applied); Assert.NotNull(appliedInfo.Existing); @@ -297,7 +297,7 @@ public void Update_SetTimestamp_Test() Assert.AreEqual(timestamp, statement.Timestamp); timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(10)); mapper.UpdateIf(Cql.New("UPDATE tbl1 SET t1 = ? WHERE id = ?", - new object[] {1, 2}, + new object[] { 1, 2 }, CqlQueryOptions.New().SetTimestamp(timestamp))); Assert.AreEqual(timestamp, statement.Timestamp); } @@ -311,14 +311,14 @@ public void Update_Poco_With_Enum_Collections() { parameters = p; }, config); - var collectionValues = new[]{ HairColor.Blonde, HairColor.Gray }; - var expectedCollection = collectionValues.Select(x => (int) x).ToArray(); + var collectionValues = new[] { HairColor.Blonde, HairColor.Gray }; + var expectedCollection = collectionValues.Select(x => (int)x).ToArray(); mapper.Update("UPDATE tbl1 SET list1 = ? WHERE id = ?", mapper.ConvertCqlArgument, IEnumerable>(collectionValues), 3L); - Assert.AreEqual(new object[]{ expectedCollection, 3L }, parameters); + Assert.AreEqual(new object[] { expectedCollection, 3L }, parameters); mapper.Update("UPDATE tbl1 SET list1 = ? WHERE id = ?", mapper.ConvertCqlArgument>(collectionValues), 3L); - Assert.AreEqual(new object[]{ expectedCollection, 3L }, parameters); + Assert.AreEqual(new object[] { expectedCollection, 3L }, parameters); } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/Mapping/Utils/CqlIdentifierHelperTests.cs b/src/Cassandra.Tests/Mapping/Utils/CqlIdentifierHelperTests.cs index b12cfb8b0..202a8008f 100644 --- a/src/Cassandra.Tests/Mapping/Utils/CqlIdentifierHelperTests.cs +++ b/src/Cassandra.Tests/Mapping/Utils/CqlIdentifierHelperTests.cs @@ -43,7 +43,7 @@ public void Should_EscapeIdentifier(string expected, string identifier, bool cas Assert.AreEqual(expected, act); } - + [TestCase("ks.\"select\"", "ks", "select", false)] [TestCase("\"ks\".\"select\"", "ks", "select", true)] [TestCase("\"select\".test", "select", "test", false)] diff --git a/src/Cassandra.Tests/MetadataHelpers/EverywhereStrategyTests.cs b/src/Cassandra.Tests/MetadataHelpers/EverywhereStrategyTests.cs index d7df2b209..10217651b 100644 --- a/src/Cassandra.Tests/MetadataHelpers/EverywhereStrategyTests.cs +++ b/src/Cassandra.Tests/MetadataHelpers/EverywhereStrategyTests.cs @@ -32,7 +32,7 @@ public void Should_ReturnAllReplicasPerToken() var result = target.ComputeTokenToReplicaMap( testData.Ring, testData.PrimaryReplicas, testData.NumberOfHostsWithTokens, testData.Datacenters); - + // 3 dcs, 3 hosts per rack, 2 racks per dc, 10 tokens per host Assert.AreEqual(10 * 3 * 2 * 3, result.Count); diff --git a/src/Cassandra.Tests/MetadataHelpers/NetworkTopologyStrategyTests.cs b/src/Cassandra.Tests/MetadataHelpers/NetworkTopologyStrategyTests.cs index 5c474f057..ac6e576cc 100644 --- a/src/Cassandra.Tests/MetadataHelpers/NetworkTopologyStrategyTests.cs +++ b/src/Cassandra.Tests/MetadataHelpers/NetworkTopologyStrategyTests.cs @@ -68,7 +68,7 @@ public void AreReplicationFactorsSatisfied_Should_ReturnFalse_When_LessReplicasT }; Assert.False(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters)); } - + [Test] public void AreReplicationFactorsSatisfied_Should_ReturnTrue_When_OnlyFullReplicas() { @@ -93,7 +93,7 @@ public void AreReplicationFactorsSatisfied_Should_ReturnTrue_When_OnlyFullReplic }; Assert.True(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters)); } - + [Test] public void AreReplicationFactorsSatisfied_Should_ReturnFalse_When_LessReplicasThanRf() { @@ -118,7 +118,7 @@ public void AreReplicationFactorsSatisfied_Should_ReturnFalse_When_LessReplicasT }; Assert.False(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters)); } - + [Test] public void Should_ReturnAppropriateReplicasPerDcPerToken() { @@ -133,7 +133,7 @@ public void Should_ReturnAppropriateReplicasPerDcPerToken() var result = target.ComputeTokenToReplicaMap( testData.Ring, testData.PrimaryReplicas, testData.NumberOfHostsWithTokens, testData.Datacenters); - + // 3 dcs, 3 hosts per rack, 3 racks per dc, 10 tokens per host Assert.AreEqual(10 * 3 * 3 * 3, result.Count); @@ -143,7 +143,7 @@ public void Should_ReturnAppropriateReplicasPerDcPerToken() Assert.AreEqual(2 + 2 + 1, token.Value.Count); } } - + [Test] public void Should_ReturnEqualsTrueAndSameHashCode_When_BothStrategiesHaveSameReplicationSettings() { @@ -167,7 +167,7 @@ public void Should_ReturnEqualsTrueAndSameHashCode_When_BothStrategiesHaveSameRe Assert.IsTrue(target2.Equals(target1)); Assert.AreEqual(target1, target2); } - + [Test] public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentReplicationFactors() { @@ -185,13 +185,13 @@ public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentReplicationFa { "dc1", ReplicationFactor.Parse("2") }, { "dc2", ReplicationFactor.Parse("3/2") } }); - + Assert.AreNotEqual(target1.GetHashCode(), target2.GetHashCode()); Assert.IsFalse(target1.Equals(target2)); Assert.IsFalse(target2.Equals(target1)); Assert.AreNotEqual(target1, target2); } - + [Test] public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentDatacenters() { @@ -206,7 +206,7 @@ public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentDatacenters() { { "dc1", ReplicationFactor.Parse("2") }, }); - + Assert.AreNotEqual(target1.GetHashCode(), target2.GetHashCode()); Assert.IsFalse(target1.Equals(target2)); Assert.IsFalse(target2.Equals(target1)); diff --git a/src/Cassandra.Tests/MetadataHelpers/ReplicationFactorTests.cs b/src/Cassandra.Tests/MetadataHelpers/ReplicationFactorTests.cs index 8ec08c36d..9eb327ec4 100644 --- a/src/Cassandra.Tests/MetadataHelpers/ReplicationFactorTests.cs +++ b/src/Cassandra.Tests/MetadataHelpers/ReplicationFactorTests.cs @@ -30,7 +30,7 @@ public void Should_Parse_When_TransientReplicationIsEnabled() Assert.AreEqual(2, target.FullReplicas); Assert.IsTrue(target.HasTransientReplicas()); } - + [Test] public void Should_Parse_When_TransientReplicationIsDisabled() { diff --git a/src/Cassandra.Tests/MetadataHelpers/ReplicationStrategyTestData.cs b/src/Cassandra.Tests/MetadataHelpers/ReplicationStrategyTestData.cs index 06894243b..6cb6fb4b9 100644 --- a/src/Cassandra.Tests/MetadataHelpers/ReplicationStrategyTestData.cs +++ b/src/Cassandra.Tests/MetadataHelpers/ReplicationStrategyTestData.cs @@ -41,7 +41,7 @@ public static ReplicationStrategyTestData Create( foreach (var dc in Enumerable.Range(1, numberOfDcs)) { - hosts.Add($"dc{dc}", new Tuple>, DatacenterInfo>(new Dictionary>(), new DatacenterInfo { HostLength = numberOfHostsPerRack * numberOfRacksPerDc})); + hosts.Add($"dc{dc}", new Tuple>, DatacenterInfo>(new Dictionary>(), new DatacenterInfo { HostLength = numberOfHostsPerRack * numberOfRacksPerDc })); foreach (var rack in Enumerable.Range(1, numberOfRacksPerDc)) { hosts[$"dc{dc}"].Item1.Add($"rack{rack}", new List()); @@ -52,7 +52,7 @@ public static ReplicationStrategyTestData Create( var tokensStrList = new List(); for (var i = 1; i <= numberOfTokensPerHost; i++) { - var token = new M3PToken(dc*1000000+rack*100000+host*10000 + 1000 * i); + var token = new M3PToken(dc * 1000000 + rack * 100000 + host * 10000 + 1000 * i); tokensList.Add(token); tokensStrList.Add(i.ToString()); } diff --git a/src/Cassandra.Tests/MetadataHelpers/SimpleStrategyTests.cs b/src/Cassandra.Tests/MetadataHelpers/SimpleStrategyTests.cs index 9e515879e..1291f6d21 100644 --- a/src/Cassandra.Tests/MetadataHelpers/SimpleStrategyTests.cs +++ b/src/Cassandra.Tests/MetadataHelpers/SimpleStrategyTests.cs @@ -31,7 +31,7 @@ public void Should_ReturnTwoReplicasPerToken() var result = target.ComputeTokenToReplicaMap( testData.Ring, testData.PrimaryReplicas, testData.NumberOfHostsWithTokens, testData.Datacenters); - + // 3 dcs, 3 hosts per rack, 3 racks per dc, 10 tokens per host Assert.AreEqual(10 * 3 * 3 * 3, result.Count); @@ -40,7 +40,7 @@ public void Should_ReturnTwoReplicasPerToken() Assert.AreEqual(2, token.Value.Count); } } - + [Test] public void Should_ReturnTwoReplicasPerToken_When_TransientReplicationIsEnabled() { @@ -49,7 +49,7 @@ public void Should_ReturnTwoReplicasPerToken_When_TransientReplicationIsEnabled( var result = target.ComputeTokenToReplicaMap( testData.Ring, testData.PrimaryReplicas, testData.NumberOfHostsWithTokens, testData.Datacenters); - + // 3 dcs, 3 hosts per rack, 3 racks per dc, 10 tokens per host Assert.AreEqual(10 * 3 * 3 * 3, result.Count); diff --git a/src/Cassandra.Tests/MetadataHelpers/TestHelpers/FakeSchemaParserFactory.cs b/src/Cassandra.Tests/MetadataHelpers/TestHelpers/FakeSchemaParserFactory.cs index 84353c9a9..913883d62 100644 --- a/src/Cassandra.Tests/MetadataHelpers/TestHelpers/FakeSchemaParserFactory.cs +++ b/src/Cassandra.Tests/MetadataHelpers/TestHelpers/FakeSchemaParserFactory.cs @@ -55,7 +55,7 @@ public static KeyspaceMetadata CreateNetworkTopologyKeyspace(string name, IDicti true, ReplicationStrategies.NetworkTopologyStrategy, replicationFactors, - factory ?? new ReplicationStrategyFactory(), + factory ?? new ReplicationStrategyFactory(), null); } } diff --git a/src/Cassandra.Tests/MetadataTests/TaskBasedTimerTests.cs b/src/Cassandra.Tests/MetadataTests/TaskBasedTimerTests.cs index 29bb055b6..e4095685e 100644 --- a/src/Cassandra.Tests/MetadataTests/TaskBasedTimerTests.cs +++ b/src/Cassandra.Tests/MetadataTests/TaskBasedTimerTests.cs @@ -54,7 +54,7 @@ public async Task Should_InvokeActOnce_When_ChangeIsCalledTwice() await Task.Delay(100).ConfigureAwait(false); Assert.AreEqual(1, Interlocked.Read(ref _counter)); } - + [Test] public async Task Should_NotInvokeAct_When_CancelIsCalled() { @@ -66,7 +66,7 @@ public async Task Should_NotInvokeAct_When_CancelIsCalled() await Task.Delay(1000).ConfigureAwait(false); Assert.AreEqual(0, Interlocked.Read(ref _counter)); } - + [Test] public async Task Should_InvokeActOnce_When_ChangeIsCalled() { @@ -77,7 +77,7 @@ public async Task Should_InvokeActOnce_When_ChangeIsCalled() await Task.Delay(500).ConfigureAwait(false); Assert.AreEqual(1, Interlocked.Read(ref _counter)); } - + [Test] [Repeat(5)] public void Should_NotLogExceptions_When_CancellationTokenIsCancelledAndDisposed() @@ -103,7 +103,7 @@ public void Should_NotLogExceptions_When_CancellationTokenIsCancelledAndDisposed Diagnostics.CassandraTraceSwitch.Level = logLevel; } } - + [Test] public void Should_LogExceptions_When_ExceptionsAreThrownByProvidedAction() { diff --git a/src/Cassandra.Tests/Metrics/MetricsTests.cs b/src/Cassandra.Tests/Metrics/MetricsTests.cs index e8d68b66a..6a835d6d1 100644 --- a/src/Cassandra.Tests/Metrics/MetricsTests.cs +++ b/src/Cassandra.Tests/Metrics/MetricsTests.cs @@ -39,7 +39,7 @@ public void Should_BeEqual_When_NodeMetricEqualsNodeMetric() Assert.IsTrue(metric.Equals(metric2)); Assert.IsTrue(nodeMetric.Equals(NodeMetric.Counters.AuthenticationErrors)); } - + [Test] public void Should_BeEqual_When_SessionMetricEqualsSessionMetric() { @@ -63,7 +63,7 @@ public void Should_NotBeEqual_WhenNodeMetricEqualsSessionMetric() var nodeMetric = NodeMetric.Counters.AuthenticationErrors; IMetric nodeMetricBase = nodeMetric; IMetric nodeMetricBase2 = nodeMetric; - + Assert.IsFalse(nodeMetric.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(nodeMetric)); @@ -72,7 +72,7 @@ public void Should_NotBeEqual_WhenNodeMetricEqualsSessionMetric() Assert.IsFalse(nodeMetric.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(nodeMetric)); - + Assert.IsFalse(nodeMetricBase.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(nodeMetricBase)); @@ -81,7 +81,7 @@ public void Should_NotBeEqual_WhenNodeMetricEqualsSessionMetric() Assert.IsFalse(nodeMetricBase.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(nodeMetricBase)); - + Assert.IsFalse(nodeMetricBase2.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(nodeMetricBase2)); @@ -91,7 +91,7 @@ public void Should_NotBeEqual_WhenNodeMetricEqualsSessionMetric() Assert.IsFalse(nodeMetricBase2.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(nodeMetricBase2)); } - + [Test] public void Should_NotBeEqual_WhenCustomMetricEqualsSessionMetric() { @@ -102,7 +102,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsSessionMetric() var testMetric = new TestMetric { Name = NodeMetric.Counters.AuthenticationErrors.Name }; IMetric testMetricBase = testMetric; IMetric testMetricBase2 = testMetric; - + Assert.IsFalse(testMetric.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(testMetric)); @@ -111,7 +111,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsSessionMetric() Assert.IsFalse(testMetric.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(testMetric)); - + Assert.IsFalse(testMetricBase.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(testMetricBase)); @@ -120,7 +120,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsSessionMetric() Assert.IsFalse(testMetricBase.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(testMetricBase)); - + Assert.IsFalse(testMetricBase2.Equals(sessionMetric)); Assert.IsFalse(sessionMetric.Equals(testMetricBase2)); @@ -130,7 +130,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsSessionMetric() Assert.IsFalse(testMetricBase2.Equals(sessionMetricBase2)); Assert.IsFalse(sessionMetricBase2.Equals(testMetricBase2)); } - + [Test] public void Should_NotBeEqual_WhenCustomMetricEqualsNodeMetric() { @@ -141,7 +141,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsNodeMetric() var testMetric = new TestMetric { Name = NodeMetric.Counters.AuthenticationErrors.Name }; IMetric testMetricBase = testMetric; IMetric testMetricBase2 = testMetric; - + Assert.IsFalse(testMetric.Equals(nodeMetric)); Assert.IsFalse(nodeMetric.Equals(testMetric)); @@ -150,7 +150,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsNodeMetric() Assert.IsFalse(testMetric.Equals(nodeMetricBase2)); Assert.IsFalse(nodeMetricBase2.Equals(testMetric)); - + Assert.IsFalse(testMetricBase.Equals(nodeMetric)); Assert.IsFalse(nodeMetric.Equals(testMetricBase)); @@ -159,7 +159,7 @@ public void Should_NotBeEqual_WhenCustomMetricEqualsNodeMetric() Assert.IsFalse(testMetricBase.Equals(nodeMetricBase2)); Assert.IsFalse(nodeMetricBase2.Equals(testMetricBase)); - + Assert.IsFalse(testMetricBase2.Equals(nodeMetric)); Assert.IsFalse(nodeMetric.Equals(testMetricBase2)); diff --git a/src/Cassandra.Tests/ObsoletedMemberTests.cs b/src/Cassandra.Tests/ObsoletedMemberTests.cs index c99c4466a..ebe2efa34 100644 --- a/src/Cassandra.Tests/ObsoletedMemberTests.cs +++ b/src/Cassandra.Tests/ObsoletedMemberTests.cs @@ -61,14 +61,14 @@ public void RowSet_Dispose_Obsolete() public void Linq_Attributes_Obsolete() { - var linqAttributes = typeof (Cassandra.Data.Linq.TableAttribute).GetTypeInfo().Assembly.GetTypes() + var linqAttributes = typeof(Cassandra.Data.Linq.TableAttribute).GetTypeInfo().Assembly.GetTypes() .Select(t => t.GetTypeInfo()) .Where(t => t.IsPublic && t.IsSubclassOf(typeof(Attribute)) && t.Namespace == "Cassandra.Data.Linq") .ToArray(); Assert.Greater(linqAttributes.Length, 5); foreach (var attr in linqAttributes) { - Assert.AreEqual(1, attr.GetCustomAttributes(typeof (ObsoleteAttribute), true).Count(), "Type not obsolete " + attr.FullName); + Assert.AreEqual(1, attr.GetCustomAttributes(typeof(ObsoleteAttribute), true).Count(), "Type not obsolete " + attr.FullName); } } } diff --git a/src/Cassandra.Tests/OpenTelemetryTests.cs b/src/Cassandra.Tests/OpenTelemetryTests.cs index aea120b09..7359e745a 100644 --- a/src/Cassandra.Tests/OpenTelemetryTests.cs +++ b/src/Cassandra.Tests/OpenTelemetryTests.cs @@ -40,7 +40,7 @@ public async Task OpenTelemetryRequestTrackerOnStartAsync_StatementIsNull_DbQuer }) { ActivitySource.AddActivityListener(listener); - + var cassandraInstrumentationOptions = new CassandraInstrumentationOptions { IncludeDatabaseStatement = true }; var requestTracker = new OpenTelemetryRequestTracker(cassandraInstrumentationOptions); IStatement statement = null; @@ -97,7 +97,7 @@ public async Task OpenTelemetryRequestTrackerOnNodeStartAsync_StatementIsNull_Db var cassandraInstrumentationOptions = new CassandraInstrumentationOptions { IncludeDatabaseStatement = true }; var requestTracker = new OpenTelemetryRequestTracker(cassandraInstrumentationOptions); - + IStatement statement = null; var requestTrackingInfo = new SessionRequestInfo(statement, null); @@ -130,10 +130,10 @@ public async Task OpenTelemetryRequestTrackerOnNodeStartAsync_ListenerNotSamplin var cassandraInstrumentationOptions = new CassandraInstrumentationOptions { IncludeDatabaseStatement = true }; var requestTracker = new OpenTelemetryRequestTracker(cassandraInstrumentationOptions); - + IStatement statement = null; var requestTrackingInfo = new SessionRequestInfo(statement, null); - + var host = new Host(new System.Net.IPEndPoint(1, 9042), new ConstantReconnectionPolicy(1)); var hostTrackingInfo = new NodeRequestInfo(host, null); diff --git a/src/Cassandra.Tests/OperationStateExtensions.cs b/src/Cassandra.Tests/OperationStateExtensions.cs index 91c020840..4190a2eda 100644 --- a/src/Cassandra.Tests/OperationStateExtensions.cs +++ b/src/Cassandra.Tests/OperationStateExtensions.cs @@ -33,9 +33,9 @@ public static OperationState CreateMock(Action action) { action(error?.Exception, response); return TaskHelper.Completed; - }, - null, - 0, + }, + null, + 0, new MetricsOperationObserver(new NodeMetrics(new NullDriverMetricsProvider(), new DriverMetricsOptions(), false, "c"), false)); } } diff --git a/src/Cassandra.Tests/Policies/DefaultLoadBalancingTests.cs b/src/Cassandra.Tests/Policies/DefaultLoadBalancingTests.cs index 3e4c958e2..42c739837 100644 --- a/src/Cassandra.Tests/Policies/DefaultLoadBalancingTests.cs +++ b/src/Cassandra.Tests/Policies/DefaultLoadBalancingTests.cs @@ -31,7 +31,7 @@ public void Should_Yield_Preferred_Host_First() statement.PreferredHost = new Host(new IPEndPoint(201, 9042), ReconnectionPolicy); var hosts = lbp.NewQueryPlan(null, statement); CollectionAssert.AreEqual( - new[] { "201.0.0.0:9042", "101.0.0.0:9042", "102.0.0.0:9042" }, + new[] { "201.0.0.0:9042", "101.0.0.0:9042", "102.0.0.0:9042" }, hosts.Select(h => h.Address.ToString())); } diff --git a/src/Cassandra.Tests/PoliciesUnitTests.cs b/src/Cassandra.Tests/PoliciesUnitTests.cs index 95a111ceb..928e6e574 100644 --- a/src/Cassandra.Tests/PoliciesUnitTests.cs +++ b/src/Cassandra.Tests/PoliciesUnitTests.cs @@ -109,7 +109,7 @@ public void RoundRobinIsCyclicTestInParallel() { actions.Add(action); } - + var parallelOptions = new ParallelOptions(); parallelOptions.TaskScheduler = new ThreadPerTaskScheduler(); parallelOptions.MaxDegreeOfParallelism = 1000; @@ -153,7 +153,7 @@ public void DCAwareRoundRobinPolicyNeverHitsRemoteWhenSet() followingRounds.AddRange(policy.NewQueryPlan(null, new SimpleStatement()).ToList()); } Assert.AreEqual(10 * (hostLength - 2), followingRounds.Count); - + //Check that there aren't remote nodes. Assert.AreEqual(0, followingRounds.Count(h => h.Datacenter != "local")); } @@ -299,7 +299,7 @@ public void DCAwareRoundRobinPolicyTestInParallel() { if (h.Datacenter == localDc) { - Assert.AreEqual(times/localHostsLength, firstHosts.Count(hc => hc == h)); + Assert.AreEqual(times / localHostsLength, firstHosts.Count(hc => hc == h)); } else { @@ -396,7 +396,7 @@ public void DCAwareRoundRobinPolicyWithNodesChanging() hostList.Add(host); clusterMock.Raise(c => c.HostAdded += null, host); }); - + actionList.Insert(400, () => { var host = hostToRemove; @@ -449,7 +449,7 @@ public void DowngradingConsistencyRetryTest() [Test] public void FixedReconnectionPolicyTests() { - var delays = new long[] {0, 2, 100, 200, 500, 1000}; + var delays = new long[] { 0, 2, 100, 200, 500, 1000 }; var policy = new FixedReconnectionPolicy(delays); var schedule = policy.NewSchedule(); const int times = 30; @@ -518,7 +518,7 @@ public void TokenAwarePolicyReturnsLocalReplicasFirst() hosts = policy.NewQueryPlan(null, new SimpleStatement().SetRoutingKey(k)).ToList(); Assert.AreEqual(7, hosts.Count); //local replicas first - CollectionAssert.AreEquivalent(new[] { 2, 5}, hosts.Take(2).Select(TestHelper.GetLastAddressByte)); + CollectionAssert.AreEquivalent(new[] { 2, 5 }, hosts.Take(2).Select(TestHelper.GetLastAddressByte)); //next should be local nodes Assert.AreEqual("dc1", hosts[2].Datacenter); Assert.AreEqual("dc1", hosts[3].Datacenter); diff --git a/src/Cassandra.Tests/PreparedStatementTests.cs b/src/Cassandra.Tests/PreparedStatementTests.cs index 4d9b7b88a..786561e64 100644 --- a/src/Cassandra.Tests/PreparedStatementTests.cs +++ b/src/Cassandra.Tests/PreparedStatementTests.cs @@ -21,18 +21,18 @@ namespace Cassandra.Tests [TestFixture] public class PreparedStatementTests { - [Test] - public void Should_Allow_Bind_With_Empty_Query() - { + [Test] + public void Should_Allow_Bind_With_Empty_Query() + { var ps = new PreparedStatement(); Assert.NotNull(ps.Bind()); } - [Test] - public void Bind_Should_Create_BoundStatement_With_Provided_Values() + [Test] + public void Bind_Should_Create_BoundStatement_With_Provided_Values() { var ps = new PreparedStatement(); - ps.SetRoutingKey(new RoutingKey(new byte[] {0x01})); + ps.SetRoutingKey(new RoutingKey(new byte[] { 0x01 })); ps.SetConsistencyLevel(ConsistencyLevel.LocalQuorum); ps.SetIdempotence(true); var statement = ps.Bind(); @@ -41,8 +41,8 @@ public void Bind_Should_Create_BoundStatement_With_Provided_Values() Assert.True(statement.IsIdempotent); } - [Test] - public void Bind_Should_Create_BoundStatement_With_Default_Values() + [Test] + public void Bind_Should_Create_BoundStatement_With_Default_Values() { var statement = new PreparedStatement().Bind(); Assert.Null(statement.ConsistencyLevel); diff --git a/src/Cassandra.Tests/ProtocolTests.cs b/src/Cassandra.Tests/ProtocolTests.cs index 6540f154c..f17e10d85 100644 --- a/src/Cassandra.Tests/ProtocolTests.cs +++ b/src/Cassandra.Tests/ProtocolTests.cs @@ -24,7 +24,7 @@ public class ProtocolTests { private readonly Configuration _config = new TestConfigurationBuilder { AllowBetaProtocolVersions = false }.Build(); private readonly Configuration _configBeta = new TestConfigurationBuilder { AllowBetaProtocolVersions = true }.Build(); - + [TestCase(ProtocolVersion.V4, ProtocolVersion.V5)] [TestCase(ProtocolVersion.V2, ProtocolVersion.V3)] [TestCase(ProtocolVersion.V3, ProtocolVersion.V4)] @@ -38,7 +38,7 @@ public void GetLowerSupported_Should_NotSkipBetaVersions_When_AllowBetaProtocolV { Assert.AreEqual(version, initialVersion.GetLowerSupported(_configBeta)); } - + [TestCase(ProtocolVersion.V4, ProtocolVersion.V5)] [TestCase(ProtocolVersion.V2, ProtocolVersion.V3)] [TestCase(ProtocolVersion.V3, ProtocolVersion.V4)] @@ -67,7 +67,7 @@ public void GetHighestCommon_Should_Downgrade_To_Protocol_VX_With_Hosts(Protocol { Assert.AreEqual(version, ProtocolVersion.MaxSupported.GetHighestCommon(_config, cassandraVersions.Select(GetHost))); } - + [TestCase(ProtocolVersion.V5, "4.0.0", "1.2.19")] [TestCase(ProtocolVersion.V3, "4.0.0", "2.1.17")] @@ -91,7 +91,7 @@ public void GetHighestCommon_Should_Downgrade_To_Protocol_VX_With_Dse_Hosts(Prot { Assert.AreEqual(version, ProtocolVersion.MaxSupported.GetHighestCommon(_config, cassandraVersions.Select(GetHost))); } - + [TestCase(ProtocolVersion.V4, "4.0.0")] [TestCase(ProtocolVersion.V4, "4.0.0", "1.2.19")] [TestCase(ProtocolVersion.V4, "3.0.13", "3.0.11", "2.2.9")] @@ -104,7 +104,7 @@ public void GetHighestCommon_Should_Not_Downgrade_Protocol_With_Hosts(ProtocolVe { Assert.AreEqual(version, version.GetHighestCommon(_config, cassandraVersions.Select(GetHost))); } - + [TestCase(ProtocolVersion.V5, "4.0.0")] [TestCase(ProtocolVersion.V5, "4.0.0", "1.2.19")] [TestCase(ProtocolVersion.V4, "3.0.13", "3.0.11", "2.2.9")] diff --git a/src/Cassandra.Tests/RequestExecutionTests.cs b/src/Cassandra.Tests/RequestExecutionTests.cs index 4be76b9c3..34e754499 100644 --- a/src/Cassandra.Tests/RequestExecutionTests.cs +++ b/src/Cassandra.Tests/RequestExecutionTests.cs @@ -42,8 +42,8 @@ public void Should_ThrowException_When_NoValidHosts(bool currentHostRetry) var requestTrackingInfo = new SessionRequestInfo(mockStatement, null); Mock.Get(requestHandlerFactory) .Setup(r => r.CreateAsync( - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -72,8 +72,8 @@ public void Should_NotThrowException_When_AValidHostIsObtained(bool currentHostR var requestTrackingInfo = new SessionRequestInfo(mockStatement, null); Mock.Get(requestHandlerFactory) .Setup(r => r.CreateAsync( - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -109,8 +109,8 @@ public void Should_SendRequest_When_AConnectionIsObtained(bool currentHostRetry) var requestTrackingInfo = new SessionRequestInfo(mockStatement, null); Mock.Get(requestHandlerFactory) .Setup(r => r.CreateAsync( - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -160,8 +160,8 @@ public void Should_RetryRequestToSameHost_When_ConnectionFailsAndRetryDecisionIs var requestTrackingInfo = new SessionRequestInfo(mockStatement, null); Mock.Get(requestHandlerFactory) .Setup(r => r.CreateAsync( - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -203,7 +203,7 @@ public void Should_RetryRequestToSameHost_When_ConnectionFailsAndRetryDecisionIs .Returns(() => Mock.Of(a => a.OnRequestError( - It.IsAny(), config, exception, 0) + It.IsAny(), config, exception, 0) == RetryDecision.Retry(null, true))); // Setup connection failure diff --git a/src/Cassandra.Tests/RequestHandlerMockTests.cs b/src/Cassandra.Tests/RequestHandlerMockTests.cs index 72bd8502d..f5a4b32c4 100644 --- a/src/Cassandra.Tests/RequestHandlerMockTests.cs +++ b/src/Cassandra.Tests/RequestHandlerMockTests.cs @@ -82,7 +82,7 @@ public void Should_ThrowNoHostAvailableException_When_QueryPlanMoveNextReturnsFa var requestTrackingInfoAndObserver = RequestHandler.CreateRequestObserver(sessionMock, null).GetAwaiter().GetResult(); var sut = new RequestHandler( - sessionMock, + sessionMock, new SerializerManager(ProtocolVersion.V4).GetCurrentSerializer(), requestTrackingInfoAndObserver.Item1, requestTrackingInfoAndObserver.Item2); Assert.Throws(() => sut.GetNextValidHost(triedHosts)); } @@ -106,7 +106,7 @@ public void Should_ThrowNoHostAvailableException_When_QueryPlanMoveNextReturnsTr var requestTrackingInfoAndObserver = RequestHandler.CreateRequestObserver(sessionMock, null).GetAwaiter().GetResult(); var sut = new RequestHandler( - sessionMock, + sessionMock, new SerializerManager(ProtocolVersion.V4).GetCurrentSerializer(), requestTrackingInfoAndObserver.Item1, requestTrackingInfoAndObserver.Item2); Assert.Throws(() => sut.GetNextValidHost(triedHosts)); } diff --git a/src/Cassandra.Tests/RequestHandlerTests.cs b/src/Cassandra.Tests/RequestHandlerTests.cs index 44154d309..b8a65f506 100644 --- a/src/Cassandra.Tests/RequestHandlerTests.cs +++ b/src/Cassandra.Tests/RequestHandlerTests.cs @@ -57,11 +57,11 @@ private static PreparedStatement GetPrepared( byte[] queryId = null, ISerializerManager serializerManager = null, RowSetMetadata rowSetMetadata = null) { return new PreparedStatement( - null, - queryId, - new ResultMetadata(new byte[16], rowSetMetadata), - "DUMMY QUERY", - null, + null, + queryId, + new ResultMetadata(new byte[16], rowSetMetadata), + "DUMMY QUERY", + null, serializerManager ?? RequestHandlerTests.SerializerManager); } @@ -168,7 +168,7 @@ public void Should_SkipMetadata_When_BoundStatementContainsColumnDefinitionsAndP var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, serializerManager.GetCurrentSerializer(), GetRequestOptions(queryOptions)); Assert.AreEqual(isSet, request.SkipMetadata); } - + [Test] [TestCase(ProtocolVersion.V5)] [TestCase(ProtocolVersion.DseV2)] @@ -342,7 +342,7 @@ public void GetRequest_With_Timestamp_Generator_Empty_Value_With_Statement_Times Cassandra.Policies.DefaultRetryPolicy, Cassandra.Policies.DefaultSpeculativeExecutionPolicy, new NoTimestampGenerator(), null); var config = RequestHandlerTests.GetConfig(new QueryOptions(), policies, PoolingOptions.Create()); - + var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions); var bodyBuffer = GetBodyBuffer(request); @@ -816,7 +816,7 @@ internal static RetryDecision GetRetryDecisionFromServerError(Exception ex, IExt { return RequestExecution.GetRetryDecisionWithReason(RequestError.CreateServerError(ex), policy, statement, config, retryCount).Decision; } - + internal static RetryDecision GetRetryDecisionFromClientError(Exception ex, IExtendedRetryPolicy policy, IStatement statement, Configuration config, int retryCount) { return RequestExecution.GetRetryDecisionWithReason(RequestError.CreateClientError(ex, false), policy, statement, config, retryCount).Decision; diff --git a/src/Cassandra.Tests/Requests/GraphTypeSerializerFactoryTests.cs b/src/Cassandra.Tests/Requests/GraphTypeSerializerFactoryTests.cs index bb67e4ba1..9cd3e684d 100644 --- a/src/Cassandra.Tests/Requests/GraphTypeSerializerFactoryTests.cs +++ b/src/Cassandra.Tests/Requests/GraphTypeSerializerFactoryTests.cs @@ -75,7 +75,7 @@ public void Should_IgnoreProtocolOnOptionsAndStatement_When_ResolvingDefaultGrap Assert.AreEqual(expected, actual); } - + [TestCase(GraphProtocol.GraphSON1, "ks2", null, null)] [TestCase(GraphProtocol.GraphSON3, "ks2", "ks2", null)] [TestCase(GraphProtocol.GraphSON3, "ks2", null, "ks2")] @@ -117,7 +117,7 @@ public void Should_UseStatementGraphNameBeforeOptions_When_ResolvingDefaultGraph Assert.AreEqual(expected, actual); } - + [Test] public void Should_CacheSerializerInstances_When_SameParametersAreUsed() { @@ -126,7 +126,7 @@ public void Should_CacheSerializerInstances_When_SameParametersAreUsed() var deserializers1 = new Dictionary { { "byte", new ByteBufferDeserializer() } }; - + var deserializers2 = new Dictionary { { "duration", new Duration2Serializer() } }; @@ -213,29 +213,29 @@ private IInternalSession MockSession(string keyspace, bool coreEngine) // unique configurations keyspaces.AddOrUpdate( - keyspace, - FakeSchemaParserFactory.CreateSimpleKeyspace(keyspace, 2, graphEngine: coreEngine ? "Core" : null), + keyspace, + FakeSchemaParserFactory.CreateSimpleKeyspace(keyspace, 2, graphEngine: coreEngine ? "Core" : null), (s, keyspaceMetadata) => keyspaceMetadata); - + var schemaParser = new FakeSchemaParser(keyspaces); var config = new TestConfigurationBuilder { ConnectionFactory = new FakeConnectionFactory() }.Build(); - - var metadata = new Metadata(config, schemaParser) {Partitioner = "Murmur3Partitioner"}; + + var metadata = new Metadata(config, schemaParser) { Partitioner = "Murmur3Partitioner" }; var cluster = Mock.Of(); Mock.Get(cluster).SetupGet(c => c.Metadata).Returns(metadata); var session = Mock.Of(); Mock.Get(session).SetupGet(s => s.Cluster).Returns(cluster); - + metadata.ControlConnection = new ControlConnection( Mock.Of(), - new ProtocolEventDebouncer(new TaskBasedTimerFactory(), TimeSpan.FromMilliseconds(20), TimeSpan.FromSeconds(100)), - ProtocolVersion.V3, - config, + new ProtocolEventDebouncer(new TaskBasedTimerFactory(), TimeSpan.FromMilliseconds(20), TimeSpan.FromSeconds(100)), + ProtocolVersion.V3, + config, metadata, new List { diff --git a/src/Cassandra.Tests/Requests/PrepareHandlerTests.cs b/src/Cassandra.Tests/Requests/PrepareHandlerTests.cs index 1a76562ea..f2968fbb2 100644 --- a/src/Cassandra.Tests/Requests/PrepareHandlerTests.cs +++ b/src/Cassandra.Tests/Requests/PrepareHandlerTests.cs @@ -53,10 +53,10 @@ public async Task Should_NotSendRequestToSecondHost_When_SecondHostDoesntHavePoo builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -87,8 +87,8 @@ public async Task Should_NotSendRequestToSecondHost_When_SecondHostDoesntHavePoo var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); @@ -109,7 +109,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + [Test] public async Task Should_NotSendRequestToSecondHost_When_SecondHostPoolDoesNotHaveConnections() { @@ -124,10 +124,10 @@ public async Task Should_NotSendRequestToSecondHost_When_SecondHostPoolDoesNotHa builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -159,12 +159,12 @@ public async Task Should_NotSendRequestToSecondHost_When_SecondHostPoolDoesNotHa var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); - + pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); Assert.AreEqual(2, results.Length); @@ -181,7 +181,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + [Test] public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnections() { @@ -196,10 +196,10 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnections() builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -227,17 +227,17 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnections() await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false); var pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); - + var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount); var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); - + pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); Assert.AreEqual(3, results.Length); @@ -255,7 +255,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + [Test] public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFirstHostDoesntHavePool() { @@ -270,10 +270,10 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFi builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -304,12 +304,12 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFi var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); - + pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); Assert.AreEqual(3, results.Length); @@ -327,7 +327,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + [Test] public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFirstHostPoolDoesntHaveConnections() { @@ -342,10 +342,10 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFi builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -376,12 +376,12 @@ public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFi var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); - + pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); Assert.AreEqual(3, results.Length); @@ -399,7 +399,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + [Test] public async Task Should_SendRequestToFirstHostOnly_When_PrepareOnAllHostsIsFalseAndAllHostsHaveConnectionsButFirstHostPoolDoesntHaveConnections() { @@ -415,10 +415,10 @@ public async Task Should_SendRequestToFirstHostOnly_When_PrepareOnAllHostsIsFals builder.SocketOptions = new SocketOptions().SetReadTimeoutMillis(10); builder.Policies = new Cassandra.Policies( - lbpCluster, - new ConstantReconnectionPolicy(5), - new DefaultRetryPolicy(), - NoSpeculativeExecutionPolicy.Instance, + lbpCluster, + new ConstantReconnectionPolicy(5), + new DefaultRetryPolicy(), + NoSpeculativeExecutionPolicy.Instance, new AtomicMonotonicTimestampGenerator(), null); }); @@ -449,12 +449,12 @@ public async Task Should_SendRequestToFirstHostOnly_When_PrepareOnAllHostsIsFals var request = new InternalPrepareRequest(_serializer, "TEST", null, null); await mockResult.PrepareHandler.Prepare( - request, - mockResult.Session, + request, + mockResult.Session, queryPlan.GetEnumerator()).ConfigureAwait(false); var results = mockResult.SendResults.ToArray(); - + pools = mockResult.Session.GetPools().ToList(); Assert.AreEqual(3, pools.Count); Assert.AreEqual(1, results.Length); @@ -465,7 +465,7 @@ await mockResult.PrepareHandler.Prepare( Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[1].Address].Count); Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count); // Assert that pool of first host contains only one connection that was called send - var poolConnections = + var poolConnections = pools .Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))) .Where(p => mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Contains(p.SingleOrDefault())) @@ -476,7 +476,7 @@ await mockResult.PrepareHandler.Prepare( Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once); } } - + private PrepareHandlerMockResult BuildPrepareHandler(Action configBuilderAct) { var factory = new FakeConnectionFactory(MockConnection); @@ -504,7 +504,7 @@ private PrepareHandlerMockResult BuildPrepareHandler(Action()); cluster.Connect(); factory.CreatedConnections.Clear(); - + // create session var session = new Session(cluster, config, null, SerializerManager.Default, null); @@ -513,21 +513,21 @@ private PrepareHandlerMockResult BuildPrepareHandler(Action(); - + Mock.Get(connection) .SetupGet(c => c.EndPoint) .Returns(new ConnectionEndPoint(endpoint, new ServerNameResolver(new ProtocolOptions()), null)); return connection; } - + private class ConnectionSendResult { public IRequest Request { get; set; } diff --git a/src/Cassandra.Tests/Requests/StartupOptionsFactoryTests.cs b/src/Cassandra.Tests/Requests/StartupOptionsFactoryTests.cs index b627a551b..95855c1a2 100644 --- a/src/Cassandra.Tests/Requests/StartupOptionsFactoryTests.cs +++ b/src/Cassandra.Tests/Requests/StartupOptionsFactoryTests.cs @@ -55,7 +55,7 @@ public void Should_ReturnCorrectProtocolStartupOptions_When_OptionsAreSet() // Assert.AreEqual("3.8.0", versionPrefix); // Assert.AreEqual("3.8.0", assemblyVersion); } - + [Test] public void Should_ReturnCorrectDseSpecificStartupOptions_When_OptionsAreSet() { diff --git a/src/Cassandra.Tests/ResponseFrameTest.cs b/src/Cassandra.Tests/ResponseFrameTest.cs index fb3986f4d..2ab6decbb 100644 --- a/src/Cassandra.Tests/ResponseFrameTest.cs +++ b/src/Cassandra.Tests/ResponseFrameTest.cs @@ -37,6 +37,6 @@ public void Ctor_BodyIsNull_Throws() // ReSharper disable once ObjectCreationAsStatement Assert.Throws(() => new Frame( new FrameHeader(), null, new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), null)); - } + } } } \ No newline at end of file diff --git a/src/Cassandra.Tests/RowSetUnitTests.cs b/src/Cassandra.Tests/RowSetUnitTests.cs index 1661d85a2..585b38121 100644 --- a/src/Cassandra.Tests/RowSetUnitTests.cs +++ b/src/Cassandra.Tests/RowSetUnitTests.cs @@ -424,7 +424,7 @@ private static RowSet CreateSampleRowSet() 100 }; rs.AddRow(new Row(rowValues, columns.ToArray(), columnIndexes)); - rs.AddRow(new Row(new object[] { null, null}, columns.ToArray(), columnIndexes)); + rs.AddRow(new Row(new object[] { null, null }, columns.ToArray(), columnIndexes)); return rs; } @@ -453,7 +453,7 @@ public void RowSet_Empty_Call_AddRow_Throws() [Test] public void Row_TryConvertToType_Should_Convert_Timestamps() { - var timestampTypeInfo = new CqlColumn {TypeCode = ColumnTypeCode.Timestamp}; + var timestampTypeInfo = new CqlColumn { TypeCode = ColumnTypeCode.Timestamp }; var values = new[] { //column desc, value, type and expected type @@ -474,7 +474,7 @@ public void Row_TryConvertToType_Should_Convert_Lists() { var listIntTypeInfo = new CqlColumn { - TypeCode = ColumnTypeCode.List, + TypeCode = ColumnTypeCode.List, TypeInfo = new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Int }, Type = typeof(IEnumerable) }; @@ -499,7 +499,7 @@ public void Row_TryConvertToType_Should_Convert_Sets() { var setIntTypeInfo = new CqlColumn { - TypeCode = ColumnTypeCode.Set, + TypeCode = ColumnTypeCode.Set, TypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int }, Type = typeof(IEnumerable) }; @@ -516,7 +516,7 @@ public void Row_TryConvertToType_Should_Convert_Sets() { var value = Row.TryConvertToType(item[0], (CqlColumn)item[1], (Type)item[2]); Assert.AreEqual(item.Length > 3 ? item[3] : item[2], value.GetType()); - CollectionAssert.AreEqual((int[]) item[0], (IEnumerable) value); + CollectionAssert.AreEqual((int[])item[0], (IEnumerable)value); } } @@ -565,7 +565,7 @@ public void Row_TryConvertToType_Should_Convert_Nested_Collections() TypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Set, - KeyTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int } + KeyTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int } } }; var listTypeInfo = new CqlColumn @@ -592,7 +592,7 @@ public void Row_TryConvertToType_Should_Convert_Nested_Collections() var value = Row.TryConvertToType(item.Item1, item.Item2, item.Item3); Assert.True(item.Item3.GetTypeInfo().IsInstanceOfType(value), "{0} is not assignable from {1}", item.Item3, value.GetType()); - Assert.AreEqual(TestHelper.FirstString(item.Item1), TestHelper.FirstString((IEnumerable) value)); + Assert.AreEqual(TestHelper.FirstString(item.Item1), TestHelper.FirstString((IEnumerable)value)); } } diff --git a/src/Cassandra.Tests/SchemaParserTests.cs b/src/Cassandra.Tests/SchemaParserTests.cs index 6f0ea484a..64bb9be82 100644 --- a/src/Cassandra.Tests/SchemaParserTests.cs +++ b/src/Cassandra.Tests/SchemaParserTests.cs @@ -49,7 +49,7 @@ private static SchemaParserV2 GetV2Instance(IControlConnection cc, Func /// Helper method to get a QueryTrace instance.. /// @@ -96,7 +96,7 @@ public void SchemaParserV1_GetKeyspace_Should_Retrieve_And_Parse_Keyspace_With_S Assert.AreEqual(ksName, ks.Name); Assert.AreEqual(true, ks.DurableWrites); Assert.AreEqual("Simple", ks.StrategyClass); - CollectionAssert.AreEqual(new Dictionary {{"replication_factor", 4}}, ks.Replication); + CollectionAssert.AreEqual(new Dictionary { { "replication_factor", 4 } }, ks.Replication); } [Test] @@ -135,7 +135,7 @@ public void SchemaParserV1_GetTable_Should_Parse_2_0_Table_With_Compact_Storage( {"type","Standard"}, {"value_alias",null} }); - var columnRows = new [] { + var columnRows = new[] { new Dictionary{{"keyspace_name","ks_tbl_meta"},{"columnfamily_name","tbl1"},{"column_name","id" },{"component_index",null},{"index_name",null},{"index_options",null},{"index_type",null},{"type","partition_key"},{"validator","org.apache.cassandra.db.marshal.UUIDType"}}, new Dictionary{{"keyspace_name","ks_tbl_meta"},{"columnfamily_name","tbl1"},{"column_name","text1"},{"component_index",null},{"index_name",null},{"index_options",null},{"index_type",null},{"type","regular" },{"validator","org.apache.cassandra.db.marshal.UTF8Type"}}, new Dictionary{{"keyspace_name","ks_tbl_meta"},{"columnfamily_name","tbl1"},{"column_name","text2"},{"component_index",null},{"index_name",null},{"index_options",null},{"index_type",null},{"type","regular" },{"validator","org.apache.cassandra.db.marshal.UTF8Type"}} @@ -247,14 +247,14 @@ public void SchemaParserV1_GetTable_Should_Parse_2_0_Table_With_StaticColumn() [Test] public void SchemaParserV1_GetTable_Should_Parse_1_2_Table_With_Partition_And_Clustering_Keys() { - var tableRow = TestHelper.CreateRow(new Dictionary - { - {"keyspace_name", "ks_tbl_meta"}, {"columnfamily_name", "tbl1"}, {"bloom_filter_fp_chance", 0.01}, {"caching", "KEYS_ONLY"}, + var tableRow = TestHelper.CreateRow(new Dictionary + { + {"keyspace_name", "ks_tbl_meta"}, {"columnfamily_name", "tbl1"}, {"bloom_filter_fp_chance", 0.01}, {"caching", "KEYS_ONLY"}, {"column_aliases", "[\"zck\"]"}, {"comment", ""}, {"compaction_strategy_class", "org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy"}, {"compaction_strategy_options", "{}"}, {"comparator", "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimeUUIDType,org.apache.cassandra.db.marshal.UTF8Type)"}, {"compression_parameters", "{\"sstable_compression\":\"org.apache.cassandra.io.compress.SnappyCompressor\"}"}, {"default_validator", "org.apache.cassandra.db.marshal.BytesType"}, {"gc_grace_seconds", 864000}, {"id", null}, {"key_alias", null}, {"key_aliases", "[\"pk1\",\"apk2\"]"}, {"key_validator", "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UUIDType,org.apache.cassandra.db.marshal.UTF8Type)"}, {"local_read_repair_chance", 0D}, {"max_compaction_threshold", 32}, {"min_compaction_threshold", 4}, {"populate_io_cache_on_flush", false}, {"read_repair_chance", 0.1}, {"replicate_on_write", true}, {"subcomparator", null}, {"type", "Standard"}, {"value_alias", null} }); - var columnRows = new [] + var columnRows = new[] { new Dictionary { {"keyspace_name", "ks_tbl_meta"}, {"columnfamily_name", "tbl1"}, {"column_name", "val2" }, {"component_index", 1}, {"index_name", null}, {"index_options", null}, {"index_type", null}, {"validator", "org.apache.cassandra.db.marshal.BytesType"}}, new Dictionary { {"keyspace_name", "ks_tbl_meta"}, {"columnfamily_name", "tbl1"}, {"column_name", "valz1"}, {"component_index", 1}, {"index_name", null}, {"index_options", null}, {"index_type", null}, {"validator", "org.apache.cassandra.db.marshal.Int32Type"}} @@ -636,13 +636,13 @@ public void SchemaParserV2_GetTable_Should_Parse_3_0_Table_With_SecondaryIndexes .Returns(() => TestHelper.DelayedTask(columnRows)); queryProviderMock .Setup(cc => cc.QueryAsync(It.IsRegex("system_schema\\.indexes.*ks1"), It.IsAny())) - .Returns(() => TestHelper.DelayedTask>(new[] {indexRow})); + .Returns(() => TestHelper.DelayedTask>(new[] { indexRow })); var parser = GetV2Instance(queryProviderMock.Object); var ks = TaskHelper.WaitToComplete(parser.GetKeyspaceAsync("ks1")); Assert.NotNull(ks); var table = ks.GetTableMetadata("tbl4"); Assert.False(table.Options.IsCompactStorage); - CollectionAssert.AreEquivalent(new[] { "pk", "ck", "val"}, table.TableColumns.Select(c => c.Name)); + CollectionAssert.AreEquivalent(new[] { "pk", "ck", "val" }, table.TableColumns.Select(c => c.Name)); CollectionAssert.AreEqual(new[] { "pk" }, table.PartitionKeys.Select(c => c.Name)); CollectionAssert.AreEqual(new[] { "ck" }, table.ClusteringKeys.Select(c => c.Item1.Name)); CollectionAssert.AreEqual(new[] { SortOrder.Descending }, table.ClusteringKeys.Select(c => c.Item2)); @@ -672,7 +672,7 @@ public void SchemaParserV2_GetTable_Should_Propagate_Exceptions_From_Query_Provi //This will cause the task to be faulted queryProviderMock .Setup(cc => cc.QueryAsync(It.IsRegex("system_schema\\.columns.*ks1"), It.IsAny())) - .Returns(() => TaskHelper.FromException>(new NoHostAvailableException(new Dictionary()))); + .Returns(() => TaskHelper.FromException>(new NoHostAvailableException(new Dictionary()))); queryProviderMock .Setup(cc => cc.QueryAsync(It.IsRegex("system_schema\\.indexes.*ks1"), It.IsAny())) .Returns(() => TestHelper.DelayedTask(Enumerable.Empty())); @@ -784,7 +784,7 @@ public void SchemaParser_GetQueryTrace_Should_Try_Multiple_Times_To_Get_The_Trac {"parameters", null}, {"started_at", DateTimeOffset.Now} }); - return TestHelper.DelayedTask>(new[] {sessionRow}); + return TestHelper.DelayedTask>(new[] { sessionRow }); }); queryProviderMock .Setup(cc => cc.QueryAsync(It.IsRegex("system_traces\\.events"), It.IsAny())) diff --git a/src/Cassandra.Tests/SerializerTests.cs b/src/Cassandra.Tests/SerializerTests.cs index 5826723b7..edb79224c 100644 --- a/src/Cassandra.Tests/SerializerTests.cs +++ b/src/Cassandra.Tests/SerializerTests.cs @@ -104,18 +104,18 @@ public void EncodeDecodeSingleValuesDefaultsFactory(object[] feed) static IEnumerable SingleValuesTestCases() { // 2-element array, type code - yield return new object[] { new [] {"just utf8 text olé!", "another"}, ColumnTypeCode.Text}; - yield return new object[] { new []{123, -1}, ColumnTypeCode.Int }; - yield return new object[] { new []{Int64.MinValue + 100, 1}, ColumnTypeCode.Bigint }; - yield return new object[] { new[]{-144F, 1.25F}, ColumnTypeCode.Float }; - yield return new object[] { new []{1120D, 1.3456D}, ColumnTypeCode.Double }; - yield return new object[] { new []{-9999.89770M, 8.0923M}, ColumnTypeCode.Decimal }; - yield return new object[] { new[]{new DateTimeOffset(new DateTime(2010, 4, 29)), new DateTimeOffset(new DateTime(1980, 1, 9))}, ColumnTypeCode.Timestamp }; - yield return new object[] { new[]{new IPAddress(new byte[] { 10, 0, 5, 5 }), new IPAddress(new byte[]{127,0,0,1})}, ColumnTypeCode.Inet }; - yield return new object[] { new[]{Guid.NewGuid(), Guid.NewGuid()}, ColumnTypeCode.Uuid }; - yield return new object[] { new[]{true, false}, ColumnTypeCode.Boolean }; - yield return new object[] { new[]{new byte[] { 255, 128, 64, 32, 16, 9, 9 }, new byte[]{0,1,128,9,1,2,3,4}}, ColumnTypeCode.Blob }; - yield return new object[] { new[] { TimeUuid.NewId().ToGuid(), TimeUuid.NewId().ToGuid() }, ColumnTypeCode.Timeuuid }; + yield return new object[] { new[] { "just utf8 text olé!", "another" }, ColumnTypeCode.Text }; + yield return new object[] { new[] { 123, -1 }, ColumnTypeCode.Int }; + yield return new object[] { new[] { Int64.MinValue + 100, 1 }, ColumnTypeCode.Bigint }; + yield return new object[] { new[] { -144F, 1.25F }, ColumnTypeCode.Float }; + yield return new object[] { new[] { 1120D, 1.3456D }, ColumnTypeCode.Double }; + yield return new object[] { new[] { -9999.89770M, 8.0923M }, ColumnTypeCode.Decimal }; + yield return new object[] { new[] { new DateTimeOffset(new DateTime(2010, 4, 29)), new DateTimeOffset(new DateTime(1980, 1, 9)) }, ColumnTypeCode.Timestamp }; + yield return new object[] { new[] { new IPAddress(new byte[] { 10, 0, 5, 5 }), new IPAddress(new byte[] { 127, 0, 0, 1 }) }, ColumnTypeCode.Inet }; + yield return new object[] { new[] { Guid.NewGuid(), Guid.NewGuid() }, ColumnTypeCode.Uuid }; + yield return new object[] { new[] { true, false }, ColumnTypeCode.Boolean }; + yield return new object[] { new[] { new byte[] { 255, 128, 64, 32, 16, 9, 9 }, new byte[] { 0, 1, 128, 9, 1, 2, 3, 4 } }, ColumnTypeCode.Blob }; + yield return new object[] { new[] { TimeUuid.NewId().ToGuid(), TimeUuid.NewId().ToGuid() }, ColumnTypeCode.Timeuuid }; yield return new object[] { new sbyte[] { 0, 1 }, ColumnTypeCode.TinyInt }; yield return new object[] { new short[] { -1, 1 }, ColumnTypeCode.SmallInt }; yield return new object[] { new[] { BigInteger.Parse("10000000"), BigInteger.One }, ColumnTypeCode.Varint }; @@ -133,13 +133,13 @@ static IEnumerable CollectionsTestCases() yield return new object[] { row[0], ColumnTypeCode.List, new ListColumnInfo() { ValueTypeCode = (ColumnTypeCode)row[1] } }; IEnumerable list = ((Array)row[0]).Cast().ToList(); - + yield return new object[] { new List(list), ColumnTypeCode.List, new ListColumnInfo() { ValueTypeCode = (ColumnTypeCode)row[1], ValueTypeInfo = new ListColumnInfo(){}} }; - + // Set yield return new object[] { @@ -156,7 +156,7 @@ static IEnumerable CollectionsTestCases() row[0], ColumnTypeCode.Set, new SetColumnInfo() { KeyTypeCode = (ColumnTypeCode)row[1] } }; - + // Vector yield return new object[] { @@ -191,7 +191,7 @@ static IEnumerable VectorsTestCases() }; } } - + static object CreateCqlVectorDynamicType(Array array) { Type elementType = array.GetType().GetElementType(); @@ -199,7 +199,7 @@ static object CreateCqlVectorDynamicType(Array array) ConstructorInfo constructor = cqlVectorType.GetConstructor(new Type[] { array.GetType() }); return constructor.Invoke(new object[] { array }); } - + [Test] [TestCaseSource(nameof(CollectionsTestCases))] public void EncodeDecodeListSetFactoryTest(object[] feed) @@ -207,7 +207,7 @@ public void EncodeDecodeListSetFactoryTest(object[] feed) foreach (var version in _protocolVersions) { var serializer = NewInstance(version); - var valueToEncode = (IEnumerable) feed [0]; + var valueToEncode = (IEnumerable)feed[0]; var encoded = serializer.Serialize(valueToEncode); var decoded = (IEnumerable)serializer.Deserialize(encoded, (ColumnTypeCode)feed[1], (IColumnInfo)feed[2]); CollectionAssert.AreEqual(valueToEncode, decoded); @@ -221,7 +221,7 @@ public void EncodeDecodeVectorFactoryTest(object[] feed) foreach (var version in _protocolVersions) { var serializer = NewInstance(version); - var valueToEncode = (IEnumerable) feed [0]; + var valueToEncode = (IEnumerable)feed[0]; var encoded = serializer.Serialize(valueToEncode); var decoded = (IEnumerable)serializer.Deserialize(encoded, (ColumnTypeCode)feed[1], (IColumnInfo)feed[2]); CollectionAssert.AreEqual(valueToEncode, decoded); @@ -297,14 +297,14 @@ public void EncodeDecodeTupleAsSubtypeFactoryTest() { new object[] { - new List>{new Tuple("val1")}, - ColumnTypeCode.List, + new List>{new Tuple("val1")}, + ColumnTypeCode.List, new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Tuple, ValueTypeInfo = new TupleColumnInfo() { Elements = new List() {new ColumnDesc(){TypeCode = ColumnTypeCode.Text}}}} }, new object[] { - new List>{new Tuple("val2ZZ", 0)}, - ColumnTypeCode.List, + new List>{new Tuple("val2ZZ", 0)}, + ColumnTypeCode.List, new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Tuple, ValueTypeInfo = new TupleColumnInfo() { Elements = new List() {new ColumnDesc(){TypeCode = ColumnTypeCode.Text}, new ColumnDesc(){TypeCode = ColumnTypeCode.Int}}}} } }; @@ -369,17 +369,17 @@ public void Encode_Decode_Nested_Map() var initialValues = new object[] { new object[] { - new SortedDictionary>{{"first", new List(new [] {1, 2, 1000})}}, + new SortedDictionary>{{"first", new List(new [] {1, 2, 1000})}}, ColumnTypeCode.Map, new MapColumnInfo { KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.List, ValueTypeInfo = new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Int}} }, new object[] { - new SortedDictionary>{{120, new SortedSet(new [] {"a", "b", "c"})}}, + new SortedDictionary>{{120, new SortedSet(new [] {"a", "b", "c"})}}, ColumnTypeCode.Map, new MapColumnInfo { KeyTypeCode = ColumnTypeCode.Int, ValueTypeCode = ColumnTypeCode.Set, ValueTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Text}} }, new object[] { - new SortedDictionary>{{"first-b", new SortedDictionary {{"A", 1}, {"B", 2}}}}, + new SortedDictionary>{{"first-b", new SortedDictionary {{"A", 1}, {"B", 2}}}}, ColumnTypeCode.Map, new MapColumnInfo { KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Map, ValueTypeInfo = new MapColumnInfo{ KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Int}} } @@ -446,7 +446,7 @@ public void Encode_Decode_Date() public void Encode_Decode_SmallInt() { var serializer = NewInstance(); - for (var i = Int16.MinValue; ; i++ ) + for (var i = Int16.MinValue; ; i++) { var encoded = serializer.Serialize(i); var decoded = (short)serializer.Deserialize(encoded, ColumnTypeCode.SmallInt, null); @@ -505,7 +505,7 @@ public void Encode_Decode_With_Binary_Representation() { var encoded = serializer.Serialize(val.Item1); CollectionAssert.AreEqual(val.Item2, encoded); - var padEncoded = new byte[] {0xFF, 0xFA}.Concat(encoded).ToArray(); + var padEncoded = new byte[] { 0xFF, 0xFA }.Concat(encoded).ToArray(); Assert.AreEqual(val.Item1, serializer.Deserialize(padEncoded, 2, encoded.Length, serializer.GetCqlTypeForPrimitive(val.Item1.GetType()), null)); } } @@ -533,15 +533,15 @@ public void GetClrType_Should_Get_Clr_Type_For_Primitive_Cql_Types() [Test] public void GetClrType_Should_Get_Clr_Type_For_Non_Primitive_Cql_Types() { - var notPrimitive = new [] + var notPrimitive = new[] { Tuple.Create(typeof(IEnumerable), ColumnTypeCode.List, new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Text}), Tuple.Create(typeof(IEnumerable), ColumnTypeCode.Set, new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int}), - Tuple.Create(typeof(IEnumerable>), ColumnTypeCode.List, + Tuple.Create(typeof(IEnumerable>), ColumnTypeCode.List, new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Set, ValueTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Timestamp}}), - Tuple.Create(typeof(IDictionary), ColumnTypeCode.Map, + Tuple.Create(typeof(IDictionary), ColumnTypeCode.Map, new MapColumnInfo { KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Int }), - Tuple.Create(typeof(Tuple), ColumnTypeCode.Tuple, + Tuple.Create(typeof(Tuple), ColumnTypeCode.Tuple, new TupleColumnInfo(new [] { ColumnTypeCode.Text, ColumnTypeCode.Int, ColumnTypeCode.Date}.Select(c => new ColumnDesc {TypeCode = c}))) }; var serializer = NewInstance(); diff --git a/src/Cassandra.Tests/SessionTests.cs b/src/Cassandra.Tests/SessionTests.cs index 4657b03ae..0fc8519fd 100644 --- a/src/Cassandra.Tests/SessionTests.cs +++ b/src/Cassandra.Tests/SessionTests.cs @@ -41,8 +41,8 @@ public void Should_GenerateNewSessionId_When_SessionIsCreated() var config = new TestConfigurationBuilder { Policies = new Cassandra.Policies( - new RoundRobinPolicy(), - new ConstantReconnectionPolicy(100), + new RoundRobinPolicy(), + new ConstantReconnectionPolicy(100), new DefaultRetryPolicy()), SessionFactory = sessionFactoryMock, ControlConnectionFactory = new FakeControlConnectionFactory(), diff --git a/src/Cassandra.Tests/StatementTests.cs b/src/Cassandra.Tests/StatementTests.cs index 69a99142b..1591e9e0c 100644 --- a/src/Cassandra.Tests/StatementTests.cs +++ b/src/Cassandra.Tests/StatementTests.cs @@ -90,8 +90,8 @@ public void SimpleStatement_Constructor_Dictionary_Named_Test() { var valuesDictionary = new Dictionary { - {"Name", "Futurama"}, - {"Description", "In Stereo where available"}, + {"Name", "Futurama"}, + {"Description", "In Stereo where available"}, {"Time", DateTimeOffset.Parse("1963-08-28")} }; var stmt = new SimpleStatement(valuesDictionary, Query); @@ -155,7 +155,7 @@ public void PreparedStatement_Bind_SetsRoutingKey_Single() { Columns = new[] { - new CqlColumn { Name = "name" }, + new CqlColumn { Name = "name" }, new CqlColumn { Name = "id" } } }; @@ -201,12 +201,12 @@ public void PreparedStatement_Bind_SetsRoutingKey_Multiple() Assert.NotNull(bound.RoutingKey); var serializer = new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(); var expectedRoutingKey = new byte[0] - .Concat(new byte[] {0, 4}) + .Concat(new byte[] { 0, 4 }) .Concat(serializer.Serialize(1001)) - .Concat(new byte[] {0}) - .Concat(new byte[] {0, 4}) + .Concat(new byte[] { 0 }) + .Concat(new byte[] { 0, 4 }) .Concat(serializer.Serialize(2001)) - .Concat(new byte[] {0}); + .Concat(new byte[] { 0 }); CollectionAssert.AreEqual(expectedRoutingKey, bound.RoutingKey.RawRoutingKey); } @@ -289,7 +289,7 @@ public void BatchStatement_Max_Queries_Test() [Test] public void BatchStatement_Should_Use_Routing_Key_Of_First_Statement_With_SimpleStatement_Instances() { - var rawRoutingKey = new byte[] {1, 2, 3, 4}; + var rawRoutingKey = new byte[] { 1, 2, 3, 4 }; var s1 = new SimpleStatement("Q1").SetRoutingKey(new RoutingKey(rawRoutingKey)); var s2 = new SimpleStatement("Q2").SetRoutingKey(new RoutingKey(new byte[] { 100, 101, 102 })); var batch = new BatchStatement().Add(s1).Add(s2); @@ -300,7 +300,7 @@ public void BatchStatement_Should_Use_Routing_Key_Of_First_Statement_With_Simple [Test] public void BatchStatement_Should_Use_Routing_Key_Of_First_Statement_With_Statement_Instances() { - var rawRoutingKey = new byte[] {1, 2, 3, 4}; + var rawRoutingKey = new byte[] { 1, 2, 3, 4 }; var s1MockCalled = 0; var s1MockCalledKeyspace = 0; var s2MockCalled = 0; @@ -327,7 +327,7 @@ public void BatchStatement_Should_Use_Routing_Key_Of_First_Statement_With_Statem [Test] public void BatchStatement_Should_UseRoutingKeyAndKeyspaceOfFirstStatement_When_TokenAwareLbpIsUsed() { - var rawRoutingKey = new byte[] {1, 2, 3, 4}; + var rawRoutingKey = new byte[] { 1, 2, 3, 4 }; var lbp = new TokenAwarePolicy(new ClusterTests.FakeLoadBalancingPolicy()); var clusterMock = Mock.Of(); Mock.Get(clusterMock).Setup(c => c.GetReplicas(It.IsAny(), It.IsAny())) @@ -335,7 +335,7 @@ public void BatchStatement_Should_UseRoutingKeyAndKeyspaceOfFirstStatement_When_ Mock.Get(clusterMock).Setup(c => c.AllHosts()) .Returns(new List()); lbp.Initialize(clusterMock); - + var s1Mock = new Mock(MockBehavior.Loose); s1Mock.Setup(s => s.RoutingKey).Returns(new RoutingKey(rawRoutingKey)); s1Mock.Setup(s => s.Keyspace).Returns("ks1"); diff --git a/src/Cassandra.Tests/TaskTests.cs b/src/Cassandra.Tests/TaskTests.cs index bdde7a5e6..181d1bd5e 100644 --- a/src/Cassandra.Tests/TaskTests.cs +++ b/src/Cassandra.Tests/TaskTests.cs @@ -177,7 +177,7 @@ public void ConfigureAwait_Used_For_Every_Awaited_Task() { Assert.Fail("Library source folder could not be determined"); } - var regex = new Regex("\\bawait\\b(?![^;]*ConfigureAwait\\(false\\))[^;]*;", + var regex = new Regex("\\bawait\\b(?![^;]*ConfigureAwait\\(false\\))[^;]*;", RegexOptions.Multiline | RegexOptions.Compiled); foreach (var fileInfo in directory.GetFiles("*.cs", SearchOption.AllDirectories)) { @@ -185,7 +185,7 @@ public void ConfigureAwait_Used_For_Every_Awaited_Task() var match = regex.Match(source); if (match.Success) { - Assert.Fail("Awaited Task without ConfigureAwait() call in file {0}: {1}", + Assert.Fail("Awaited Task without ConfigureAwait() call in file {0}: {1}", fileInfo.FullName, match.Value); } } diff --git a/src/Cassandra.Tests/TestAttributes/WinOnlyAttribute.cs b/src/Cassandra.Tests/TestAttributes/WinOnlyAttribute.cs index 5b6b21ce2..3aa820e30 100644 --- a/src/Cassandra.Tests/TestAttributes/WinOnlyAttribute.cs +++ b/src/Cassandra.Tests/TestAttributes/WinOnlyAttribute.cs @@ -51,7 +51,7 @@ public WinOnlyAttribute(int major, int minor) /// public WinOnlyAttribute() : this(0, 0) { - + } public void ApplyToTest(NUnit.Framework.Internal.Test test) diff --git a/src/Cassandra.Tests/TestCategory.cs b/src/Cassandra.Tests/TestCategory.cs index a10cef494..17d1731ab 100644 --- a/src/Cassandra.Tests/TestCategory.cs +++ b/src/Cassandra.Tests/TestCategory.cs @@ -30,7 +30,7 @@ public static class TestCategory /// These tests run in all CI schedules (both Appveyor and Jenkins) except if they are marked with the categories below. /// public const string Short = "short"; - + /// /// These tests run once in Appveyor per commit (not for the entire matrix) and in all Jenkins schedules. /// @@ -40,19 +40,19 @@ public static class TestCategory /// These tests run in Jenkins nightly builds only. /// public const string RealClusterLong = "realclusterlong"; - + /// /// These tests run once in Jenkins per commit (not for the entire matrix). /// public const string Cloud = "cloud"; - + /// /// These tests can also be marked with other categories. /// This category is used in the smoke tests against DSE or Apache C* release candidates. /// https://github.com/datastax/cassandra-drivers-smoke-test /// public const string ServerApi = "serverapi"; - + /// /// These tests can only run against a kerberos enabled cluster. /// At the moment, they are skipped in all CI schedules. diff --git a/src/Cassandra.Tests/TestConfigurationBuilder.cs b/src/Cassandra.Tests/TestConfigurationBuilder.cs index 308637a60..df2a06c62 100644 --- a/src/Cassandra.Tests/TestConfigurationBuilder.cs +++ b/src/Cassandra.Tests/TestConfigurationBuilder.cs @@ -110,14 +110,14 @@ internal class TestConfigurationBuilder public ISupportedOptionsInitializerFactory SupportedOptionsInitializerFactory { get; set; } = new SupportedOptionsInitializerFactory(); public IServerEventsSubscriber ServerEventsSubscriber { get; set; } = new ServerEventsSubscriber(); - + public IProtocolVersionNegotiator ProtocolVersionNegotiator { get; set; } = new ProtocolVersionNegotiator(); - + public MonitorReportingOptions MonitorReportingOptions { get; set; } = new MonitorReportingOptions(); public IInsightsSupportVerifier InsightsSupportVerifier { get; set; } = new InsightsSupportVerifier(); - public IInsightsClientFactory InsightsClientFactory { get; set; } = + public IInsightsClientFactory InsightsClientFactory { get; set; } = new InsightsClientFactory( Configuration.DefaultInsightsStartupMessageFactory, Configuration.DefaultInsightsStatusMessageFactory); diff --git a/src/Cassandra.Tests/TestHelper.cs b/src/Cassandra.Tests/TestHelper.cs index 08db9850e..9de99fedd 100644 --- a/src/Cassandra.Tests/TestHelper.cs +++ b/src/Cassandra.Tests/TestHelper.cs @@ -504,7 +504,7 @@ private static void SendNew(Func> action, TaskCompletionSource tcs.TrySetException(ex); return; } - + var received = counter.IncrementReceived(); if (received == maxLength) { diff --git a/src/Cassandra.Tests/TestHelpers/FakeInitializer.cs b/src/Cassandra.Tests/TestHelpers/FakeInitializer.cs index 01c569c63..1cf41a9c5 100644 --- a/src/Cassandra.Tests/TestHelpers/FakeInitializer.cs +++ b/src/Cassandra.Tests/TestHelpers/FakeInitializer.cs @@ -28,7 +28,7 @@ public FakeInitializer(Configuration config) { _config = config; } - + public FakeInitializer(Configuration config, IEnumerable endpts) { _config = config; diff --git a/src/Cassandra.Tests/TestTimeoutAttribute.cs b/src/Cassandra.Tests/TestTimeoutAttribute.cs index 8d6cad600..de10c4aab 100644 --- a/src/Cassandra.Tests/TestTimeoutAttribute.cs +++ b/src/Cassandra.Tests/TestTimeoutAttribute.cs @@ -20,7 +20,7 @@ namespace Cassandra.Tests { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, Inherited = false)] - public class TestTimeoutAttribute : + public class TestTimeoutAttribute : #if NETFRAMEWORK TimeoutAttribute #else diff --git a/src/Cassandra.Tests/ThreadPerTaskScheduler.cs b/src/Cassandra.Tests/ThreadPerTaskScheduler.cs index d24c7be8b..ea50e3887 100644 --- a/src/Cassandra.Tests/ThreadPerTaskScheduler.cs +++ b/src/Cassandra.Tests/ThreadPerTaskScheduler.cs @@ -14,7 +14,7 @@ // limitations under the License. // -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/src/Cassandra.Tests/TimeUuidTests.cs b/src/Cassandra.Tests/TimeUuidTests.cs index 4398917ca..2cc3cbb79 100644 --- a/src/Cassandra.Tests/TimeUuidTests.cs +++ b/src/Cassandra.Tests/TimeUuidTests.cs @@ -73,7 +73,7 @@ public void UuidEqualityTest() Assert.AreEqual(id4, id4TimeId); Assert.AreEqual(id4.ToByteArray(), id4Id.ToByteArray()); } - + [Test] public void CheckCollisionsTest() { @@ -139,7 +139,7 @@ public void Compare_Test1() public void Compare_Test2() { var dt0 = new DateTimeOffset(1582, 10, 15, 0, 0, 0, TimeSpan.Zero); - var arr = new [] + var arr = new[] { TimeUuid.NewId(dt0.AddTicks(0x00000000007fffL)), TimeUuid.NewId(dt0.AddTicks(0x00ff0000000000L)), @@ -167,8 +167,8 @@ public void Min_Test() var timestamp = DateTimeOffset.Now; var timeuuid = TimeUuid.Min(timestamp); Assert.AreEqual(timestamp, timeuuid.GetDate()); - Assert.AreEqual(new byte[] {0x80, 0x80}, timeuuid.ToByteArray().Skip(8).Take(2)); - Assert.AreEqual(new byte[] {0x80, 0x80, 0x80, 0x80, 0x80, 0x80}, timeuuid.ToByteArray().Skip(10).Take(6)); + Assert.AreEqual(new byte[] { 0x80, 0x80 }, timeuuid.ToByteArray().Skip(8).Take(2)); + Assert.AreEqual(new byte[] { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }, timeuuid.ToByteArray().Skip(10).Take(6)); } [Test] @@ -178,8 +178,8 @@ public void Max_Test() var timeuuid = TimeUuid.Max(timestamp); Assert.AreEqual(timestamp, timeuuid.GetDate()); // Variant Byte at index 8: 0x7f is changed into 0xbf - Assert.AreEqual(new byte[] {0xbf, 0x7f}, timeuuid.ToByteArray().Skip(8).Take(2)); - Assert.AreEqual(new byte[] {0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f}, timeuuid.ToByteArray().Skip(10).Take(6)); + Assert.AreEqual(new byte[] { 0xbf, 0x7f }, timeuuid.ToByteArray().Skip(8).Take(2)); + Assert.AreEqual(new byte[] { 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f }, timeuuid.ToByteArray().Skip(10).Take(6)); } } } diff --git a/src/Cassandra.Tests/TimeoutTests.cs b/src/Cassandra.Tests/TimeoutTests.cs index c555a0d1e..e15baa851 100644 --- a/src/Cassandra.Tests/TimeoutTests.cs +++ b/src/Cassandra.Tests/TimeoutTests.cs @@ -87,31 +87,31 @@ public void WheelTimer_Bucket_Should_Remove_Head_Items_Correctly() var t4 = new TimeoutItem(timer, EmptyAction, null); bucket.Add(t1); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t1}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t1 }); Assert.AreEqual(bucket.GetTail(), t1); bucket.Add(t2); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t1, t2}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t1, t2 }); Assert.AreEqual(bucket.GetTail(), t2); bucket.Add(t3); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t1, t2, t3}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t1, t2, t3 }); Assert.AreEqual(bucket.GetTail(), t3); bucket.Add(t4); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t1, t2, t3, t4}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t1, t2, t3, t4 }); Assert.AreEqual(bucket.GetTail(), t4); bucket.Remove(t1); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t2, t3, t4}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t2, t3, t4 }); Assert.AreEqual(bucket.GetTail(), t4); bucket.Remove(t3); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t2, t4}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t2, t4 }); Assert.AreEqual(bucket.GetTail(), t4); bucket.Remove(t4); - CollectionAssert.AreEqual(bucket.ToArray(), new[] {t2}); + CollectionAssert.AreEqual(bucket.ToArray(), new[] { t2 }); Assert.AreEqual(bucket.GetTail(), t2); bucket.Remove(t2); diff --git a/src/Cassandra.Tests/TokenTests.cs b/src/Cassandra.Tests/TokenTests.cs index 4d9ab7592..92ad7869a 100644 --- a/src/Cassandra.Tests/TokenTests.cs +++ b/src/Cassandra.Tests/TokenTests.cs @@ -414,7 +414,7 @@ public void Build_Should_OnlyCallOncePerReplicationConfiguration_When_MultipleKe AssertOnlyOneStrategyIsCalled(proxyStrategies, 4, 8); AssertOnlyOneStrategyIsCalled(proxyStrategies, 5, 7); } - + /// /// If the replication strategy returns Equals true for different hashcodes then /// it is possible for Dictionary to accept a "duplicate" but the TokenMap constructor @@ -425,14 +425,14 @@ public void Build_Should_OnlyCallOncePerReplicationConfiguration_When_MultipleKe public void Build_Should_CopyReplicationStrategiesFromDictionaryToConcurrentDictionary_When_DifferentStrategiesAreUsed() { foreach (var rf1 in Enumerable.Range(1, 32).Select(r => r.ToString())) - foreach (var rf2 in Enumerable.Range(1, 32).Select(r => r.ToString())) - { - if (rf1 == rf2) + foreach (var rf2 in Enumerable.Range(1, 32).Select(r => r.ToString())) { - continue; - } + if (rf1 == rf2) + { + continue; + } - var keyspaces = new List + var keyspaces = new List { // unique configurations FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2), @@ -449,34 +449,34 @@ public void Build_Should_CopyReplicationStrategiesFromDictionaryToConcurrentDict FakeSchemaParserFactory.CreateSimpleKeyspace("ks10", 10), FakeSchemaParserFactory.CreateSimpleKeyspace("ks11", 2) }; - var strategies = keyspaces.Select(k => k.Strategy).ToList(); + var strategies = keyspaces.Select(k => k.Strategy).ToList(); - var dictionary = new Dictionary(); - foreach (var strategy in strategies) - { - if (!dictionary.ContainsKey(strategy)) + var dictionary = new Dictionary(); + foreach (var strategy in strategies) { - dictionary.Add(strategy, ""); + if (!dictionary.ContainsKey(strategy)) + { + dictionary.Add(strategy, ""); + } } - } - // private const in ConcurrentDictionary - const int defaultCapacity = 31; + // private const in ConcurrentDictionary + const int defaultCapacity = 31; - // would love to test every possible value but it would take too much time - foreach (var concurrencyLevel in Enumerable.Range(1, 512)) - { - var concurrentDictionary = new ConcurrentDictionary(concurrencyLevel, defaultCapacity); - foreach (var strategy in dictionary) + // would love to test every possible value but it would take too much time + foreach (var concurrencyLevel in Enumerable.Range(1, 512)) { - if (!concurrentDictionary.TryAdd(strategy.Key, strategy.Value)) + var concurrentDictionary = new ConcurrentDictionary(concurrencyLevel, defaultCapacity); + foreach (var strategy in dictionary) { - Assert.Fail($"This would throw ArgumentException, duplicate values with processor count: {concurrencyLevel}, rf1: {rf1}, rf2: {rf2}"); - return; + if (!concurrentDictionary.TryAdd(strategy.Key, strategy.Value)) + { + Assert.Fail($"This would throw ArgumentException, duplicate values with processor count: {concurrencyLevel}, rf1: {rf1}, rf2: {rf2}"); + return; + } } } } - } } [Test] @@ -505,12 +505,12 @@ public void Should_UpdateKeyspacesAndTokenMapCorrectly_When_MultipleThreadsCalli { ConnectionFactory = new FakeConnectionFactory() }.Build(); - var metadata = new Metadata(config, schemaParser) {Partitioner = "Murmur3Partitioner"}; + var metadata = new Metadata(config, schemaParser) { Partitioner = "Murmur3Partitioner" }; metadata.ControlConnection = new ControlConnection( Mock.Of(), - new ProtocolEventDebouncer(new TaskBasedTimerFactory(), TimeSpan.FromMilliseconds(20), TimeSpan.FromSeconds(100)), - ProtocolVersion.V3, - config, + new ProtocolEventDebouncer(new TaskBasedTimerFactory(), TimeSpan.FromMilliseconds(20), TimeSpan.FromSeconds(100)), + ProtocolVersion.V3, + config, metadata, new List { @@ -570,7 +570,7 @@ public void Should_UpdateKeyspacesAndTokenMapCorrectly_When_MultipleThreadsCalli } } } - else + else if (j % 2 == 0) { if (bag.TryTake(out var ksName)) @@ -632,21 +632,21 @@ public void RefreshSingleKeyspace_Should_BuildTokenMap_When_TokenMapIsNull() } private KeyspaceMetadata CreateKeyspaceMetadata( - Metadata parent, - string name, - bool durableWrites, + Metadata parent, + string name, + bool durableWrites, string strategyClass, IDictionary replicationOptions, bool isVirtual = false) { return new KeyspaceMetadata( - parent, - name, - durableWrites, - strategyClass, - replicationOptions, - new ReplicationStrategyFactory(), - null, + parent, + name, + durableWrites, + strategyClass, + replicationOptions, + new ReplicationStrategyFactory(), + null, isVirtual); } diff --git a/src/Cassandra.Tests/UtilsTests.cs b/src/Cassandra.Tests/UtilsTests.cs index 3a8f105b2..987374b9d 100644 --- a/src/Cassandra.Tests/UtilsTests.cs +++ b/src/Cassandra.Tests/UtilsTests.cs @@ -56,13 +56,13 @@ public void ByteArrayComparer_GetHashCode_Test() Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, true), Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, new byte[]{ 1, 2, 3, 4, 5, 6, 7, 9, 9, 10 }, false), Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 }, false), - Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, true), - Tuple.Create(new byte[]{ 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 160}, + Tuple.Create(new byte[]{ 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 160}, new byte[]{ 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 160}, true), - Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17 }, false), - Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new byte[]{ 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, false), Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 10 }, new byte[]{ 1, 2, 3, 4, 5, 10 }, true), Tuple.Create(new byte[]{ 1, 2, 3, 4, 5, 10 }, new byte[]{ 2, 2, 3, 4, 5, 11 }, false) @@ -76,7 +76,7 @@ public void ByteArrayComparer_GetHashCode_Test() } else { - Assert.AreNotEqual(comparer.GetHashCode(item.Item1), comparer.GetHashCode(item.Item2), + Assert.AreNotEqual(comparer.GetHashCode(item.Item1), comparer.GetHashCode(item.Item2), "For value: " + string.Join(", ", item.Item1)); } } diff --git a/src/Cassandra/AggregateMetadata.cs b/src/Cassandra/AggregateMetadata.cs index 2a7c1be1c..caa02839f 100644 --- a/src/Cassandra/AggregateMetadata.cs +++ b/src/Cassandra/AggregateMetadata.cs @@ -74,10 +74,10 @@ public class AggregateMetadata public AggregateMetadata() { - + } - public AggregateMetadata(string name, string keyspaceName, string[] signature, ColumnDesc[] argumentTypes, + public AggregateMetadata(string name, string keyspaceName, string[] signature, ColumnDesc[] argumentTypes, string stateFunction, ColumnDesc stateType, string finalFunction, string initialCondition, ColumnDesc returnType) { diff --git a/src/Cassandra/BeConverter.cs b/src/Cassandra/BeConverter.cs index ed584c9d5..462ef6c25 100644 --- a/src/Cassandra/BeConverter.cs +++ b/src/Cassandra/BeConverter.cs @@ -30,7 +30,7 @@ internal static class BeConverter /// public static byte[] GetBytes(short value) { - return new[] { (byte)((value & 0xFF00) >> 8), (byte) (value & 0xFF)}; + return new[] { (byte)((value & 0xFF00) >> 8), (byte)(value & 0xFF) }; } /// @@ -38,7 +38,7 @@ public static byte[] GetBytes(short value) /// public static byte[] GetBytes(ushort value) { - return GetBytes((short) value); + return GetBytes((short)value); } /// @@ -60,7 +60,7 @@ public static byte[] GetBytes(int value) /// public static byte[] GetBytes(long value) { - return new [] + return new[] { (byte) (((ulong) value & 0xFF00000000000000) >> 56), (byte) ((value & 0xFF000000000000) >> 48), @@ -129,7 +129,7 @@ public static int ToInt32(byte[] value, int offset = 0) public static long ToInt64(byte[] value, int offset = 0) { return (long)( - ((ulong)value[offset] << 56) + ((ulong)value[offset] << 56) | ((ulong)value[offset + 1] << 48) | ((ulong)value[offset + 2] << 40) | ((ulong)value[offset + 3] << 32) diff --git a/src/Cassandra/BigIntegerTypeAdapter.cs b/src/Cassandra/BigIntegerTypeAdapter.cs index bf55adbe0..75fcc7629 100644 --- a/src/Cassandra/BigIntegerTypeAdapter.cs +++ b/src/Cassandra/BigIntegerTypeAdapter.cs @@ -24,7 +24,7 @@ public class BigIntegerTypeAdapter : ITypeAdapter { public Type GetDataType() { - return typeof (BigInteger); + return typeof(BigInteger); } public object ConvertFrom(byte[] decimalBuf) @@ -35,7 +35,7 @@ public object ConvertFrom(byte[] decimalBuf) public byte[] ConvertTo(object value) { TypeSerializer.CheckArgument(value); - return ((BigInteger) value).ToByteArray(); + return ((BigInteger)value).ToByteArray(); } } } \ No newline at end of file diff --git a/src/Cassandra/BoundStatement.cs b/src/Cassandra/BoundStatement.cs index b3fc34480..0247cda7c 100644 --- a/src/Cassandra/BoundStatement.cs +++ b/src/Cassandra/BoundStatement.cs @@ -97,7 +97,7 @@ public BoundStatement(PreparedStatement statement) SetIdempotence(statement.IsIdempotent.Value); } } - + /// /// Set the routing key for this query. This method allows to manually /// provide a routing key for this BoundStatement. It is thus optional since the routing @@ -127,7 +127,7 @@ private object[] ValidateValues(object[] values, ISerializer serializer) { throw new DriverInternalError("Serializer can not be null"); } - + if (values == null) { return null; @@ -182,21 +182,21 @@ internal override IQueryRequest CreateBatchRequest(ISerializer serializer) // Use the default query options as the individual options of the query will be ignored var options = QueryProtocolOptions.CreateForBatchItem(this, PreparedStatement.Variables); return new ExecuteRequest( - serializer, + serializer, PreparedStatement.Id, - PreparedStatement.ResultMetadata, - options, - IsTracing, + PreparedStatement.ResultMetadata, + options, + IsTracing, null, true); } internal void CalculateRoutingKey( ISerializer serializer, - bool useNamedParameters, - int[] routingIndexes, - string[] routingNames, - object[] valuesByPosition, + bool useNamedParameters, + int[] routingIndexes, + string[] routingNames, + object[] valuesByPosition, object[] rawValues) { if (_routingKey != null) diff --git a/src/Cassandra/Builder.cs b/src/Cassandra/Builder.cs index 6c2c42c8f..eb52ef96b 100644 --- a/src/Cassandra/Builder.cs +++ b/src/Cassandra/Builder.cs @@ -150,7 +150,7 @@ public ICollection ContactPoints { get { return _contactPoints.Select(c => c as IPEndPoint).Where(c => c != null).ToList(); } } - + /// /// The configuration that will be used for the new cluster.

You should /// not modify this object directly as change made to the returned object may @@ -165,7 +165,7 @@ public Configuration GetConfiguration() { ConfigureCloudCluster(_bundlePath); } - + var typeSerializerDefinitions = _typeSerializerDefinitions ?? new TypeSerializerDefinitions(); var policies = GetPolicies(); var graphOptions = GetGraphOptions(); @@ -225,12 +225,12 @@ private void SetLegacySettingsFromDefaultProfile() { _socketOptions.SetReadTimeoutMillis(profile.ReadTimeoutMillis.Value); } - + if (profile.ConsistencyLevel.HasValue) { _queryOptions.SetConsistencyLevel(profile.ConsistencyLevel.Value); } - + if (profile.SerialConsistencyLevel.HasValue) { _queryOptions.SetSerialConsistencyLevel(profile.SerialConsistencyLevel.Value); @@ -273,7 +273,7 @@ private Policies GetPolicies() "and another through the default execution profile. Policies provided through the default execution profile " + "take precedence over policies specified through the Builder methods."); } - + if (profile.SpeculativeExecutionPolicy != null && _speculativeExecutionPolicy != null) { Builder.Logger.Warning( @@ -281,7 +281,7 @@ private Policies GetPolicies() "and another through the default execution profile. Policies provided through the default execution profile " + "take precedence over policies specified through the Builder methods."); } - + if (profile.RetryPolicy != null && _retryPolicy != null) { Builder.Logger.Warning( @@ -607,7 +607,7 @@ public Builder WithLoadBalancingPolicy(ILoadBalancingPolicy policy) _loadBalancingPolicy = policy; return this; } - + ///

/// Configure the reconnection policy to use for the new cluster.

If no /// reconnection policy is set through this method, @@ -923,7 +923,7 @@ public Builder WithTypeSerializers(TypeSerializerDefinitions definitions) _typeSerializerDefinitions = definitions ?? throw new ArgumentNullException(nameof(definitions)); return this; } - + internal Builder WithEndPointResolver(IEndPointResolver endPointResolver) { _endPointResolver = endPointResolver ?? throw new ArgumentNullException(nameof(endPointResolver)); @@ -971,7 +971,7 @@ public Builder WithMetrics(IDriverMetricsProvider driverMetricsProvider) _metricsOptions = null; return this; } - + ///

/// /// Enables metrics. DataStax provides an implementation based on a third party library (App.Metrics) @@ -1100,7 +1100,7 @@ public Builder WithMetadataSyncOptions(MetadataSyncOptions metadataSyncOptions) _metadataSyncOptions = metadataSyncOptions; return this; } - + /// /// objects created through the built from this builder will have /// set to the value provided in this method. @@ -1190,7 +1190,7 @@ public Cluster Build() return Cluster.BuildFrom(this, _contactPoints.Where(c => !(c is IPEndPoint)).ToList(), config); } - + /// /// Clear and set contact points. /// @@ -1199,19 +1199,19 @@ private Builder SetContactPoints(IEnumerable contactPoints) _contactPoints.Clear(); return AddMultipleContactPointsInternal(contactPoints); } - + private Builder ConfigureCloudCluster(string bundlePath) { if (_addedSsl) { throw new ArgumentException("SSL options can not be set when a secure connection bundle is provided."); } - + if (_addedContactPoints) { throw new ArgumentException("Contact points can not be set when a secure connection bundle is provided."); } - + if (!_addedAuth) { throw new ArgumentException( @@ -1255,7 +1255,7 @@ private Builder ConfigureCloudCluster(SecureConnectionBundle bundle) }); builder = builder.WithEndPointResolver(sniEndPointResolver); - + if (!_addedLbp) { if (cloudMetadata.ContactInfo.LocalDc == null) diff --git a/src/Cassandra/CassandraConnectionStringBuilder.cs b/src/Cassandra/CassandraConnectionStringBuilder.cs index c8bd17c0e..2c56d9c35 100644 --- a/src/Cassandra/CassandraConnectionStringBuilder.cs +++ b/src/Cassandra/CassandraConnectionStringBuilder.cs @@ -86,14 +86,14 @@ private T DefaultIfNotExists(string name, T def) { if (!base.ContainsKey(name)) return def; - return (T) Convert.ChangeType(base[name], typeof (T)); + return (T)Convert.ChangeType(base[name], typeof(T)); } private T ThrowIfNotExists(string name) { if (!base.ContainsKey(name)) throw new FormatException(name + " value are missing in connection string"); - return (T) Convert.ChangeType(base[name], typeof (T)); + return (T)Convert.ChangeType(base[name], typeof(T)); } } } diff --git a/src/Cassandra/Cluster.cs b/src/Cassandra/Cluster.cs index b958671ad..159687962 100644 --- a/src/Cassandra/Cluster.cs +++ b/src/Cassandra/Cluster.cs @@ -179,11 +179,11 @@ private Cluster(IEnumerable contactPoints, Configuration configuration) var parsedContactPoints = configuration.ContactPointParser.ParseContactPoints(contactPoints); _controlConnection = configuration.ControlConnectionFactory.Create( - this, - _protocolEventDebouncer, - protocolVersion, - Configuration, - _metadata, + this, + _protocolEventDebouncer, + protocolVersion, + Configuration, + _metadata, parsedContactPoints); _metadata.ControlConnection = _controlConnection; @@ -223,7 +223,7 @@ private async Task Init() loadBalancingPolicies.Add(options.LoadBalancingPolicy); speculativeExecutionPolicies.Add(options.SpeculativeExecutionPolicy); } - + _loadBalancingPolicies = loadBalancingPolicies.ToList(); // Only abort the async operations when at least twice the time for ConnectTimeout per host passed @@ -252,7 +252,7 @@ private async Task Init() }, TaskContinuationOptions.ExecuteSynchronously).Forget(); throw newEx; } - + // Initialize policies foreach (var lbp in loadBalancingPolicies) { @@ -653,7 +653,7 @@ private async Task ReprepareAllQueries(Host host) { return; } - + // Get the first pool for that host that has open connections var pool = sessions.Select(s => s.GetExistingPool(host.Address)).Where(p => p != null).FirstOrDefault(p => p.HasConnections); if (pool == null) @@ -673,10 +673,10 @@ private async Task ReprepareAllQueries(Host host) var request = new InternalPrepareRequest(serializer, ps.Cql, ps.Keyspace, null); await semaphore.WaitAsync().ConfigureAwait(false); tasks.Add(Task.Run(() => handler.ReprepareOnSingleNodeAsync( - new KeyValuePair(host, pool), - ps, - request, - semaphore, + new KeyValuePair(host, pool), + ps, + request, + semaphore, true))); } diff --git a/src/Cassandra/Collections/ArrayBackedList.cs b/src/Cassandra/Collections/ArrayBackedList.cs index 6b5ac118f..23316f8c7 100644 --- a/src/Cassandra/Collections/ArrayBackedList.cs +++ b/src/Cassandra/Collections/ArrayBackedList.cs @@ -73,7 +73,8 @@ public int Count get { return _items.Length; } } - public bool IsReadOnly { + public bool IsReadOnly + { get { return true; } } diff --git a/src/Cassandra/Collections/ByteArrayComparer.cs b/src/Cassandra/Collections/ByteArrayComparer.cs index d079622fe..185635b91 100644 --- a/src/Cassandra/Collections/ByteArrayComparer.cs +++ b/src/Cassandra/Collections/ByteArrayComparer.cs @@ -43,7 +43,7 @@ public int GetHashCode(byte[] key) { // Use int32 values hash = Utils.CombineHashCode( - new[] { hash, BeConverter.ToInt32(new [] { key[i], key[i+1], key[i+2], key[i+3] }) }); + new[] { hash, BeConverter.ToInt32(new[] { key[i], key[i + 1], key[i + 2], key[i + 3] }) }); } if (rest > 0) { diff --git a/src/Cassandra/Collections/CopyOnWriteDictionary.cs b/src/Cassandra/Collections/CopyOnWriteDictionary.cs index c4b67286b..968d94320 100644 --- a/src/Cassandra/Collections/CopyOnWriteDictionary.cs +++ b/src/Cassandra/Collections/CopyOnWriteDictionary.cs @@ -47,7 +47,7 @@ public CopyOnWriteDictionary(IDictionary toCopy) { _map = new Dictionary(toCopy); } - + public CopyOnWriteDictionary() { //Start with an instance without nodes @@ -277,7 +277,7 @@ public TValue CompareAndUpdate( { throw new ArgumentNullException(nameof(key)); } - + if (updateValueFactory == null) { throw new ArgumentNullException(nameof(updateValueFactory)); @@ -320,7 +320,7 @@ private void CloneMapAndUpdateUnsafe(TKey key, TValue value) _map = newMap; } - + private bool CloneMapAndRemoveUnsafe(TKey key) { var newMap = new Dictionary(_map); diff --git a/src/Cassandra/Collections/ReadOnlyCollection.cs b/src/Cassandra/Collections/ReadOnlyCollection.cs index 99950e5c5..4afd2de3e 100644 --- a/src/Cassandra/Collections/ReadOnlyCollection.cs +++ b/src/Cassandra/Collections/ReadOnlyCollection.cs @@ -31,7 +31,7 @@ internal ReadOnlyCollection(ICollection items) { _items = items ?? throw new ArgumentNullException(nameof(items)); } - + public IEnumerator GetEnumerator() { return _items.GetEnumerator(); diff --git a/src/Cassandra/Compression/Snappy/SnappyDecompressor.cs b/src/Cassandra/Compression/Snappy/SnappyDecompressor.cs index 50e915900..52069d85b 100644 --- a/src/Cassandra/Compression/Snappy/SnappyDecompressor.cs +++ b/src/Cassandra/Compression/Snappy/SnappyDecompressor.cs @@ -160,11 +160,11 @@ private static int DecompressAllTags( { int opCode = SnappyInternalUtils.LoadByte(input, ipIndex++); int entry = SnappyInternalUtils.LookupShort(_opLookupTable, opCode); - var trailerBytes = (int) ((uint) entry >> 11); + var trailerBytes = (int)((uint)entry >> 11); int trailer = ReadTrailer(input, ipIndex, trailerBytes); // advance the ipIndex past the op codes - ipIndex += (int) ((uint) entry >> 11); + ipIndex += (int)((uint)entry >> 11); int length = entry & 0xff; if ((opCode & 0x3) == Literal) @@ -268,7 +268,7 @@ private static int[] DecompressTagSlow(byte[] input, int ipIndex, byte[] output, // read the op code int opCode = SnappyInternalUtils.LoadByte(input, ipIndex++); int entry = SnappyInternalUtils.LookupShort(_opLookupTable, opCode); - var trailerBytes = (int) ((uint) entry >> 11); + var trailerBytes = (int)((uint)entry >> 11); // // Key difference here // @@ -335,7 +335,7 @@ private static int[] DecompressTagSlow(byte[] input, int ipIndex, byte[] output, } opIndex += length; } - return new[] {ipIndex, opIndex}; + return new[] { ipIndex, opIndex }; } private static int ReadTrailer(byte[] data, int index, int bytes) @@ -360,7 +360,7 @@ private static void CopyLiteral(byte[] input, int ipIndex, byte[] output, int op } else { - var fastLength = (int) (((uint) length) & 0xFFFFFFF8); + var fastLength = (int)(((uint)length) & 0xFFFFFFF8); if (fastLength <= 64) { // copy long-by-long @@ -454,7 +454,7 @@ private static int[] ReadUncompressedLength(byte[] compressed, int compressedOff } } } - return new[] {result, bytesRead}; + return new[] { result, bytesRead }; } } } \ No newline at end of file diff --git a/src/Cassandra/Configuration.cs b/src/Cassandra/Configuration.cs index 711f31bae..5288bc151 100644 --- a/src/Cassandra/Configuration.cs +++ b/src/Cassandra/Configuration.cs @@ -209,7 +209,7 @@ public class Configuration /// A unique identifier for the created cluster instance. /// public Guid ClusterId { get; } - + /// /// Gets the options related to graph instance. /// @@ -237,9 +237,9 @@ public class Configuration internal IInsightsClientFactory InsightsClientFactory { get; } internal IRequestOptions DefaultRequestOptions => RequestOptions[Configuration.DefaultExecutionProfileName]; - + internal static IInsightsSupportVerifier DefaultInsightsSupportVerifier => new InsightsSupportVerifier(); - + internal static IInsightsClientFactory DefaultInsightsClientFactory => new InsightsClientFactory( Configuration.DefaultInsightsStartupMessageFactory, Configuration.DefaultInsightsStatusMessageFactory); @@ -359,7 +359,7 @@ internal Configuration(Policies policies, AddressTranslator = addressTranslator ?? throw new ArgumentNullException(nameof(addressTranslator)); QueryOptions = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions)); GraphOptions = graphOptions ?? new GraphOptions(); - + ClusterId = clusterId ?? Guid.NewGuid(); ApplicationVersion = appVersion ?? Configuration.DefaultApplicationVersion; ApplicationName = appName ?? Configuration.FallbackApplicationName; @@ -391,7 +391,7 @@ internal Configuration(Policies policies, TypeSerializers = typeSerializerDefinitions?.Definitions; KeepContactPointsUnresolved = keepContactPointsUnresolved ?? false; AllowBetaProtocolVersions = allowBetaProtocolVersions ?? false; - + ObserverFactoryBuilder = new CompositeObserverFactoryBuilder( new MetricsObserverFactoryBuilder(MetricsEnabled), new RequestTrackerObserverFactoryBuilder(requestTracker)); @@ -406,7 +406,7 @@ internal Configuration(Policies policies, RequestOptions = RequestOptionsMapper.BuildRequestOptionsDictionary(executionProfiles, policies, socketOptions, clientOptions, queryOptions, GraphOptions); ExecutionProfiles = BuildExecutionProfilesDictionary(executionProfiles, RequestOptions); - + MonitorReportingOptions = monitorReportingOptions ?? new MonitorReportingOptions(); InsightsSupportVerifier = insightsSupportVerifier ?? Configuration.DefaultInsightsSupportVerifier; InsightsClientFactory = insightsClientFactory ?? Configuration.DefaultInsightsClientFactory; diff --git a/src/Cassandra/Connections/Connection.cs b/src/Cassandra/Connections/Connection.cs index 720268ef1..f69f82887 100644 --- a/src/Cassandra/Connections/Connection.cs +++ b/src/Cassandra/Connections/Connection.cs @@ -147,7 +147,7 @@ public bool IsDisposed { get { return Interlocked.Read(ref _disposed) > 0L; } } - + /// /// Gets the current keyspace. /// @@ -179,7 +179,7 @@ internal Connection( _connectionObserver = connectionObserver; _timerEnabled = configuration.MetricsEnabled && configuration.MetricsOptions.EnabledNodeMetrics.Contains(NodeMetric.Timers.CqlMessages); - + _freeOperations = new ConcurrentStack(Enumerable.Range(0, GetMaxConcurrentRequests(Serializer)).Select(s => (short)s).Reverse()); _pendingOperations = new ConcurrentDictionary(); _writeQueue = new ConcurrentQueue(); @@ -326,8 +326,8 @@ private void CloseInternal(Exception ex, SocketError? socketError, bool dispose) { if (ex == null || ex is ObjectDisposedException) { - ex = socketError != null - ? new SocketException((int)socketError.Value) + ex = socketError != null + ? new SocketException((int)socketError.Value) : new SocketException((int)SocketError.NotConnected); } @@ -363,7 +363,7 @@ private void CloseInternal(Exception ex, SocketError? socketError, bool dispose) InternalDispose(); } } - + private void OnSocketError(Exception ex, SocketError? socketError) { CloseInternal(ex, socketError, false); @@ -510,7 +510,7 @@ public async Task DoOpen() } throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name); } - + private void ReadHandler(byte[] buffer, int bytesReceived) { if (_isClosed) @@ -831,7 +831,7 @@ public OperationState Send(IRequest request, Func return null; } } - + _writeQueue.Enqueue(state); RunWriteQueue(); return state; diff --git a/src/Cassandra/Connections/ConnectionEndpoint.cs b/src/Cassandra/Connections/ConnectionEndpoint.cs index e816e3102..107cd4e04 100644 --- a/src/Cassandra/Connections/ConnectionEndpoint.cs +++ b/src/Cassandra/Connections/ConnectionEndpoint.cs @@ -25,7 +25,7 @@ namespace Cassandra.Connections internal class ConnectionEndPoint : IConnectionEndPoint { private readonly IServerNameResolver _serverNameResolver; - + public ConnectionEndPoint(IPEndPoint hostIpEndPoint, IServerNameResolver serverNameResolver, IContactPoint contactPoint) { _serverNameResolver = serverNameResolver ?? throw new ArgumentNullException(nameof(serverNameResolver)); diff --git a/src/Cassandra/Connections/ConnectionFactory.cs b/src/Cassandra/Connections/ConnectionFactory.cs index 51552d828..39cb69aeb 100644 --- a/src/Cassandra/Connections/ConnectionFactory.cs +++ b/src/Cassandra/Connections/ConnectionFactory.cs @@ -33,10 +33,10 @@ public IConnection Create( public IConnection CreateUnobserved(ISerializer serializer, IConnectionEndPoint endPoint, Configuration configuration) { return new Connection( - serializer, - endPoint, - configuration, - new StartupRequestFactory(configuration.StartupOptionsFactory), + serializer, + endPoint, + configuration, + new StartupRequestFactory(configuration.StartupOptionsFactory), NullConnectionObserver.Instance); } } diff --git a/src/Cassandra/Connections/Control/ContactPointParser.cs b/src/Cassandra/Connections/Control/ContactPointParser.cs index 4a47856ad..7f9f9c980 100644 --- a/src/Cassandra/Connections/Control/ContactPointParser.cs +++ b/src/Cassandra/Connections/Control/ContactPointParser.cs @@ -28,8 +28,8 @@ internal class ContactPointParser : IContactPointParser private readonly bool _keepContactPointsUnresolved; public ContactPointParser( - IDnsResolver dnsResolver, - ProtocolOptions protocolOptions, + IDnsResolver dnsResolver, + ProtocolOptions protocolOptions, IServerNameResolver serverNameResolver, bool keepContactPointsUnresolved) { @@ -58,27 +58,27 @@ public IEnumerable ParseContactPoints(IEnumerable provide parsedContactPoint = new IpLiteralContactPoint(ipAddressContactPoint, _protocolOptions, _serverNameResolver); break; case string contactPointText: - { - if (IPAddress.TryParse(contactPointText, out var ipAddress)) { - parsedContactPoint = new IpLiteralContactPoint(ipAddress, _protocolOptions, _serverNameResolver); - } - else - { - parsedContactPoint = new HostnameContactPoint( - _dnsResolver, - _protocolOptions, - _serverNameResolver, - _keepContactPointsUnresolved, - contactPointText); - } + if (IPAddress.TryParse(contactPointText, out var ipAddress)) + { + parsedContactPoint = new IpLiteralContactPoint(ipAddress, _protocolOptions, _serverNameResolver); + } + else + { + parsedContactPoint = new HostnameContactPoint( + _dnsResolver, + _protocolOptions, + _serverNameResolver, + _keepContactPointsUnresolved, + contactPointText); + } - break; - } + break; + } default: throw new InvalidOperationException("Contact points should be either string or IPEndPoint instances"); } - + if (result.Contains(parsedContactPoint)) { Cluster.Logger.Warning("Found duplicate contact point: {0}. Ignoring it.", contactPoint.ToString()); diff --git a/src/Cassandra/Connections/Control/ControlConnection.cs b/src/Cassandra/Connections/Control/ControlConnection.cs index f61bc0519..1083706d3 100644 --- a/src/Cassandra/Connections/Control/ControlConnection.cs +++ b/src/Cassandra/Connections/Control/ControlConnection.cs @@ -152,14 +152,14 @@ private async Task> ResolveContactPoint(IContac catch (Exception ex) { ControlConnection.Logger.Warning( - "Failed to resolve contact point {0}. Exception: {1}", + "Failed to resolve contact point {0}. Exception: {1}", contactPoint.StringRepresentation, ex.ToString()); return Enumerable.Empty(); } } private async Task> ResolveHostContactPointOrConnectionEndpointAsync( - ConcurrentDictionary attemptedContactPoints, Host host, + ConcurrentDictionary attemptedContactPoints, Host host, bool refreshContactPoints, bool refreshEndpoints) { if (host.ContactPoint != null && attemptedContactPoints.TryAdd(host.ContactPoint, null)) @@ -267,7 +267,7 @@ private async Task Connect(bool isInitializing) if (isInitializing) { ControlConnection.Logger.Verbose("Control Connection {0} connecting.", GetHashCode()); - } + } else { ControlConnection.Logger.Verbose("Control Connection {0} reconnecting.", GetHashCode()); @@ -322,7 +322,7 @@ private async Task Connect(bool isInitializing) endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( AllHostsEndPointResolutionTasksEnumerable(attemptedContactPoints, attemptedHosts, true, _config.KeepContactPointsUnresolved, true)); } - + var oldConnection = _connection; var oldHost = _host; var oldEndpoint = _currentConnectionEndPoint; @@ -379,7 +379,7 @@ await _config.ProtocolVersionNegotiator.ChangeProtocolVersion( connection = await _config.ProtocolVersionNegotiator.NegotiateVersionAsync( _config, _metadata, connection, _serializer).ConfigureAwait(false); } - + if (!SetCurrentConnection(connection, currentHost, endPoint)) { ControlConnection.Logger.Info( @@ -431,7 +431,7 @@ private void ReconnectEventHandler(object state) { ReconnectFireAndForget(null); } - + internal void OnConnectionClosing(IConnection connection) { connection.Closing -= OnConnectionClosing; @@ -444,7 +444,7 @@ internal void OnConnectionClosing(IConnection connection) "Connection {0} used by the ControlConnection {1} is closing.", connection.EndPoint.EndpointFriendlyName, GetHashCode()); ReconnectFireAndForget(connection); } - + /// /// Handler that gets invoked when if there is a socket exception when making a heartbeat/idle request /// @@ -464,7 +464,7 @@ private void OnIdleRequestException(IConnection c, Exception ex) c.Close(); } } - + private async void ReconnectFireAndForget(IConnection closedConnection) { try @@ -485,7 +485,7 @@ internal async Task Reconnect(IConnection closedConnection) { // If there is another thread reconnecting, use the same task var oldConnectionInPreviousReconnect = await currentTask.ConfigureAwait(false); - + // if his reconnect was triggered by a connection closed event // and the previous reconnect task was for a different connection // then reconnect again @@ -572,7 +572,7 @@ private async Task Refresh() var currentEndPoint = _currentConnectionEndPoint; var currentHost = await _topologyRefresher.RefreshNodeListAsync( currentEndPoint, _connection, _serializer.GetCurrentSerializer()).ConfigureAwait(false); - + SetCurrentConnectionEndpoint(currentHost, currentEndPoint); await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false); @@ -625,7 +625,7 @@ private void Unsubscribe(Host h, IConnection c) { h.Down -= OnHostDown; } - + if (c != null) { c.Closing -= OnConnectionClosing; @@ -766,10 +766,10 @@ private void SetCurrentConnectionEndpoint(Host host, IConnectionEndPoint endPoin _currentConnectionEndPoint = endPoint; _metadata.SetCassandraVersion(host.CassandraVersion); } - + private bool SetCurrentConnection( IConnection connection, - Host host, + Host host, IConnectionEndPoint endPoint) { if (host != null) diff --git a/src/Cassandra/Connections/Control/ControlConnectionFactory.cs b/src/Cassandra/Connections/Control/ControlConnectionFactory.cs index 3490389c7..f4aad8a76 100644 --- a/src/Cassandra/Connections/Control/ControlConnectionFactory.cs +++ b/src/Cassandra/Connections/Control/ControlConnectionFactory.cs @@ -24,17 +24,17 @@ internal class ControlConnectionFactory : IControlConnectionFactory { public IControlConnection Create( IInternalCluster cluster, - IProtocolEventDebouncer protocolEventDebouncer, - ProtocolVersion initialProtocolVersion, - Configuration config, + IProtocolEventDebouncer protocolEventDebouncer, + ProtocolVersion initialProtocolVersion, + Configuration config, Metadata metadata, IEnumerable contactPoints) { return new ControlConnection( cluster, - protocolEventDebouncer, - initialProtocolVersion, - config, + protocolEventDebouncer, + initialProtocolVersion, + config, metadata, contactPoints); } diff --git a/src/Cassandra/Connections/Control/IControlConnection.cs b/src/Cassandra/Connections/Control/IControlConnection.cs index 54cfcf585..c951d8936 100644 --- a/src/Cassandra/Connections/Control/IControlConnection.cs +++ b/src/Cassandra/Connections/Control/IControlConnection.cs @@ -25,7 +25,7 @@ internal interface IControlConnection : IMetadataQueryProvider, IDisposable /// Host to which the control connection is currently connected. /// Host Host { get; } - + /// /// Tries to create a connection to any of the contact points and retrieve cluster metadata for the first time. /// Not thread-safe. @@ -34,7 +34,7 @@ internal interface IControlConnection : IMetadataQueryProvider, IDisposable /// /// Task InitAsync(); - + /// /// Updates keyspace metadata and token map if necessary. /// @@ -52,7 +52,7 @@ internal interface IControlConnection : IMetadataQueryProvider, IDisposable /// then the returned task will be complete when the refresh has been added to the queue (event debouncer). /// Task ScheduleKeyspaceRefreshAsync(string keyspace, bool processNow); - + /// /// Schedule a refresh of all keyspaces. If is true, /// the returned task will be complete when the refresh is done. If it's false diff --git a/src/Cassandra/Connections/Control/IControlConnectionFactory.cs b/src/Cassandra/Connections/Control/IControlConnectionFactory.cs index ac8af1cd5..f3879cb40 100644 --- a/src/Cassandra/Connections/Control/IControlConnectionFactory.cs +++ b/src/Cassandra/Connections/Control/IControlConnectionFactory.cs @@ -25,8 +25,8 @@ internal interface IControlConnectionFactory IControlConnection Create( IInternalCluster cluster, IProtocolEventDebouncer protocolEventDebouncer, - ProtocolVersion initialProtocolVersion, - Configuration config, + ProtocolVersion initialProtocolVersion, + Configuration config, Metadata metadata, IEnumerable contactPoints); } diff --git a/src/Cassandra/Connections/Control/IProtocolVersionNegotiator.cs b/src/Cassandra/Connections/Control/IProtocolVersionNegotiator.cs index 12938263e..9d13d7e27 100644 --- a/src/Cassandra/Connections/Control/IProtocolVersionNegotiator.cs +++ b/src/Cassandra/Connections/Control/IProtocolVersionNegotiator.cs @@ -21,7 +21,7 @@ namespace Cassandra.Connections.Control internal interface IProtocolVersionNegotiator { Task ChangeProtocolVersion(Configuration config, ISerializerManager serializer, ProtocolVersion nextVersion, IConnection previousConnection, UnsupportedProtocolVersionException ex = null, ProtocolVersion? previousVersion = null); - + Task NegotiateVersionAsync(Configuration config, Metadata metadata, IConnection connection, ISerializerManager serializer); } } \ No newline at end of file diff --git a/src/Cassandra/Connections/Control/IpLiteralContactPoint.cs b/src/Cassandra/Connections/Control/IpLiteralContactPoint.cs index 6ca410b3b..638a5133a 100644 --- a/src/Cassandra/Connections/Control/IpLiteralContactPoint.cs +++ b/src/Cassandra/Connections/Control/IpLiteralContactPoint.cs @@ -83,7 +83,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - return Utils.CombineHashCodeWithNulls(new object[] {_ipEndPoint, _ipAddress}); + return Utils.CombineHashCodeWithNulls(new object[] { _ipEndPoint, _ipAddress }); } public Task> GetConnectionEndPointsAsync(bool refreshCache) diff --git a/src/Cassandra/Connections/Control/TopologyRefresher.cs b/src/Cassandra/Connections/Control/TopologyRefresher.cs index 7aa89e546..aa038a05d 100644 --- a/src/Cassandra/Connections/Control/TopologyRefresher.cs +++ b/src/Cassandra/Connections/Control/TopologyRefresher.cs @@ -58,14 +58,14 @@ public async Task RefreshNodeListAsync( var localTask = SendSystemLocalRequestAsync(connection, serializer); var peersTask = SendSystemPeersRequestAsync(localIsPeersV2, connection, serializer); - + await Task.WhenAll(localTask, peersTask).ConfigureAwait(false); var peersResponse = peersTask.Result; localIsPeersV2 = peersResponse.IsPeersV2; var rsPeers = _config.MetadataRequestHandler.GetRowSet(peersResponse.Response); - + var localRow = _config.MetadataRequestHandler.GetRowSet(localTask.Result).FirstOrDefault(); if (localRow == null) { @@ -79,7 +79,7 @@ public async Task RefreshNodeListAsync( ControlConnection.Logger.Info("Node list retrieved successfully"); return host; } - + private Task SendSystemLocalRequestAsync(IConnection connection, ISerializer serializer) { return _config.MetadataRequestHandler.SendMetadataRequestAsync( @@ -89,9 +89,9 @@ private Task SendSystemLocalRequestAsync(IConnection connection, ISeri private Task SendSystemPeersRequestAsync(bool isPeersV2, IConnection connection, ISerializer serializer) { var peersTask = _config.MetadataRequestHandler.SendMetadataRequestAsync( - connection, - serializer, - isPeersV2 ? TopologyRefresher.SelectPeersV2 : TopologyRefresher.SelectPeers, + connection, + serializer, + isPeersV2 ? TopologyRefresher.SelectPeersV2 : TopologyRefresher.SelectPeers, QueryProtocolOptions.Default); return GetPeersResponseAsync(isPeersV2, peersTask, connection, serializer); @@ -134,8 +134,8 @@ private async Task GetPeersResponseAsync( /// private Host GetAndUpdateLocalHost(IConnectionEndPoint endPoint, IRow row) { - var hostIpEndPoint = - endPoint.GetHostIpEndPoint() + var hostIpEndPoint = + endPoint.GetHostIpEndPoint() ?? GetRpcEndPoint(false, row, _config.AddressTranslator, _config.ProtocolOptions.Port); if (hostIpEndPoint == null) @@ -186,7 +186,7 @@ private void UpdatePeersInfo(bool isPeersV2, IEnumerable peersRs, Host cur } } } - + /// /// Parses address from system table query response and translates it using the provided . /// @@ -229,7 +229,7 @@ internal IPEndPoint GetRpcEndPoint(bool isPeersV2, IRow row, IAddressTranslator "Found host with 0.0.0.0 as rpc_address, using listen_address ({0}) to contact it instead. " + "If this is incorrect you should avoid the use of 0.0.0.0 server side.", address.ToString()); } - + var rpcPort = defaultPort; if (isPeersV2) { @@ -247,17 +247,17 @@ internal IPEndPoint GetRpcEndPoint(bool isPeersV2, IRow row, IAddressTranslator return translator.Translate(new IPEndPoint(address, rpcPort)); } - + private IPAddress GetRpcAddressFromPeersV2(IRow row) { return row.GetValue("native_address"); } - + private IPAddress GetRpcAddressFromLocalPeersV1(IRow row) { return row.GetValue("rpc_address"); } - + private int? GetRpcPortFromPeersV2(IRow row) { return row.GetValue("native_port"); @@ -265,9 +265,9 @@ private IPAddress GetRpcAddressFromLocalPeersV1(IRow row) private class PeersResponse { - public bool IsPeersV2 { get; set; } + public bool IsPeersV2 { get; set; } - public Response Response { get; set; } + public Response Response { get; set; } } } } \ No newline at end of file diff --git a/src/Cassandra/Connections/EndPointResolver.cs b/src/Cassandra/Connections/EndPointResolver.cs index 984c0a642..33a76f043 100644 --- a/src/Cassandra/Connections/EndPointResolver.cs +++ b/src/Cassandra/Connections/EndPointResolver.cs @@ -27,7 +27,7 @@ public EndPointResolver(IServerNameResolver serverNameResolver) { _serverNameResolver = serverNameResolver ?? throw new ArgumentNullException(nameof(serverNameResolver)); } - + /// public Task GetConnectionEndPointAsync(Host host, bool refreshCache) { diff --git a/src/Cassandra/Connections/HostConnectionPool.cs b/src/Cassandra/Connections/HostConnectionPool.cs index 4b37bb32f..d6ce4a36d 100644 --- a/src/Cassandra/Connections/HostConnectionPool.cs +++ b/src/Cassandra/Connections/HostConnectionPool.cs @@ -96,7 +96,7 @@ private static class PoolState /// public int OpenConnections => _connections.Count; - + /// public int InFlight => _connections.Sum(c => c.InFlight); @@ -133,10 +133,10 @@ public async Task BorrowConnectionAsync() { throw new DriverInternalError("No connection could be borrowed"); } - + return BorrowLeastBusyConnection(connections); } - + /// public IConnection BorrowExistingConnection() { @@ -184,7 +184,7 @@ public void CheckHealth(IConnection c) { return; } - HostConnectionPool.Logger.Warning("Connection to {0} considered as unhealthy after {1} timed out operations", + HostConnectionPool.Logger.Warning("Connection to {0} considered as unhealthy after {1} timed out operations", _host.Address, timedOutOps); Remove(c); } @@ -235,10 +235,10 @@ public void ConsiderResizingPool(int inFlight) return; } _expectedConnectionLength++; - HostConnectionPool.Logger.Info("Increasing pool #{0} size to {1}, as in-flight requests are above threshold ({2})", + HostConnectionPool.Logger.Info("Increasing pool #{0} size to {1}, as in-flight requests are above threshold ({2})", GetHashCode(), _expectedConnectionLength, _maxInflightThresholdToConsiderResizing); StartCreatingConnection(null); - _resizingEndTimeout = _timer.NewTimeout(_ => Interlocked.Exchange(ref _poolResizing, 0), null, + _resizingEndTimeout = _timer.NewTimeout(_ => Interlocked.Exchange(ref _poolResizing, 0), null, HostConnectionPool.BetweenResizeDelay); } @@ -247,7 +247,7 @@ public void ConsiderResizingPool(int inFlight) /// public void Dispose() { - var markShuttingDown = + var markShuttingDown = (Interlocked.CompareExchange(ref _state, PoolState.ShuttingDown, PoolState.Init) == PoolState.Init) || (Interlocked.CompareExchange(ref _state, PoolState.ShuttingDown, PoolState.Closing) == PoolState.Closing); @@ -294,7 +294,7 @@ public virtual async Task DoCreateAndOpen(bool isReconnection) } return c; } - + public void OnHostRemoved() { var previousState = Interlocked.Exchange(ref _state, PoolState.ShuttingDown); @@ -445,7 +445,7 @@ private void OnDistanceChanged(HostDistance previousDistance, HostDistance dista return; } // Host is now ignored - var isClosing = Interlocked.CompareExchange(ref _state, PoolState.Closing, PoolState.Init) == + var isClosing = Interlocked.CompareExchange(ref _state, PoolState.Closing, PoolState.Init) == PoolState.Init; if (!isClosing) { @@ -460,7 +460,7 @@ private void OnDistanceChanged(HostDistance previousDistance, HostDistance dista }); CancelNewConnectionTimeout(); } - + /// /// Removes the connections from the pool and defers the closing of the connections until twice the /// readTimeout. The connection might be already selected and sending requests. @@ -475,14 +475,14 @@ private void DrainConnections(Action afterDrainHandler) } // The request handler might execute up to 2 queries with a single connection: // Changing the keyspace + the actual query - var delay = _config.SocketOptions.ReadTimeoutMillis*2; + var delay = _config.SocketOptions.ReadTimeoutMillis * 2; // Use a sane maximum of 5 mins - const int maxDelay = 5*60*1000; + const int maxDelay = 5 * 60 * 1000; if (delay <= 0 || delay > maxDelay) { delay = maxDelay; } - DrainConnectionsTimer(connections, afterDrainHandler, delay/1000); + DrainConnectionsTimer(connections, afterDrainHandler, delay / 1000); } private void DrainConnectionsTimer(IConnection[] connections, Action afterDrainHandler, int steps) @@ -715,7 +715,7 @@ private async Task CreateOpenConnection(bool satisfyWithAnOpenConne if (IsClosing) { - HostConnectionPool.Logger.Info("Connection to {0} opened successfully but pool #{1} was being closed", + HostConnectionPool.Logger.Info("Connection to {0} opened successfully but pool #{1} was being closed", _host.Address, GetHashCode()); c.Dispose(); return await FinishOpen(tcs, false, HostConnectionPool.GetNotConnectedException()).ConfigureAwait(false); @@ -751,8 +751,8 @@ private async Task CreateOpenConnection(bool satisfyWithAnOpenConne private Task FinishOpen( TaskCompletionSource tcs, - bool preventForeground, - Exception ex, + bool preventForeground, + Exception ex, IConnection c = null) { // Instruction ordering: canCreateForeground flag must be set before resetting of the tcs @@ -839,7 +839,7 @@ private IConnection[] GetExistingConnections() public void SetDistance(HostDistance distance) { _expectedConnectionLength = _poolingOptions.GetCoreConnectionsPerHost(distance); - _maxInflightThresholdToConsiderResizing = _poolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(distance); + _maxInflightThresholdToConsiderResizing = _poolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(distance); _maxConnectionLength = _poolingOptions.GetMaxConnectionPerHost(distance); } @@ -853,21 +853,21 @@ public void MarkAsDownAndScheduleReconnection() ScheduleReconnection(); } } - + /// public Task GetConnectionFromHostAsync( IDictionary triedHosts, Func getKeyspaceFunc) { return GetConnectionFromHostAsync(triedHosts, getKeyspaceFunc, true); } - + /// public Task GetExistingConnectionFromHostAsync( IDictionary triedHosts, Func getKeyspaceFunc) { return GetConnectionFromHostAsync(triedHosts, getKeyspaceFunc, false); } - + private async Task GetConnectionFromHostAsync( IDictionary triedHosts, Func getKeyspaceFunc, bool createIfNeeded) { diff --git a/src/Cassandra/Connections/HostnameContactPoint.cs b/src/Cassandra/Connections/HostnameContactPoint.cs index cd8ed2b97..ea991e944 100644 --- a/src/Cassandra/Connections/HostnameContactPoint.cs +++ b/src/Cassandra/Connections/HostnameContactPoint.cs @@ -33,10 +33,10 @@ internal class HostnameContactPoint : IContactPoint private readonly bool _keepContactPointsUnresolved; public HostnameContactPoint( - IDnsResolver dnsResolver, - ProtocolOptions protocolOptions, - IServerNameResolver serverNameResolver, - bool keepContactPointsUnresolved, + IDnsResolver dnsResolver, + ProtocolOptions protocolOptions, + IServerNameResolver serverNameResolver, + bool keepContactPointsUnresolved, string hostname) { _dns = dnsResolver ?? throw new ArgumentNullException(nameof(dnsResolver)); @@ -49,7 +49,7 @@ public HostnameContactPoint( public bool CanBeResolved => true; public string StringRepresentation => _hostname; - + public override string ToString() { return StringRepresentation; diff --git a/src/Cassandra/Connections/IConnection.cs b/src/Cassandra/Connections/IConnection.cs index a55da1b1b..27f026520 100644 --- a/src/Cassandra/Connections/IConnection.cs +++ b/src/Cassandra/Connections/IConnection.cs @@ -59,12 +59,12 @@ internal interface IConnection : IDisposable IConnectionEndPoint EndPoint { get; } IPEndPoint LocalAddress { get; } - + /// /// Length of the internal write queue (expensive operation!) /// int WriteQueueLength { get; } - + /// /// Length of the internal write queue (expensive operation!) /// @@ -74,7 +74,7 @@ internal interface IConnection : IDisposable /// Determines the amount of operations that are not finished. /// int InFlight { get; } - + /// /// Determines if there isn't any operations pending to be written or inflight. /// @@ -84,7 +84,7 @@ internal interface IConnection : IDisposable /// Gets the amount of operations that timed out and didn't get a response /// int TimedOutOperations { get; } - + bool IsDisposed { get; } /// @@ -98,7 +98,7 @@ internal interface IConnection : IDisposable int GetMaxConcurrentRequests(ISerializer serializer); ProtocolOptions Options { get; } - + /// /// Initializes the connection. /// @@ -111,7 +111,7 @@ internal interface IConnection : IDisposable /// Sends a new request if possible. If it is not possible it queues it up. /// Task Send(IRequest request, int timeoutMillis); - + /// /// Sends a new request if possible and executes the callback when the response is parsed. If it is not possible it queues it up. /// diff --git a/src/Cassandra/Connections/IConnectionEndpoint.cs b/src/Cassandra/Connections/IConnectionEndpoint.cs index a9905cd2d..138d6f1d7 100644 --- a/src/Cassandra/Connections/IConnectionEndpoint.cs +++ b/src/Cassandra/Connections/IConnectionEndpoint.cs @@ -39,7 +39,7 @@ internal interface IConnectionEndPoint : IEquatable /// IpEndPoint to which the driver will connect to (via ). This can never be null. /// IPEndPoint SocketIpEndPoint { get; } - + /// /// Useful for logging purposes. /// diff --git a/src/Cassandra/Connections/IHostConnectionPool.cs b/src/Cassandra/Connections/IHostConnectionPool.cs index 975161499..f9acd0091 100644 --- a/src/Cassandra/Connections/IHostConnectionPool.cs +++ b/src/Cassandra/Connections/IHostConnectionPool.cs @@ -33,19 +33,19 @@ internal interface IHostConnectionPool : IDisposable /// Gets the total of in-flight requests on all connections. /// int InFlight { get; } - + /// /// Determines whether the connection pool has opened connections using snapshot semantics. /// bool HasConnections { get; } event Action AllConnectionClosed; - + /// /// Gets a snapshot of the current state of the pool. /// IConnection[] ConnectionsSnapshot { get; } - + /// /// Gets an open connection from the host pool (creating if necessary). /// It returns null if the load balancing policy didn't allow connections to this host. @@ -93,7 +93,7 @@ internal interface IHostConnectionPool : IDisposable Task GetConnectionFromHostAsync( IDictionary triedHosts, Func getKeyspaceFunc); - + Task GetExistingConnectionFromHostAsync( IDictionary triedHosts, Func getKeyspaceFunc); } diff --git a/src/Cassandra/Connections/RequestError.cs b/src/Cassandra/Connections/RequestError.cs index 573551784..f44200598 100644 --- a/src/Cassandra/Connections/RequestError.cs +++ b/src/Cassandra/Connections/RequestError.cs @@ -27,7 +27,7 @@ private RequestError(Exception ex, bool isServerError, bool unsent) IsServerError = isServerError; Unsent = unsent; } - + /// /// Creates a server side request error based on a server error. /// @@ -35,7 +35,7 @@ public static IRequestError CreateServerError(ErrorResponse response) { return new RequestError(response.Output.CreateException(), true, false); } - + /// /// Creates a client side request error based on an exception. /// @@ -43,7 +43,7 @@ public static IRequestError CreateServerError(Exception ex) { return new RequestError(ex, true, false); } - + /// /// Creates a client side request error based on a exception. /// @@ -51,7 +51,7 @@ public static IRequestError CreateClientError(Exception ex, bool unsent) { return new RequestError(ex, false, unsent); } - + public Exception Exception { get; } public bool IsServerError { get; } diff --git a/src/Cassandra/Connections/TcpSocket.cs b/src/Cassandra/Connections/TcpSocket.cs index 2b9bfc846..602d1c4e1 100644 --- a/src/Cassandra/Connections/TcpSocket.cs +++ b/src/Cassandra/Connections/TcpSocket.cs @@ -39,7 +39,7 @@ internal class TcpSocket : ITcpSocket private readonly Socket _socket; private readonly SocketAsyncEventArgs _receiveSocketEvent; private readonly SocketAsyncEventArgs _sendSocketEvent; - + private byte[] _receiveBuffer; private Action _writeFlushCallback; @@ -77,7 +77,7 @@ public TcpSocket(IConnectionEndPoint endPoint, SocketOptions options, SSLOptions EndPoint = endPoint; Options = options; SSLOptions = sslOptions; - + _socket = new Socket(EndPoint.SocketIpEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = Options.ConnectTimeoutMillis @@ -103,7 +103,7 @@ public TcpSocket(IConnectionEndPoint endPoint, SocketOptions options, SSLOptions _socket.NoDelay = Options.TcpNoDelay.Value; } _receiveBuffer = new byte[_socket.ReceiveBufferSize]; - + if (SSLOptions == null && !Options.UseStreamMode) { _receiveSocketEvent = new SocketAsyncEventArgs(); @@ -113,7 +113,7 @@ public TcpSocket(IConnectionEndPoint endPoint, SocketOptions options, SSLOptions _sendSocketEvent.Completed += OnSendCompleted; } } - + /// /// Get this socket's local address. /// @@ -488,7 +488,7 @@ public void Dispose() { // ignore } - + try { //Try to close it. @@ -507,7 +507,7 @@ public void Dispose() { //We should not mind if socket's Close method throws an exception } - + //dereference to make the byte array GC-able as soon as possible _receiveBuffer = null; } diff --git a/src/Cassandra/CqlQueryTools.cs b/src/Cassandra/CqlQueryTools.cs index d556e1a79..2ec84c897 100644 --- a/src/Cassandra/CqlQueryTools.cs +++ b/src/Cassandra/CqlQueryTools.cs @@ -79,7 +79,7 @@ public static string GetCreateKeyspaceCql(string keyspace, Dictionary /// Gets whether this command has been prepared. /// - public bool IsPrepared { + public bool IsPrepared + { get { return Parameters.Count == 0 || _preparedStatement != null; } } @@ -160,12 +161,12 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) } else //if _preparedStatement != null { - + var query = _preparedStatement.Bind(GetParameterValues()); query.SetConsistencyLevel(ConsistencyLevel); rowSet = CqlConnection.ManagedConnection.Execute(query); } - + return new CqlReader(rowSet); } diff --git a/src/Cassandra/Data/CqlConnection.cs b/src/Cassandra/Data/CqlConnection.cs index c71b64e30..acb56ff86 100644 --- a/src/Cassandra/Data/CqlConnection.cs +++ b/src/Cassandra/Data/CqlConnection.cs @@ -15,8 +15,8 @@ // using System; -using System.Collections.Concurrent; -using System.Data; +using System.Collections.Concurrent; +using System.Data; using System.Data.Common; namespace Cassandra.Data diff --git a/src/Cassandra/Data/CqlParameter.cs b/src/Cassandra/Data/CqlParameter.cs index a4a6abe4d..08cf27f33 100644 --- a/src/Cassandra/Data/CqlParameter.cs +++ b/src/Cassandra/Data/CqlParameter.cs @@ -122,7 +122,7 @@ public override string ParameterName /// The default is an empty string. /// public override string SourceColumn { get; set; } - + /// /// Gets or sets the /// to use when loading . diff --git a/src/Cassandra/Data/CqlParameterCollection.cs b/src/Cassandra/Data/CqlParameterCollection.cs index 8eb9eb835..9d41d2664 100644 --- a/src/Cassandra/Data/CqlParameterCollection.cs +++ b/src/Cassandra/Data/CqlParameterCollection.cs @@ -51,7 +51,7 @@ public override object SyncRoot { get { return _syncLock; } } - + /// /// Specifies whether the collection is a fixed size. /// @@ -343,9 +343,9 @@ public override void AddRange(Array values) } } -#endregion + #endregion -#region Private Methods + #region Private Methods private void SetParameter(string parameterName, CqlParameter value) { @@ -373,6 +373,6 @@ private CqlParameter GetCqlParameter(string parameterName) return _parameters[index]; } -#endregion + #endregion } } \ No newline at end of file diff --git a/src/Cassandra/Data/CqlProviderFactory.cs b/src/Cassandra/Data/CqlProviderFactory.cs index 93fd311b0..61d6d76cf 100644 --- a/src/Cassandra/Data/CqlProviderFactory.cs +++ b/src/Cassandra/Data/CqlProviderFactory.cs @@ -51,7 +51,7 @@ public override DbParameter CreateParameter() { throw new NotSupportedException(); } - + public override bool CanCreateDataSourceEnumerator { get { return false; } diff --git a/src/Cassandra/Data/CqlReader.cs b/src/Cassandra/Data/CqlReader.cs index c75bd24fe..0b4471d6b 100644 --- a/src/Cassandra/Data/CqlReader.cs +++ b/src/Cassandra/Data/CqlReader.cs @@ -91,13 +91,13 @@ public override DataTable GetSchemaTable() /// public override bool GetBoolean(int ordinal) { - return (bool) GetValue(ordinal); + return (bool)GetValue(ordinal); } /// public override byte GetByte(int ordinal) { - return (byte) GetValue(ordinal); + return (byte)GetValue(ordinal); } /// @@ -109,7 +109,7 @@ public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int b /// public override char GetChar(int ordinal) { - return (char) GetValue(ordinal); + return (char)GetValue(ordinal); } /// @@ -127,19 +127,19 @@ public override string GetDataTypeName(int ordinal) /// public override DateTime GetDateTime(int ordinal) { - return (DateTime) GetValue(ordinal); + return (DateTime)GetValue(ordinal); } /// public override decimal GetDecimal(int ordinal) { - return (decimal) GetValue(ordinal); + return (decimal)GetValue(ordinal); } /// public override double GetDouble(int ordinal) { - return (double) GetValue(ordinal); + return (double)GetValue(ordinal); } public override IEnumerator GetEnumerator() @@ -156,31 +156,31 @@ public override Type GetFieldType(int ordinal) /// public override float GetFloat(int ordinal) { - return (float) GetValue(ordinal); + return (float)GetValue(ordinal); } /// public override Guid GetGuid(int ordinal) { - return (Guid) GetValue(ordinal); + return (Guid)GetValue(ordinal); } /// public override short GetInt16(int ordinal) { - return (Int16) GetValue(ordinal); + return (Int16)GetValue(ordinal); } /// public override int GetInt32(int ordinal) { - return (Int32) GetValue(ordinal); + return (Int32)GetValue(ordinal); } /// public override long GetInt64(int ordinal) { - return (Int64) GetValue(ordinal); + return (Int64)GetValue(ordinal); } /// @@ -197,7 +197,7 @@ public override int GetOrdinal(string name) public override string GetString(int ordinal) { - return (string) GetValue(ordinal); + return (string)GetValue(ordinal); } /// diff --git a/src/Cassandra/Data/Linq/Batch.cs b/src/Cassandra/Data/Linq/Batch.cs index 7a05e9cf2..04f0e326a 100644 --- a/src/Cassandra/Data/Linq/Batch.cs +++ b/src/Cassandra/Data/Linq/Batch.cs @@ -68,7 +68,7 @@ internal Batch(ISession session, BatchType batchType) _timestamp = timestamp; return this; } - + public Batch Append(IEnumerable cqlCommands) { foreach (var cmd in cqlCommands) @@ -82,21 +82,21 @@ public void Execute() { Execute(Configuration.DefaultExecutionProfileName); } - + public void Execute(string executionProfile) { WaitToCompleteWithMetrics(InternalExecuteAsync(executionProfile), QueryAbortTimeout); } protected abstract Task InternalExecuteAsync(); - + protected abstract Task InternalExecuteAsync(string executionProfile); - + public Task ExecuteAsync() { return InternalExecuteAsync(); } - + public Task ExecuteAsync(string executionProfile) { return InternalExecuteAsync(executionProfile); diff --git a/src/Cassandra/Data/Linq/BatchV1.cs b/src/Cassandra/Data/Linq/BatchV1.cs index 9e6f44da4..757b61dfa 100644 --- a/src/Cassandra/Data/Linq/BatchV1.cs +++ b/src/Cassandra/Data/Linq/BatchV1.cs @@ -45,7 +45,7 @@ protected override Task InternalExecuteAsync() { return InternalExecuteAsync(Configuration.DefaultExecutionProfileName); } - + protected override Task InternalExecuteAsync(string executionProfile) { if (_batchScript.Length == 0) diff --git a/src/Cassandra/Data/Linq/BatchV2.cs b/src/Cassandra/Data/Linq/BatchV2.cs index a9bcf8587..4ab32a04d 100644 --- a/src/Cassandra/Data/Linq/BatchV2.cs +++ b/src/Cassandra/Data/Linq/BatchV2.cs @@ -41,7 +41,7 @@ public override void Append(CqlCommand cqlCommand) } _batchScript.Add(cqlCommand); } - + protected override Task InternalExecuteAsync() { return InternalExecuteAsync(Configuration.DefaultExecutionProfileName); diff --git a/src/Cassandra/Data/Linq/ClientProjectionCqlQuery.cs b/src/Cassandra/Data/Linq/ClientProjectionCqlQuery.cs index af2507c19..f12c09619 100644 --- a/src/Cassandra/Data/Linq/ClientProjectionCqlQuery.cs +++ b/src/Cassandra/Data/Linq/ClientProjectionCqlQuery.cs @@ -39,7 +39,7 @@ internal class ClientProjectionCqlQuery : CqlQuery, I /// The source /// The projection expression /// Determines if the projection can be compiled and the delegate called. - internal ClientProjectionCqlQuery(Expression expression, CqlQuery source, + internal ClientProjectionCqlQuery(Expression expression, CqlQuery source, Expression> projectionExpression, bool canCompile) : base(expression, source.Table, source.MapperFactory, source.StatementFactory, source.PocoData) { diff --git a/src/Cassandra/Data/Linq/CqlConditionalCommand.cs b/src/Cassandra/Data/Linq/CqlConditionalCommand.cs index 0c344698c..54c686838 100644 --- a/src/Cassandra/Data/Linq/CqlConditionalCommand.cs +++ b/src/Cassandra/Data/Linq/CqlConditionalCommand.cs @@ -23,7 +23,7 @@ namespace Cassandra.Data.Linq /// /// Represents an INSERT/UPDATE/DELETE command with support for Lightweight transactions. /// - public class CqlConditionalCommand: CqlCommand + public class CqlConditionalCommand : CqlCommand { private readonly MapperFactory _mapperFactory; private readonly CqlCommand _origin; @@ -72,7 +72,7 @@ protected internal override string GetCql(out object[] values) var cql = GetCql(out object[] values); var session = GetTable().GetSession(); var stmt = await InternalRef.StatementFactory.GetStatementAsync( - session, + session, Cql.New(cql, values).WithExecutionProfile(executionProfile)).ConfigureAwait(false); this.CopyQueryPropertiesTo(stmt); var rs = await session.ExecuteAsync(stmt, executionProfile).ConfigureAwait(false); @@ -89,11 +89,11 @@ protected internal override string GetCql(out object[] values) { throw new ArgumentNullException(nameof(executionProfile)); } - + var queryAbortTimeout = GetTable().GetSession().Cluster.Configuration.ClientOptions.QueryAbortTimeout; return WaitToCompleteWithMetrics(ExecuteAsync(executionProfile), queryAbortTimeout); } - + public new CqlConditionalCommand SetConsistencyLevel(ConsistencyLevel? consistencyLevel) { base.SetConsistencyLevel(consistencyLevel); diff --git a/src/Cassandra/Data/Linq/CqlExpressionVisitor.cs b/src/Cassandra/Data/Linq/CqlExpressionVisitor.cs index 63929439d..a432a825a 100644 --- a/src/Cassandra/Data/Linq/CqlExpressionVisitor.cs +++ b/src/Cassandra/Data/Linq/CqlExpressionVisitor.cs @@ -113,9 +113,9 @@ public string GetSelect(Expression expression, out object[] values) { query.Append(" ORDER BY "); query.Append(string.Join( - ", ", - _orderBy.Select(item => - CqlExpressionVisitor.CqlIdentifierHelper.EscapeIdentifierIfNecessary(_pocoData, item.Item1) + ", ", + _orderBy.Select(item => + CqlExpressionVisitor.CqlIdentifierHelper.EscapeIdentifierIfNecessary(_pocoData, item.Item1) + (item.Item2 ? "" : " DESC")))); } @@ -205,7 +205,7 @@ public string GetDelete(Expression expression, out object[] values, DateTimeOffs /// /// Gets a cql UPDATE statement based on the current state /// - public string GetUpdate(Expression expression, out object[] values, int? ttl, DateTimeOffset? timestamp, + public string GetUpdate(Expression expression, out object[] values, int? ttl, DateTimeOffset? timestamp, MapperFactory mapperFactory) { Visit(expression); @@ -317,7 +317,7 @@ protected override Expression VisitMemberInit(MemberInitExpression node) { throw new CqlLinqNotSupportedException(node, _parsePhase.Get()); } - + // Visit new instance creation (constructor and parameters) VisitNew(node.NewExpression); @@ -540,7 +540,7 @@ private Expression FillSelectFunction(ParsePhase phase, MethodCallExpression nod { _selectFields.Add("COUNT(*)"); return node; - } + } else { Visit(node.Arguments[0]); @@ -574,7 +574,7 @@ private Expression AddProjection(Expression node, PocoColumn column = null) object value; if (node is MemberExpression) { - value = CqlExpressionVisitor.GetClosureValue((MemberExpression) node); + value = CqlExpressionVisitor.GetClosureValue((MemberExpression)node); } else { @@ -586,7 +586,7 @@ private Expression AddProjection(Expression node, PocoColumn column = null) if (column == null) { throw new CqlLinqNotSupportedException(node, _parsePhase.Get()); - } + } } _projections.Add(Tuple.Create(column, value, ExpressionType.Assign)); return node; @@ -614,7 +614,7 @@ private Expression EvaluateConditionFunction(MethodCallExpression node) var column = condition.Column; condition.SetOperator(ExpressionType.GreaterThanOrEqual) .SetParameter(startString); - + condition = new BinaryConditionItem(); condition.SetColumn(column) .SetOperator(ExpressionType.LessThan) @@ -678,7 +678,7 @@ private void EvaluateContainsMethod(MethodCallExpression node) { EvaluateCompositeColumn(columnExpression); } - + var values = Expression.Lambda(parameterExpression).Compile().DynamicInvoke() as IEnumerable; if (values == null) { @@ -703,10 +703,10 @@ private void EvaluateCompositeColumn(Expression expression) switch (expression.NodeType) { case ExpressionType.Call: - columnsExpression = ((MethodCallExpression) expression).Arguments; + columnsExpression = ((MethodCallExpression)expression).Arguments; break; case ExpressionType.New: - columnsExpression = ((NewExpression) expression).Arguments; + columnsExpression = ((NewExpression)expression).Arguments; break; default: throw new CqlLinqNotSupportedException(expression, _parsePhase.Get()); @@ -720,7 +720,7 @@ private void EvaluateCompositeColumn(Expression expression) private bool EvaluateOperatorMethod(MethodCallExpression node) { - if (node.Method.DeclaringType != typeof (CqlOperator)) + if (node.Method.DeclaringType != typeof(CqlOperator)) { return false; } @@ -775,7 +775,7 @@ protected override Expression VisitUnary(UnaryExpression node) if (node.NodeType == ExpressionType.Not && node.Operand.NodeType == ExpressionType.MemberAccess) { // We are evaluating a boolean expression parameter, the value we are trying to match is false - FillBooleanCondition((MemberExpression) node.Operand, condition, false); + FillBooleanCondition((MemberExpression)node.Operand, condition, false); return node; } if (BinaryConditionItem.IsSupported(node.NodeType)) @@ -832,7 +832,7 @@ private void FillBooleanCondition(MemberExpression node, IConditionItem conditio private bool IsBoolMember(Expression node) { return node.NodeType == ExpressionType.MemberAccess && node.Type == typeof(bool) && - _pocoData.PocoType.GetTypeInfo().IsAssignableFrom(((MemberExpression) node).Member.DeclaringType); + _pocoData.PocoType.GetTypeInfo().IsAssignableFrom(((MemberExpression)node).Member.DeclaringType); } protected override Expression VisitBinary(BinaryExpression node) @@ -843,7 +843,7 @@ protected override Expression VisitBinary(BinaryExpression node) { // It's the AND of the WHERE/IF clause Visit(node.Left); - + // Add the new condition for the right portion _conditions.Add(new BinaryConditionItem()); Visit(node.Right); @@ -907,41 +907,41 @@ protected override Expression VisitConstant(ConstantExpression node) _conditions.Last().SetParameter(node.Value); return node; case ParsePhase.SelectBinding: - { - var column = _pocoData.GetColumnByMemberName(_currentBindingName.Get()); - if (column == null) { - //selecting a field that is not part of PocoType - break; - } - var expressionType = ExpressionType.Assign; - if (column.IsCounter) - { - if (!(node.Value is long || node.Value is int)) + var column = _pocoData.GetColumnByMemberName(_currentBindingName.Get()); + if (column == null) { - throw new ArgumentException("Only Int64 and Int32 values are supported as counter increment of decrement values"); + //selecting a field that is not part of PocoType + break; } - expressionType = ExpressionType.Increment; + var expressionType = ExpressionType.Assign; + if (column.IsCounter) + { + if (!(node.Value is long || node.Value is int)) + { + throw new ArgumentException("Only Int64 and Int32 values are supported as counter increment of decrement values"); + } + expressionType = ExpressionType.Increment; + } + _projections.Add(Tuple.Create(column, node.Value, expressionType)); + _selectFields.Add(column.ColumnName); + return node; } - _projections.Add(Tuple.Create(column, node.Value, expressionType)); - _selectFields.Add(column.ColumnName); - return node; - } case ParsePhase.Take: - _limit = (int) node.Value; + _limit = (int)node.Value; return node; case ParsePhase.OrderBy: case ParsePhase.OrderByDescending: - { - var columnName = _pocoData.GetColumnNameByMemberName((string) node.Value); - if (columnName == null) { - //order by a field that is not part of PocoType - break; + var columnName = _pocoData.GetColumnNameByMemberName((string)node.Value); + if (columnName == null) + { + //order by a field that is not part of PocoType + break; + } + _orderBy.Add(Tuple.Create(columnName, _parsePhase.Get() == ParsePhase.OrderBy)); + return node; } - _orderBy.Add(Tuple.Create(columnName, _parsePhase.Get() == ParsePhase.OrderBy)); - return node; - } } throw new CqlLinqNotSupportedException(node, _parsePhase.Get()); diff --git a/src/Cassandra/Data/Linq/CqlFunction.cs b/src/Cassandra/Data/Linq/CqlFunction.cs index 1d8836fc6..716423628 100644 --- a/src/Cassandra/Data/Linq/CqlFunction.cs +++ b/src/Cassandra/Data/Linq/CqlFunction.cs @@ -204,7 +204,7 @@ public static CqlFunction Token(object key1, object key2, object key3, object ke { throw new InvalidOperationException(); } - + public static bool operator >(CqlFunction a, Guid b) { throw new InvalidOperationException(); @@ -224,12 +224,12 @@ public static CqlFunction Token(object key1, object key2, object key3, object ke { throw new InvalidOperationException(); } - + public static bool operator <(Guid b, CqlFunction a) { throw new InvalidOperationException(); } - + public static bool operator >(Guid b, CqlFunction a) { throw new InvalidOperationException(); @@ -249,7 +249,7 @@ public override int GetHashCode() public static object ToObject(CqlFunction value) { - return (object) value; + return (object)value; } public static implicit operator Guid(CqlFunction value) diff --git a/src/Cassandra/Data/Linq/CqlMthHelps.cs b/src/Cassandra/Data/Linq/CqlMthHelps.cs index 17de349b3..ebb3038a8 100644 --- a/src/Cassandra/Data/Linq/CqlMthHelps.cs +++ b/src/Cassandra/Data/Linq/CqlMthHelps.cs @@ -20,7 +20,7 @@ namespace Cassandra.Data.Linq { internal class CqlMthHelps { - internal static MethodInfo SelectMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("Select", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo SelectMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("Select", BindingFlags.NonPublic | BindingFlags.Static); internal static MethodInfo WhereMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("Where", BindingFlags.NonPublic | BindingFlags.Static); internal static MethodInfo GroupByMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("GroupBy", BindingFlags.NonPublic | BindingFlags.Static); internal static MethodInfo UpdateIfMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("UpdateIf", BindingFlags.NonPublic | BindingFlags.Static); @@ -30,30 +30,30 @@ internal class CqlMthHelps internal static MethodInfo UpdateIfNotExistsMi = typeof(CqlMthHelps) .GetTypeInfo().GetMethod(nameof(UpdateIfNotExists), BindingFlags.NonPublic | BindingFlags.Static); - + internal static MethodInfo DeleteIfMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("DeleteIf", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo FirstMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("First", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo FirstMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("First", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo First_ForCQLTableMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("First", - new[] {typeof (ITable), typeof (int), typeof (object)}); + internal static MethodInfo First_ForCQLTableMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("First", + new[] { typeof(ITable), typeof(int), typeof(object) }); - internal static MethodInfo FirstOrDefaultMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("FirstOrDefault", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo FirstOrDefaultMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("FirstOrDefault", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo FirstOrDefault_ForCQLTableMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("FirstOrDefault", + internal static MethodInfo FirstOrDefault_ForCQLTableMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("FirstOrDefault", new[] {typeof (ITable), typeof (int), typeof (object)}); - internal static MethodInfo TakeMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("Take", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo AllowFilteringMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("AllowFiltering", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo CountMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("Count", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo OrderByMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("OrderBy", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo TakeMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("Take", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo AllowFilteringMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("AllowFiltering", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo CountMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("Count", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo OrderByMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("OrderBy", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo OrderByDescendingMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("OrderByDescending", + internal static MethodInfo OrderByDescendingMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("OrderByDescending", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo ThenByMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("ThenBy", BindingFlags.NonPublic | BindingFlags.Static); + internal static MethodInfo ThenByMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("ThenBy", BindingFlags.NonPublic | BindingFlags.Static); - internal static MethodInfo ThenByDescendingMi = typeof (CqlMthHelps).GetTypeInfo().GetMethod("ThenByDescending", + internal static MethodInfo ThenByDescendingMi = typeof(CqlMthHelps).GetTypeInfo().GetMethod("ThenByDescending", BindingFlags.NonPublic | BindingFlags.Static); internal static object Select(object a, object b) diff --git a/src/Cassandra/Data/Linq/CqlOperator.cs b/src/Cassandra/Data/Linq/CqlOperator.cs index 637d77e62..1261f1662 100644 --- a/src/Cassandra/Data/Linq/CqlOperator.cs +++ b/src/Cassandra/Data/Linq/CqlOperator.cs @@ -27,15 +27,15 @@ public static class CqlOperator /// /// Represents the CQL add assign (+=) operator for collections /// - public static T Append(T value) where T: IEnumerable + public static T Append(T value) where T : IEnumerable { - return default(T); + return default(T); } /// /// Represents the CQL prepend operator for collections (col1 = ? + col1) /// - public static T Prepend(T value) where T: IEnumerable + public static T Prepend(T value) where T : IEnumerable { return default(T); } @@ -43,7 +43,7 @@ public static T Prepend(T value) where T: IEnumerable /// /// Represents the CQL operator to remove an item from lists and sets (col1 = col1 - ?). /// - public static T SubstractAssign(T value) where T: IEnumerable + public static T SubstractAssign(T value) where T : IEnumerable { return default(T); } diff --git a/src/Cassandra/Data/Linq/CqlQuery.cs b/src/Cassandra/Data/Linq/CqlQuery.cs index 5ea17410f..66fd53b74 100644 --- a/src/Cassandra/Data/Linq/CqlQuery.cs +++ b/src/Cassandra/Data/Linq/CqlQuery.cs @@ -118,7 +118,7 @@ public IPage ExecutePaged() { return ExecutePaged(Configuration.DefaultExecutionProfileName); } - + /// /// Asynchronously executes the query with the provided execution profile and returns a task of a page of results /// @@ -128,7 +128,7 @@ public async Task> ExecutePagedAsync(string executionProfile) { throw new ArgumentNullException(nameof(executionProfile)); } - + SetAutoPage(false); var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); var cql = visitor.GetSelect(Expression, out object[] values); @@ -146,10 +146,10 @@ public IPage ExecutePaged(string executionProfile) { throw new ArgumentNullException(nameof(executionProfile)); } - + return WaitToCompleteWithMetrics(ExecutePagedAsync(executionProfile), QueryAbortTimeout); } - + /// /// Generates and returns cql query for this instance /// diff --git a/src/Cassandra/Data/Linq/CqlQueryBase.cs b/src/Cassandra/Data/Linq/CqlQueryBase.cs index a5eb77f9b..bcb3c5ded 100644 --- a/src/Cassandra/Data/Linq/CqlQueryBase.cs +++ b/src/Cassandra/Data/Linq/CqlQueryBase.cs @@ -41,7 +41,7 @@ public abstract class CqlQueryBase : Statement, IInternalStatement public Type ElementType { - get { return typeof (TEntity); } + get { return typeof(TEntity); } } /// @@ -103,14 +103,14 @@ public ITable GetTable() } protected abstract string GetCql(out object[] values); - + protected async Task InternalExecuteWithProfileAsync(string executionProfile, string cqlQuery, object[] values) { var session = GetTable().GetSession(); var statement = await StatementFactory.GetStatementAsync( session, Cql.New(cqlQuery, values).WithExecutionProfile(executionProfile)).ConfigureAwait(false); - + this.CopyQueryPropertiesTo(statement); var rs = await session.ExecuteAsync(statement, executionProfile).ConfigureAwait(false); QueryTrace = rs.Info.QueryTrace; @@ -141,7 +141,7 @@ public IEnumerable Execute() { return ExecuteCqlQuery(Configuration.DefaultExecutionProfileName); } - + /// /// Evaluates the Linq query, executes asynchronously the cql statement with the provided execution profile /// and adapts the results. @@ -179,12 +179,12 @@ public IEnumerable EndExecute(IAsyncResult ar) var task = (Task>)ar; return task.Result; } - + private IEnumerable ExecuteCqlQuery(string executionProfile) { return WaitToCompleteWithMetrics(ExecuteCqlQueryAsync(executionProfile), QueryAbortTimeout); } - + private async Task> ExecuteCqlQueryAsync(string executionProfile) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); diff --git a/src/Cassandra/Data/Linq/CqlQueryExtensions.cs b/src/Cassandra/Data/Linq/CqlQueryExtensions.cs index 53d7a7a7b..67584b9b1 100644 --- a/src/Cassandra/Data/Linq/CqlQueryExtensions.cs +++ b/src/Cassandra/Data/Linq/CqlQueryExtensions.cs @@ -38,10 +38,10 @@ internal static void CopyQueryPropertiesTo(this IStatement src, IStatement dst) } if (src.IsIdempotent.HasValue) { - dst.SetIdempotence(src.IsIdempotent.Value); + dst.SetIdempotence(src.IsIdempotent.Value); } } - + /// /// Projects each element of a sequence into a new form. /// @@ -56,7 +56,7 @@ public static CqlQuery Select(this CqlQuery { Expression expression = source.Expression; CqlQuery result; - if (typeof (TSource) != typeof (TResult)) + if (typeof(TSource) != typeof(TResult)) { //Its a client projection of an existent CqlQuery if (!(source is IClientProjectionCqlQuery)) @@ -83,7 +83,7 @@ public static CqlQuery Select(this CqlQuery } public static CqlQuery Select( - this CqlQuery> source, + this CqlQuery> source, Expression, TResult>> selector) { var expression = Expression.Call(null, CqlMthHelps.SelectMi, new[] { source.Expression, selector }); @@ -104,9 +104,9 @@ public static CqlQuery Select( /// that contains elements from the input sequence that satisfy the condition. public static CqlQuery Where(this CqlQuery source, Expression> predicate) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.WhereMi, - new[] {source.Expression, predicate})); + new[] { source.Expression, predicate })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -121,7 +121,7 @@ public static CqlQuery Where(this CqlQuery source, Ex /// A function to test each element for a condition. /// a CqlQuery<TSource> which after execution will return an IEnumerable<TSource> /// that contains elements from the input sequence that satisfy the condition. - public static CqlQuery> GroupBy(this CqlQuery source, + public static CqlQuery> GroupBy(this CqlQuery source, Expression> predicate) { if (source == null) @@ -186,7 +186,7 @@ public static CqlQuerySingleElement FirstOrDefault(this Table< { var ret = new CqlQuerySingleElement(source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.FirstOrDefault_ForCQLTableMi, - new[] {source.Expression, Expression.Constant(1), predicate})).Expression, source); + new[] { source.Expression, Expression.Constant(1), predicate })).Expression, source); source.CopyQueryPropertiesTo(ret); return ret; } @@ -202,7 +202,7 @@ public static CqlQuerySingleElement First(this CqlQuery(source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.FirstMi, - new[] {source.Expression, Expression.Constant(1)})).Expression, source); + new[] { source.Expression, Expression.Constant(1) })).Expression, source); source.CopyQueryPropertiesTo(ret); return ret; } @@ -220,7 +220,7 @@ public static CqlQuerySingleElement FirstOrDefault(this CqlQue { var ret = new CqlQuerySingleElement(source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.FirstOrDefaultMi, - new[] {source.Expression, Expression.Constant(1)})).Expression, source); + new[] { source.Expression, Expression.Constant(1) })).Expression, source); source.CopyQueryPropertiesTo(ret); return ret; } @@ -242,7 +242,7 @@ public static CqlConditionalCommand DeleteIf(this CqlQuery(delete, source.MapperFactory); } @@ -292,9 +292,9 @@ public static CqlConditionalCommand UpdateIfExists(this CqlQue /// with specified number of contiguous elements from the start of a sequence. public static CqlQuery Take(this CqlQuery source, int count) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.TakeMi, - new[] {source.Expression, Expression.Constant(count)})); + new[] { source.Expression, Expression.Constant(count) })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -307,7 +307,7 @@ public static CqlQuery AllowFiltering(this CqlQuery s { var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.AllowFilteringMi, - new[] {source.Expression})); + new[] { source.Expression })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -322,9 +322,9 @@ public static CqlQuery AllowFiltering(this CqlQuery s /// a CqlQuery<TSource> which after execution returns an IEnumerable<TSource> sorted in ascending manner according to a key. public static CqlQuery OrderBy(this CqlQuery source, Expression> keySelector) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.OrderByMi, - new[] {source.Expression, keySelector})); + new[] { source.Expression, keySelector })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -339,9 +339,9 @@ public static CqlQuery OrderBy(this CqlQuery so /// a CqlQuery<TSource> which after execution returns an IEnumerable<TSource> sorted in descending manner according to a key. public static CqlQuery OrderByDescending(this CqlQuery source, Expression> func) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.OrderByDescendingMi, - new[] {source.Expression, func})); + new[] { source.Expression, func })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -352,9 +352,9 @@ public static CqlQuery OrderByDescending(this CqlQuery public static CqlQuery ThenBy(this CqlQuery source, Expression> func) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.ThenByMi, - new[] {source.Expression, func})); + new[] { source.Expression, func })); source.CopyQueryPropertiesTo(ret); return ret; } @@ -364,9 +364,9 @@ public static CqlQuery ThenBy(this CqlQuery sou /// public static CqlQuery ThenByDescending(this CqlQuery source, Expression> func) { - var ret = (CqlQuery) source.Table.CreateQuery(Expression.Call( + var ret = (CqlQuery)source.Table.CreateQuery(Expression.Call( null, CqlMthHelps.ThenByDescendingMi, - new[] {source.Expression, func})); + new[] { source.Expression, func })); source.CopyQueryPropertiesTo(ret); return ret; } diff --git a/src/Cassandra/Data/Linq/CqlQuerySingleElement.cs b/src/Cassandra/Data/Linq/CqlQuerySingleElement.cs index 41917603d..2e7a41be3 100644 --- a/src/Cassandra/Data/Linq/CqlQuerySingleElement.cs +++ b/src/Cassandra/Data/Linq/CqlQuerySingleElement.cs @@ -27,7 +27,7 @@ public class CqlQuerySingleElement : CqlQueryBase internal CqlQuerySingleElement(Expression expression, CqlQuery source) : base(expression, source.Table, source.MapperFactory, source.StatementFactory, source.PocoData) { - + } protected override string GetCql(out object[] values) @@ -84,7 +84,7 @@ public override string ToString() { return Execute(Configuration.DefaultExecutionProfileName); } - + /// /// Evaluates the Linq query, executes the cql statement with the provided execution profile and returns the first result. /// diff --git a/src/Cassandra/Data/Linq/CqlScalar.cs b/src/Cassandra/Data/Linq/CqlScalar.cs index 2314fa7b0..3ae4443ad 100644 --- a/src/Cassandra/Data/Linq/CqlScalar.cs +++ b/src/Cassandra/Data/Linq/CqlScalar.cs @@ -40,7 +40,7 @@ internal CqlScalar(Expression expression, ITable table, StatementFactory stmtFac { return Execute(Configuration.DefaultExecutionProfileName); } - + public new TEntity Execute(string executionProfile) { return WaitToCompleteWithMetrics(ExecuteAsync(executionProfile), QueryAbortTimeout); @@ -68,7 +68,7 @@ public override string ToString() { return ExecuteAsync(Configuration.DefaultExecutionProfileName); } - + public new async Task ExecuteAsync(string executionProfile) { if (executionProfile == null) diff --git a/src/Cassandra/Data/Linq/CqlToken.cs b/src/Cassandra/Data/Linq/CqlToken.cs index a912af8fc..bec2d8fe6 100644 --- a/src/Cassandra/Data/Linq/CqlToken.cs +++ b/src/Cassandra/Data/Linq/CqlToken.cs @@ -29,32 +29,32 @@ private CqlToken(object[] v) public static CqlToken Create(T v) { - return new CqlToken(new object[] {v}); + return new CqlToken(new object[] { v }); } public static CqlToken Create(T1 v1, T2 v2) { - return new CqlToken(new object[] {v1, v2}); + return new CqlToken(new object[] { v1, v2 }); } public static CqlToken Create(T1 v1, T2 v2, T3 v3) { - return new CqlToken(new object[] {v1, v2, v3}); + return new CqlToken(new object[] { v1, v2, v3 }); } public static CqlToken Create(T1 v1, T2 v2, T3 v3, T4 v4) { - return new CqlToken(new object[] {v1, v2, v3, v4}); + return new CqlToken(new object[] { v1, v2, v3, v4 }); } public static CqlToken Create(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { - return new CqlToken(new object[] {v1, v2, v3, v4, v5}); + return new CqlToken(new object[] { v1, v2, v3, v4, v5 }); } public static CqlToken Create(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { - return new CqlToken(new object[] {v1, v2, v3, v4, v5, v6}); + return new CqlToken(new object[] { v1, v2, v3, v4, v5, v6 }); } public override int GetHashCode() diff --git a/src/Cassandra/Data/Linq/ExpressionParsing/BinaryConditionItem.cs b/src/Cassandra/Data/Linq/ExpressionParsing/BinaryConditionItem.cs index be85fe915..d35cfe0ae 100644 --- a/src/Cassandra/Data/Linq/ExpressionParsing/BinaryConditionItem.cs +++ b/src/Cassandra/Data/Linq/ExpressionParsing/BinaryConditionItem.cs @@ -288,7 +288,7 @@ private void ToCqlParameters(StringBuilder query, string functionName) public IConditionItem SetAsCompareTo() { _isCompareTo = true; - if (_parameters.Count == 1&& _operator != null) + if (_parameters.Count == 1 && _operator != null) { if (!Equals(_parameters[0], 0)) { diff --git a/src/Cassandra/Data/Linq/LinqAttributeBasedColumnDefinition.cs b/src/Cassandra/Data/Linq/LinqAttributeBasedColumnDefinition.cs index 9b4424ba4..4a8e84815 100644 --- a/src/Cassandra/Data/Linq/LinqAttributeBasedColumnDefinition.cs +++ b/src/Cassandra/Data/Linq/LinqAttributeBasedColumnDefinition.cs @@ -40,8 +40,8 @@ internal class LinqAttributeBasedColumnDefinition : IColumnDefinition /// /// Creates a new column definition for the field specified using any attributes on the field to determine mapping configuration. /// - public LinqAttributeBasedColumnDefinition(FieldInfo fieldInfo) - : this((MemberInfo) fieldInfo) + public LinqAttributeBasedColumnDefinition(FieldInfo fieldInfo) + : this((MemberInfo)fieldInfo) { MemberInfoType = fieldInfo.FieldType; } @@ -49,8 +49,8 @@ public LinqAttributeBasedColumnDefinition(FieldInfo fieldInfo) /// /// Creates a new column definition for the property specified using any attributes on the property to determine mapping configuration. /// - public LinqAttributeBasedColumnDefinition(PropertyInfo propertyInfo) - : this((MemberInfo) propertyInfo) + public LinqAttributeBasedColumnDefinition(PropertyInfo propertyInfo) + : this((MemberInfo)propertyInfo) { MemberInfoType = propertyInfo.PropertyType; } @@ -59,7 +59,7 @@ private LinqAttributeBasedColumnDefinition(MemberInfo memberInfo) { MemberInfo = memberInfo; - var columnAttribute = (ColumnAttribute) memberInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); + var columnAttribute = (ColumnAttribute)memberInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); if (columnAttribute != null) { IsExplicitlyDefined = true; @@ -69,7 +69,7 @@ private LinqAttributeBasedColumnDefinition(MemberInfo memberInfo) ColumnName = columnAttribute.Name; } } - SecondaryIndex = HasAttribute(memberInfo, typeof (SecondaryIndexAttribute)); + SecondaryIndex = HasAttribute(memberInfo, typeof(SecondaryIndexAttribute)); IsCounter = HasAttribute(memberInfo, typeof(CounterAttribute)); IsStatic = HasAttribute(memberInfo, typeof(StaticColumnAttribute)); Ignore = HasAttribute(memberInfo, typeof(IgnoreAttribute)); diff --git a/src/Cassandra/Data/Linq/LinqAttributeBasedTypeDefinition.cs b/src/Cassandra/Data/Linq/LinqAttributeBasedTypeDefinition.cs index 71b9974ee..ae3deabea 100644 --- a/src/Cassandra/Data/Linq/LinqAttributeBasedTypeDefinition.cs +++ b/src/Cassandra/Data/Linq/LinqAttributeBasedTypeDefinition.cs @@ -53,14 +53,14 @@ public LinqAttributeBasedTypeDefinition(Type type, string tableName, string keys .GetTypeInfo() .GetFields(PublicInstanceBindingFlags) .Where(field => field.IsInitOnly == false) - .Select(field => (MemberInfo) field) + .Select(field => (MemberInfo)field) .Concat(type.GetTypeInfo().GetProperties(PublicInstanceBindingFlags).Where(p => p.CanWrite)); var partitionKeys = new List>(); var clusteringKeys = new List>(); foreach (var member in mappable) { var columnName = member.Name; - var columnAttribute = (ColumnAttribute) member.GetCustomAttributes(typeof (ColumnAttribute), true).FirstOrDefault(); + var columnAttribute = (ColumnAttribute)member.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); if (columnAttribute?.Name != null) { columnName = columnAttribute.Name; diff --git a/src/Cassandra/Data/Linq/ParsePhase.cs b/src/Cassandra/Data/Linq/ParsePhase.cs index 2eee93b45..10f78d537 100644 --- a/src/Cassandra/Data/Linq/ParsePhase.cs +++ b/src/Cassandra/Data/Linq/ParsePhase.cs @@ -42,7 +42,7 @@ internal enum ParsePhase /// Take() method calls. /// Take, - + /// /// OrderBy() method calls. /// @@ -52,7 +52,7 @@ internal enum ParsePhase /// OrderByDescending() method calls. /// OrderByDescending, - + /// /// GroupBy() method calls. /// diff --git a/src/Cassandra/Data/Linq/SessionExtensions.cs b/src/Cassandra/Data/Linq/SessionExtensions.cs index 084c3a0fc..6232fe030 100644 --- a/src/Cassandra/Data/Linq/SessionExtensions.cs +++ b/src/Cassandra/Data/Linq/SessionExtensions.cs @@ -37,10 +37,10 @@ public static Table GetTable(this ISession session, string tab { //Use Linq defaults if no definition has been set for this types //Linq attributes are marked as Obsolete - #pragma warning disable 612 +#pragma warning disable 612 MappingConfiguration.Global.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(TEntity), - () => new LinqAttributeBasedTypeDefinition(typeof (TEntity), tableName, keyspaceName)); - #pragma warning restore 612 + () => new LinqAttributeBasedTypeDefinition(typeof(TEntity), tableName, keyspaceName)); +#pragma warning restore 612 var config = MappingConfiguration.Global; return new Table(session, config, tableName, keyspaceName); } @@ -48,7 +48,7 @@ public static Table GetTable(this ISession session, string tab public static Batch CreateBatch(this ISession session) { return CreateBatch(session, BatchType.Logged); - } + } public static Batch CreateBatch(this ISession session, BatchType batchType) { diff --git a/src/Cassandra/Data/Linq/Table.cs b/src/Cassandra/Data/Linq/Table.cs index d49f91962..835a3390c 100644 --- a/src/Cassandra/Data/Linq/Table.cs +++ b/src/Cassandra/Data/Linq/Table.cs @@ -68,10 +68,10 @@ public Table(ISession session, MappingConfiguration config, string tableName, st _keyspaceName = keyspaceName; //In case no mapping has been defined for the type, determine if the attributes used are Linq or Cassandra.Mapping //Linq attributes are marked as Obsolete - #pragma warning disable 612 +#pragma warning disable 612 config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(TEntity), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(TEntity))); - #pragma warning restore 612 +#pragma warning restore 612 var pocoData = config.MapperFactory.GetPocoData(); InternalInitialize(Expression.Constant(this), this, config.MapperFactory, config.StatementFactory, pocoData); } @@ -145,7 +145,7 @@ object IQueryProvider.Execute(Expression expression) public Type GetEntityType() { - return typeof (TEntity); + return typeof(TEntity); } public void Create() diff --git a/src/Cassandra/Data/Linq/TableAttribute.cs b/src/Cassandra/Data/Linq/TableAttribute.cs index 2d4df9be3..e3ece9466 100644 --- a/src/Cassandra/Data/Linq/TableAttribute.cs +++ b/src/Cassandra/Data/Linq/TableAttribute.cs @@ -28,7 +28,7 @@ public sealed class TableAttribute : Attribute /// /// Gets or sets the table name in Cassandra /// - public string Name {get; set; } + public string Name { get; set; } /// /// Determines if the table and column names are defined as case sensitive (default to true). diff --git a/src/Cassandra/Data/Linq/VisitingParam.cs b/src/Cassandra/Data/Linq/VisitingParam.cs index 8d8cc8073..c2973fe5d 100644 --- a/src/Cassandra/Data/Linq/VisitingParam.cs +++ b/src/Cassandra/Data/Linq/VisitingParam.cs @@ -34,7 +34,7 @@ public VisitingParam(T defaultValue) public VisitingParam() : this(default(T)) { - + } public IDisposable Set(T val) diff --git a/src/Cassandra/DataCollectionMetadata.cs b/src/Cassandra/DataCollectionMetadata.cs index 39c5a06c1..104f00205 100644 --- a/src/Cassandra/DataCollectionMetadata.cs +++ b/src/Cassandra/DataCollectionMetadata.cs @@ -66,7 +66,7 @@ public enum SortOrder : sbyte protected DataCollectionMetadata() { - + } internal void SetValues(IDictionary columns, TableColumn[] partitionKeys, Tuple[] clusteringKeys, TableOptions options) diff --git a/src/Cassandra/DataStax/Auth/DseGssapiAuthProvider.cs b/src/Cassandra/DataStax/Auth/DseGssapiAuthProvider.cs index f297fa155..04dfc73ae 100644 --- a/src/Cassandra/DataStax/Auth/DseGssapiAuthProvider.cs +++ b/src/Cassandra/DataStax/Auth/DseGssapiAuthProvider.cs @@ -96,7 +96,7 @@ private class GssapiDseAuthenticator : BaseDseAuthenticator, IDisposable private readonly string _service; private readonly IGssapiClient _client; - public GssapiDseAuthenticator(string authenticatorName, string hostName, string service) : + public GssapiDseAuthenticator(string authenticatorName, string hostName, string service) : base(authenticatorName) { _hostName = hostName; diff --git a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBuffer.cs b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBuffer.cs index 0995c0531..b9998e045 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBuffer.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBuffer.cs @@ -32,7 +32,7 @@ namespace Cassandra.DataStax.Auth.Sspi.Buffers /// Represents a native SecureBuffer structure, which is used for communicating /// buffers to the native APIs. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal struct SecureBufferInternal { /// @@ -73,7 +73,7 @@ internal class SecureBuffer /// The buffer to wrap. /// The type or purpose of the buffer, for purposes of /// invoking the native API. - public SecureBuffer( byte[] buffer, BufferType type ) + public SecureBuffer(byte[] buffer, BufferType type) { this.Buffer = buffer; this.Type = type; diff --git a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferAdapter.cs b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferAdapter.cs index 9ed98fe3e..ad6bd44bc 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferAdapter.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferAdapter.cs @@ -124,8 +124,8 @@ internal sealed class SecureBufferAdapter : CriticalFinalizerObject, IDisposable /// Initializes a SecureBufferAdapter to carry a single buffer to the native api. /// /// - public SecureBufferAdapter( SecureBuffer buffer ) - : this( new[] { buffer } ) + public SecureBufferAdapter(SecureBuffer buffer) + : this(new[] { buffer }) { } @@ -133,7 +133,7 @@ public SecureBufferAdapter( SecureBuffer buffer ) /// Initializes the SecureBufferAdapter to carry a list of buffers to the native api. /// /// - public SecureBufferAdapter( IList buffers ) : base() + public SecureBufferAdapter(IList buffers) : base() { this.buffers = buffers; @@ -142,9 +142,9 @@ public SecureBufferAdapter( IList buffers ) : base() this.bufferHandles = new GCHandle[this.buffers.Count]; this.bufferCarrier = new SecureBufferInternal[this.buffers.Count]; - for ( int i = 0; i < this.buffers.Count; i++ ) + for (int i = 0; i < this.buffers.Count; i++) { - this.bufferHandles[i] = GCHandle.Alloc( this.buffers[i].Buffer, GCHandleType.Pinned ); + this.bufferHandles[i] = GCHandle.Alloc(this.buffers[i].Buffer, GCHandleType.Pinned); this.bufferCarrier[i] = new SecureBufferInternal(); this.bufferCarrier[i].Type = this.buffers[i].Type; @@ -152,23 +152,23 @@ public SecureBufferAdapter( IList buffers ) : base() this.bufferCarrier[i].Buffer = bufferHandles[i].AddrOfPinnedObject(); } - this.bufferCarrierHandle = GCHandle.Alloc( bufferCarrier, GCHandleType.Pinned ); + this.bufferCarrierHandle = GCHandle.Alloc(bufferCarrier, GCHandleType.Pinned); this.descriptor = new SecureBufferDescInternal(); this.descriptor.Version = SecureBufferDescInternal.ApiVersion; this.descriptor.NumBuffers = this.buffers.Count; this.descriptor.Buffers = bufferCarrierHandle.AddrOfPinnedObject(); - this.descriptorHandle = GCHandle.Alloc( descriptor, GCHandleType.Pinned ); + this.descriptorHandle = GCHandle.Alloc(descriptor, GCHandleType.Pinned); } - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] ~SecureBufferAdapter() { // We bend the typical Dispose pattern here. This finalizer runs in a Constrained Execution Region, // and so we shouldn't call virtual methods. There's no need to extend this class, so we prevent it // and mark the protected Dispose method as non-virtual. - Dispose( false ); + Dispose(false); } /// @@ -178,9 +178,9 @@ public IntPtr Handle { get { - if ( this.disposed ) + if (this.disposed) { - throw new ObjectDisposedException( "Cannot use SecureBufferListHandle after it has been disposed" ); + throw new ObjectDisposedException("Cannot use SecureBufferListHandle after it has been disposed"); } return this.descriptorHandle.AddrOfPinnedObject(); @@ -192,8 +192,8 @@ public IntPtr Handle /// public void Dispose() { - this.Dispose( true ); - GC.SuppressFinalize( this ); + this.Dispose(true); + GC.SuppressFinalize(this); } /// @@ -203,36 +203,36 @@ public void Dispose() /// nor should we anyway since they may be gone. /// /// Whether Dispose is being called. - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - private void Dispose( bool disposing ) + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + private void Dispose(bool disposing) { - if ( this.disposed == true ) { return; } + if (this.disposed == true) { return; } - if ( disposing ) + if (disposing) { // When this class is actually being used for its original purpose - to convey buffers // back and forth to SSPI calls - we need to copy the potentially modified structure members // back to our caller's buffer. - for( int i = 0; i < this.buffers.Count; i++ ) + for (int i = 0; i < this.buffers.Count; i++) { this.buffers[i].Length = this.bufferCarrier[i].Count; } } - for( int i = 0; i < this.bufferHandles.Length; i++ ) + for (int i = 0; i < this.bufferHandles.Length; i++) { - if( this.bufferHandles[i].IsAllocated ) + if (this.bufferHandles[i].IsAllocated) { this.bufferHandles[i].Free(); } } - if( this.bufferCarrierHandle.IsAllocated ) + if (this.bufferCarrierHandle.IsAllocated) { this.bufferCarrierHandle.Free(); } - if( this.descriptorHandle.IsAllocated ) + if (this.descriptorHandle.IsAllocated) { this.descriptorHandle.Free(); } diff --git a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferDesc.cs b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferDesc.cs index 5cf0e7572..38f7aa07a 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferDesc.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferDesc.cs @@ -32,7 +32,7 @@ namespace Cassandra.DataStax.Auth.Sspi.Buffers /// Represents the native layout of the secure buffer descriptor that is provided directly /// to native API calls. /// - [StructLayout( LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct SecureBufferDescInternal { /// diff --git a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferType.cs b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferType.cs index bf0755675..e5d2f912a 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferType.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Buffers/SecureBufferType.cs @@ -76,7 +76,7 @@ internal enum BufferType : int Stream = 0x0A, ChannelBindings = 0x0E, TargetHost = 0x10, - ReadOnlyFlag = unchecked( (int)0x80000000 ), + ReadOnlyFlag = unchecked((int)0x80000000), ReadOnlyWithChecksum = 0x10000000 } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/ByteWriter.cs b/src/Cassandra/DataStax/Auth/Sspi/ByteWriter.cs index 8f8e8c8ba..459a95878 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/ByteWriter.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/ByteWriter.cs @@ -33,17 +33,17 @@ namespace Cassandra.DataStax.Auth.Sspi internal static class ByteWriter { // Big endian: Most significant byte at lowest address in memory. - + /// /// Writes a 2-byte signed integer to the buffer in big-endian format. /// /// The value to write to the buffer. /// The buffer to write to. /// The index of the first byte to write to. - public static void WriteInt16_BE( Int16 value, byte[] buffer, int position ) + public static void WriteInt16_BE(Int16 value, byte[] buffer, int position) { - buffer[position + 0] = (byte)( value >> 8 ); - buffer[position + 1] = (byte)( value ); + buffer[position + 0] = (byte)(value >> 8); + buffer[position + 1] = (byte)(value); } /// @@ -52,12 +52,12 @@ public static void WriteInt16_BE( Int16 value, byte[] buffer, int position ) /// The value to write to the buffer. /// The buffer to write to. /// The index of the first byte to write to. - public static void WriteInt32_BE( Int32 value, byte[] buffer, int position ) + public static void WriteInt32_BE(Int32 value, byte[] buffer, int position) { - buffer[position + 0] = (byte)( value >> 24 ); - buffer[position + 1] = (byte)( value >> 16 ); - buffer[position + 2] = (byte)( value >> 8 ); - buffer[position + 3] = (byte)( value); + buffer[position + 0] = (byte)(value >> 24); + buffer[position + 1] = (byte)(value >> 16); + buffer[position + 2] = (byte)(value >> 8); + buffer[position + 3] = (byte)(value); } @@ -68,12 +68,12 @@ public static void WriteInt32_BE( Int32 value, byte[] buffer, int position ) /// The buffer to read. /// The index of the first byte to read. /// - public static Int16 ReadInt16_BE( byte[] buffer, int position ) + public static Int16 ReadInt16_BE(byte[] buffer, int position) { Int16 value; - value = (Int16)( buffer[position + 0] << 8 ); - value += (Int16)( buffer[position + 1] ); + value = (Int16)(buffer[position + 0] << 8); + value += (Int16)(buffer[position + 1]); return value; } @@ -85,14 +85,14 @@ public static Int16 ReadInt16_BE( byte[] buffer, int position ) /// The buffer to read. /// The index of the first byte to read. /// - public static Int32 ReadInt32_BE( byte[] buffer, int position ) + public static Int32 ReadInt32_BE(byte[] buffer, int position) { Int32 value; - value = (Int32)( buffer[position + 0] << 24 ); - value |= (Int32)( buffer[position + 1] << 16 ); - value |= (Int32)( buffer[position + 2] << 8 ); - value |= (Int32)( buffer[position + 3] ); + value = (Int32)(buffer[position + 0] << 24); + value |= (Int32)(buffer[position + 1] << 16); + value |= (Int32)(buffer[position + 2] << 8); + value |= (Int32)(buffer[position + 3]); return value; } diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ClientContext.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ClientContext.cs index 48de9c961..48f509973 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ClientContext.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ClientContext.cs @@ -53,8 +53,8 @@ internal class ClientContext : Context /// Requested attributes that describe the desired properties of the /// context once it is established. If a context cannot be established that satisfies the indicated /// properties, the context initialization is aborted. - public ClientContext( ClientCredential cred, string serverPrinc, ContextAttrib requestedAttribs ) - : base( cred ) + public ClientContext(ClientCredential cred, string serverPrinc, ContextAttrib requestedAttribs) + : base(cred) { this.serverPrinc = serverPrinc; this.requestedAttribs = requestedAttribs; @@ -82,7 +82,7 @@ public ClientContext( ClientCredential cred, string serverPrinc, ContextAttrib r /// is not null, it must be sent to the server. /// A status of 'Continue' indicates that the output token should be sent to the server and /// a response should be anticipated. - public SecurityStatus Init( byte[] serverToken, out byte[] outToken ) + public SecurityStatus Init(byte[] serverToken, out byte[] outToken) { TimeStamp rawExpiry = new TimeStamp(); @@ -93,31 +93,31 @@ public SecurityStatus Init( byte[] serverToken, out byte[] outToken ) SecureBuffer serverBuffer; SecureBufferAdapter serverAdapter; - - if( this.Disposed ) + + if (this.Disposed) { - throw new ObjectDisposedException( "ClientContext" ); + throw new ObjectDisposedException("ClientContext"); } - else if( ( serverToken != null ) && ( this.ContextHandle.IsInvalid ) ) + else if ((serverToken != null) && (this.ContextHandle.IsInvalid)) { - throw new InvalidOperationException( "Out-of-order usage detected - have a server token, but no previous client token had been created." ); + throw new InvalidOperationException("Out-of-order usage detected - have a server token, but no previous client token had been created."); } - else if( ( serverToken == null ) && ( this.ContextHandle.IsInvalid == false ) ) + else if ((serverToken == null) && (this.ContextHandle.IsInvalid == false)) { - throw new InvalidOperationException( "Must provide the server's response when continuing the init process." ); + throw new InvalidOperationException("Must provide the server's response when continuing the init process."); } - + // The security package tells us how big its biggest token will be. We'll allocate a buffer // that size, and it'll tell us how much it used. - outTokenBuffer = new SecureBuffer( - new byte[ this.Credential.PackageInfo.MaxTokenLength ], - BufferType.Token + outTokenBuffer = new SecureBuffer( + new byte[this.Credential.PackageInfo.MaxTokenLength], + BufferType.Token ); serverBuffer = null; - if ( serverToken != null ) + if (serverToken != null) { - serverBuffer = new SecureBuffer( serverToken, BufferType.Token ); + serverBuffer = new SecureBuffer(serverToken, BufferType.Token); } // Some notes on handles and invoking InitializeSecurityContext @@ -135,9 +135,9 @@ public SecurityStatus Init( byte[] serverToken, out byte[] outToken ) // Windows, 128 bits on 64-bit Windows. // - So in the end, on a 64-bit machine, we're passing a 64-bit value (the pointer to the struct) that // points to 128 bits of memory (the struct itself) for where to write the handle numbers. - using ( outAdapter = new SecureBufferAdapter( outTokenBuffer ) ) + using (outAdapter = new SecureBufferAdapter(outTokenBuffer)) { - if ( this.ContextHandle.IsInvalid ) + if (this.ContextHandle.IsInvalid) { status = ContextNativeMethods.InitializeSecurityContext_1( ref this.Credential.Handle.rawHandle, @@ -156,7 +156,7 @@ ref rawExpiry } else { - using ( serverAdapter = new SecureBufferAdapter( serverBuffer ) ) + using (serverAdapter = new SecureBufferAdapter(serverBuffer)) { status = ContextNativeMethods.InitializeSecurityContext_2( ref this.Credential.Handle.rawHandle, @@ -176,24 +176,24 @@ ref rawExpiry } } - if( status.IsError() == false ) + if (status.IsError() == false) { - if( status == SecurityStatus.OK ) + if (status == SecurityStatus.OK) { - base.Initialize( rawExpiry.ToDateTime() ); + base.Initialize(rawExpiry.ToDateTime()); } outToken = null; - if( outTokenBuffer.Length != 0 ) + if (outTokenBuffer.Length != 0) { outToken = new byte[outTokenBuffer.Length]; - Array.Copy( outTokenBuffer.Buffer, outToken, outToken.Length ); + Array.Copy(outTokenBuffer.Buffer, outToken, outToken.Length); } } else { - throw new SspiException( "Failed to invoke InitializeSecurityContext for a client", status ); + throw new SspiException("Failed to invoke InitializeSecurityContext for a client", status); } return status; diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/Context.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/Context.cs index 26e5f3727..9e7233630 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/Context.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/Context.cs @@ -52,7 +52,7 @@ internal abstract class Context : IDisposable /// and the Initialize method has been called. /// /// - protected Context( Credential cred ) + protected Context(Credential cred) { this.Credential = cred; @@ -76,7 +76,7 @@ protected Context( Credential cred ) /// A reference to the security context's handle. /// public SafeContextHandle ContextHandle { get; private set; } - + /// /// The UTC time when the context expires. /// @@ -91,7 +91,7 @@ protected Context( Credential cred ) /// Marks the context as having completed the initialization process, ie, exchanging of authentication tokens. /// /// The date and time that the context will expire. - protected void Initialize( DateTime expiry ) + protected void Initialize(DateTime expiry) { this.Expiry = expiry; this.Initialized = true; @@ -102,19 +102,19 @@ protected void Initialize( DateTime expiry ) /// public void Dispose() { - Dispose( true ); - GC.SuppressFinalize( this ); + Dispose(true); + GC.SuppressFinalize(this); } /// /// Releases resources associated with the context. /// /// If true, release managed resources, else release only unmanaged resources. - protected virtual void Dispose( bool disposing ) + protected virtual void Dispose(bool disposing) { - if( this.Disposed ) { return; } + if (this.Disposed) { return; } - if( disposing ) + if (disposing) { this.ContextHandle.Dispose(); } @@ -136,7 +136,7 @@ protected virtual void Dispose( bool disposing ) /// /// The raw message to encrypt. /// The packed and encrypted message. - public byte[] Encrypt( byte[] input ) + public byte[] Encrypt(byte[] input) { // The message is encrypted in place in the buffer we provide to Win32 EncryptMessage SecPkgContext_Sizes sizes; @@ -151,13 +151,13 @@ public byte[] Encrypt( byte[] input ) sizes = QueryBufferSizes(); - trailerBuffer = new SecureBuffer( new byte[sizes.SecurityTrailer], BufferType.Token ); - dataBuffer = new SecureBuffer( new byte[input.Length], BufferType.Data ); - paddingBuffer = new SecureBuffer( new byte[sizes.BlockSize], BufferType.Padding ); + trailerBuffer = new SecureBuffer(new byte[sizes.SecurityTrailer], BufferType.Token); + dataBuffer = new SecureBuffer(new byte[input.Length], BufferType.Data); + paddingBuffer = new SecureBuffer(new byte[sizes.BlockSize], BufferType.Padding); - Array.Copy( input, dataBuffer.Buffer, input.Length ); + Array.Copy(input, dataBuffer.Buffer, input.Length); - using( adapter = new SecureBufferAdapter( new[] { trailerBuffer, dataBuffer, paddingBuffer } ) ) + using (adapter = new SecureBufferAdapter(new[] { trailerBuffer, dataBuffer, paddingBuffer })) { status = ContextNativeMethods.SafeEncryptMessage( this.ContextHandle, @@ -167,23 +167,23 @@ public byte[] Encrypt( byte[] input ) ); } - if( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to encrypt message", status ); + throw new SspiException("Failed to encrypt message", status); } int position = 0; - + // Return 1 buffer with the 3 buffers joined var result = new byte[trailerBuffer.Length + dataBuffer.Length + paddingBuffer.Length]; - Array.Copy( trailerBuffer.Buffer, 0, result, position, trailerBuffer.Length ); + Array.Copy(trailerBuffer.Buffer, 0, result, position, trailerBuffer.Length); position += trailerBuffer.Length; - Array.Copy( dataBuffer.Buffer, 0, result, position, dataBuffer.Length ); + Array.Copy(dataBuffer.Buffer, 0, result, position, dataBuffer.Length); position += dataBuffer.Length; - Array.Copy( paddingBuffer.Buffer, 0, result, position, paddingBuffer.Length ); + Array.Copy(paddingBuffer.Buffer, 0, result, position, paddingBuffer.Length); return result; } @@ -200,7 +200,7 @@ public byte[] Encrypt( byte[] input ) /// The packed and encrypted data. /// Null /// Exception thrown when hash validation fails. - public byte[] Decrypt( byte[] input ) + public byte[] Decrypt(byte[] input) { SecurityStatus status; @@ -208,12 +208,12 @@ public byte[] Decrypt( byte[] input ) var trailerLength = input.Length; - var dataBuffer = new SecureBuffer( new byte[0], BufferType.Data ); - var trailerBuffer = new SecureBuffer( new byte[trailerLength], BufferType.Stream ); + var dataBuffer = new SecureBuffer(new byte[0], BufferType.Data); + var trailerBuffer = new SecureBuffer(new byte[trailerLength], BufferType.Stream); - Array.Copy( input, 0, trailerBuffer.Buffer, 0, trailerBuffer.Length ); + Array.Copy(input, 0, trailerBuffer.Buffer, 0, trailerBuffer.Length); - using (var adapter = new SecureBufferAdapter( new[] { dataBuffer, trailerBuffer } ) ) + using (var adapter = new SecureBufferAdapter(new[] { dataBuffer, trailerBuffer })) { status = ContextNativeMethods.SafeDecryptMessage( this.ContextHandle, @@ -223,9 +223,9 @@ public byte[] Decrypt( byte[] input ) ); } - if( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to decrypt message", status ); + throw new SspiException("Failed to decrypt message", status); } return null; @@ -244,11 +244,11 @@ private SecPkgContext_Sizes QueryBufferSizes() RuntimeHelpers.PrepareConstrainedRegions(); try { - this.ContextHandle.DangerousAddRef( ref gotRef ); + this.ContextHandle.DangerousAddRef(ref gotRef); } - catch ( Exception ) + catch (Exception) { - if ( gotRef ) + if (gotRef) { this.ContextHandle.DangerousRelease(); gotRef = false; @@ -258,7 +258,7 @@ private SecPkgContext_Sizes QueryBufferSizes() } finally { - if ( gotRef ) + if (gotRef) { status = ContextNativeMethods.QueryContextAttributes_Sizes( ref this.ContextHandle.rawHandle, @@ -269,9 +269,9 @@ ref sizes } } - if( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to query context buffer size attributes", status ); + throw new SspiException("Failed to query context buffer size attributes", status); } return sizes; @@ -283,13 +283,13 @@ ref sizes /// private void CheckLifecycle() { - if( this.Initialized == false ) + if (this.Initialized == false) { - throw new InvalidOperationException( "The context is not yet fully formed." ); + throw new InvalidOperationException("The context is not yet fully formed."); } - else if( this.Disposed ) + else if (this.Disposed) { - throw new ObjectDisposedException( "Context" ); + throw new ObjectDisposedException("Context"); } } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextAttrib.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextAttrib.cs index 3842af34f..980ab0b56 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextAttrib.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextAttrib.cs @@ -35,13 +35,13 @@ namespace Cassandra.DataStax.Auth.Sspi.Contexts /// actually has. /// [Flags] - internal enum ContextAttrib : int + internal enum ContextAttrib : int { /// /// No additional attributes are provided. /// Zero = 0, - + /// /// The server can use the context to authenticate to other servers as the client. The /// MutualAuth flag must be set for this flag to work. Valid for Kerberos. Ignore this flag for @@ -76,12 +76,12 @@ internal enum ContextAttrib : int // Confidentiality is supported for NTLM with Microsoft // Windows NT version 4.0, SP4 and later and with the // Kerberos protocol in Microsoft Windows 2000 and later. - + /// /// The context must protect data while in transit. Encrypt messages by using the EncryptMessage function. /// Confidentiality = 0x00000010, - + /// /// A new session key must be negotiated. /// This value is supported only by the Kerberos security package. @@ -133,7 +133,7 @@ internal enum ContextAttrib : int /// Replayed and out-of-sequence messages will not be detected with the setting of this attribute. /// Set ReplayDetect and SequenceDetect also if these behaviors are desired. /// - InitIntegrity = 0x00010000, + InitIntegrity = 0x00010000, /// /// Sign messages and verify signatures by using the EncryptMessage and MakeSignature functions. diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextNativeMethods.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextNativeMethods.cs index ac7e838f5..360231cf5 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextNativeMethods.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextNativeMethods.cs @@ -65,7 +65,7 @@ _Out_opt_ PTimeStamp ptsExpiry // [out] receives the life ); */ - [DllImport( "Secur32.dll", EntryPoint = "AcceptSecurityContext",CharSet = CharSet.Unicode )] + [DllImport("Secur32.dll", EntryPoint = "AcceptSecurityContext", CharSet = CharSet.Unicode)] internal static extern SecurityStatus AcceptSecurityContext_1( ref RawSspiHandle credHandle, IntPtr oldContextHandle, @@ -79,7 +79,7 @@ ref TimeStamp expiry ); - [DllImport( "Secur32.dll", EntryPoint = "AcceptSecurityContext", CharSet = CharSet.Unicode )] + [DllImport("Secur32.dll", EntryPoint = "AcceptSecurityContext", CharSet = CharSet.Unicode)] internal static extern SecurityStatus AcceptSecurityContext_2( ref RawSspiHandle credHandle, ref RawSspiHandle oldContextHandle, @@ -93,7 +93,7 @@ ref TimeStamp expiry ); - [DllImport( "Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode )] + [DllImport("Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode)] internal static extern SecurityStatus InitializeSecurityContext_1( ref RawSspiHandle credentialHandle, IntPtr zero, @@ -110,7 +110,7 @@ ref TimeStamp expiry ); - [DllImport( "Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode )] + [DllImport("Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode)] internal static extern SecurityStatus InitializeSecurityContext_2( ref RawSspiHandle credentialHandle, ref RawSspiHandle previousHandle, @@ -126,13 +126,13 @@ internal static extern SecurityStatus InitializeSecurityContext_2( ref TimeStamp expiry ); - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "DeleteSecurityContext", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus DeleteSecurityContext( ref RawSspiHandle contextHandle ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "DeleteSecurityContext", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus DeleteSecurityContext(ref RawSspiHandle contextHandle); - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail )] - [DllImport( "Secur32.dll", EntryPoint = "EncryptMessage", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [DllImport("Secur32.dll", EntryPoint = "EncryptMessage", CharSet = CharSet.Unicode)] internal static extern SecurityStatus EncryptMessage( ref RawSspiHandle contextHandle, uint qualityOfProtection, @@ -140,8 +140,8 @@ internal static extern SecurityStatus EncryptMessage( int sequenceNumber ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] - [DllImport( "Secur32.dll", EntryPoint = "DecryptMessage", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [DllImport("Secur32.dll", EntryPoint = "DecryptMessage", CharSet = CharSet.Unicode)] internal static extern SecurityStatus DecryptMessage( ref RawSspiHandle contextHandle, IntPtr bufferDescriptor, @@ -149,8 +149,8 @@ internal static extern SecurityStatus DecryptMessage( int qualityOfProtection ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] - [DllImport( "Secur32.dll", EntryPoint = "MakeSignature", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [DllImport("Secur32.dll", EntryPoint = "MakeSignature", CharSet = CharSet.Unicode)] internal static extern SecurityStatus MakeSignature( ref RawSspiHandle contextHandle, int qualityOfProtection, @@ -158,8 +158,8 @@ internal static extern SecurityStatus MakeSignature( int sequenceNumber ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] - [DllImport( "Secur32.dll", EntryPoint = "VerifySignature", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [DllImport("Secur32.dll", EntryPoint = "VerifySignature", CharSet = CharSet.Unicode)] internal static extern SecurityStatus VerifySignature( ref RawSspiHandle contextHandle, IntPtr bufferDescriptor, @@ -167,34 +167,34 @@ internal static extern SecurityStatus VerifySignature( int qualityOfProtection ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode)] internal static extern SecurityStatus QueryContextAttributes_Sizes( ref RawSspiHandle contextHandle, ContextQueryAttrib attrib, ref SecPkgContext_Sizes sizes ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)] - [DllImport( "Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode)] internal static extern SecurityStatus QueryContextAttributes_String( ref RawSspiHandle contextHandle, ContextQueryAttrib attrib, ref SecPkgContext_String names ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus FreeContextBuffer( IntPtr handle ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus FreeContextBuffer(IntPtr handle); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "ImpersonateSecurityContext", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus ImpersonateSecurityContext( ref RawSspiHandle contextHandle ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "ImpersonateSecurityContext", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus ImpersonateSecurityContext(ref RawSspiHandle contextHandle); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "RevertSecurityContext", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus RevertSecurityContext( ref RawSspiHandle contextHandle ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "RevertSecurityContext", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus RevertSecurityContext(ref RawSspiHandle contextHandle); /// /// Safely invokes the native EncryptMessage function, making sure that handle ref counting is @@ -209,7 +209,7 @@ internal static SecurityStatus SafeEncryptMessage( SafeContextHandle handle, uint qualityOfProtection, SecureBufferAdapter bufferAdapter, - int sequenceNumber ) + int sequenceNumber) { SecurityStatus status = SecurityStatus.InternalError; bool gotRef = false; @@ -217,11 +217,11 @@ internal static SecurityStatus SafeEncryptMessage( RuntimeHelpers.PrepareConstrainedRegions(); try { - handle.DangerousAddRef( ref gotRef ); + handle.DangerousAddRef(ref gotRef); } - catch ( Exception ) + catch (Exception) { - if ( gotRef ) + if (gotRef) { handle.DangerousRelease(); gotRef = false; @@ -231,7 +231,7 @@ internal static SecurityStatus SafeEncryptMessage( } finally { - if ( gotRef ) + if (gotRef) { status = ContextNativeMethods.EncryptMessage( ref handle.rawHandle, @@ -256,11 +256,11 @@ internal static SecurityStatus SafeEncryptMessage( /// /// /// - internal static SecurityStatus SafeDecryptMessage( - SafeContextHandle handle, - int qualityOfProtection, - SecureBufferAdapter bufferAdapter, - int sequenceNumber ) + internal static SecurityStatus SafeDecryptMessage( + SafeContextHandle handle, + int qualityOfProtection, + SecureBufferAdapter bufferAdapter, + int sequenceNumber) { SecurityStatus status = SecurityStatus.InvalidHandle; bool gotRef = false; @@ -268,11 +268,11 @@ internal static SecurityStatus SafeDecryptMessage( RuntimeHelpers.PrepareConstrainedRegions(); try { - handle.DangerousAddRef( ref gotRef ); + handle.DangerousAddRef(ref gotRef); } - catch( Exception ) + catch (Exception) { - if( gotRef ) + if (gotRef) { handle.DangerousRelease(); gotRef = false; @@ -282,7 +282,7 @@ internal static SecurityStatus SafeDecryptMessage( } finally { - if( gotRef ) + if (gotRef) { status = ContextNativeMethods.DecryptMessage( ref handle.rawHandle, @@ -311,7 +311,7 @@ internal static SecurityStatus SafeMakeSignature( SafeContextHandle handle, int qualityOfProtection, SecureBufferAdapter adapter, - int sequenceNumber ) + int sequenceNumber) { bool gotRef = false; SecurityStatus status = SecurityStatus.InternalError; @@ -319,11 +319,11 @@ internal static SecurityStatus SafeMakeSignature( RuntimeHelpers.PrepareConstrainedRegions(); try { - handle.DangerousAddRef( ref gotRef ); + handle.DangerousAddRef(ref gotRef); } - catch ( Exception ) + catch (Exception) { - if ( gotRef ) + if (gotRef) { handle.DangerousRelease(); gotRef = false; @@ -333,7 +333,7 @@ internal static SecurityStatus SafeMakeSignature( } finally { - if ( gotRef ) + if (gotRef) { status = ContextNativeMethods.MakeSignature( ref handle.rawHandle, @@ -362,7 +362,7 @@ internal static SecurityStatus SafeVerifySignature( SafeContextHandle handle, int qualityOfProtection, SecureBufferAdapter adapter, - int sequenceNumber ) + int sequenceNumber) { bool gotRef = false; SecurityStatus status = SecurityStatus.InternalError; @@ -370,11 +370,11 @@ internal static SecurityStatus SafeVerifySignature( RuntimeHelpers.PrepareConstrainedRegions(); try { - handle.DangerousAddRef( ref gotRef ); + handle.DangerousAddRef(ref gotRef); } - catch ( Exception ) + catch (Exception) { - if ( gotRef ) + if (gotRef) { handle.DangerousRelease(); gotRef = false; @@ -384,7 +384,7 @@ internal static SecurityStatus SafeVerifySignature( } finally { - if ( gotRef ) + if (gotRef) { status = ContextNativeMethods.VerifySignature( ref handle.rawHandle, diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextQueries.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextQueries.cs index 5d08cfc84..9fbb35caf 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextQueries.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/ContextQueries.cs @@ -31,7 +31,7 @@ namespace Cassandra.DataStax.Auth.Sspi.Contexts /// /// Stores the result of a context query for the context's buffer sizes. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal struct SecPkgContext_Sizes { public int MaxToken; @@ -43,7 +43,7 @@ internal struct SecPkgContext_Sizes /// /// Stores the result of a context query for a string-valued context attribute. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal struct SecPkgContext_String { public IntPtr StringResult; diff --git a/src/Cassandra/DataStax/Auth/Sspi/Contexts/SafeContextHandle.cs b/src/Cassandra/DataStax/Auth/Sspi/Contexts/SafeContextHandle.cs index 5edea098d..44ffd54d6 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Contexts/SafeContextHandle.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Contexts/SafeContextHandle.cs @@ -32,7 +32,7 @@ namespace Cassandra.DataStax.Auth.Sspi.Contexts /// internal class SafeContextHandle : SafeSspiHandle { - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { SecurityStatus status = ContextNativeMethods.DeleteSecurityContext( diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/ClientCredential.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/ClientCredential.cs index da86260c1..bed40fa7e 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/ClientCredential.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/ClientCredential.cs @@ -34,8 +34,8 @@ internal class ClientCredential : CurrentCredential /// Initializes a new instance of the ClientCredential class. /// /// The security package to acquire the credential handle from. - public ClientCredential( string package ) - : base( package, CredentialUse.Outbound ) + public ClientCredential(string package) + : base(package, CredentialUse.Outbound) { } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/Credential.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/Credential.cs index 6a8a42cd4..3f5c90651 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/Credential.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/Credential.cs @@ -58,16 +58,16 @@ internal class Credential : IDisposable /// Initializes a new instance of the Credential class. /// /// The security package to acquire the credential from. - public Credential( string package ) + public Credential(string package) { this.disposed = false; this.securityPackage = package; this.expiry = DateTime.MinValue; - this.PackageInfo = PackageSupport.GetPackageCapabilities( this.SecurityPackage ); + this.PackageInfo = PackageSupport.GetPackageCapabilities(this.SecurityPackage); } - + /// /// Gets metadata for the security package associated with the credential. /// @@ -108,11 +108,11 @@ public string PrincipleName RuntimeHelpers.PrepareConstrainedRegions(); try { - this.safeCredHandle.DangerousAddRef( ref gotRef ); + this.safeCredHandle.DangerousAddRef(ref gotRef); } - catch( Exception ) + catch (Exception) { - if( gotRef == true ) + if (gotRef == true) { this.safeCredHandle.DangerousRelease(); gotRef = false; @@ -121,7 +121,7 @@ public string PrincipleName } finally { - if( gotRef ) + if (gotRef) { status = CredentialNativeMethods.QueryCredentialsAttribute_Name( ref this.safeCredHandle.rawHandle, @@ -131,23 +131,23 @@ ref carrier this.safeCredHandle.DangerousRelease(); - if( status == SecurityStatus.OK && carrier.Name != IntPtr.Zero ) + if (status == SecurityStatus.OK && carrier.Name != IntPtr.Zero) { try { - name = Marshal.PtrToStringUni( carrier.Name ); + name = Marshal.PtrToStringUni(carrier.Name); } finally { - NativeMethods.FreeContextBuffer( carrier.Name ); + NativeMethods.FreeContextBuffer(carrier.Name); } } } } - if( status.IsError() ) + if (status.IsError()) { - throw new SspiException( "Failed to query credential name", status ); + throw new SspiException("Failed to query credential name", status); } return name; @@ -169,7 +169,7 @@ public DateTime Expiry protected set { CheckLifecycle(); - + this.expiry = value; } } @@ -199,15 +199,15 @@ protected set /// public void Dispose() { - Dispose( true ); - GC.SuppressFinalize( this ); + Dispose(true); + GC.SuppressFinalize(this); } - protected virtual void Dispose( bool disposing ) + protected virtual void Dispose(bool disposing) { - if ( this.disposed == false ) + if (this.disposed == false) { - if ( disposing ) + if (disposing) { this.safeCredHandle.Dispose(); } @@ -218,9 +218,9 @@ protected virtual void Dispose( bool disposing ) private void CheckLifecycle() { - if( this.disposed ) + if (this.disposed) { - throw new ObjectDisposedException( "Credential" ); + throw new ObjectDisposedException("Credential"); } } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/CredentialNativeMethods.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/CredentialNativeMethods.cs index d12ab48c2..a02af853d 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/CredentialNativeMethods.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/CredentialNativeMethods.cs @@ -31,8 +31,8 @@ namespace Cassandra.DataStax.Auth.Sspi.Credentials { internal static class CredentialNativeMethods { - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail)] - [DllImport( "Secur32.dll", EntryPoint = "AcquireCredentialsHandle", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [DllImport("Secur32.dll", EntryPoint = "AcquireCredentialsHandle", CharSet = CharSet.Unicode)] internal static extern SecurityStatus AcquireCredentialsHandle( string principleName, string packageName, @@ -45,8 +45,8 @@ internal static extern SecurityStatus AcquireCredentialsHandle( ref TimeStamp expiry ); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "FreeCredentialsHandle", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "FreeCredentialsHandle", CharSet = CharSet.Unicode)] internal static extern SecurityStatus FreeCredentialsHandle( ref RawSspiHandle credentialHandle ); @@ -61,8 +61,8 @@ ref RawSspiHandle credentialHandle /// /// /// - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "QueryCredentialsAttributes", CharSet = CharSet.Unicode )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "QueryCredentialsAttributes", CharSet = CharSet.Unicode)] internal static extern SecurityStatus QueryCredentialsAttribute_Name( ref RawSspiHandle credentialHandle, CredentialQueryAttrib attributeName, diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/CurrentCredential.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/CurrentCredential.cs index e624d3cd0..a30aeb51e 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/CurrentCredential.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/CurrentCredential.cs @@ -40,13 +40,13 @@ internal class CurrentCredential : Credential /// from. /// The manner in which the credentials will be used - Inbound typically /// represents servers, outbound typically represent clients. - public CurrentCredential( string securityPackage, CredentialUse use ) : - base( securityPackage ) + public CurrentCredential(string securityPackage, CredentialUse use) : + base(securityPackage) { - Init( use ); + Init(use); } - private void Init( CredentialUse use ) + private void Init(CredentialUse use) { string packageName; TimeStamp rawExpiry = new TimeStamp(); @@ -78,9 +78,9 @@ ref rawExpiry ); } - if ( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to call AcquireCredentialHandle", status ); + throw new SspiException("Failed to call AcquireCredentialHandle", status); } this.Expiry = rawExpiry.ToDateTime(); diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/QueryNameSupport.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/QueryNameSupport.cs index a48748a02..fb55cec46 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/QueryNameSupport.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/QueryNameSupport.cs @@ -31,7 +31,7 @@ namespace Cassandra.DataStax.Auth.Sspi.Credentials /// /// Stores the result from a query of a credential's principle name. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal struct QueryNameAttribCarrier { /// diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/SafeCredentialHandle.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/SafeCredentialHandle.cs index 04ae1b184..08f11ded9 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/SafeCredentialHandle.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/SafeCredentialHandle.cs @@ -36,7 +36,7 @@ public SafeCredentialHandle() : base() { } - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { SecurityStatus status = CredentialNativeMethods.FreeCredentialsHandle( diff --git a/src/Cassandra/DataStax/Auth/Sspi/Credentials/ServerCredential.cs b/src/Cassandra/DataStax/Auth/Sspi/Credentials/ServerCredential.cs index 72ecd6e28..8ecaf9277 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/Credentials/ServerCredential.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/Credentials/ServerCredential.cs @@ -35,8 +35,8 @@ internal class ServerCredential : CurrentCredential /// the current thread's security context. /// /// The name of the security package to obtain credentials from. - public ServerCredential( string package ) - : base( package, CredentialUse.Inbound ) + public ServerCredential(string package) + : base(package, CredentialUse.Inbound) { } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/EnumMgr.cs b/src/Cassandra/DataStax/Auth/Sspi/EnumMgr.cs index b461682e9..27475769e 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/EnumMgr.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/EnumMgr.cs @@ -28,10 +28,10 @@ namespace Cassandra.DataStax.Auth.Sspi { - [AttributeUsage( AttributeTargets.Field )] + [AttributeUsage(AttributeTargets.Field)] internal class EnumStringAttribute : Attribute { - public EnumStringAttribute( string text ) + public EnumStringAttribute(string text) { this.Text = text; } @@ -41,18 +41,18 @@ public EnumStringAttribute( string text ) internal class EnumMgr { - public static string ToText( Enum value ) + public static string ToText(Enum value) { - FieldInfo field = value.GetType().GetField( value.ToString() ); + FieldInfo field = value.GetType().GetField(value.ToString()); if (field == null) { return null; } - EnumStringAttribute[] attribs = (EnumStringAttribute[])field.GetCustomAttributes( typeof( EnumStringAttribute ), false ); + EnumStringAttribute[] attribs = (EnumStringAttribute[])field.GetCustomAttributes(typeof(EnumStringAttribute), false); - if( attribs == null || attribs.Length == 0 ) + if (attribs == null || attribs.Length == 0) { return null; } @@ -62,26 +62,26 @@ public static string ToText( Enum value ) } } - public static T FromText( string text ) + public static T FromText(string text) { - FieldInfo[] fields = typeof( T ).GetFields(); + FieldInfo[] fields = typeof(T).GetFields(); EnumStringAttribute[] attribs; - foreach( FieldInfo field in fields ) + foreach (FieldInfo field in fields) { - attribs = (EnumStringAttribute[])field.GetCustomAttributes( typeof( EnumStringAttribute ), false ); + attribs = (EnumStringAttribute[])field.GetCustomAttributes(typeof(EnumStringAttribute), false); - foreach( EnumStringAttribute attrib in attribs ) + foreach (EnumStringAttribute attrib in attribs) { - if( attrib.Text == text ) + if (attrib.Text == text) { - return (T)field.GetValue( null ); + return (T)field.GetValue(null); } } } - throw new ArgumentException( "Could not find a matching enumeration value for the text '" + text + "'." ); + throw new ArgumentException("Could not find a matching enumeration value for the text '" + text + "'."); } } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/NativeMethods.cs b/src/Cassandra/DataStax/Auth/Sspi/NativeMethods.cs index 31f2343d9..9ce593f29 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/NativeMethods.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/NativeMethods.cs @@ -31,18 +31,18 @@ namespace Cassandra.DataStax.Auth.Sspi { internal static class NativeMethods { - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)] - [DllImport( "Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus FreeContextBuffer( IntPtr buffer ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus FreeContextBuffer(IntPtr buffer); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "QuerySecurityPackageInfo", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus QuerySecurityPackageInfo( string packageName, ref IntPtr pkgInfo ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "QuerySecurityPackageInfo", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus QuerySecurityPackageInfo(string packageName, ref IntPtr pkgInfo); - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] - [DllImport( "Secur32.dll", EntryPoint = "EnumerateSecurityPackages", CharSet = CharSet.Unicode )] - internal static extern SecurityStatus EnumerateSecurityPackages( ref int numPackages, ref IntPtr pkgInfoArry ); + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + [DllImport("Secur32.dll", EntryPoint = "EnumerateSecurityPackages", CharSet = CharSet.Unicode)] + internal static extern SecurityStatus EnumerateSecurityPackages(ref int numPackages, ref IntPtr pkgInfoArry); } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/PackageSupport.cs b/src/Cassandra/DataStax/Auth/Sspi/PackageSupport.cs index a2d8bef5b..8aa9dfbe3 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/PackageSupport.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/PackageSupport.cs @@ -39,13 +39,13 @@ internal static class PackageSupport /// /// The name of the package. /// - public static SecPkgInfo GetPackageCapabilities( string packageName ) + public static SecPkgInfo GetPackageCapabilities(string packageName) { SecPkgInfo info; SecurityStatus status = SecurityStatus.InternalError; IntPtr rawInfoPtr; - + rawInfoPtr = new IntPtr(); info = new SecPkgInfo(); @@ -54,28 +54,28 @@ public static SecPkgInfo GetPackageCapabilities( string packageName ) { } finally { - status = NativeMethods.QuerySecurityPackageInfo( packageName, ref rawInfoPtr ); + status = NativeMethods.QuerySecurityPackageInfo(packageName, ref rawInfoPtr); - if ( rawInfoPtr != IntPtr.Zero ) + if (rawInfoPtr != IntPtr.Zero) { try { - if ( status == SecurityStatus.OK ) + if (status == SecurityStatus.OK) { // This performs allocations as it makes room for the strings contained in the SecPkgInfo class. - Marshal.PtrToStructure( rawInfoPtr, info ); + Marshal.PtrToStructure(rawInfoPtr, info); } } finally { - NativeMethods.FreeContextBuffer( rawInfoPtr ); + NativeMethods.FreeContextBuffer(rawInfoPtr); } } } - if( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to query security package provider details", status ); + throw new SspiException("Failed to query security package provider details", status); } return info; @@ -92,7 +92,7 @@ public static SecPkgInfo[] EnumeratePackages() IntPtr pkgArrayPtr; IntPtr pkgPtr; int numPackages = 0; - int pkgSize = Marshal.SizeOf( typeof(SecPkgInfo) ); + int pkgSize = Marshal.SizeOf(typeof(SecPkgInfo)); pkgArrayPtr = new IntPtr(); @@ -100,13 +100,13 @@ public static SecPkgInfo[] EnumeratePackages() try { } finally { - status = NativeMethods.EnumerateSecurityPackages( ref numPackages, ref pkgArrayPtr ); + status = NativeMethods.EnumerateSecurityPackages(ref numPackages, ref pkgArrayPtr); - if( pkgArrayPtr != IntPtr.Zero ) + if (pkgArrayPtr != IntPtr.Zero) { try { - if( status == SecurityStatus.OK ) + if (status == SecurityStatus.OK) { // Bwooop Bwooop Alocation Alert // 1) We allocate the array @@ -116,29 +116,29 @@ public static SecPkgInfo[] EnumeratePackages() packages = new SecPkgInfo[numPackages]; - for( int i = 0; i < numPackages; i++ ) + for (int i = 0; i < numPackages; i++) { packages[i] = new SecPkgInfo(); } - - for( int i = 0; i < numPackages; i++ ) + + for (int i = 0; i < numPackages; i++) { - pkgPtr = IntPtr.Add( pkgArrayPtr, i * pkgSize ); + pkgPtr = IntPtr.Add(pkgArrayPtr, i * pkgSize); - Marshal.PtrToStructure( pkgPtr, packages[i] ); + Marshal.PtrToStructure(pkgPtr, packages[i]); } } } finally { - NativeMethods.FreeContextBuffer( pkgArrayPtr ); + NativeMethods.FreeContextBuffer(pkgArrayPtr); } } } - if( status != SecurityStatus.OK ) + if (status != SecurityStatus.OK) { - throw new SspiException( "Failed to enumerate security package providers", status ); + throw new SspiException("Failed to enumerate security package providers", status); } return packages; diff --git a/src/Cassandra/DataStax/Auth/Sspi/SecPkgInfo.cs b/src/Cassandra/DataStax/Auth/Sspi/SecPkgInfo.cs index bbf0b41cb..af4054d88 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/SecPkgInfo.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/SecPkgInfo.cs @@ -31,7 +31,7 @@ namespace Cassandra.DataStax.Auth.Sspi /// /// Stores information about a particular security package. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal class SecPkgInfo { /// @@ -57,13 +57,13 @@ internal class SecPkgInfo /// /// The human-readable name of the package. /// - [MarshalAs( UnmanagedType.LPWStr )] + [MarshalAs(UnmanagedType.LPWStr)] public string Name; /// /// A short description of the package. /// - [MarshalAs( UnmanagedType.LPWStr )] + [MarshalAs(UnmanagedType.LPWStr)] public string Comment; } @@ -71,52 +71,52 @@ internal class SecPkgInfo /// Describes the capabilities of a security package. /// [Flags] - internal enum SecPkgCapability : uint + internal enum SecPkgCapability : uint { /// /// Whether the package supports generating messages with integrity information. Required for MakeSignature and VerifySignature. /// - Integrity = 0x1, + Integrity = 0x1, /// /// Whether the package supports generating encrypted messages. Required for EncryptMessage and DecryptMessage. /// - Privacy = 0x2, + Privacy = 0x2, /// /// Whether the package uses any other buffer information than token buffers. /// - TokenOnly = 0x4, + TokenOnly = 0x4, /// /// Whether the package supports datagram-style authentication. /// - Datagram = 0x8, + Datagram = 0x8, /// /// Whether the package supports creating contexts with connection semantics /// - Connection = 0x10, + Connection = 0x10, /// /// Multiple legs are neccessary for authentication. /// - MultiLeg = 0x20, + MultiLeg = 0x20, /// /// Server authentication is not supported. /// - ClientOnly = 0x40, + ClientOnly = 0x40, /// /// Supports extended error handling facilities. /// - ExtendedError = 0x80, + ExtendedError = 0x80, /// /// Supports client impersonation on the server. /// - Impersonation = 0x100, + Impersonation = 0x100, /// /// Understands Windows princple and target names. @@ -126,42 +126,42 @@ internal enum SecPkgCapability : uint /// /// Supports stream semantics /// - Stream = 0x400, + Stream = 0x400, /// /// Package may be used by the Negiotiate meta-package. /// - Negotiable = 0x800, + Negotiable = 0x800, /// /// Compatible with GSS. /// - GssCompatible = 0x1000, + GssCompatible = 0x1000, /// /// Supports LsaLogonUser /// - Logon = 0x2000, + Logon = 0x2000, /// /// Token buffers are in Ascii format. /// - AsciiBuffers = 0x4000, + AsciiBuffers = 0x4000, /// /// Supports separating large tokens into multiple buffers. /// - Fragment = 0x8000, + Fragment = 0x8000, /// /// Supports mutual authentication between a client and server. /// - MutualAuth = 0x10000, + MutualAuth = 0x10000, /// /// Supports credential delegation from the server to a third context. /// - Delegation = 0x20000, + Delegation = 0x20000, /// /// Supports calling EncryptMessage with the read-only-checksum flag, which protects data only @@ -178,11 +178,11 @@ internal enum SecPkgCapability : uint /// /// Extends the negotiate package; only one such package may be registered at any time. /// - ExtendsNego = 0x00100000, + ExtendsNego = 0x00100000, /// /// This package is negotiated by the package of type ExtendsNego. /// - Negotiable2 = 0x00200000, + Negotiable2 = 0x00200000, } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/SecurityStatus.cs b/src/Cassandra/DataStax/Auth/Sspi/SecurityStatus.cs index 2ddfd79c2..5bdf567a9 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/SecurityStatus.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/SecurityStatus.cs @@ -49,100 +49,100 @@ internal enum SecurityStatus : uint /// /// The request completed successfully /// - [EnumString( "No error" )] - OK = 0x00000000, - + [EnumString("No error")] + OK = 0x00000000, + /// /// The token returned by the context needs to be provided to the cooperating party /// to continue construction of the context. /// - [EnumString( "Authentication cycle needs to continue" )] + [EnumString("Authentication cycle needs to continue")] ContinueNeeded = 0x00090312, /// /// Occurs after a client calls InitializeSecurityContext to indicate that the client /// must call CompleteAuthToken. /// - [EnumString( "Authentication cycle needs to perform a 'complete'." )] - CompleteNeeded = 0x00090313, + [EnumString("Authentication cycle needs to perform a 'complete'.")] + CompleteNeeded = 0x00090313, /// /// Occurs after a client calls InitializeSecurityContext to indicate that the client /// must call CompleteAuthToken and pass the result to the server. /// - [EnumString( "Authentication cycle needs to perform a 'complete' and then continue." )] + [EnumString("Authentication cycle needs to perform a 'complete' and then continue.")] CompAndContinue = 0x00090314, /// /// An attempt to use the context was performed after the context's expiration time elapsed. /// - [EnumString( "The security context was used after its expiration time passed." )] + [EnumString("The security context was used after its expiration time passed.")] ContextExpired = 0x00090317, - [EnumString( "The credentials supplied to the security context were not fully initialized." )] + [EnumString("The credentials supplied to the security context were not fully initialized.")] CredentialsNeeded = 0x00090320, - [EnumString( "The context data must be re-negotiated with the peer" )] - Renegotiate = 0x00090321, + [EnumString("The context data must be re-negotiated with the peer")] + Renegotiate = 0x00090321, // Errors - [EnumString( "Not enough memory.")] - OutOfMemory = 0x80090300, + [EnumString("Not enough memory.")] + OutOfMemory = 0x80090300, + + [EnumString("The handle provided to the API was invalid.")] + InvalidHandle = 0x80090301, - [EnumString( "The handle provided to the API was invalid.")] - InvalidHandle = 0x80090301, + [EnumString("The attempted operation is not supported")] + Unsupported = 0x80090302, - [EnumString( "The attempted operation is not supported")] - Unsupported = 0x80090302, + [EnumString("The specified principle is not known in the authentication system.")] + TargetUnknown = 0x80090303, - [EnumString( "The specified principle is not known in the authentication system.")] - TargetUnknown = 0x80090303, - - [EnumString( "An internal error occurred" )] - InternalError = 0x80090304, + [EnumString("An internal error occurred")] + InternalError = 0x80090304, /// /// No security provider package was found with the given name. /// - [EnumString( "The requested security package was not found.")] - PackageNotFound = 0x80090305, + [EnumString("The requested security package was not found.")] + PackageNotFound = 0x80090305, - NotOwner = 0x80090306, - CannotInstall = 0x80090307, + NotOwner = 0x80090306, + CannotInstall = 0x80090307, /// /// A token was provided that contained incorrect or corrupted data. /// [EnumString("The provided authentication token is invalid or corrupted.")] - InvalidToken = 0x80090308, - - CannotPack = 0x80090309, - QopNotSupported = 0x8009030A, + InvalidToken = 0x80090308, + + CannotPack = 0x80090309, + QopNotSupported = 0x8009030A, /// /// Impersonation is not supported. /// [EnumString("Impersonation is not supported with the current security package.")] - NoImpersonation = 0x8009030B, + NoImpersonation = 0x8009030B, [EnumString("The logon was denied, perhaps because the provided credentials were incorrect.")] - LogonDenied = 0x8009030C, + LogonDenied = 0x8009030C, - [EnumString( "The credentials provided are not recognized by the selected security package.")] - UnknownCredentials = 0x8009030D, + [EnumString("The credentials provided are not recognized by the selected security package.")] + UnknownCredentials = 0x8009030D, - [EnumString( "No credentials are available in the selected security package.")] - NoCredentials = 0x8009030E, + [EnumString("No credentials are available in the selected security package.")] + NoCredentials = 0x8009030E, - [EnumString( "A message that was provided to the Decrypt or VerifySignature functions was altered " + + [EnumString("A message that was provided to the Decrypt or VerifySignature functions was altered " + "after it was created.")] - MessageAltered = 0x8009030F, + MessageAltered = 0x8009030F, - [EnumString( "A message was received out of the expected order.")] - OutOfSequence = 0x80090310, + [EnumString("A message was received out of the expected order.")] + OutOfSequence = 0x80090310, - [EnumString( "The current security package cannot contact an authenticating authority.")] + [EnumString("The current security package cannot contact an authenticating authority.")] NoAuthenticatingAuthority = 0x80090311, /// @@ -156,20 +156,20 @@ internal enum SecurityStatus : uint /// will indicate success, but will save off the extra, unrelated data in a buffer of /// type 'extra'. /// - IncompleteMessage = 0x80090318, + IncompleteMessage = 0x80090318, IncompleteCredentials = 0x80090320, - BufferNotEnough = 0x80090321, - WrongPrincipal = 0x80090322, - TimeSkew = 0x80090324, - UntrustedRoot = 0x80090325, - IllegalMessage = 0x80090326, - CertUnknown = 0x80090327, - CertExpired = 0x80090328, - AlgorithmMismatch = 0x80090331, - SecurityQosFailed = 0x80090332, + BufferNotEnough = 0x80090321, + WrongPrincipal = 0x80090322, + TimeSkew = 0x80090324, + UntrustedRoot = 0x80090325, + IllegalMessage = 0x80090326, + CertUnknown = 0x80090327, + CertExpired = 0x80090328, + AlgorithmMismatch = 0x80090331, + SecurityQosFailed = 0x80090332, SmartcardLogonRequired = 0x8009033E, - UnsupportedPreauth = 0x80090343, - BadBinding = 0x80090346 + UnsupportedPreauth = 0x80090343, + BadBinding = 0x80090346 } /// @@ -182,7 +182,7 @@ internal static class SecurityStatusExtensions /// /// /// True if the status represents an error condition. - public static bool IsError( this SecurityStatus status ) + public static bool IsError(this SecurityStatus status) { return (uint)status > 0x80000000u; } diff --git a/src/Cassandra/DataStax/Auth/Sspi/SspiException.cs b/src/Cassandra/DataStax/Auth/Sspi/SspiException.cs index 02528717a..69f05cab9 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/SspiException.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/SspiException.cs @@ -44,7 +44,7 @@ public class SspiException : Exception /// /// A message explaining what part of the system failed. /// The error code observed during the failure. - internal SspiException( string message, SecurityStatus errorCode ) + internal SspiException(string message, SecurityStatus errorCode) { this.message = message; this.errorCode = errorCode; @@ -53,22 +53,22 @@ internal SspiException( string message, SecurityStatus errorCode ) /// /// Creates a new instance of . /// - public SspiException(string message, int errorCode) : this(message, (SecurityStatus) errorCode) + public SspiException(string message, int errorCode) : this(message, (SecurityStatus)errorCode) { - + } - + #if NET452 /// /// Initializes a new instance of the SSPIException class from serialization data. /// /// /// - protected SspiException( SerializationInfo info, StreamingContext context ) - : base( info, context ) + protected SspiException(SerializationInfo info, StreamingContext context) + : base(info, context) { - this.message = info.GetString( "messsage" ); - this.errorCode = (SecurityStatus)info.GetUInt32( "errorCode" ); + this.message = info.GetString("messsage"); + this.errorCode = (SecurityStatus)info.GetUInt32("errorCode"); } /// @@ -76,12 +76,12 @@ protected SspiException( SerializationInfo info, StreamingContext context ) /// /// /// - public override void GetObjectData( SerializationInfo info, StreamingContext context ) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { - base.GetObjectData( info, context ); + base.GetObjectData(info, context); - info.AddValue( "message", this.message ); - info.AddValue( "errorCode", this.errorCode ); + info.AddValue("message", this.message); + info.AddValue("errorCode", this.errorCode); } #endif @@ -92,7 +92,7 @@ public int ErrorCode { get { - return (int) this.errorCode; + return (int)this.errorCode; } } @@ -103,11 +103,11 @@ public override string Message { get { - return string.Format( - "{0}. Error Code = '0x{1:X}' - \"{2}\".", - this.message, - this.errorCode, - EnumMgr.ToText(this.errorCode) + return string.Format( + "{0}. Error Code = '0x{1:X}' - \"{2}\".", + this.message, + this.errorCode, + EnumMgr.ToText(this.errorCode) ); } } diff --git a/src/Cassandra/DataStax/Auth/Sspi/SspiHandle.cs b/src/Cassandra/DataStax/Auth/Sspi/SspiHandle.cs index 6b44269ab..04c077cb5 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/SspiHandle.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/SspiHandle.cs @@ -44,7 +44,7 @@ namespace Cassandra.DataStax.Auth.Sspi /// to this handle for performing work (InitializeSecurityContext, eg) should be performed a CER /// that employs handle reference counting across the native API invocation. /// - [StructLayout( LayoutKind.Sequential, Pack = 1 ) ] + [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct RawSspiHandle { private IntPtr lowPart; @@ -65,7 +65,7 @@ public bool IsZero() /// /// This method is executed in a CER during handle release. /// - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void SetInvalid() { this.lowPart = IntPtr.Zero; @@ -81,17 +81,17 @@ internal abstract class SafeSspiHandle : SafeHandle internal RawSspiHandle rawHandle; protected SafeSspiHandle() - : base( IntPtr.Zero, true ) + : base(IntPtr.Zero, true) { this.rawHandle = new RawSspiHandle(); } public override bool IsInvalid { - get { return IsClosed || this.rawHandle.IsZero(); } + get { return IsClosed || this.rawHandle.IsZero(); } } - [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { this.rawHandle.SetInvalid(); diff --git a/src/Cassandra/DataStax/Auth/Sspi/TimeStamp.cs b/src/Cassandra/DataStax/Auth/Sspi/TimeStamp.cs index 792be05d2..990609f8c 100644 --- a/src/Cassandra/DataStax/Auth/Sspi/TimeStamp.cs +++ b/src/Cassandra/DataStax/Auth/Sspi/TimeStamp.cs @@ -32,10 +32,10 @@ namespace Cassandra.DataStax.Auth.Sspi /// Represents a Windows API Timestamp structure, which stores time in units of 100 nanosecond /// ticks, counting from January 1st, year 1601 at 00:00 UTC. Time is stored as a 64-bit value. /// - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] internal struct TimeStamp { - public static readonly DateTime Epoch = new DateTime( 1601, 1, 1, 0, 0, 0, DateTimeKind.Utc ); + public static readonly DateTime Epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// /// Stores the time value. Infinite times are often represented as values near, but not exactly @@ -56,13 +56,13 @@ public DateTime ToDateTime() // somewhere in the year 30848. This would overflow DateTime, since it peaks at 31-Dec-9999. // It turns out that this value corresponds to a TimeStamp's maximum value, reduced by my local timezone // http://stackoverflow.com/questions/24478056/ - if ( test > (ulong)DateTime.MaxValue.Ticks ) + if (test > (ulong)DateTime.MaxValue.Ticks) { return DateTime.MaxValue; } else { - return DateTime.FromFileTimeUtc( this.time ); + return DateTime.FromFileTimeUtc(this.time); } } } diff --git a/src/Cassandra/DataStax/Auth/SspiClient.cs b/src/Cassandra/DataStax/Auth/SspiClient.cs index bb097ffbc..253d2fa62 100644 --- a/src/Cassandra/DataStax/Auth/SspiClient.cs +++ b/src/Cassandra/DataStax/Auth/SspiClient.cs @@ -113,7 +113,7 @@ public void Dispose() var credentials = _credentials; if (credentials != null) { - credentials.Dispose(); + credentials.Dispose(); } } } diff --git a/src/Cassandra/DataStax/Cloud/CloudConfiguration.cs b/src/Cassandra/DataStax/Cloud/CloudConfiguration.cs index fea434eb0..b3889649c 100644 --- a/src/Cassandra/DataStax/Cloud/CloudConfiguration.cs +++ b/src/Cassandra/DataStax/Cloud/CloudConfiguration.cs @@ -29,7 +29,7 @@ internal class CloudConfiguration : IEquatable [JsonProperty("port")] public int Port { get; private set; } - + [JsonProperty("pfxCertPassword")] public string CertificatePassword { get; private set; } diff --git a/src/Cassandra/DataStax/Cloud/CloudConfigurationParser.cs b/src/Cassandra/DataStax/Cloud/CloudConfigurationParser.cs index e46c65bd6..3f1950ae7 100644 --- a/src/Cassandra/DataStax/Cloud/CloudConfigurationParser.cs +++ b/src/Cassandra/DataStax/Cloud/CloudConfigurationParser.cs @@ -39,7 +39,7 @@ public CloudConfiguration ParseConfig(Stream stream) return cloudConfiguration; } - + private void ValidateConfiguration(CloudConfiguration config) { if (config == null) @@ -56,7 +56,7 @@ private void ValidateConfiguration(CloudConfiguration config) { throw new ArgumentException("Could not parse the \"host\" property from the config file."); } - + if (string.IsNullOrEmpty(config.CertificatePassword)) { CloudConfigurationParser.Logger.Warning("Could not parse the \"pfxCertPassword\" property from the config file."); diff --git a/src/Cassandra/DataStax/Cloud/CloudMetadataService.cs b/src/Cassandra/DataStax/Cloud/CloudMetadataService.cs index b39df894d..610ebe899 100644 --- a/src/Cassandra/DataStax/Cloud/CloudMetadataService.cs +++ b/src/Cassandra/DataStax/Cloud/CloudMetadataService.cs @@ -69,10 +69,10 @@ private async Task GetWithWebRequestAsync( try { - using (var response = (HttpWebResponse) await request.GetResponseAsync().ConfigureAwait(false)) + using (var response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false)) { var responseString = await new StreamReader(response.GetResponseStream()).ReadToEndAsync().ConfigureAwait(false); - if ((int) response.StatusCode < 200 || (int) response.StatusCode >= 300) + if ((int)response.StatusCode < 200 || (int)response.StatusCode >= 300) { throw GetServiceRequestException(false, url, null, (int)response.StatusCode); } @@ -104,17 +104,17 @@ private SecurityProtocolType ConvertSslProtocolEnum(SslProtocols protocol) { securityProtocolType |= SecurityProtocolType.Ssl3; } - + if ((protocol & SslProtocols.Tls) != 0) { securityProtocolType |= SecurityProtocolType.Tls; } - + if ((protocol & SslProtocols.Tls11) != 0) { securityProtocolType |= SecurityProtocolType.Tls11; } - + if ((protocol & SslProtocols.Tls12) != 0) { securityProtocolType |= SecurityProtocolType.Tls12; diff --git a/src/Cassandra/DataStax/Cloud/ContactInfo.cs b/src/Cassandra/DataStax/Cloud/ContactInfo.cs index cf0762348..dd1d8e422 100644 --- a/src/Cassandra/DataStax/Cloud/ContactInfo.cs +++ b/src/Cassandra/DataStax/Cloud/ContactInfo.cs @@ -31,7 +31,7 @@ internal class ContactInfo [JsonRequired] [JsonProperty("contact_points")] public List ContactPoints { get; set; } - + [JsonRequired] [JsonProperty("sni_proxy_address")] public string SniProxyAddress { get; set; } diff --git a/src/Cassandra/DataStax/Cloud/CustomCACertificateValidator.cs b/src/Cassandra/DataStax/Cloud/CustomCACertificateValidator.cs index 30d816720..216196188 100644 --- a/src/Cassandra/DataStax/Cloud/CustomCACertificateValidator.cs +++ b/src/Cassandra/DataStax/Cloud/CustomCACertificateValidator.cs @@ -149,7 +149,7 @@ public bool Validate(X509Certificate cert, X509Chain chain, SslPolicyErrors erro // clone CA object because on Mono it gets reset for some reason after using it to build a new chain var clonedCa = new X509Certificate2(_trustedRootCertificateAuthority); chain.ChainPolicy.ExtraStore.Add(clonedCa); - + GetOrCreateCert2(ref cert2, cert); if (!chain.Build(cert2)) { diff --git a/src/Cassandra/DataStax/Graph/Edge.cs b/src/Cassandra/DataStax/Graph/Edge.cs index f93fd9899..d60cf93ba 100644 --- a/src/Cassandra/DataStax/Graph/Edge.cs +++ b/src/Cassandra/DataStax/Graph/Edge.cs @@ -50,7 +50,7 @@ public class Edge : Element, IEdge /// /// Creates a new instance of . /// - public Edge(GraphNode id, string label, IDictionary properties, + public Edge(GraphNode id, string label, IDictionary properties, GraphNode inV, string inVLabel, GraphNode outV, string outVLabel) : base(id, label, properties) { diff --git a/src/Cassandra/DataStax/Graph/Element.cs b/src/Cassandra/DataStax/Graph/Element.cs index 0d09ddc5a..07a76d5e1 100644 --- a/src/Cassandra/DataStax/Graph/Element.cs +++ b/src/Cassandra/DataStax/Graph/Element.cs @@ -34,7 +34,7 @@ public override bool Equals(object obj) if (object.ReferenceEquals(null, obj)) return false; if (object.ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; - return Equals((IElement) obj); + return Equals((IElement)obj); } public override int GetHashCode() @@ -72,8 +72,8 @@ protected Element(GraphNode id, string label, IDictionary pro /// Gets the properties /// [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Naming", - "CA1721:Property names should not match get methods", + "Naming", + "CA1721:Property names should not match get methods", Justification = "Public API")] public IDictionary Properties { get; } diff --git a/src/Cassandra/DataStax/Graph/EnumWrapper.cs b/src/Cassandra/DataStax/Graph/EnumWrapper.cs index 51d6f1acb..605c206a8 100644 --- a/src/Cassandra/DataStax/Graph/EnumWrapper.cs +++ b/src/Cassandra/DataStax/Graph/EnumWrapper.cs @@ -65,7 +65,7 @@ public override bool Equals(object obj) if (object.ReferenceEquals(null, obj)) return false; if (object.ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((EnumWrapper) obj); + return Equals((EnumWrapper)obj); } /// diff --git a/src/Cassandra/DataStax/Graph/FluentGraphStatement.cs b/src/Cassandra/DataStax/Graph/FluentGraphStatement.cs index 7aa3e08b1..9295a6d47 100644 --- a/src/Cassandra/DataStax/Graph/FluentGraphStatement.cs +++ b/src/Cassandra/DataStax/Graph/FluentGraphStatement.cs @@ -26,8 +26,8 @@ namespace Cassandra.DataStax.Graph public class FluentGraphStatement : GraphStatement { private FluentGraphStatement( - object queryBytecode, - IReadOnlyDictionary> customSerializers, + object queryBytecode, + IReadOnlyDictionary> customSerializers, IReadOnlyDictionary> customDeserializers, bool deserializeGraphNodes) { @@ -36,18 +36,18 @@ private FluentGraphStatement( CustomSerializers = customSerializers; CustomDeserializers = customDeserializers; } - + public FluentGraphStatement( - object queryBytecode, - IReadOnlyDictionary> customSerializers, + object queryBytecode, + IReadOnlyDictionary> customSerializers, IReadOnlyDictionary> customDeserializers) : this(queryBytecode, customSerializers, customDeserializers, false) { } - + public FluentGraphStatement( object queryBytecode, - IReadOnlyDictionary> customSerializers) + IReadOnlyDictionary> customSerializers) : this(queryBytecode, customSerializers, null, true) { } @@ -56,11 +56,11 @@ public FluentGraphStatement( /// Bytecode of the query represented by this statement. /// public object QueryBytecode { get; } - + internal bool DeserializeGraphNodes { get; } internal IReadOnlyDictionary> CustomSerializers { get; } - + internal IReadOnlyDictionary> CustomDeserializers { get; } internal override IStatement GetIStatement(GraphOptions options) diff --git a/src/Cassandra/DataStax/Graph/GraphNode.cs b/src/Cassandra/DataStax/Graph/GraphNode.cs index 03d62d489..8f3cee541 100644 --- a/src/Cassandra/DataStax/Graph/GraphNode.cs +++ b/src/Cassandra/DataStax/Graph/GraphNode.cs @@ -51,7 +51,7 @@ public class GraphNode : DynamicObject, IEquatable, IGraphNode, ISeri /// Returns true if the underlying value is a scalar value (string, double, boolean, ...). /// public bool IsScalar => _node.IsScalar; - + /// /// Returns the GraphSON type (@type property). Returns null if there isn't one. /// @@ -237,8 +237,8 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) public T To() { var type = typeof(T); - if ((type == typeof(object) && _node.DeserializeGraphNodes) - || type == typeof(GraphNode) + if ((type == typeof(object) && _node.DeserializeGraphNodes) + || type == typeof(GraphNode) || type == typeof(IGraphNode)) { return (T)(object)this; @@ -258,8 +258,8 @@ public object To(Type type) { throw new ArgumentNullException(nameof(type)); } - if ((type == typeof(object) && _node.DeserializeGraphNodes) - || type == typeof(GraphNode) + if ((type == typeof(object) && _node.DeserializeGraphNodes) + || type == typeof(GraphNode) || type == typeof(IGraphNode)) { return this; diff --git a/src/Cassandra/DataStax/Graph/GraphOptions.cs b/src/Cassandra/DataStax/Graph/GraphOptions.cs index 75ba11a1a..d15f87d6b 100644 --- a/src/Cassandra/DataStax/Graph/GraphOptions.cs +++ b/src/Cassandra/DataStax/Graph/GraphOptions.cs @@ -34,13 +34,13 @@ public class GraphOptions /// Default value for graph language. /// public const string DefaultLanguage = GraphOptions.GremlinGroovy; - + /// /// Default value for graph language. /// internal const string BytecodeJson = "bytecode-json"; - + internal const string GremlinGroovy = "gremlin-groovy"; /// @@ -115,7 +115,7 @@ public ConsistencyLevel? ReadConsistencyLevel { return null; } - return (ConsistencyLevel) value; + return (ConsistencyLevel)value; } } @@ -156,7 +156,7 @@ public string Source /// /// /// - public GraphProtocol? GraphProtocolVersion => (GraphProtocol?) _nullableGraphProtocol; + public GraphProtocol? GraphProtocolVersion => (GraphProtocol?)_nullableGraphProtocol; /// /// Gets the consistency level used for read queries @@ -307,7 +307,7 @@ internal IDictionary BuildPayload(IGraphStatement statement) { //The user has not used the graph settings at statement level //Or is a system query but there isn't a name defined at GraphOptions level - return _defaultPayload; + return _defaultPayload; } } var payload = new Dictionary(); @@ -384,7 +384,7 @@ private void RebuildDefaultPayload() if (GraphProtocolVersion != null) { payload.Add( - PayloadKey.Results, + PayloadKey.Results, GraphOptions.ToUtf8Buffer(GraphProtocolVersion.Value.GetInternalRepresentation())); } _defaultPayload = payload; @@ -408,7 +408,7 @@ private static byte[] ToUtf8Buffer(string value) private static byte[] ToBuffer(long value) { var serializer = Serialization.TypeSerializer.PrimitiveLongSerializer; - return serializer.Serialize((ushort) Cluster.MaxProtocolVersion, value); + return serializer.Serialize((ushort)Cluster.MaxProtocolVersion, value); } } } diff --git a/src/Cassandra/DataStax/Graph/IGraphStatement.cs b/src/Cassandra/DataStax/Graph/IGraphStatement.cs index 3d330b42d..5dae5e225 100644 --- a/src/Cassandra/DataStax/Graph/IGraphStatement.cs +++ b/src/Cassandra/DataStax/Graph/IGraphStatement.cs @@ -38,7 +38,7 @@ public interface IGraphStatement /// Gets the graph name to use with this statement. /// string GraphName { get; } - + /// /// Gets the graph protocol version to use with this statement. See . /// diff --git a/src/Cassandra/DataStax/Graph/IPath.cs b/src/Cassandra/DataStax/Graph/IPath.cs index ca66f3543..f9becdb6e 100644 --- a/src/Cassandra/DataStax/Graph/IPath.cs +++ b/src/Cassandra/DataStax/Graph/IPath.cs @@ -27,7 +27,7 @@ public interface IPath /// Gets the sets of labels of the steps traversed by this path, or an empty list, if this path is empty. /// ICollection> Labels { get; } - + /// /// Gets the objects traversed by this path, or an empty list, if this path is empty. /// diff --git a/src/Cassandra/DataStax/Graph/IProperty.cs b/src/Cassandra/DataStax/Graph/IProperty.cs index 7507274de..d63d927d8 100644 --- a/src/Cassandra/DataStax/Graph/IProperty.cs +++ b/src/Cassandra/DataStax/Graph/IProperty.cs @@ -27,7 +27,7 @@ public interface IProperty : IEquatable /// Gets the property name. /// string Name { get; } - + /// /// Gets the property value. /// diff --git a/src/Cassandra/DataStax/Graph/Path.cs b/src/Cassandra/DataStax/Graph/Path.cs index f76f3a50a..c083da754 100644 --- a/src/Cassandra/DataStax/Graph/Path.cs +++ b/src/Cassandra/DataStax/Graph/Path.cs @@ -33,7 +33,7 @@ public class Path : IPath /// public ICollection Objects { get; protected set; } - ICollection IPath.Objects => (ICollection) Objects; + ICollection IPath.Objects => (ICollection)Objects; /// /// Creates a new instance of . diff --git a/src/Cassandra/DataStax/Graph/Property.cs b/src/Cassandra/DataStax/Graph/Property.cs index d4db4c35a..4b6f1b358 100644 --- a/src/Cassandra/DataStax/Graph/Property.cs +++ b/src/Cassandra/DataStax/Graph/Property.cs @@ -35,19 +35,19 @@ internal Property(string name, IGraphNode value, IGraphNode element) protected bool Equals(Property other) { - return string.Equals(Name, other.Name) - && object.Equals(Value, other.Value) + return string.Equals(Name, other.Name) + && object.Equals(Value, other.Value) && object.Equals(Element, other.Element); } public bool Equals(IProperty other) { - return Equals((object) other); + return Equals((object)other); } - + public bool Equals(IPropertyWithElement other) { - return Equals((object) other); + return Equals((object)other); } public override bool Equals(object obj) @@ -64,7 +64,7 @@ public override bool Equals(object obj) { return false; } - return Equals((Property) obj); + return Equals((Property)obj); } public override int GetHashCode() diff --git a/src/Cassandra/DataStax/Graph/SimpleGraphStatement.cs b/src/Cassandra/DataStax/Graph/SimpleGraphStatement.cs index acaed267b..1a89d217f 100644 --- a/src/Cassandra/DataStax/Graph/SimpleGraphStatement.cs +++ b/src/Cassandra/DataStax/Graph/SimpleGraphStatement.cs @@ -50,7 +50,7 @@ public class SimpleGraphStatement : GraphStatement /// The graph query string. public SimpleGraphStatement(string query) : this(query, null) { - + } /// diff --git a/src/Cassandra/DataStax/Graph/Traverser.cs b/src/Cassandra/DataStax/Graph/Traverser.cs index 274c196f4..89648a2fa 100644 --- a/src/Cassandra/DataStax/Graph/Traverser.cs +++ b/src/Cassandra/DataStax/Graph/Traverser.cs @@ -63,7 +63,7 @@ public override bool Equals(object obj) if (object.ReferenceEquals(null, obj)) return false; if (object.ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; - return Equals((Traverser) obj); + return Equals((Traverser)obj); } /// diff --git a/src/Cassandra/DataStax/Graph/Vertex.cs b/src/Cassandra/DataStax/Graph/Vertex.cs index 22abc7100..e6b3b154d 100644 --- a/src/Cassandra/DataStax/Graph/Vertex.cs +++ b/src/Cassandra/DataStax/Graph/Vertex.cs @@ -28,7 +28,7 @@ public class Vertex : Element, IVertex /// /// Creates a new instance. /// - public Vertex(GraphNode id, string label, IDictionary properties) + public Vertex(GraphNode id, string label, IDictionary properties) : base(id, label, properties) { if (properties == null) @@ -51,25 +51,25 @@ public Vertex(GraphNode id, string label, IDictionary propert { return GetProperties(name).FirstOrDefault(); } - + IProperty IElement.GetProperty(string name) { return GetProperty(name); } - + /// /// Gets the properties of this element that has the given name. /// /// The name of the property [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Naming", - "CA1721:Property names should not match get methods", + "Naming", + "CA1721:Property names should not match get methods", Justification = "Public API")] public IEnumerable GetProperties(string name) { if (!Properties.TryGetValue(name, out var result)) { - return Enumerable.Empty(); + return Enumerable.Empty(); } if (!result.IsArray) { @@ -77,13 +77,13 @@ public IEnumerable GetProperties(string name) } return result.ToArray().Select(item => item.To()); } - + /// /// Gets the properties of this element. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Naming", - "CA1721:Property names should not match get methods", + "Naming", + "CA1721:Property names should not match get methods", Justification = "Public API")] public new IEnumerable GetProperties() { diff --git a/src/Cassandra/DataStax/Graph/VertexProperty.cs b/src/Cassandra/DataStax/Graph/VertexProperty.cs index 73318ac46..1de7cd776 100644 --- a/src/Cassandra/DataStax/Graph/VertexProperty.cs +++ b/src/Cassandra/DataStax/Graph/VertexProperty.cs @@ -24,10 +24,10 @@ namespace Cassandra.DataStax.Graph internal class VertexProperty : Element, IVertexProperty { internal VertexProperty( - GraphNode id, - string name, - IGraphNode value, - IGraphNode vertex, + GraphNode id, + string name, + IGraphNode value, + IGraphNode vertex, IDictionary properties) : base(id, name, properties) { @@ -44,20 +44,20 @@ internal VertexProperty( public bool Equals(IProperty other) { - return Equals((object) other); + return Equals((object)other); } protected bool Equals(VertexProperty other) { - return string.Equals(Name, other.Name) - && object.Equals(Value, other.Value) + return string.Equals(Name, other.Name) + && object.Equals(Value, other.Value) && object.Equals(Vertex, other.Vertex) && string.Equals(Label, other.Label); } public bool Equals(IVertexProperty other) { - return Equals((object) other); + return Equals((object)other); } public override bool Equals(object obj) @@ -74,7 +74,7 @@ public override bool Equals(object obj) { return false; } - return Equals((VertexProperty) obj); + return Equals((VertexProperty)obj); } public override int GetHashCode() diff --git a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ConfigAntiPatternsInfoProvider.cs b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ConfigAntiPatternsInfoProvider.cs index dd2b75af8..ab195ac21 100644 --- a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ConfigAntiPatternsInfoProvider.cs +++ b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ConfigAntiPatternsInfoProvider.cs @@ -27,8 +27,8 @@ static ConfigAntiPatternsInfoProvider() { ConfigAntiPatternsInfoProvider.AntiPatternsProviders = new Dictionary, Dictionary>> { - { - typeof(DCAwareRoundRobinPolicy), + { + typeof(DCAwareRoundRobinPolicy), (obj, antiPatterns) => { var typedPolicy = (DCAwareRoundRobinPolicy) obj; @@ -52,16 +52,16 @@ static ConfigAntiPatternsInfoProvider() return antiPatterns; } }, - { - typeof(DefaultLoadBalancingPolicy), + { + typeof(DefaultLoadBalancingPolicy), (obj, antiPatterns) => { var typedPolicy = (DefaultLoadBalancingPolicy) obj; return ConfigAntiPatternsInfoProvider.AddAntiPatterns(typedPolicy.ChildPolicy, antiPatterns); } }, - { - typeof(RetryLoadBalancingPolicy), + { + typeof(RetryLoadBalancingPolicy), (obj, antiPatterns) => { var typedPolicy = (RetryLoadBalancingPolicy) obj; @@ -69,8 +69,8 @@ static ConfigAntiPatternsInfoProvider() return ConfigAntiPatternsInfoProvider.AddAntiPatterns(typedPolicy.LoadBalancingPolicy, antiPatterns); } }, - { - typeof(TokenAwarePolicy), + { + typeof(TokenAwarePolicy), (obj, antiPatterns) => { var typedPolicy = (TokenAwarePolicy) obj; @@ -121,7 +121,7 @@ public Dictionary GetInformation(IInternalCluster cluster, IInte var contactPointsHosts = cluster .AllHosts() - .Where(host => (host.ContactPoint != null && resolvedContactPoints.ContainsKey(host.ContactPoint)) + .Where(host => (host.ContactPoint != null && resolvedContactPoints.ContainsKey(host.ContactPoint)) || contactPointsEndPoints.Contains(host.Address)) .ToList(); @@ -141,8 +141,8 @@ public Dictionary GetInformation(IInternalCluster cluster, IInte private static Dictionary AddAntiPatterns(object obj, Dictionary antiPatterns) { - return ConfigAntiPatternsInfoProvider.AntiPatternsProviders.TryGetValue(obj.GetType(), out var provider) - ? provider.Invoke(obj, antiPatterns) + return ConfigAntiPatternsInfoProvider.AntiPatternsProviders.TryGetValue(obj.GetType(), out var provider) + ? provider.Invoke(obj, antiPatterns) : antiPatterns; } } diff --git a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/DataCentersInfoProvider.cs b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/DataCentersInfoProvider.cs index 577cc84c4..72fa5cdf0 100644 --- a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/DataCentersInfoProvider.cs +++ b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/DataCentersInfoProvider.cs @@ -30,7 +30,7 @@ public HashSet GetInformation(IInternalCluster cluster, IInternalSession .GetOrCreatePoolingOptions(cluster.Metadata.ControlConnection.ProtocolVersion) .GetCoreConnectionsPerHost(HostDistance.Remote); - foreach (var h in cluster.AllHosts()) + foreach (var h in cluster.AllHosts()) { if (h.Datacenter == null) { diff --git a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ExecutionProfileInfoProvider.cs b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ExecutionProfileInfoProvider.cs index ad69bb0c0..b9cc7ae57 100644 --- a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ExecutionProfileInfoProvider.cs +++ b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ExecutionProfileInfoProvider.cs @@ -37,7 +37,7 @@ public ExecutionProfileInfoProvider( _speculativeExecutionPolicyInfoProvider = speculativeExecutionPolicyInfoProvider; _retryPolicyInfoProvider = retryPolicyInfoProvider; } - + public Dictionary GetInformation(IInternalCluster cluster, IInternalSession session) { // add default first so that it is on top diff --git a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ReconnectionPolicyInfoProvider.cs b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ReconnectionPolicyInfoProvider.cs index 888fd30b4..a0ae680df 100644 --- a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ReconnectionPolicyInfoProvider.cs +++ b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/ReconnectionPolicyInfoProvider.cs @@ -27,24 +27,24 @@ static ReconnectionPolicyInfoProvider() { ReconnectionPolicyInfoProvider.PolicyOptionsProviders = new Dictionary>> { - { - typeof(ConstantReconnectionPolicy), + { + typeof(ConstantReconnectionPolicy), policy => { var typedPolicy = (ConstantReconnectionPolicy) policy; return new Dictionary {{ "constantDelayMs", typedPolicy.ConstantDelayMs }}; } }, - { - typeof(ExponentialReconnectionPolicy), + { + typeof(ExponentialReconnectionPolicy), policy => { var typedPolicy = (ExponentialReconnectionPolicy) policy; return new Dictionary {{ "baseDelayMs", typedPolicy.BaseDelayMs }, { "maxDelayMs", typedPolicy.MaxDelayMs }}; } }, - { - typeof(FixedReconnectionPolicy), + { + typeof(FixedReconnectionPolicy), policy => { var typedPolicy = (FixedReconnectionPolicy) policy; diff --git a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/RetryPolicyInfoProvider.cs b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/RetryPolicyInfoProvider.cs index ff7e1abeb..c9cc178aa 100644 --- a/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/RetryPolicyInfoProvider.cs +++ b/src/Cassandra/DataStax/Insights/InfoProviders/StartupMessage/RetryPolicyInfoProvider.cs @@ -64,7 +64,7 @@ private static PolicyInfo GetRetryPolicyInfo(IRetryPolicy policy) if (retryPolicyType == typeof(RetryPolicyExtensions.WrappedExtendedRetryPolicy)) { - var typedPolicy = (RetryPolicyExtensions.WrappedExtendedRetryPolicy) policy; + var typedPolicy = (RetryPolicyExtensions.WrappedExtendedRetryPolicy)policy; return RetryPolicyInfoProvider.GetRetryPolicyInfo(typedPolicy.Policy); } diff --git a/src/Cassandra/DataStax/Insights/InsightsClient.cs b/src/Cassandra/DataStax/Insights/InsightsClient.cs index b2343614b..7122b6ad5 100644 --- a/src/Cassandra/DataStax/Insights/InsightsClient.cs +++ b/src/Cassandra/DataStax/Insights/InsightsClient.cs @@ -69,7 +69,7 @@ private async Task SendStartupMessageAsync() } catch (Exception ex) { - if (_cancellationTokenSource.IsCancellationRequested || + if (_cancellationTokenSource.IsCancellationRequested || _errorCount >= InsightsClient.ErrorCountThresholdForLogging) { return false; @@ -91,7 +91,7 @@ private async Task SendStatusMessageAsync() } catch (Exception ex) { - if (_cancellationTokenSource.IsCancellationRequested || + if (_cancellationTokenSource.IsCancellationRequested || _errorCount >= InsightsClient.ErrorCountThresholdForLogging) { return false; @@ -146,9 +146,9 @@ private async Task MainLoopAsync() // The initial delay should contain some random portion // Initial delay should be statusEventDelay - (0 to 10%) var percentageToSubtract = new Random(Guid.NewGuid().GetHashCode()).NextDouble() * 0.1; - var delay = _monitorReportingOptions.StatusEventDelayMilliseconds - + var delay = _monitorReportingOptions.StatusEventDelayMilliseconds - (_monitorReportingOptions.StatusEventDelayMilliseconds * percentageToSubtract); - + while (!_cancellationTokenSource.IsCancellationRequested) { if (!startupSent) @@ -159,7 +159,7 @@ private async Task MainLoopAsync() { await SendStatusMessageAsync().ConfigureAwait(false); } - + await TaskHelper.DelayWithCancellation( TimeSpan.FromMilliseconds(delay), _cancellationTokenSource.Token).ConfigureAwait(false); @@ -191,9 +191,9 @@ private async Task SendJsonMessageAsync(T message) null, null); - var response = await RunWithTokenAsync(() => + var response = await RunWithTokenAsync(() => _cluster.Metadata.ControlConnection.UnsafeSendQueryRequestAsync( - InsightsClient.ReportInsightRpc, + InsightsClient.ReportInsightRpc, queryProtocolOptions)).ConfigureAwait(false); if (response == null) diff --git a/src/Cassandra/DataStax/Insights/InsightsSupportVerifier.cs b/src/Cassandra/DataStax/Insights/InsightsSupportVerifier.cs index f60bb72c3..78f6dd31f 100644 --- a/src/Cassandra/DataStax/Insights/InsightsSupportVerifier.cs +++ b/src/Cassandra/DataStax/Insights/InsightsSupportVerifier.cs @@ -31,7 +31,7 @@ public bool SupportsInsights(IInternalCluster cluster) var allHosts = cluster.AllHosts(); return allHosts.Count != 0 && allHosts.All(h => DseVersionSupportsInsights(h.DseVersion)); } - + public bool DseVersionSupportsInsights(Version dseVersion) { if (dseVersion == null) diff --git a/src/Cassandra/DataStax/Insights/MessageFactories/InsightsMetadataTimestampGenerator.cs b/src/Cassandra/DataStax/Insights/MessageFactories/InsightsMetadataTimestampGenerator.cs index 48ed87075..3823a1cee 100644 --- a/src/Cassandra/DataStax/Insights/MessageFactories/InsightsMetadataTimestampGenerator.cs +++ b/src/Cassandra/DataStax/Insights/MessageFactories/InsightsMetadataTimestampGenerator.cs @@ -25,7 +25,7 @@ internal class InsightsMetadataTimestampGenerator : IInsightsMetadataTimestampGe public long GenerateTimestamp() { var t = DateTimeOffset.UtcNow - InsightsMetadataTimestampGenerator.UnixEpoch; - return (long) t.TotalMilliseconds; + return (long)t.TotalMilliseconds; } } } \ No newline at end of file diff --git a/src/Cassandra/DataStax/Insights/MessageFactories/InsightsStartupMessageFactory.cs b/src/Cassandra/DataStax/Insights/MessageFactories/InsightsStartupMessageFactory.cs index 05944b4d4..631078749 100644 --- a/src/Cassandra/DataStax/Insights/MessageFactories/InsightsStartupMessageFactory.cs +++ b/src/Cassandra/DataStax/Insights/MessageFactories/InsightsStartupMessageFactory.cs @@ -26,7 +26,7 @@ internal class InsightsStartupMessageFactory : IInsightsMessageFactory CreateMessage(IInternalCluster cluster, IInt ApplicationName = cluster.Configuration.ApplicationName, ApplicationVersion = cluster.Configuration.ApplicationVersion, ApplicationNameWasGenerated = cluster.Configuration.ApplicationNameWasGenerated, - ContactPoints = + ContactPoints = cluster.Metadata.ResolvedContactPoints.ToDictionary( kvp => kvp.Key.StringRepresentation, kvp => kvp.Value.Select(ipEndPoint => ipEndPoint.GetHostIpEndPointWithFallback().ToString()).ToList()), DataCenters = _infoProviders.DataCentersInfoProvider.GetInformation(cluster, session), @@ -61,7 +61,7 @@ public Insight CreateMessage(IInternalCluster cluster, IInt ProtocolVersion = (byte)cluster.Metadata.ControlConnection.ProtocolVersion, ExecutionProfiles = _infoProviders.ExecutionProfileInfoProvider.GetInformation(cluster, session), PoolSizeByHostDistance = _infoProviders.PoolSizeByHostDistanceInfoProvider.GetInformation(cluster, session), - HeartbeatInterval = + HeartbeatInterval = cluster .Configuration .GetOrCreatePoolingOptions(cluster.Metadata.ControlConnection.ProtocolVersion) diff --git a/src/Cassandra/DataStax/Insights/Schema/Converters/CompressionTypeInsightsConverter.cs b/src/Cassandra/DataStax/Insights/Schema/Converters/CompressionTypeInsightsConverter.cs index 294e71729..24ad4f9cf 100644 --- a/src/Cassandra/DataStax/Insights/Schema/Converters/CompressionTypeInsightsConverter.cs +++ b/src/Cassandra/DataStax/Insights/Schema/Converters/CompressionTypeInsightsConverter.cs @@ -27,7 +27,7 @@ internal class CompressionTypeInsightsConverter : InsightsEnumConverter EnumToJsonValueMap => CompressionTypeInsightsConverter.CompressionTypeStringMap; } diff --git a/src/Cassandra/DataStax/Insights/Schema/Converters/ConsistencyInsightsConverter.cs b/src/Cassandra/DataStax/Insights/Schema/Converters/ConsistencyInsightsConverter.cs index ace42ee35..c6131ef45 100644 --- a/src/Cassandra/DataStax/Insights/Schema/Converters/ConsistencyInsightsConverter.cs +++ b/src/Cassandra/DataStax/Insights/Schema/Converters/ConsistencyInsightsConverter.cs @@ -36,7 +36,7 @@ internal class ConsistencyInsightsConverter : InsightsEnumConverter EnumToJsonValueMap => + protected override IReadOnlyDictionary EnumToJsonValueMap => ConsistencyInsightsConverter.ConsistencyLevelStringMap; } } \ No newline at end of file diff --git a/src/Cassandra/DataStax/Insights/Schema/Converters/InsightTypeInsightsConverter.cs b/src/Cassandra/DataStax/Insights/Schema/Converters/InsightTypeInsightsConverter.cs index b9a1e4ace..36e1372fc 100644 --- a/src/Cassandra/DataStax/Insights/Schema/Converters/InsightTypeInsightsConverter.cs +++ b/src/Cassandra/DataStax/Insights/Schema/Converters/InsightTypeInsightsConverter.cs @@ -26,7 +26,7 @@ internal class InsightTypeInsightsConverter : InsightsEnumConverter EnumToJsonValueMap => + protected override IReadOnlyDictionary EnumToJsonValueMap => InsightTypeInsightsConverter.InsightTypeStringMap; } } \ No newline at end of file diff --git a/src/Cassandra/DataStax/Insights/Schema/Converters/InsightsEnumConverter.cs b/src/Cassandra/DataStax/Insights/Schema/Converters/InsightsEnumConverter.cs index 434651fb7..2b1991b45 100644 --- a/src/Cassandra/DataStax/Insights/Schema/Converters/InsightsEnumConverter.cs +++ b/src/Cassandra/DataStax/Insights/Schema/Converters/InsightsEnumConverter.cs @@ -43,7 +43,7 @@ public bool TryConvert(TEnumType value, out TJsonType output) if (!EnumToJsonValueMap.TryGetValue(value, out output)) { InsightsEnumConverter.Logger.Error( - $"Unrecognized value for type { InsightsEnumConverter.TypeString }."); + $"Unrecognized value for type {InsightsEnumConverter.TypeString}."); return false; } @@ -65,11 +65,11 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s var enumValue = (TEnumType)value; if (!TryConvert(enumValue, out var enumValueJsonValue)) { - InsightsEnumConverter.Logger.Error($"Unrecognized value for type { InsightsEnumConverter.TypeString }."); + InsightsEnumConverter.Logger.Error($"Unrecognized value for type {InsightsEnumConverter.TypeString}."); writer.WriteNull(); return; } - + writer.WriteValue(enumValueJsonValue); } diff --git a/src/Cassandra/DataStax/Insights/Schema/Insight.cs b/src/Cassandra/DataStax/Insights/Schema/Insight.cs index d6a980e04..e65cd7e80 100644 --- a/src/Cassandra/DataStax/Insights/Schema/Insight.cs +++ b/src/Cassandra/DataStax/Insights/Schema/Insight.cs @@ -23,7 +23,7 @@ internal class Insight { [JsonProperty("metadata")] public InsightsMetadata Metadata; - + [JsonProperty("data")] public T Data; } diff --git a/src/Cassandra/DataStax/Insights/Schema/StartupMessage/ExecutionProfileInfo.cs b/src/Cassandra/DataStax/Insights/Schema/StartupMessage/ExecutionProfileInfo.cs index 07ef688db..7c785cfbc 100644 --- a/src/Cassandra/DataStax/Insights/Schema/StartupMessage/ExecutionProfileInfo.cs +++ b/src/Cassandra/DataStax/Insights/Schema/StartupMessage/ExecutionProfileInfo.cs @@ -25,7 +25,7 @@ internal class ExecutionProfileInfo { [JsonProperty("readTimeout")] public int? ReadTimeout { get; set; } - + [JsonProperty("retry")] public PolicyInfo Retry { get; set; } diff --git a/src/Cassandra/DataStax/Insights/Schema/StatusMessage/InsightsStatusData.cs b/src/Cassandra/DataStax/Insights/Schema/StatusMessage/InsightsStatusData.cs index 38447694e..ede1e92a9 100644 --- a/src/Cassandra/DataStax/Insights/Schema/StatusMessage/InsightsStatusData.cs +++ b/src/Cassandra/DataStax/Insights/Schema/StatusMessage/InsightsStatusData.cs @@ -27,7 +27,7 @@ internal class InsightsStatusData [JsonProperty("sessionId")] public string SessionId { get; set; } - + [JsonProperty("controlConnection")] public string ControlConnection { get; set; } diff --git a/src/Cassandra/DataStax/Search/DateRange.cs b/src/Cassandra/DataStax/Search/DateRange.cs index 4d9e7f3bc..09600ede1 100644 --- a/src/Cassandra/DataStax/Search/DateRange.cs +++ b/src/Cassandra/DataStax/Search/DateRange.cs @@ -100,7 +100,7 @@ public static DateRange Parse(string value) return new DateRange(DateRangeBound.Parse(value)); } return new DateRange( - DateRangeBound.Parse(match.Groups[1].Value), + DateRangeBound.Parse(match.Groups[1].Value), DateRangeBound.ParseUpperBound(match.Groups[2].Value)); } @@ -126,7 +126,7 @@ public override bool Equals(object obj) { return false; } - return Equals((DateRange) obj); + return Equals((DateRange)obj); } /// diff --git a/src/Cassandra/DataStax/Search/DateRangeBound.cs b/src/Cassandra/DataStax/Search/DateRangeBound.cs index b0bdf6d6e..b4eac1d64 100644 --- a/src/Cassandra/DataStax/Search/DateRangeBound.cs +++ b/src/Cassandra/DataStax/Search/DateRangeBound.cs @@ -77,7 +77,7 @@ public DateRangePrecision Precision /// /// Creates a new instance of . /// - public DateRangeBound(DateTimeOffset timestamp, DateRangePrecision precision) : + public DateRangeBound(DateTimeOffset timestamp, DateRangePrecision precision) : this(precision, timestamp.ToUniversalTime()) { } @@ -100,7 +100,7 @@ private DateRangeBound(DateRangePrecision precision, DateTimeOffset utcTimestamp _timestamp = utcTimestamp; _precision = precision; } - + /// /// Private constructor only intended for creating the unbounded instance /// @@ -109,7 +109,7 @@ private DateRangeBound(bool asUnbounded) { // Workaround: we can not declare a parameter-less constructor on a struct _timestamp = DateTimeOffset.MinValue; - _precision = (DateRangePrecision) byte.MaxValue; + _precision = (DateRangePrecision)byte.MaxValue; } /// @@ -127,9 +127,9 @@ public override bool Equals(object obj) { return false; } - return Equals((DateRangeBound) obj); + return Equals((DateRangeBound)obj); } - + /// public override int GetHashCode() { @@ -151,8 +151,8 @@ public override string ToString() { return "*"; } - return string.Format(DateRangeBound.FormatByPrecision[(int) Precision], - Timestamp.Year, Timestamp.Month, Timestamp.Day, + return string.Format(DateRangeBound.FormatByPrecision[(int)Precision], + Timestamp.Year, Timestamp.Month, Timestamp.Day, Timestamp.Hour, Timestamp.Minute, Timestamp.Second, Timestamp.Millisecond); } @@ -288,7 +288,7 @@ public void Set(int index, string value, string stringDate) private void Set(DateRangePrecision precision, int value) { - _values[(int) precision] = value; + _values[(int)precision] = value; } public DateRangeBound Build() @@ -304,7 +304,7 @@ public DateRangeBound Build() public DateRangeBound BuildUpperBound() { - var precision = (DateRangePrecision) _index; + var precision = (DateRangePrecision)_index; if (precision == DateRangePrecision.Year) { Set(DateRangePrecision.Month, 12); diff --git a/src/Cassandra/DataStax/Search/DateRangePrecision.cs b/src/Cassandra/DataStax/Search/DateRangePrecision.cs index 362c000b4..6be80f8c7 100644 --- a/src/Cassandra/DataStax/Search/DateRangePrecision.cs +++ b/src/Cassandra/DataStax/Search/DateRangePrecision.cs @@ -25,27 +25,27 @@ public enum DateRangePrecision : byte /// Year precision. Any timestamp precision beyond the year portion will be ignored. /// Year = 0, - + /// /// Year precision. Any timestamp precision beyond the years portion will be ignored. /// Month = 1, - + /// /// Day precision. Any timestamp precision beyond the days portion will be ignored. /// Day = 2, - + /// /// Hour precision. Any timestamp precision beyond the hours portion will be ignored. /// Hour = 3, - + /// /// Minute precision. Any timestamp precision beyond the minutes portion will be ignored. /// Minute = 4, - + /// /// Second precision. Any timestamp precision beyond the seconds portion will be ignored. /// diff --git a/src/Cassandra/DecimalTypeAdapter.cs b/src/Cassandra/DecimalTypeAdapter.cs index fb2d8f3c4..1d8ed7610 100644 --- a/src/Cassandra/DecimalTypeAdapter.cs +++ b/src/Cassandra/DecimalTypeAdapter.cs @@ -25,7 +25,7 @@ public class DecimalTypeAdapter : ITypeAdapter { public Type GetDataType() { - return typeof (decimal); + return typeof(decimal); } public object ConvertFrom(byte[] decimalBuf) diff --git a/src/Cassandra/Duration.cs b/src/Cassandra/Duration.cs index 1d7f77a63..7bdf237ed 100644 --- a/src/Cassandra/Duration.cs +++ b/src/Cassandra/Duration.cs @@ -61,7 +61,7 @@ public struct Duration : IEquatable, IComparable /// Gets the number of days. /// public int Days { get; private set; } - + /// /// Gets the number of nanoseconds. /// @@ -97,7 +97,7 @@ public override bool Equals(object obj) { return false; } - return Equals((Duration) obj); + return Equals((Duration)obj); } /// @@ -148,11 +148,11 @@ public static Duration FromTimeSpan(TimeSpan timespan) long nanos; if (days != 0L) { - nanos = (ticks%TicksPerDay)*NanosPerTick; + nanos = (ticks % TicksPerDay) * NanosPerTick; } else { - nanos = ticks*NanosPerTick; + nanos = ticks * NanosPerTick; } return new Duration(0, days, nanos); } @@ -268,8 +268,8 @@ internal string ToJavaDurationString() // No leap seconds considered const long hoursPerDay = 24L; var nanos = Math.Abs(Nanoseconds); - var remainder = nanos%NanosPerHour; - long hours = Math.Abs(Days)*hoursPerDay + nanos/NanosPerHour; + var remainder = nanos % NanosPerHour; + long hours = Math.Abs(Days) * hoursPerDay + nanos / NanosPerHour; if (hours > 0L) { builder.Append(hours).Append("H"); @@ -289,7 +289,7 @@ private static long Append(StringBuilder builder, long dividend, long divisor, s { return dividend; } - builder.Append(dividend/divisor).Append(unit); + builder.Append(dividend / divisor).Append(unit); return dividend % divisor; } @@ -456,7 +456,7 @@ private class Builder null, "years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds","microseconds", "nanoseconds" }; - + public Builder(bool isNegative) { _isNegative = isNegative; @@ -605,7 +605,7 @@ private void ValidateOrder(int order) if (order < _index) { throw new FormatException( - string.Format("Invalid duration. The {0} should be after {1}", + string.Format("Invalid duration. The {0} should be after {1}", GetUnitName(_index), GetUnitName(order))); } _index = order; @@ -618,8 +618,8 @@ private string GetUnitName(int order) public Duration Build() { - return _isNegative ? - new Duration(-_months, -_days, -_nanoseconds) : + return _isNegative ? + new Duration(-_months, -_days, -_nanoseconds) : new Duration(_months, _days, _nanoseconds); } } diff --git a/src/Cassandra/DynamicCompositeTypeAdapter.cs b/src/Cassandra/DynamicCompositeTypeAdapter.cs index 52a10e955..076ba7c05 100644 --- a/src/Cassandra/DynamicCompositeTypeAdapter.cs +++ b/src/Cassandra/DynamicCompositeTypeAdapter.cs @@ -23,7 +23,7 @@ public class DynamicCompositeTypeAdapter : ITypeAdapter { public Type GetDataType() { - return typeof (byte[]); + return typeof(byte[]); } public object ConvertFrom(byte[] decimalBuf) @@ -34,7 +34,7 @@ public object ConvertFrom(byte[] decimalBuf) public byte[] ConvertTo(object value) { TypeSerializer.CheckArgument(value); - return (byte[]) value; + return (byte[])value; } } } \ No newline at end of file diff --git a/src/Cassandra/EndianBitConverter.cs b/src/Cassandra/EndianBitConverter.cs index 8e86e771d..38792e027 100644 --- a/src/Cassandra/EndianBitConverter.cs +++ b/src/Cassandra/EndianBitConverter.cs @@ -35,10 +35,10 @@ internal static void SetBytes(bool isLittleEndian, byte[] buffer, int offset, in buffer[offset + 3] = (byte)((value & 0xFF000000) >> 24); return; } - buffer[offset] = (byte) ((value & 0xFF000000) >> 24); - buffer[offset + 1] = (byte) ((value & 0xFF0000) >> 16); - buffer[offset + 2] = (byte) ((value & 0xFF00) >> 8); - buffer[offset + 3] = (byte) (value & 0xFF); + buffer[offset] = (byte)((value & 0xFF000000) >> 24); + buffer[offset + 1] = (byte)((value & 0xFF0000) >> 16); + buffer[offset + 2] = (byte)((value & 0xFF00) >> 8); + buffer[offset + 3] = (byte)(value & 0xFF); } /// @@ -66,14 +66,14 @@ internal static void SetBytes(bool isLittleEndian, byte[] buffer, int offset, lo buffer[offset + 7] = (byte)(((ulong)value & 0xFF00000000000000) >> 56); return; } - buffer[offset] = (byte) (((ulong) value & 0xFF00000000000000) >> 56); - buffer[offset + 1] = (byte) ((value & 0xFF000000000000) >> 48); - buffer[offset + 2] = (byte) ((value & 0xFF0000000000) >> 40); - buffer[offset + 3] = (byte) ((value & 0xFF00000000) >> 32); - buffer[offset + 4] = (byte) ((value & 0xFF000000) >> 24); - buffer[offset + 5] = (byte) ((value & 0xFF0000) >> 16); - buffer[offset + 6] = (byte) ((value & 0xFF00) >> 8); - buffer[offset + 7] = (byte) (value & 0xFF); + buffer[offset] = (byte)(((ulong)value & 0xFF00000000000000) >> 56); + buffer[offset + 1] = (byte)((value & 0xFF000000000000) >> 48); + buffer[offset + 2] = (byte)((value & 0xFF0000000000) >> 40); + buffer[offset + 3] = (byte)((value & 0xFF00000000) >> 32); + buffer[offset + 4] = (byte)((value & 0xFF000000) >> 24); + buffer[offset + 5] = (byte)((value & 0xFF0000) >> 16); + buffer[offset + 6] = (byte)((value & 0xFF00) >> 8); + buffer[offset + 7] = (byte)(value & 0xFF); } /// diff --git a/src/Cassandra/Exceptions/BusyPoolException.cs b/src/Cassandra/Exceptions/BusyPoolException.cs index 4bf798f4b..e4133cb35 100644 --- a/src/Cassandra/Exceptions/BusyPoolException.cs +++ b/src/Cassandra/Exceptions/BusyPoolException.cs @@ -50,13 +50,13 @@ public BusyPoolException(IPEndPoint address, int maxRequestsPerConnection, int c MaxRequestsPerConnection = maxRequestsPerConnection; ConnectionLength = connectionLength; } - + private static string GetMessage(IPEndPoint address, int maxRequestsPerConnection, int connectionLength) { return $"All connections to host {address} are busy, {maxRequestsPerConnection} requests " + $"are in-flight on {(connectionLength > 0 ? "each " : "")}{connectionLength} connection(s)"; } - + private static string GetMessage(IConnectionEndPoint endPoint, int maxRequestsPerConnection, int connectionLength) { return $"All connections to host {endPoint.EndpointFriendlyName} are busy, {maxRequestsPerConnection} requests " + diff --git a/src/Cassandra/Exceptions/DriverException.cs b/src/Cassandra/Exceptions/DriverException.cs index 4ccd3e4d6..ec0c598b5 100644 --- a/src/Cassandra/Exceptions/DriverException.cs +++ b/src/Cassandra/Exceptions/DriverException.cs @@ -34,11 +34,11 @@ public DriverException(string message, Exception innerException) : base(message, innerException) { } - + protected DriverException(SerializationInfo info, StreamingContext context) : base(info, context) { - + } } } diff --git a/src/Cassandra/Exceptions/DriverInternalError.cs b/src/Cassandra/Exceptions/DriverInternalError.cs index 5cf1d083a..7f4007b2d 100644 --- a/src/Cassandra/Exceptions/DriverInternalError.cs +++ b/src/Cassandra/Exceptions/DriverInternalError.cs @@ -23,8 +23,8 @@ namespace Cassandra /// indicates an unexpected behavior (either in the driver or in Cassandra). /// [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Naming", - "CA1710:Identifiers should have correct suffix", + "Naming", + "CA1710:Identifiers should have correct suffix", Justification = "Public API")] public class DriverInternalError : Exception { diff --git a/src/Cassandra/Exceptions/FunctionFailureException.cs b/src/Cassandra/Exceptions/FunctionFailureException.cs index d2a32e497..348d16e74 100644 --- a/src/Cassandra/Exceptions/FunctionFailureException.cs +++ b/src/Cassandra/Exceptions/FunctionFailureException.cs @@ -47,7 +47,7 @@ public FunctionFailureException(string message) : base(message) public FunctionFailureException(string message, Exception innerException) : base(message, innerException) { } - + protected FunctionFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/src/Cassandra/Exceptions/InitFatalErrorException.cs b/src/Cassandra/Exceptions/InitFatalErrorException.cs index c985d5dd3..141f1f86c 100644 --- a/src/Cassandra/Exceptions/InitFatalErrorException.cs +++ b/src/Cassandra/Exceptions/InitFatalErrorException.cs @@ -19,7 +19,7 @@ namespace Cassandra { public class InitFatalErrorException : Exception { - private const string ExceptionMessage = + private const string ExceptionMessage = "An error occured during the initialization of the cluster instance. Further initialization attempts " + "for this cluster instance will never succeed and will return this exception instead. The InnerException property holds " + "a reference to the exception that originally caused the initialization error."; diff --git a/src/Cassandra/Exceptions/NoHostAvailableException.cs b/src/Cassandra/Exceptions/NoHostAvailableException.cs index 933fff892..0b67d77bf 100644 --- a/src/Cassandra/Exceptions/NoHostAvailableException.cs +++ b/src/Cassandra/Exceptions/NoHostAvailableException.cs @@ -36,7 +36,7 @@ public class NoHostAvailableException : DriverException { private const string StartMessage = "All hosts tried for query failed (tried "; private const int MaxTriedInfo = 2; - + /// /// Gets the hosts tried along with descriptions of the error encountered while trying them. /// @@ -55,7 +55,7 @@ internal NoHostAvailableException(string message) : base(message) { Errors = new Dictionary(0); } - + /// /// Creates a new instance of NoHostAvailableException with a custom message, an empty error dictionary and an inner exception. /// @@ -63,11 +63,11 @@ internal NoHostAvailableException(string message, Exception innerException) : ba { Errors = new Dictionary(0); } - + protected NoHostAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { - + } private static string CreateMessage(Dictionary errors) @@ -82,7 +82,7 @@ private static string CreateMessage(Dictionary errors) { if (!first) { - builder.Append("; "); + builder.Append("; "); } builder.Append(kv.Key); if (kv.Value != null) @@ -91,7 +91,7 @@ private static string CreateMessage(Dictionary errors) builder.Append(kv.Value.GetType().Name); builder.Append(" '"); builder.Append(kv.Value.Message); - builder.Append("'"); + builder.Append("'"); } first = false; } diff --git a/src/Cassandra/Exceptions/PreparedQueryNotFoundException.cs b/src/Cassandra/Exceptions/PreparedQueryNotFoundException.cs index dd7ec4ed5..eef531f98 100644 --- a/src/Cassandra/Exceptions/PreparedQueryNotFoundException.cs +++ b/src/Cassandra/Exceptions/PreparedQueryNotFoundException.cs @@ -20,7 +20,7 @@ public class PreparedQueryNotFoundException : QueryValidationException { public byte[] UnknownId { get; private set; } - public PreparedQueryNotFoundException(string message, byte[] unknownId) + public PreparedQueryNotFoundException(string message, byte[] unknownId) : base(message) { UnknownId = unknownId; diff --git a/src/Cassandra/Exceptions/PreparedStatementIdMismatchException.cs b/src/Cassandra/Exceptions/PreparedStatementIdMismatchException.cs index bd2b85c2e..86f0eb751 100644 --- a/src/Cassandra/Exceptions/PreparedStatementIdMismatchException.cs +++ b/src/Cassandra/Exceptions/PreparedStatementIdMismatchException.cs @@ -30,12 +30,12 @@ namespace Cassandra /// public class PreparedStatementIdMismatchException : DriverException { - public PreparedStatementIdMismatchException(byte[] originalId, byte[] outputId) - : base("ID mismatch while trying to reprepare (expected " - + $"{BitConverter.ToString(originalId).Replace("-", "")}, " - + $"got {BitConverter.ToString(outputId).Replace("-", "")}). " - + "This prepared statement won't work anymore. " - + "This usually happens when you run a 'USE...' query after " + public PreparedStatementIdMismatchException(byte[] originalId, byte[] outputId) + : base("ID mismatch while trying to reprepare (expected " + + $"{BitConverter.ToString(originalId).Replace("-", "")}, " + + $"got {BitConverter.ToString(outputId).Replace("-", "")}). " + + "This prepared statement won't work anymore. " + + "This usually happens when you run a 'USE...' query after " + "the statement was prepared.") { Id = originalId; diff --git a/src/Cassandra/Exceptions/UnsupportedProtocolVersionException.cs b/src/Cassandra/Exceptions/UnsupportedProtocolVersionException.cs index ee4c05537..a671ad4fe 100644 --- a/src/Cassandra/Exceptions/UnsupportedProtocolVersionException.cs +++ b/src/Cassandra/Exceptions/UnsupportedProtocolVersionException.cs @@ -24,13 +24,13 @@ internal class UnsupportedProtocolVersionException : DriverException /// The version that was not supported by the server. /// public ProtocolVersion ProtocolVersion { get; } - + /// /// The version with which the server replied. /// public ProtocolVersion ResponseProtocolVersion { get; } - public UnsupportedProtocolVersionException(ProtocolVersion protocolVersion, ProtocolVersion responseProtocolVersion, Exception innerException) : + public UnsupportedProtocolVersionException(ProtocolVersion protocolVersion, ProtocolVersion responseProtocolVersion, Exception innerException) : base($"Protocol version {protocolVersion} not supported", innerException) { ProtocolVersion = protocolVersion; diff --git a/src/Cassandra/Exceptions/WriteFailureException.cs b/src/Cassandra/Exceptions/WriteFailureException.cs index 3f0d71483..b460e7bcc 100644 --- a/src/Cassandra/Exceptions/WriteFailureException.cs +++ b/src/Cassandra/Exceptions/WriteFailureException.cs @@ -88,7 +88,7 @@ public class WriteFailureException : QueryExecutionException /// Creates a new instance of . /// public WriteFailureException(ConsistencyLevel consistency, int received, int required, string writeType, - int failures) : base(string.Format(FailureMessage, + int failures) : base(string.Format(FailureMessage, consistency.ToString().ToUpperInvariant(), required, received, failures)) { ConsistencyLevel = consistency; diff --git a/src/Cassandra/Exceptions/WriteTimeoutException.cs b/src/Cassandra/Exceptions/WriteTimeoutException.cs index 5f5c8d32b..27a855cb9 100644 --- a/src/Cassandra/Exceptions/WriteTimeoutException.cs +++ b/src/Cassandra/Exceptions/WriteTimeoutException.cs @@ -23,12 +23,12 @@ public class WriteTimeoutException : QueryTimeoutException { private const string BatchLogMessage = "Server timeout during batchlog write at consistency {0}" + " ({1} peer(s) acknowledged the write over {2} required)"; - + private const string QueryMessage = "Server timeout during write query at consistency {0}" + " ({1} peer(s) acknowledged the write over {2} required)"; - + private const string BatchLogWriteType = "BATCH_LOG"; - + /// /// Gets the type of write operation that timed out. /// Possible values: SIMPLE, BATCH, BATCH_LOG, UNLOGGED_BATCH and COUNTER. diff --git a/src/Cassandra/ExecutionProfiles/ExecutionProfile.cs b/src/Cassandra/ExecutionProfiles/ExecutionProfile.cs index cce034ce4..a69e99459 100644 --- a/src/Cassandra/ExecutionProfiles/ExecutionProfile.cs +++ b/src/Cassandra/ExecutionProfiles/ExecutionProfile.cs @@ -22,20 +22,20 @@ namespace Cassandra.ExecutionProfiles internal class ExecutionProfile : IExecutionProfile { internal ExecutionProfile( - ConsistencyLevel? consistencyLevel, - ConsistencyLevel? serialConsistencyLevel, - int? readTimeoutMillis, - ILoadBalancingPolicy loadBalancingPolicy, - ISpeculativeExecutionPolicy speculativeExecutionPolicy, + ConsistencyLevel? consistencyLevel, + ConsistencyLevel? serialConsistencyLevel, + int? readTimeoutMillis, + ILoadBalancingPolicy loadBalancingPolicy, + ISpeculativeExecutionPolicy speculativeExecutionPolicy, IExtendedRetryPolicy retryPolicy, GraphOptions graphOptions) { Initialize( - consistencyLevel, - serialConsistencyLevel, - readTimeoutMillis, - loadBalancingPolicy, - speculativeExecutionPolicy, + consistencyLevel, + serialConsistencyLevel, + readTimeoutMillis, + loadBalancingPolicy, + speculativeExecutionPolicy, retryPolicy, graphOptions); } @@ -46,18 +46,18 @@ internal ExecutionProfile(IExecutionProfile baseProfile, IExecutionProfile profi { throw new ArgumentNullException(nameof(baseProfile)); } - + if (profile == null) { throw new ArgumentNullException(nameof(profile)); } - + Initialize( - profile.ConsistencyLevel ?? baseProfile.ConsistencyLevel, - profile.SerialConsistencyLevel ?? baseProfile.SerialConsistencyLevel, - profile.ReadTimeoutMillis ?? baseProfile.ReadTimeoutMillis, - profile.LoadBalancingPolicy ?? baseProfile.LoadBalancingPolicy, - profile.SpeculativeExecutionPolicy ?? baseProfile.SpeculativeExecutionPolicy, + profile.ConsistencyLevel ?? baseProfile.ConsistencyLevel, + profile.SerialConsistencyLevel ?? baseProfile.SerialConsistencyLevel, + profile.ReadTimeoutMillis ?? baseProfile.ReadTimeoutMillis, + profile.LoadBalancingPolicy ?? baseProfile.LoadBalancingPolicy, + profile.SpeculativeExecutionPolicy ?? baseProfile.SpeculativeExecutionPolicy, profile.RetryPolicy ?? baseProfile.RetryPolicy, profile.GraphOptions ?? baseProfile.GraphOptions); } @@ -70,11 +70,11 @@ internal ExecutionProfile(IRequestOptions requestOptions) } Initialize( - requestOptions.ConsistencyLevel, - requestOptions.SerialConsistencyLevel, - requestOptions.ReadTimeoutMillis, - requestOptions.LoadBalancingPolicy, - requestOptions.SpeculativeExecutionPolicy, + requestOptions.ConsistencyLevel, + requestOptions.SerialConsistencyLevel, + requestOptions.ReadTimeoutMillis, + requestOptions.LoadBalancingPolicy, + requestOptions.SpeculativeExecutionPolicy, requestOptions.RetryPolicy, requestOptions.GraphOptions); } diff --git a/src/Cassandra/ExecutionProfiles/ExecutionProfileBuilder.cs b/src/Cassandra/ExecutionProfiles/ExecutionProfileBuilder.cs index 8dad68d80..c76fd3b92 100644 --- a/src/Cassandra/ExecutionProfiles/ExecutionProfileBuilder.cs +++ b/src/Cassandra/ExecutionProfiles/ExecutionProfileBuilder.cs @@ -29,7 +29,7 @@ internal class ExecutionProfileBuilder : IExecutionProfileBuilder private IExtendedRetryPolicy _retryPolicy; private GraphOptions _graphOptions; - + public IExecutionProfileBuilder WithLoadBalancingPolicy(ILoadBalancingPolicy loadBalancingPolicy) { _loadBalancingPolicy = loadBalancingPolicy ?? throw new ArgumentNullException(nameof(loadBalancingPolicy)); @@ -53,13 +53,13 @@ public IExecutionProfileBuilder WithConsistencyLevel(ConsistencyLevel consistenc _consistencyLevel = consistencyLevel; return this; } - + public IExecutionProfileBuilder WithSerialConsistencyLevel(ConsistencyLevel serialConsistencyLevel) { _serialConsistencyLevel = serialConsistencyLevel; return this; } - + public IExecutionProfileBuilder WithReadTimeoutMillis(int readTimeoutMillis) { _readTimeoutMillis = readTimeoutMillis; diff --git a/src/Cassandra/ExecutionProfiles/ExecutionProfileOptions.cs b/src/Cassandra/ExecutionProfiles/ExecutionProfileOptions.cs index f0d30a889..54f62288e 100644 --- a/src/Cassandra/ExecutionProfiles/ExecutionProfileOptions.cs +++ b/src/Cassandra/ExecutionProfiles/ExecutionProfileOptions.cs @@ -29,7 +29,7 @@ public IExecutionProfileOptions WithProfile(string name, Action public IExecutionProfileOptions WithDerivedProfile(string name, string baseProfile, Action profileBuildAction) { @@ -42,7 +42,7 @@ private IExecutionProfileOptions WithProfile(string name, IExecutionProfile prof { throw new ArgumentNullException(nameof(name)); } - + if (_profiles.ContainsKey(name)) { throw new ArgumentException("There is already an execution profile with that name."); @@ -63,12 +63,12 @@ private IExecutionProfileOptions WithDerivedProfile(string name, string baseProf { throw new ArgumentException("There is already an execution profile with that name."); } - + if (profile == null) { throw new ArgumentNullException(nameof(profile)); } - + if (baseProfile == null) { throw new ArgumentNullException(nameof(baseProfile)); @@ -78,7 +78,7 @@ private IExecutionProfileOptions WithDerivedProfile(string name, string baseProf { throw new ArgumentException("The base Execution Profile must be added before the derived Execution Profile."); } - + _profiles[name] = new ExecutionProfile(baseProfileInstance, profile); return this; } diff --git a/src/Cassandra/ExecutionProfiles/IRequestOptions.cs b/src/Cassandra/ExecutionProfiles/IRequestOptions.cs index fb4ea7de4..9390e20a9 100644 --- a/src/Cassandra/ExecutionProfiles/IRequestOptions.cs +++ b/src/Cassandra/ExecutionProfiles/IRequestOptions.cs @@ -44,7 +44,7 @@ internal interface IRequestOptions bool DefaultIdempotence { get; } int QueryAbortTimeout { get; } - + /// /// Gets the serial consistency level of the statement or the default value from the query options. /// diff --git a/src/Cassandra/ExecutionProfiles/RequestOptions.cs b/src/Cassandra/ExecutionProfiles/RequestOptions.cs index 9bec75bc4..58ef95ea0 100644 --- a/src/Cassandra/ExecutionProfiles/RequestOptions.cs +++ b/src/Cassandra/ExecutionProfiles/RequestOptions.cs @@ -46,11 +46,11 @@ internal class RequestOptions : IRequestOptions /// Must not be null. /// Must not be null. public RequestOptions( - IExecutionProfile profile, - IExecutionProfile defaultProfile, - Policies policies, - SocketOptions socketOptions, - QueryOptions queryOptions, + IExecutionProfile profile, + IExecutionProfile defaultProfile, + Policies policies, + SocketOptions socketOptions, + QueryOptions queryOptions, ClientOptions clientOptions) { _profile = profile; @@ -59,7 +59,7 @@ public RequestOptions( _socketOptions = socketOptions ?? throw new ArgumentNullException(nameof(socketOptions)); _queryOptions = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions)); _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); - + if (profile?.LoadBalancingPolicy == null && policies.LoadBalancingPolicy == null) { throw new ArgumentNullException(nameof(policies.LoadBalancingPolicy)); @@ -69,13 +69,13 @@ public RequestOptions( { throw new ArgumentNullException(nameof(policies.SpeculativeExecutionPolicy)); } - + if (profile?.RetryPolicy == null && policies.RetryPolicy == null) { throw new ArgumentNullException(nameof(policies.ExtendedRetryPolicy)); } } - + /// /// Builds a request options object without any null settings. /// @@ -87,11 +87,11 @@ public RequestOptions( /// Must not be null. /// Must not be null. public RequestOptions( - IExecutionProfile profile, - IExecutionProfile defaultProfile, - Policies policies, - SocketOptions socketOptions, - QueryOptions queryOptions, + IExecutionProfile profile, + IExecutionProfile defaultProfile, + Policies policies, + SocketOptions socketOptions, + QueryOptions queryOptions, ClientOptions clientOptions, GraphOptions graphOptions) : this(profile, defaultProfile, policies, socketOptions, queryOptions, clientOptions) { @@ -138,7 +138,7 @@ public ConsistencyLevel GetSerialConsistencyLevelOrDefault(IStatement statement) return consistency; } - + /// /// Returns the timeout in milliseconds based on the amount of queries. /// @@ -154,7 +154,7 @@ public int GetQueryAbortTimeout(int amountOfQueries) return QueryAbortTimeout; } - return QueryAbortTimeout*amountOfQueries; + return QueryAbortTimeout * amountOfQueries; } } } \ No newline at end of file diff --git a/src/Cassandra/ExecutionProfiles/RequestOptionsMapper.cs b/src/Cassandra/ExecutionProfiles/RequestOptionsMapper.cs index b8e1e8687..b60d5684a 100644 --- a/src/Cassandra/ExecutionProfiles/RequestOptionsMapper.cs +++ b/src/Cassandra/ExecutionProfiles/RequestOptionsMapper.cs @@ -41,7 +41,7 @@ public IReadOnlyDictionary BuildRequestOptionsDictionar kvp => new RequestOptions(kvp.Value, defaultProfile, policies, socketOptions, queryOptions, clientOptions, graphOptions)); requestOptions.Add( - Configuration.DefaultExecutionProfileName, + Configuration.DefaultExecutionProfileName, new RequestOptions(null, defaultProfile, policies, socketOptions, queryOptions, clientOptions, graphOptions)); return requestOptions; } diff --git a/src/Cassandra/FrameHeader.cs b/src/Cassandra/FrameHeader.cs index ff7fbdd87..14b1a5ee1 100644 --- a/src/Cassandra/FrameHeader.cs +++ b/src/Cassandra/FrameHeader.cs @@ -20,7 +20,7 @@ namespace Cassandra { internal class FrameHeader { - public const int MaxFrameSize = 256*1024*1024; + public const int MaxFrameSize = 256 * 1024 * 1024; /// /// Protocol version byte (in case of responses 0x81, 0x82, ... in case of requests 0x01, 0x02) @@ -36,9 +36,9 @@ internal class FrameHeader /// Flags applying to this frame.. /// public HeaderFlags Flags { get; set; } - + public byte Opcode { get; set; } - + public short StreamId { get; set; } /// @@ -73,7 +73,7 @@ public static FrameHeader ParseResponseHeader(ProtocolVersion version, byte[] bu if (!version.Uses2BytesStreamIds()) { //Stream id is a signed byte in v1 and v2 of the protocol - header.StreamId = (sbyte)buffer[offset++]; + header.StreamId = (sbyte)buffer[offset++]; } else { diff --git a/src/Cassandra/FrameParser.cs b/src/Cassandra/FrameParser.cs index c2920a968..97b235971 100644 --- a/src/Cassandra/FrameParser.cs +++ b/src/Cassandra/FrameParser.cs @@ -29,7 +29,7 @@ internal class FrameParser /// /// A factory to get the response handlers /// - private static readonly Dictionary> _responseHandlerFactory = + private static readonly Dictionary> _responseHandlerFactory = new Dictionary> { {AuthenticateResponse.OpCode, AuthenticateResponse.Create}, diff --git a/src/Cassandra/FrameReader.cs b/src/Cassandra/FrameReader.cs index 953c70cfc..cea8231fa 100644 --- a/src/Cassandra/FrameReader.cs +++ b/src/Cassandra/FrameReader.cs @@ -149,7 +149,7 @@ public Dictionary ReadBytesMap() return null; } var map = new Dictionary(); - for (var i = 0; i < length; i++) + for (var i = 0; i < length; i++) { map[ReadString()] = ReadBytes(); } diff --git a/src/Cassandra/FrameWriter.cs b/src/Cassandra/FrameWriter.cs index 4458e9ae0..b5c0c19de 100644 --- a/src/Cassandra/FrameWriter.cs +++ b/src/Cassandra/FrameWriter.cs @@ -96,7 +96,7 @@ public void WriteLong(long value) public void WriteString(string str) { var bytes = Encoding.UTF8.GetBytes(str); - WriteUInt16((ushort) bytes.Length); + WriteUInt16((ushort)bytes.Length); Write(bytes); } @@ -115,7 +115,7 @@ public void WriteLongString(string str) /// public void WriteStringList(ICollection l) { - WriteUInt16((ushort) l.Count); + WriteUInt16((ushort)l.Count); foreach (var str in l) { WriteString(str); @@ -148,7 +148,7 @@ public void WriteAsBytes(object value) { WriteBytes(_serializer.Serialize(value)); } - + /// /// Serializes (and potentially encrypts) and writes as protocol bytes (length + bytes) /// @@ -162,7 +162,7 @@ public void WriteAndEncryptAsBytes(string defaultKs, RowSetMetadata metadata, in /// public void WriteShortBytes(byte[] buffer) { - WriteUInt16((ushort) buffer.Length); + WriteUInt16((ushort)buffer.Length); Write(buffer); } diff --git a/src/Cassandra/FunctionMetadata.cs b/src/Cassandra/FunctionMetadata.cs index 08509f983..726afbc1e 100644 --- a/src/Cassandra/FunctionMetadata.cs +++ b/src/Cassandra/FunctionMetadata.cs @@ -99,13 +99,13 @@ public class FunctionMetadata /// public FunctionMetadata() { - + } /// /// Creates a new instance of Function metadata. /// - public FunctionMetadata(string name, string keyspaceName, string[] signature, string[] argumentNames, ColumnDesc[] argumentTypes, + public FunctionMetadata(string name, string keyspaceName, string[] signature, string[] argumentNames, ColumnDesc[] argumentTypes, string body, bool calledOnNullInput, string language, ColumnDesc returnType) { Name = name; diff --git a/src/Cassandra/Geometry/Geometry.cs b/src/Cassandra/Geometry/Geometry.cs index 138108d11..8edc961c7 100644 --- a/src/Cassandra/Geometry/Geometry.cs +++ b/src/Cassandra/Geometry/Geometry.cs @@ -74,7 +74,7 @@ protected int CombineHashCode(IEnumerable items) var hash = 17; foreach (var item in items) { - hash = hash * 23 + item.GetHashCode(); + hash = hash * 23 + item.GetHashCode(); } return hash; } @@ -90,7 +90,7 @@ public virtual string ToGeoJson() WriteJson(writer, DefaultJsonSerializer); return stringWriter.ToString(); } - + /// public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { diff --git a/src/Cassandra/Geometry/LineString.cs b/src/Cassandra/Geometry/LineString.cs index 8340f5e75..81b71e4e7 100644 --- a/src/Cassandra/Geometry/LineString.cs +++ b/src/Cassandra/Geometry/LineString.cs @@ -53,7 +53,7 @@ public LineString(params Point[] points) : this((IList)points) { } - + /// /// Creates a new instance of using a serialization information. /// diff --git a/src/Cassandra/Geometry/Point.cs b/src/Cassandra/Geometry/Point.cs index 7a37b6689..d733edd20 100644 --- a/src/Cassandra/Geometry/Point.cs +++ b/src/Cassandra/Geometry/Point.cs @@ -47,7 +47,7 @@ public class Point : GeometryBase, IComparable /// protected override IEnumerable GeoCoordinates { - get { return new[] {X, Y}; } + get { return new[] { X, Y }; } } /// @@ -60,7 +60,7 @@ public Point(double x, double y) X = x; Y = y; } - + /// /// Creates a new instance of . /// @@ -95,7 +95,7 @@ public override bool Equals(object obj) public override int GetHashCode() { // ReSharper disable NonReadonlyMemberInGetHashCode - return CombineHashCode(new [] { X, Y}); + return CombineHashCode(new[] { X, Y }); // ReSharper enable NonReadonlyMemberInGetHashCode } diff --git a/src/Cassandra/Geometry/Polygon.cs b/src/Cassandra/Geometry/Polygon.cs index 6e5b23865..2af26f62b 100644 --- a/src/Cassandra/Geometry/Polygon.cs +++ b/src/Cassandra/Geometry/Polygon.cs @@ -54,7 +54,7 @@ protected override IEnumerable GeoCoordinates /// /// The points of the single ring public Polygon(params Point[] points) - : this((IList>) new[] { (IList)points }) + : this((IList>)new[] { (IList)points }) { } @@ -64,7 +64,7 @@ public Polygon(params Point[] points) /// /// The points of the single ring public Polygon(params IList[] points) - : this((IList>) points) + : this((IList>)points) { } @@ -72,9 +72,9 @@ public Polygon(params IList[] points) /// /// Creates a new instance of with no rings (empty). /// - public Polygon() : this((IList>) new IList[0]) + public Polygon() : this((IList>)new IList[0]) { - + } /// @@ -88,9 +88,9 @@ public Polygon(IList> rings) throw new ArgumentNullException("rings"); } Rings = AsReadOnlyCollection(rings, r => AsReadOnlyCollection(r)); - _ringsWithOrderedPoints = Rings.Select(r => (IList) r.OrderBy(p => p).ToList()).ToList(); + _ringsWithOrderedPoints = Rings.Select(r => (IList)r.OrderBy(p => p).ToList()).ToList(); } - + /// /// Creates a new instance of using serialization information. /// @@ -100,16 +100,16 @@ protected Polygon(SerializationInfo info, StreamingContext context) Rings = AsReadOnlyCollection(coordinates .Select(r => (IList)r.Select(p => new Point(p[0], p[1])).ToList()) .ToList()); - _ringsWithOrderedPoints = Rings.Select(r => (IList) r.OrderBy(p => p).ToList()).ToList(); + _ringsWithOrderedPoints = Rings.Select(r => (IList)r.OrderBy(p => p).ToList()).ToList(); } - + internal Polygon(JObject obj) { var coordinates = obj.GetValue("coordinates").ToObject(); Rings = AsReadOnlyCollection(coordinates .Select(r => (IList)r.Select(p => new Point(p[0], p[1])).ToList()) .ToList()); - _ringsWithOrderedPoints = Rings.Select(r => (IList) r.OrderBy(p => p).ToList()).ToList(); + _ringsWithOrderedPoints = Rings.Select(r => (IList)r.OrderBy(p => p).ToList()).ToList(); } /// @@ -156,10 +156,10 @@ public override string ToString() { return "POLYGON EMPTY"; } - return string.Format("POLYGON ({0})", string.Join(", ", - Rings.Select(r => - "(" + - string.Join(", ", r.Select(p => p.X.ToString(CultureInfo.InvariantCulture) + " " + p.Y.ToString(CultureInfo.InvariantCulture))) + + return string.Format("POLYGON ({0})", string.Join(", ", + Rings.Select(r => + "(" + + string.Join(", ", r.Select(p => p.X.ToString(CultureInfo.InvariantCulture) + " " + p.Y.ToString(CultureInfo.InvariantCulture))) + ")"))); } diff --git a/src/Cassandra/HeaderFlags.cs b/src/Cassandra/HeaderFlags.cs index c3a6e6fd0..1f74b4edf 100644 --- a/src/Cassandra/HeaderFlags.cs +++ b/src/Cassandra/HeaderFlags.cs @@ -45,7 +45,7 @@ internal enum HeaderFlags : byte /// were generated by the server to go along with this response. /// Warning = 0x08, - + /// /// Indicates that the client opts in to use protocol version /// that is currently in beta. Server will respond with ERROR if protocol diff --git a/src/Cassandra/Helpers/AssemblyHelpers.cs b/src/Cassandra/Helpers/AssemblyHelpers.cs index a7c075a8f..710d8e868 100644 --- a/src/Cassandra/Helpers/AssemblyHelpers.cs +++ b/src/Cassandra/Helpers/AssemblyHelpers.cs @@ -74,7 +74,7 @@ public static Assembly GetEntryAssembly() { AssemblyHelpers.Logger.Info("Could not get entry assembly by the default method. Exception: {0}", ex.ToString()); } - + if (assembly == null) { AssemblyHelpers.Logger.Verbose("Attempting to get entry assembly by main module."); @@ -108,7 +108,7 @@ public static Assembly GetEntryAssembly() return assembly; } - + private static Assembly GetEntryAssemblyByStacktrace() { var methodFrames = new StackTrace().GetFrames()?.Select(t => t.GetMethod()).ToArray(); @@ -158,7 +158,7 @@ private static Assembly GetEntryAssemblyByStacktrace() private static Assembly GetEntryAssemblyByMainModule() { var mainModule = Process.GetCurrentProcess().MainModule; - var entryAssembly = + var entryAssembly = AppDomain .CurrentDomain .GetAssemblies() diff --git a/src/Cassandra/Helpers/CollectionHelpers.cs b/src/Cassandra/Helpers/CollectionHelpers.cs index 3cf45ba01..da894d3db 100644 --- a/src/Cassandra/Helpers/CollectionHelpers.cs +++ b/src/Cassandra/Helpers/CollectionHelpers.cs @@ -31,7 +31,7 @@ internal static void CreateOrAdd( collection.Add(elementToAdd); } - + internal static void CreateIfDoesNotExist( this IDictionary> dictionary, TKey key) { diff --git a/src/Cassandra/Helpers/PlatformHelper.cs b/src/Cassandra/Helpers/PlatformHelper.cs index 68c0e7e2e..56d80fb3c 100644 --- a/src/Cassandra/Helpers/PlatformHelper.cs +++ b/src/Cassandra/Helpers/PlatformHelper.cs @@ -80,7 +80,7 @@ public CpuInfo(string name, int length) Length = length; } } - + public static CpuInfo GetWmiCpuInfo() { var count = 0; diff --git a/src/Cassandra/Host.cs b/src/Cassandra/Host.cs index a1854ef3c..9627c6fc0 100644 --- a/src/Cassandra/Host.cs +++ b/src/Cassandra/Host.cs @@ -132,7 +132,7 @@ public bool IsConsiderablyUp /// This property might be null when using Apache Cassandra or legacy DSE server versions. /// public Version DseVersion { get; private set; } - + /// /// ContactPoint from which this endpoint was resolved. It is null if it was parsed from system tables. /// diff --git a/src/Cassandra/Hosts.cs b/src/Cassandra/Hosts.cs index 8170a6e01..9d99fefec 100644 --- a/src/Cassandra/Hosts.cs +++ b/src/Cassandra/Hosts.cs @@ -73,7 +73,7 @@ public Host Add(IPEndPoint key) { return Add(key, null); } - + /// /// Adds the host if not exists /// diff --git a/src/Cassandra/IAuthInfoProvider.cs b/src/Cassandra/IAuthInfoProvider.cs index 5f81b3620..c3f4bbe14 100644 --- a/src/Cassandra/IAuthInfoProvider.cs +++ b/src/Cassandra/IAuthInfoProvider.cs @@ -27,7 +27,7 @@ namespace Cassandra /// /// internal interface IAuthInfoProvider - // only for protocol V1 Credentials support + // only for protocol V1 Credentials support { /// /// The authentication informations to use to connect to host. diff --git a/src/Cassandra/ICluster.cs b/src/Cassandra/ICluster.cs index 84a74a922..0a52e407e 100644 --- a/src/Cassandra/ICluster.cs +++ b/src/Cassandra/ICluster.cs @@ -128,20 +128,20 @@ public interface ICluster : IDisposable /// used by it.

This method has no effect if the cluster was already shutdown.

///
void Shutdown(int timeoutMs = Timeout.Infinite); - + /// /// Shutdown this cluster instance asynchronously. This closes all connections from all the /// sessions of this * Cluster instance and reclaim all resources /// used by it.

This method has no effect if the cluster was already shutdown.

///
Task ShutdownAsync(int timeoutMs = Timeout.Infinite); - + /// /// Updates keyspace metadata (including token metadata for token aware routing) for a given keyspace or a specific keyspace table. /// If no keyspace is provided then this method will update the metadata and token map for all the keyspaces of the cluster. /// Task RefreshSchemaAsync(string keyspace = null, string table = null); - + /// /// Updates keyspace metadata (including token metadata for token aware routing) for a given keyspace or a specific keyspace table. /// If no keyspace is provided then this method will update the metadata and token map for all the keyspaces of the cluster. diff --git a/src/Cassandra/IExecutionProfile.cs b/src/Cassandra/IExecutionProfile.cs index 230535840..9a5c81dad 100644 --- a/src/Cassandra/IExecutionProfile.cs +++ b/src/Cassandra/IExecutionProfile.cs @@ -40,13 +40,13 @@ public interface IExecutionProfile /// See for additional context on this setting. /// ConsistencyLevel? ConsistencyLevel { get; } - + /// /// Retrieves the LoadBalancingPolicy set on this profile. It's null if not set. /// See for additional context on this setting. /// ILoadBalancingPolicy LoadBalancingPolicy { get; } - + /// /// The per-host read timeout in milliseconds. /// @@ -56,19 +56,19 @@ public interface IExecutionProfile /// Also note that for efficiency reasons, this read timeout is approximate, it may fire up to late. It is not meant to be used for precise timeout, but rather as a protection against misbehaving Cassandra nodes. /// int? ReadTimeoutMillis { get; } - + /// /// Retrieves the RetryPolicy set on this profile. It's null if not set. /// See for additional context on this setting. /// IExtendedRetryPolicy RetryPolicy { get; } - + /// /// Retrieves the SerialConsistencyLevel set on this profile. It's null if not set. /// See for additional context on this setting. /// ConsistencyLevel? SerialConsistencyLevel { get; } - + /// /// Retrieves the SpeculativeExecutionPolicy set on this profile. It's null if not set. /// See for additional context on this setting. diff --git a/src/Cassandra/IExecutionProfileBuilder.cs b/src/Cassandra/IExecutionProfileBuilder.cs index d7f5e5c04..6fad82aab 100644 --- a/src/Cassandra/IExecutionProfileBuilder.cs +++ b/src/Cassandra/IExecutionProfileBuilder.cs @@ -30,7 +30,7 @@ public interface IExecutionProfileBuilder /// /// This builder. IExecutionProfileBuilder WithLoadBalancingPolicy(ILoadBalancingPolicy loadBalancingPolicy); - + /// /// Sets the retry policy. /// See and for additional context on this setting. @@ -47,21 +47,21 @@ public interface IExecutionProfileBuilder /// /// This builder. IExecutionProfileBuilder WithSpeculativeExecutionPolicy(ISpeculativeExecutionPolicy speculativeExecutionPolicy); - + /// /// Sets the SerialConsistencyLevel setting. /// See for additional context on this setting. /// /// This builder. IExecutionProfileBuilder WithConsistencyLevel(ConsistencyLevel consistencyLevel); - + /// /// Sets the SerialConsistencyLevel setting. /// See for additional context on this setting. /// /// This builder. IExecutionProfileBuilder WithSerialConsistencyLevel(ConsistencyLevel serialConsistencyLevel); - + /// /// Sets the ReadTimeoutMillis setting which is the per-host read timeout in milliseconds. /// When setting this value, keep in mind the following: diff --git a/src/Cassandra/IMetadataQueryProvider.cs b/src/Cassandra/IMetadataQueryProvider.cs index 597081b09..7c2c3039e 100644 --- a/src/Cassandra/IMetadataQueryProvider.cs +++ b/src/Cassandra/IMetadataQueryProvider.cs @@ -34,7 +34,7 @@ internal interface IMetadataQueryProvider /// The address of the endpoint used by the ControlConnection /// IConnectionEndPoint EndPoint { get; } - + /// /// The local address of the socket used by the ControlConnection /// diff --git a/src/Cassandra/ISession.cs b/src/Cassandra/ISession.cs index 9f9e3f8f7..5b3037ed4 100644 --- a/src/Cassandra/ISession.cs +++ b/src/Cassandra/ISession.cs @@ -37,7 +37,7 @@ namespace Cassandra /// at a time, so one instance per keyspace is necessary. /// /// - public interface ISession: IDisposable + public interface ISession : IDisposable { /// /// Gets the Cassandra native binary protocol version @@ -144,7 +144,7 @@ public interface ISession: IDisposable /// Ends asynchronous prepare operation /// PreparedStatement EndPrepare(IAsyncResult ar); - + /// /// Executes the provided statement with the provided execution profile. /// The execution profile must have been added previously to the Cluster using . @@ -162,7 +162,7 @@ public interface ISession: IDisposable /// Executes the provided query. /// RowSet Execute(string cqlQuery); - + /// /// Executes the provided query with the provided execution profile. /// The execution profile must have been added previously to the Cluster using . @@ -170,7 +170,7 @@ public interface ISession: IDisposable /// Query to execute. /// ExecutionProfile name to be used while executing the statement. RowSet Execute(string cqlQuery, string executionProfileName); - + /// /// Executes the provided query. /// @@ -202,14 +202,14 @@ public interface ISession: IDisposable /// /// cql query to prepare PreparedStatement Prepare(string cqlQuery); - + /// /// Prepares the query string, sending the custom payload request. /// /// cql query to prepare /// Custom outgoing payload to send with the prepare request PreparedStatement Prepare(string cqlQuery, IDictionary customPayload); - + /// /// Prepares the query on the provided keyspace. /// @@ -233,7 +233,7 @@ public interface ISession: IDisposable /// /// cql query to prepare Task PrepareAsync(string cqlQuery); - + /// /// Prepares the provided query string asynchronously, and sending the custom payload request. /// @@ -263,7 +263,7 @@ public interface ISession: IDisposable /// Retrieves the driver metrics for this session. /// IDriverMetrics GetMetrics(); - + /// /// Executes a graph statement. /// @@ -299,7 +299,7 @@ public interface ISession: IDisposable /// /// GraphResultSet ExecuteGraph(IGraphStatement statement, string executionProfileName); - + /// /// Executes a graph statement asynchronously with the provided graph execution profile. /// The graph execution profile must have been added previously to the Cluster diff --git a/src/Cassandra/IndexMetadata.cs b/src/Cassandra/IndexMetadata.cs index c7932aea1..61f52f6d3 100644 --- a/src/Cassandra/IndexMetadata.cs +++ b/src/Cassandra/IndexMetadata.cs @@ -77,7 +77,7 @@ public IndexMetadata(string name, string target, IndexKind kind, IDictionary diff --git a/src/Cassandra/KeyspaceMetadata.cs b/src/Cassandra/KeyspaceMetadata.cs index dca57317a..6e637981d 100644 --- a/src/Cassandra/KeyspaceMetadata.cs +++ b/src/Cassandra/KeyspaceMetadata.cs @@ -70,18 +70,18 @@ public class KeyspaceMetadata /// Determines whether the keyspace is a virtual keyspace or not. /// public bool IsVirtual { get; } - + /// /// Returns the graph engine associated with this keyspace. Returns null if there isn't one. /// public string GraphEngine { get; } internal IReplicationStrategy Strategy { get; } - + internal KeyspaceMetadata( - Metadata parent, - string name, - bool durableWrites, + Metadata parent, + string name, + bool durableWrites, string strategyClass, IDictionary replicationOptions, IReplicationStrategyFactory replicationStrategyFactory, @@ -101,18 +101,18 @@ internal KeyspaceMetadata( StrategyClass = strategyClass; var parsedReplicationOptions = replicationOptions == null - ? null + ? null : ParseReplicationFactors(replicationOptions); - Replication = parsedReplicationOptions == null - ? null + Replication = parsedReplicationOptions == null + ? null : ConvertReplicationOptionsToLegacy(parsedReplicationOptions); - + ReplicationOptions = replicationOptions; IsVirtual = isVirtual; - Strategy = - (strategyClass == null || parsedReplicationOptions == null) - ? null + Strategy = + (strategyClass == null || parsedReplicationOptions == null) + ? null : replicationStrategyFactory.Create(StrategyClass, parsedReplicationOptions); GraphEngine = graphEngine; @@ -139,7 +139,7 @@ internal async Task GetTableMetadataAsync(string tableName) } var table = await _parent.SchemaParser.GetTableAsync(Name, tableName).ConfigureAwait(false); - + if (table == null) { return null; @@ -235,7 +235,7 @@ public ICollection GetTablesNames() { return TaskHelper.WaitToComplete(_parent.SchemaParser.GetTableNamesAsync(Name)); } - + /// /// /// Deprecated. Please use . diff --git a/src/Cassandra/LocalDate.cs b/src/Cassandra/LocalDate.cs index c5f23f654..840da2f36 100644 --- a/src/Cassandra/LocalDate.cs +++ b/src/Cassandra/LocalDate.cs @@ -24,19 +24,19 @@ namespace Cassandra /// LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. /// This class is implemented to match the Date representation CQL string literals. /// - public class LocalDate: IComparable, IEquatable + public class LocalDate : IComparable, IEquatable { /// /// Day number relatively to the year based on the month index /// - private static readonly int[] DaysToMonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; - private static readonly int[] DaysToMonthLeap = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; + private static readonly int[] DaysToMonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; + private static readonly int[] DaysToMonthLeap = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // unix epoch is represented by the number 2 ^ 31 private const long DateCenter = 2147483648L; private const long DaysFromYear0ToUnixEpoch = 719528L; // ReSharper disable once InconsistentNaming private const long DaysFromYear0March1stToUnixEpoch = LocalDate.DaysFromYear0ToUnixEpoch - 60L; - + private static readonly Regex RegexInteger = new Regex("^-?\\d+$", RegexOptions.Compiled); private const string BadFormatMessage = @@ -72,22 +72,22 @@ private void InitializeFromDaysSinceEpoch(long daysSinceEpoch) { var daysSinceShiftedEpoch = daysSinceEpoch + LocalDate.DaysFromYear0March1stToUnixEpoch; // shift epoch from 1970-01-01 to 0000-03-01 var era = // compute era (400 year period) - (daysSinceShiftedEpoch >= 0 ? daysSinceShiftedEpoch : daysSinceShiftedEpoch - 146096) - / 146097; - + (daysSinceShiftedEpoch >= 0 ? daysSinceShiftedEpoch : daysSinceShiftedEpoch - 146096) + / 146097; + var dayOfEra = (daysSinceShiftedEpoch - era * 146097); // [0, 146096] - var yearOfEra = (dayOfEra - dayOfEra/1460 + dayOfEra/36524 - dayOfEra/146096) / 365; // [0, 399] - var dayOfYear = dayOfEra - (365*yearOfEra + yearOfEra/4 - yearOfEra/100); // [0, 365] - var monthInternal = (5*dayOfYear + 2)/153; // [0, 11] + var yearOfEra = (dayOfEra - dayOfEra / 1460 + dayOfEra / 36524 - dayOfEra / 146096) / 365; // [0, 399] + var dayOfYear = dayOfEra - (365 * yearOfEra + yearOfEra / 4 - yearOfEra / 100); // [0, 365] + var monthInternal = (5 * dayOfYear + 2) / 153; // [0, 11] var yearInternal = yearOfEra + era * 400; // beginning in Mar 1st, NOT in Jan 1st - var day = dayOfYear - (153*monthInternal+2)/5 + 1; // [1, 31] + var day = dayOfYear - (153 * monthInternal + 2) / 5 + 1; // [1, 31] var monthCivil = monthInternal + (monthInternal < 10 ? 3 : -9); // [1, 12] var yearCivil = yearInternal + (monthCivil <= 2 ? 1 : 0); // shift to beginning in Jan 1st - Year = (int) yearCivil; - Month = (int) monthCivil; - Day = (int) day; + Year = (int)yearCivil; + Month = (int)monthCivil; + Day = (int)day; } /// @@ -135,7 +135,7 @@ private static long DaysSinceYearZero(int year) { return ( //days per year - year * 365L + + year * 365L + //adjusted per leap years LeapDays(year)); } @@ -160,7 +160,7 @@ public static int DaysSinceJan1(int year, int month, int day) /// 0-based year number: 0 equals to 1 AD private static long LeapDays(long year) { - var result = year/4 - year/100 + year/400; + var result = year / 4 - year / 100 + year / 400; if (year > 0 && IsLeapYear((int)year)) { result--; @@ -180,7 +180,7 @@ private static bool IsLeapYear(int year) /// public int CompareTo(LocalDate other) { - if ((object) other == null) + if ((object)other == null) { return 1; } @@ -235,7 +235,7 @@ public DateTimeOffset ToDateTimeOffset() { if (Year < 1 || Year > 9999) { - throw new ArgumentOutOfRangeException("The LocalDate can not be converted to DateTimeOffset", (Exception) null); + throw new ArgumentOutOfRangeException("The LocalDate can not be converted to DateTimeOffset", (Exception)null); } return new DateTimeOffset(Year, Month, Day, 0, 0, 0, 0, TimeSpan.Zero); } diff --git a/src/Cassandra/LocalTime.cs b/src/Cassandra/LocalTime.cs index 909b354b0..8ec793905 100644 --- a/src/Cassandra/LocalTime.cs +++ b/src/Cassandra/LocalTime.cs @@ -108,9 +108,9 @@ public LocalTime(int hour, int minute, int second, int nanosecond) throw new ArgumentOutOfRangeException("nanosecond", "Nanosecond must be a number between 0 and 999,999,999"); } TotalNanoseconds = - hour*NanosInHour + - minute*NanosInMinutes + - second*NanosInSeconds + + hour * NanosInHour + + minute * NanosInMinutes + + second * NanosInSeconds + nanosecond; } @@ -134,7 +134,7 @@ public static LocalTime Parse(string value) { var decimalSeconds = Convert.ToDecimal(parts[2], CultureInfo.InvariantCulture); var integralPart = Math.Truncate(decimalSeconds); - seconds = (int) integralPart; + seconds = (int)integralPart; nanos = (int)(NanosInSeconds * (decimalSeconds - integralPart)); } return new LocalTime(Convert.ToInt32(parts[0]), Convert.ToInt32(parts[1]), seconds, nanos); @@ -147,17 +147,17 @@ public override string ToString() if (nanos > 0) { nanosPart = Utils.FillZeros(nanos, 9); - + var lastPosition = 0; - for (var i = nanosPart.Length - 1; i > 0; i--) + for (var i = nanosPart.Length - 1; i > 0; i--) { - if (nanosPart[i] != '0') + if (nanosPart[i] != '0') { break; } lastPosition = i; } - if (lastPosition > 0) + if (lastPosition > 0) { nanosPart = nanosPart.Substring(0, lastPosition); } diff --git a/src/Cassandra/Logger.cs b/src/Cassandra/Logger.cs index 458f1d7c6..0fc23834c 100644 --- a/src/Cassandra/Logger.cs +++ b/src/Cassandra/Logger.cs @@ -78,7 +78,7 @@ public void Verbose(string message, params object[] args) { _loggerHandler.Verbose(message, args); } - + /// /// Represents the actual logger /// @@ -252,5 +252,5 @@ public void Verbose(string message, params object[] args) } } - + } \ No newline at end of file diff --git a/src/Cassandra/M3PToken.cs b/src/Cassandra/M3PToken.cs index 19f867ca1..268f7e4f4 100644 --- a/src/Cassandra/M3PToken.cs +++ b/src/Cassandra/M3PToken.cs @@ -42,12 +42,12 @@ public override bool Equals(object obj) if (obj == null || GetType() != obj.GetType()) return false; - return _value == ((M3PToken) obj)._value; + return _value == ((M3PToken)obj)._value; } public override int GetHashCode() { - return (int) (_value ^ ((long) ((ulong) _value >> 32))); + return (int)(_value ^ ((long)((ulong)_value >> 32))); } public override string ToString() @@ -102,20 +102,20 @@ private static long Murmur(byte[] bytes) long k1 = GetBlock(data, offset, i * 2 + 0); long k2 = GetBlock(data, offset, i * 2 + 1); - k1 *= c1; - k1 = Rotl64(k1, 31); - k1 *= c2; - + k1 *= c1; + k1 = Rotl64(k1, 31); + k1 *= c2; + h1 ^= k1; - h1 = Rotl64(h1, 27); - h1 += h2; + h1 = Rotl64(h1, 27); + h1 += h2; h1 = h1 * 5 + 0x52dce729; - k2 *= c2; - k2 = Rotl64(k2, 33); + k2 *= c2; + k2 = Rotl64(k2, 33); k2 *= c1; h2 ^= k2; - h2 = Rotl64(h2, 31); - h2 += h1; + h2 = Rotl64(h2, 31); + h2 += h1; h2 = h2 * 5 + 0x38495ab5; } @@ -131,56 +131,56 @@ private static long Murmur(byte[] bytes) switch (length & 15) { - case 15: + case 15: k2 ^= ((long)data[offset + 14]) << 48; goto case 14; - case 14: + case 14: k2 ^= ((long)data[offset + 13]) << 40; goto case 13; - case 13: + case 13: k2 ^= ((long)data[offset + 12]) << 32; goto case 12; - case 12: + case 12: k2 ^= ((long)data[offset + 11]) << 24; goto case 11; - case 11: + case 11: k2 ^= ((long)data[offset + 10]) << 16; goto case 10; - case 10: - k2 ^= ((long)data[offset + 9 ]) << 8; + case 10: + k2 ^= ((long)data[offset + 9]) << 8; goto case 9; - case 9: - k2 ^= ((long)data[offset + 8 ]) << 0; - k2 *= c2; - k2 = Rotl64(k2, 33); - k2 *= c1; + case 9: + k2 ^= ((long)data[offset + 8]) << 0; + k2 *= c2; + k2 = Rotl64(k2, 33); + k2 *= c1; h2 ^= k2; goto case 8; - case 8: + case 8: k1 ^= ((long)data[offset + 7]) << 56; goto case 7; - case 7: + case 7: k1 ^= ((long)data[offset + 6]) << 48; goto case 6; - case 6: + case 6: k1 ^= ((long)data[offset + 5]) << 40; goto case 5; - case 5: + case 5: k1 ^= ((long)data[offset + 4]) << 32; goto case 4; - case 4: + case 4: k1 ^= ((long)data[offset + 3]) << 24; goto case 3; - case 3: + case 3: k1 ^= ((long)data[offset + 2]) << 16; goto case 2; - case 2: + case 2: k1 ^= ((long)data[offset + 1]) << 8; goto case 1; - case 1: + case 1: k1 ^= ((long)data[offset]); - k1 *= c1; - k1 = Rotl64(k1, 31); + k1 *= c1; + k1 = Rotl64(k1, 31); k1 *= c2; h1 ^= k1; break; @@ -189,7 +189,7 @@ private static long Murmur(byte[] bytes) //---------- // finalization - h1 ^= length; + h1 ^= length; h2 ^= length; h1 += h2; diff --git a/src/Cassandra/Mapping/Attributes/AttributeBasedColumnDefinition.cs b/src/Cassandra/Mapping/Attributes/AttributeBasedColumnDefinition.cs index f3ba5c4e9..68a9c5312 100644 --- a/src/Cassandra/Mapping/Attributes/AttributeBasedColumnDefinition.cs +++ b/src/Cassandra/Mapping/Attributes/AttributeBasedColumnDefinition.cs @@ -101,8 +101,8 @@ bool IColumnDefinition.HasFrozenValue /// /// Creates a new column definition for the field specified using any attributes on the field to determine mapping configuration. /// - public AttributeBasedColumnDefinition(FieldInfo fieldInfo) - : this((MemberInfo) fieldInfo) + public AttributeBasedColumnDefinition(FieldInfo fieldInfo) + : this((MemberInfo)fieldInfo) { _memberInfoType = fieldInfo.FieldType; } @@ -110,8 +110,8 @@ public AttributeBasedColumnDefinition(FieldInfo fieldInfo) /// /// Creates a new column definition for the property specified using any attributes on the property to determine mapping configuration. /// - public AttributeBasedColumnDefinition(PropertyInfo propertyInfo) - : this((MemberInfo) propertyInfo) + public AttributeBasedColumnDefinition(PropertyInfo propertyInfo) + : this((MemberInfo)propertyInfo) { _memberInfoType = propertyInfo.PropertyType; } @@ -120,7 +120,7 @@ private AttributeBasedColumnDefinition(MemberInfo memberInfo) { _memberInfo = memberInfo; - var columnAttribute = (ColumnAttribute) memberInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); + var columnAttribute = (ColumnAttribute)memberInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); if (columnAttribute != null) { _isExplicitlyDefined = true; diff --git a/src/Cassandra/Mapping/Attributes/TableAttribute.cs b/src/Cassandra/Mapping/Attributes/TableAttribute.cs index 0a6cfa3dc..2f4e560a6 100644 --- a/src/Cassandra/Mapping/Attributes/TableAttribute.cs +++ b/src/Cassandra/Mapping/Attributes/TableAttribute.cs @@ -60,7 +60,7 @@ public class TableAttribute : Attribute /// public TableAttribute() { - + } /// diff --git a/src/Cassandra/Mapping/ColumnMap.cs b/src/Cassandra/Mapping/ColumnMap.cs index 0629ff410..f580b7a13 100644 --- a/src/Cassandra/Mapping/ColumnMap.cs +++ b/src/Cassandra/Mapping/ColumnMap.cs @@ -141,7 +141,7 @@ public ColumnMap WithDbType(Type type) /// public ColumnMap WithDbType() { - _columnType = typeof (T); + _columnType = typeof(T); return this; } diff --git a/src/Cassandra/Mapping/Cql.cs b/src/Cassandra/Mapping/Cql.cs index 587712e3f..0c0fe12d5 100644 --- a/src/Cassandra/Mapping/Cql.cs +++ b/src/Cassandra/Mapping/Cql.cs @@ -99,7 +99,7 @@ public static Cql New(string cql, params object[] args) { return new Cql(cql, args); } - + /// /// Creates an empty CQL instance for cases where a cql string is not needed like fetch queries. /// diff --git a/src/Cassandra/Mapping/CqlBatch.cs b/src/Cassandra/Mapping/CqlBatch.cs index 14551cc43..8ef6d0681 100644 --- a/src/Cassandra/Mapping/CqlBatch.cs +++ b/src/Cassandra/Mapping/CqlBatch.cs @@ -40,7 +40,7 @@ public IEnumerable Statements public CqlQueryOptions Options { get; private set; } public CqlBatch(MapperFactory mapperFactory, CqlGenerator cqlGenerator) - :this(mapperFactory, cqlGenerator, BatchType.Logged) + : this(mapperFactory, cqlGenerator, BatchType.Logged) { } @@ -57,7 +57,7 @@ public void Insert(T poco, CqlQueryOptions queryOptions = null) { Insert(poco, true, queryOptions); } - + public void Insert(T poco, bool insertNulls, CqlQueryOptions queryOptions = null) { Insert(false, insertNulls, poco, queryOptions, null); @@ -67,7 +67,7 @@ public void Insert(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryO { Insert(false, insertNulls, poco, queryOptions, ttl); } - + public void InsertIfNotExists(T poco, CqlQueryOptions queryOptions = null) { InsertIfNotExists(poco, true, queryOptions); @@ -77,12 +77,12 @@ public void InsertIfNotExists(T poco, bool insertNulls, CqlQueryOptions query { Insert(true, insertNulls, poco, queryOptions); } - + public void InsertIfNotExists(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null) { Insert(true, insertNulls, poco, queryOptions, ttl); } - + private void Insert(bool ifNotExists, bool insertNulls, T poco, CqlQueryOptions queryOptions = null, int? ttl = null) { var pocoData = _mapperFactory.PocoDataFactory.GetPocoData(); diff --git a/src/Cassandra/Mapping/ICqlBatch.cs b/src/Cassandra/Mapping/ICqlBatch.cs index 41abf0fc5..46cd2b183 100644 --- a/src/Cassandra/Mapping/ICqlBatch.cs +++ b/src/Cassandra/Mapping/ICqlBatch.cs @@ -59,12 +59,12 @@ public interface ICqlBatch : ICqlWriteClient /// Inserts the specified POCO in Cassandra if not exists. /// void InsertIfNotExists(T poco, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra if not exists. /// void InsertIfNotExists(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra if not exists. /// diff --git a/src/Cassandra/Mapping/ICqlQueryAsyncClient.cs b/src/Cassandra/Mapping/ICqlQueryAsyncClient.cs index 09af1402b..a7cd86fa8 100644 --- a/src/Cassandra/Mapping/ICqlQueryAsyncClient.cs +++ b/src/Cassandra/Mapping/ICqlQueryAsyncClient.cs @@ -28,7 +28,7 @@ public interface ICqlQueryAsyncClient /// Gets a list of all T from Cassandra. /// Task> FetchAsync(CqlQueryOptions queryOptions = null); - + /// /// Gets a list of T from Cassandra using the CQL statement and parameter values specified. /// diff --git a/src/Cassandra/Mapping/ICqlQueryClient.cs b/src/Cassandra/Mapping/ICqlQueryClient.cs index fc06216da..e7ad30a05 100644 --- a/src/Cassandra/Mapping/ICqlQueryClient.cs +++ b/src/Cassandra/Mapping/ICqlQueryClient.cs @@ -59,7 +59,7 @@ public interface ICqlQueryClient /// Cql query /// Query parameters IPage FetchPage(int pageSize, byte[] pagingState, string query, object[] args); - + /// /// Gets a single T from Cassandra using the CQL statement and parameter values specified. Will throw if /// no records or more than one record is returned. diff --git a/src/Cassandra/Mapping/ICqlWriteAsyncClient.cs b/src/Cassandra/Mapping/ICqlWriteAsyncClient.cs index af2c9eb49..22415f175 100644 --- a/src/Cassandra/Mapping/ICqlWriteAsyncClient.cs +++ b/src/Cassandra/Mapping/ICqlWriteAsyncClient.cs @@ -27,7 +27,7 @@ public interface ICqlWriteAsyncClient /// Inserts the specified POCO in Cassandra. /// Task InsertAsync(T poco, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra. /// @@ -47,7 +47,7 @@ public interface ICqlWriteAsyncClient /// Optional query options /// Task InsertAsync(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra. /// diff --git a/src/Cassandra/Mapping/ICqlWriteClient.cs b/src/Cassandra/Mapping/ICqlWriteClient.cs index 9132f2ce7..934c941a3 100644 --- a/src/Cassandra/Mapping/ICqlWriteClient.cs +++ b/src/Cassandra/Mapping/ICqlWriteClient.cs @@ -45,7 +45,7 @@ public interface ICqlWriteClient /// Optional query options /// void Insert(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra. /// @@ -67,7 +67,7 @@ public interface ICqlWriteClient /// from the database after the specified time. /// void Insert(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); - + /// /// Updates the POCO specified in Cassandra. /// @@ -90,7 +90,7 @@ public interface ICqlWriteClient /// Deletes the specified POCO from Cassandra. /// void Delete(T poco, CqlQueryOptions queryOptions = null); - + /// /// Deletes from the table for the POCO type specified (T) using the CQL string and bind variable values specified. Prepends "DELETE FROM tablname " to /// the CQL string you specify, getting the tablename appropriately from the POCO Type T. diff --git a/src/Cassandra/Mapping/IMapper.cs b/src/Cassandra/Mapping/IMapper.cs index d96003e56..46777c769 100644 --- a/src/Cassandra/Mapping/IMapper.cs +++ b/src/Cassandra/Mapping/IMapper.cs @@ -101,7 +101,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Inserts the specified POCO in Cassandra using the provided execution profile. /// void Insert(T poco, string executionProfile, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra using the provided execution profile. /// @@ -122,7 +122,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Optional query options /// void Insert(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra using the provided execution profile. /// @@ -145,7 +145,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// from the database after the specified time. /// void Insert(T poco, string executionProfile, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra using the provided execution profile. /// @@ -194,12 +194,12 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Optional query options /// Task InsertAsync(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Updates the POCO specified in Cassandra using the provided execution profile. /// void Update(T poco, string executionProfile, CqlQueryOptions queryOptions = null); - + /// /// Updates the POCO specified in Cassandra using the provided execution profile. /// @@ -209,7 +209,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Deletes the specified POCO from Cassandra using the provided execution profile. /// void Delete(T poco, string executionProfile, CqlQueryOptions queryOptions = null); - + /// /// Deletes the specified POCO from Cassandra using the provided execution profile. /// @@ -260,7 +260,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// /// Task> InsertIfNotExistsAsync(T poco, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// @@ -288,7 +288,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Optional query options /// Task> InsertIfNotExistsAsync(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// @@ -362,7 +362,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// /// AppliedInfo InsertIfNotExists(T poco, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// @@ -390,7 +390,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Optional query options /// AppliedInfo InsertIfNotExists(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// @@ -433,7 +433,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// Optional query options /// AppliedInfo InsertIfNotExists(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); - + /// /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// @@ -531,7 +531,7 @@ public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQuery /// query within the batch will be ignored. /// AppliedInfo ExecuteConditional(ICqlBatch batch); - + /// /// Executes a batch that contains a Lightweight transaction. /// diff --git a/src/Cassandra/Mapping/IPage.cs b/src/Cassandra/Mapping/IPage.cs index e6d66ca03..b33ddcd4b 100644 --- a/src/Cassandra/Mapping/IPage.cs +++ b/src/Cassandra/Mapping/IPage.cs @@ -22,8 +22,8 @@ namespace Cassandra.Mapping /// Represents the result of a paged query, returned by manually paged query executions. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Naming", - "CA1710:Identifiers should have correct suffix", + "Naming", + "CA1710:Identifiers should have correct suffix", Justification = "Public API")] public interface IPage : ICollection { diff --git a/src/Cassandra/Mapping/Map.cs b/src/Cassandra/Mapping/Map.cs index 5d1488314..428c18790 100644 --- a/src/Cassandra/Mapping/Map.cs +++ b/src/Cassandra/Mapping/Map.cs @@ -38,7 +38,7 @@ public class Map : ITypeDefinition private string[] _partitionKeyColumns; private MemberInfo[] _partitionKeyColumnMembers; private readonly List> _clusteringKeyColumns = new List>(0); - private readonly List> _clusteringKeyColumnMembers = new List>(0); + private readonly List> _clusteringKeyColumnMembers = new List>(0); private bool _compactStorage; private string _keyspaceName; @@ -86,7 +86,7 @@ string[] ITypeDefinition.PartitionKeys return _partitionKeyColumns; // If no MemberInfos available either, just bail - if (_partitionKeyColumnMembers == null) + if (_partitionKeyColumnMembers == null) return null; // Get the column names from the members @@ -118,7 +118,7 @@ Tuple[] ITypeDefinition.ClusteringKeys /// public Map() { - _pocoType = typeof (TPoco); + _pocoType = typeof(TPoco); _columnMaps = new Dictionary(); } @@ -128,7 +128,7 @@ public Map() public Map TableName(string tableName) { if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentNullException("tableName"); - + _tableName = tableName; return this; } @@ -319,7 +319,7 @@ private MemberInfo GetPropertyOrField(Expression> expr // We'll get a Convert node for the Func where the actual property expression is the operand being converted to object if (body.NodeType == ExpressionType.Convert) - body = ((UnaryExpression) body).Operand; + body = ((UnaryExpression)body).Operand; var memberExpression = body as MemberExpression; if (memberExpression == null || IsPropertyOrField(memberExpression.Member) == false) @@ -331,7 +331,7 @@ private MemberInfo GetPropertyOrField(Expression> expr string.Format("Expression {0} refers to a property or field that is not from type {1}", expression, _pocoType)); } - + return memberExpression.Member; } diff --git a/src/Cassandra/Mapping/MapperFactory.cs b/src/Cassandra/Mapping/MapperFactory.cs index ad92b6bd0..42ad8d3f8 100644 --- a/src/Cassandra/Mapping/MapperFactory.cs +++ b/src/Cassandra/Mapping/MapperFactory.cs @@ -29,9 +29,9 @@ namespace Cassandra.Mapping /// internal class MapperFactory { - private static readonly Type CassandraRowType = typeof (Row); - private static readonly Type IntType = typeof (int); - private static readonly Type ObjectType = typeof (object); + private static readonly Type CassandraRowType = typeof(Row); + private static readonly Type IntType = typeof(int); + private static readonly Type ObjectType = typeof(object); private const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance; @@ -114,11 +114,11 @@ private static Tuple GetMapperCacheKey(string cql, stri /// public Func GetValueCollector(string cql, bool primaryKeyValuesOnly = false, bool primaryKeyValuesLast = false) { - Tuple key = Tuple.Create(typeof (T), cql); + Tuple key = Tuple.Create(typeof(T), cql); Delegate valueCollectorFunc = _valueCollectorFuncCache.GetOrAdd(key, _ => CreateValueCollector(primaryKeyValuesOnly, primaryKeyValuesLast)); - return (Func) valueCollectorFunc; + return (Func)valueCollectorFunc; } - + /// /// Creates a mapper Func for going from a C* Row to a POCO, T. /// @@ -127,14 +127,14 @@ private Func CreateMapper(RowSet rows) var pocoData = GetPocoData(); // See if we retrieved only one column and if that column does not exist in the PocoData - if (rows.Columns.Length == 1 && - !Cassandra.Utils.IsAnonymousType(pocoData.PocoType) && + if (rows.Columns.Length == 1 && + !Cassandra.Utils.IsAnonymousType(pocoData.PocoType) && !pocoData.Columns.Contains(rows.Columns[0].Name)) { // Map the single column value directly to the POCO return CreateMapperForSingleColumnToPoco(rows, pocoData); } - + // Create a default POCO mapper return CreateMapperForPoco(rows, pocoData); } @@ -198,17 +198,17 @@ private Func CreateValueCollector(bool primaryKeyValuesOnly, boo } // Create a variable to hold our return value, and initialize as an object[] of correct size - var values = Expression.Variable(typeof (object[]), "values"); + var values = Expression.Variable(typeof(object[]), "values"); methodBodyExpressions.Add( // object[] values = new object[... number of columns on POCO ...]; Expression.Assign(values, Expression.NewArrayBounds(ObjectType, Expression.Constant(columns.Count, IntType)))); - + for (var idx = 0; idx < columns.Count; idx++) { PocoColumn column = columns[idx]; Expression getValueFromPoco = GetExpressionToGetValueFromPoco(poco, column); - + // values[columnIndex] = (object) ... getValueFromPoco ... methodBodyExpressions.Add( Expression.Assign(Expression.ArrayAccess(values, Expression.Constant(idx, IntType)), @@ -220,7 +220,7 @@ private Func CreateValueCollector(bool primaryKeyValuesOnly, boo methodBodyExpressions.Add(values); // Construct the method body, then create a compiled Func for the method - var methodBody = Expression.Block(new[] {values}, methodBodyExpressions); + var methodBody = Expression.Block(new[] { values }, methodBodyExpressions); return Expression.Lambda>(methodBody, poco).Compile(); } @@ -263,7 +263,7 @@ private Func CreateMapperForPoco(RowSet rows, PocoData pocoData) if (constructor == null) { throw new ArgumentException( - string.Format("RowSet columns length is {0} but type {1} does not contain a constructor with the same amount of parameters", + string.Format("RowSet columns length is {0} but type {1} does not contain a constructor with the same amount of parameters", rows.Columns.Length, pocoData.PocoType)); } @@ -358,7 +358,7 @@ private Func CreateMapperForProjection(RowSet rows, NewTypeProjection parameterExpressions.Add(getValueT); } // T poco = new T(param1, param2, ...) - methodBodyExpressions.Add(Expression.Assign(poco, + methodBodyExpressions.Add(Expression.Assign(poco, Expression.New(projection.ConstructorInfo, parameterExpressions))); } // Fill the rest of members with the rest of the column values @@ -387,15 +387,15 @@ private Func CreateMapperForProjection(RowSet rows, NewTypeProjection // if (row.IsNull(columnIndex) == false) => getValueAndAssign ... // else => ifRowIsNull ... methodBodyExpressions.Add(Expression.IfThenElse( - Expression.IsFalse(Expression.Call(row, IsNullMethod, columnIndexExpression)), - getValueAndAssign, + Expression.IsFalse(Expression.Call(row, IsNullMethod, columnIndexExpression)), + getValueAndAssign, ifRowValueIsNull)); columnIndex++; } // The last expression in the method body is the return value, so put our new POCO at the end methodBodyExpressions.Add(poco); // Create a block expression for the method body expressions - var methodBody = Expression.Block(new [] { poco }, methodBodyExpressions); + var methodBody = Expression.Block(new[] { poco }, methodBodyExpressions); // Return compiled expression return Expression.Lambda>(methodBody, row).Compile(); } @@ -414,14 +414,14 @@ private static Type GetUnderlyingType(MemberInfo member) } /// - /// Gets an Expression that gets the value of a POCO field or property. - /// + /// Gets an Expression that gets the value of a POCO field or property. + /// private Expression GetExpressionToGetValueFromPoco(ParameterExpression poco, PocoColumn column) { // Start by assuming the database wants the same type that the property is and that we'll just be getting the value from the property: // poco.SomeFieldOrProp Expression getValueFromPoco = Expression.MakeMemberAccess(poco, column.MemberInfo); - if (column.MemberInfoType == column.ColumnType) + if (column.MemberInfoType == column.ColumnType) return getValueFromPoco; // See if there is a converter available for between the two types @@ -432,7 +432,7 @@ private Expression GetExpressionToGetValueFromPoco(ParameterExpression poco, Poc // (TColumn) poco.SomeFieldOrProp return Expression.Convert(getValueFromPoco, column.ColumnType); } - + // Invoke the converter: // converter(poco.SomeFieldOrProp) return Expression.Call(converter.Target == null ? null : Expression.Constant(converter.Target), GetMethod(converter), getValueFromPoco); @@ -445,7 +445,7 @@ public object AdaptValue(PocoData pocoData, PocoColumn column, object value) return value; } // See if there is a converter available for between the two types - var converter = _typeConverter.GetToDbConverter(column.MemberInfoType, column.ColumnType); + var converter = _typeConverter.GetToDbConverter(column.MemberInfoType, column.ColumnType); if (converter == null) { // No converter available, at least try a cast: @@ -492,12 +492,12 @@ private Expression GetExpressionToGetColumnValueFromRow(ParameterExpression row, { // Invoke the converter function on getValueT (taking into account whether it's a static method): // converter(row.GetValue(columnIndex)); - convertedValue = + convertedValue = Expression.Convert( Expression.Call( - converter.Target == null ? null : Expression.Constant(converter.Target), - GetMethod(converter), - getValueT), + converter.Target == null ? null : Expression.Constant(converter.Target), + GetMethod(converter), + getValueT), pocoDestType); } // Cassandra will return null for empty collections, so make an effort to populate collection properties on the POCO with @@ -561,10 +561,10 @@ private static bool TryGetCreateEmptyCollectionExpression(CqlColumn dbColumn, Ty Type openGenericType = pocoDestType.GetGenericTypeDefinition(); // Handle IDictionary - if (openGenericType == typeof (IDictionary<,>)) + if (openGenericType == typeof(IDictionary<,>)) { // The driver currently uses SortedDictionary so we will too - Type dictionaryType = typeof (SortedDictionary<,>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); + Type dictionaryType = typeof(SortedDictionary<,>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); // (IDictionary) new SortedDictionary(); createEmptyCollection = Expression.Convert(Expression.New(dictionaryType), pocoDestType); @@ -572,10 +572,10 @@ private static bool TryGetCreateEmptyCollectionExpression(CqlColumn dbColumn, Ty } // Handle ISet - if (openGenericType == typeof (ISet<>)) + if (openGenericType == typeof(ISet<>)) { // The driver uses List (?!) but we'll use a sorted set since that's the CQL semantics - Type setType = typeof (SortedSet<>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); + Type setType = typeof(SortedSet<>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); // (ISet) new SortedSet(); createEmptyCollection = Expression.Convert(Expression.New(setType), pocoDestType); @@ -586,7 +586,7 @@ private static bool TryGetCreateEmptyCollectionExpression(CqlColumn dbColumn, Ty if (TypeConverter.ListGenericInterfaces.Contains(openGenericType)) { // The driver uses List so we'll use that as well - Type listType = typeof (List<>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); + Type listType = typeof(List<>).MakeGenericType(pocoDestType.GetTypeInfo().GetGenericArguments()); // (... IList or ICollection or IEnumerable ...) new List(); createEmptyCollection = Expression.Convert(Expression.New(listType), pocoDestType); @@ -611,7 +611,7 @@ private static bool IsCassandraCollection(CqlColumn dbColumn) /// private static bool ImplementsCollectionInterface(Type t) { - return t.GetTypeInfo().GetInterfaces().FirstOrDefault(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof (ICollection<>)) != null; + return t.GetTypeInfo().GetInterfaces().FirstOrDefault(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)) != null; } private static MethodInfo GetMethod(Delegate deleg) diff --git a/src/Cassandra/Mapping/Mappings.cs b/src/Cassandra/Mapping/Mappings.cs index 880179fde..470acf08b 100644 --- a/src/Cassandra/Mapping/Mappings.cs +++ b/src/Cassandra/Mapping/Mappings.cs @@ -46,7 +46,7 @@ public Map For() Definitions.Add(map); } - return (Map) map; + return (Map)map; } } } \ No newline at end of file diff --git a/src/Cassandra/Mapping/PocoDataFactory.cs b/src/Cassandra/Mapping/PocoDataFactory.cs index 58a0079a9..eb7bb1036 100644 --- a/src/Cassandra/Mapping/PocoDataFactory.cs +++ b/src/Cassandra/Mapping/PocoDataFactory.cs @@ -62,7 +62,7 @@ public void AddDefinitionDefault(Type type, Func definitionHand } _cache.GetOrAdd(type, t => CreatePocoData(t, definitionHandler())); } - + private PocoData CreatePocoData(Type pocoType) { // Try to get mapping from predefined collection, otherwise fallback to using attributes diff --git a/src/Cassandra/Mapping/SortOrder.cs b/src/Cassandra/Mapping/SortOrder.cs index 874c2d8b6..0f19b7309 100644 --- a/src/Cassandra/Mapping/SortOrder.cs +++ b/src/Cassandra/Mapping/SortOrder.cs @@ -20,7 +20,7 @@ namespace Cassandra.Mapping /// /// Specifies sort order /// - public enum SortOrder: sbyte + public enum SortOrder : sbyte { Unspecified = 0, Ascending = 1, diff --git a/src/Cassandra/Mapping/Statements/CqlGenerator.cs b/src/Cassandra/Mapping/Statements/CqlGenerator.cs index 1f6d5851c..31fd6f9c4 100644 --- a/src/Cassandra/Mapping/Statements/CqlGenerator.cs +++ b/src/Cassandra/Mapping/Statements/CqlGenerator.cs @@ -71,17 +71,17 @@ public void AddSelect(Cql cql) $"{CqlGenerator.CqlIdentifierHelper.EscapeTableNameIfNecessary(pocoData, pocoData.KeyspaceName, pocoData.TableName)}" + $"{suffix}"); } - + private static Func EscapeFunc(PocoData pocoData) { - Func f = + Func f = c => CqlGenerator.CqlIdentifierHelper.EscapeIdentifierIfNecessary(pocoData, c.ColumnName); return f; } private static Func EscapeFunc(PocoData pocoData, string format) { - Func f = + Func f = c => string.Format(format, CqlGenerator.CqlIdentifierHelper.EscapeIdentifierIfNecessary(pocoData, c.ColumnName)); return f; } @@ -329,7 +329,7 @@ public static List GetCreate(ISerializer serializer, PocoData pocoData, { createTable.Append(", "); createTable.Append(string.Join( - ", ", + ", ", pocoData.ClusteringKeys.Select( k => CqlGenerator.CqlIdentifierHelper.EscapeIdentifierIfNecessary(pocoData, k.Item1.ColumnName)))); } @@ -339,9 +339,9 @@ public static List GetCreate(ISerializer serializer, PocoData pocoData, createTable.Append(")"); var clusteringOrder = string.Join(", ", pocoData.ClusteringKeys .Where(k => k.Item2 != SortOrder.Unspecified) - .Select(k => - CqlGenerator.CqlIdentifierHelper.EscapeIdentifierIfNecessary(pocoData, k.Item1.ColumnName) - + " " + .Select(k => + CqlGenerator.CqlIdentifierHelper.EscapeIdentifierIfNecessary(pocoData, k.Item1.ColumnName) + + " " + (k.Item2 == SortOrder.Ascending ? "ASC" : "DESC"))); var clusteringOrderIsDefined = !string.IsNullOrEmpty(clusteringOrder); diff --git a/src/Cassandra/Mapping/Statements/StatementFactory.cs b/src/Cassandra/Mapping/Statements/StatementFactory.cs index 8b9b699d0..ce7526548 100644 --- a/src/Cassandra/Mapping/Statements/StatementFactory.cs +++ b/src/Cassandra/Mapping/Statements/StatementFactory.cs @@ -82,7 +82,7 @@ public async Task GetStatementAsync(ISession session, Cql cql, bool? // in a new attempt prepareTask = _statementCache.CompareAndUpdate( psCacheKey, - (k, v) => object.ReferenceEquals(v, prepareTask), + (k, v) => object.ReferenceEquals(v, prepareTask), (k, v) => Task.Run(() => session.PrepareAsync(query))); ps = await prepareTask.ConfigureAwait(false); } diff --git a/src/Cassandra/Mapping/TypeConversion/NullableEnumStringMapper.cs b/src/Cassandra/Mapping/TypeConversion/NullableEnumStringMapper.cs index 42743c6d4..b37ea84d2 100644 --- a/src/Cassandra/Mapping/TypeConversion/NullableEnumStringMapper.cs +++ b/src/Cassandra/Mapping/TypeConversion/NullableEnumStringMapper.cs @@ -29,7 +29,7 @@ public static class NullableEnumStringMapper static NullableEnumStringMapper() { - StringToEnumCache = Enum.GetValues(Nullable.GetUnderlyingType(typeof (T))).Cast().ToDictionary(val => val.ToString()); + StringToEnumCache = Enum.GetValues(Nullable.GetUnderlyingType(typeof(T))).Cast().ToDictionary(val => val.ToString()); } /// diff --git a/src/Cassandra/Mapping/TypeConversion/TypeConverter.cs b/src/Cassandra/Mapping/TypeConversion/TypeConverter.cs index 0f1028829..ee2c0317e 100644 --- a/src/Cassandra/Mapping/TypeConversion/TypeConverter.cs +++ b/src/Cassandra/Mapping/TypeConversion/TypeConverter.cs @@ -32,7 +32,7 @@ namespace Cassandra.Mapping.TypeConversion /// public abstract class TypeConverter { - internal static readonly IReadOnlyCollection ListGenericInterfaces = + internal static readonly IReadOnlyCollection ListGenericInterfaces = new ReadOnlyCollection(new HashSet( typeof(List<>) .GetTypeInfo() @@ -43,11 +43,11 @@ public abstract class TypeConverter private const BindingFlags PrivateStatic = BindingFlags.NonPublic | BindingFlags.Static; private const BindingFlags PrivateInstance = BindingFlags.NonPublic | BindingFlags.Instance; - - private static readonly MethodInfo FindFromDbConverterMethod = typeof (TypeConverter).GetTypeInfo() + + private static readonly MethodInfo FindFromDbConverterMethod = typeof(TypeConverter).GetTypeInfo() .GetMethod(nameof(FindFromDbConverter), PrivateInstance); - private static readonly MethodInfo FindToDbConverterMethod = typeof (TypeConverter).GetTypeInfo() + private static readonly MethodInfo FindToDbConverterMethod = typeof(TypeConverter).GetTypeInfo() .GetMethod(nameof(FindToDbConverter), PrivateInstance); private static readonly MethodInfo ConvertToDictionaryMethod = typeof(TypeConverter).GetTypeInfo() @@ -82,15 +82,15 @@ public abstract class TypeConverter private static readonly MethodInfo ConvertIEnumerableToDbTypeMethod = typeof(TypeConverter) .GetTypeInfo().GetMethod(nameof(ConvertIEnumerableToDbType), PrivateInstance); - + private static readonly MethodInfo ConvertIEnumerableToSetDbMethod = typeof(TypeConverter) .GetTypeInfo().GetMethod(nameof(ConvertIEnumerableToSetDb), PrivateInstance); - + private static readonly MethodInfo ConvertIDictionaryToDbTypeMethod = typeof(TypeConverter) .GetTypeInfo().GetMethod(nameof(ConvertIDictionaryToDbType), PrivateInstance); private readonly ConcurrentDictionary, Delegate> _fromDbConverterCache; - private readonly ConcurrentDictionary, Delegate> _toDbConverterCache; + private readonly ConcurrentDictionary, Delegate> _toDbConverterCache; /// /// Creates a new TypeConverter instance. @@ -111,7 +111,7 @@ protected TypeConverter() /// The converted value. internal TDatabase ConvertCqlArgument(TValue value) { - var converter = (Func) GetToDbConverter(typeof (TValue), typeof (TDatabase)); + var converter = (Func)GetToDbConverter(typeof(TValue), typeof(TDatabase)); if (converter == null) { throw new InvalidOperationException( @@ -180,7 +180,7 @@ private Func TryGetFromDbConverter() return ChangeType; } - return (Func) converter; + return (Func)converter; } private TResult ChangeType(TSource a) @@ -190,20 +190,20 @@ private TResult ChangeType(TSource a) return (TResult)(object)a; } catch (Exception ex) - { + { throw new InvalidCastException( $"Specified cast is not valid: from " + $"{(a == null ? $"null ({typeof(TSource)})" : a.GetType().ToString())} to {typeof(TResult)}", ex); } } - + /// /// Gets a Function that can convert a source type value on a POCO to a destination type value for storage in C*. /// internal Delegate GetToDbConverter(Type pocoType, Type dbType) { return _toDbConverterCache.GetOrAdd(Tuple.Create(pocoType, dbType), - _ => (Delegate) FindToDbConverterMethod.MakeGenericMethod(pocoType, dbType).Invoke(this, null)); + _ => (Delegate)FindToDbConverterMethod.MakeGenericMethod(pocoType, dbType).Invoke(this, null)); } /// @@ -221,16 +221,16 @@ private Delegate FindFromDbConverter() if (converter != null) return converter; - Type dbType = typeof (TDatabase); - Type pocoType = typeof (TPoco); + Type dbType = typeof(TDatabase); + Type pocoType = typeof(TPoco); if (pocoType == dbType) { Func func = d => d; return func; } - - if (pocoType.GetTypeInfo().IsGenericType + + if (pocoType.GetTypeInfo().IsGenericType && pocoType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var underlyingType = Nullable.GetUnderlyingType(pocoType); @@ -285,11 +285,11 @@ private Delegate FindFromDbConverter() if (dbType.GetTypeInfo().IsGenericType || dbType.GetInterfaces().Any(i => i.IsGenericType)) { - Type sourceEnumerableInterface = dbType.IsGenericType && dbType.GetGenericTypeDefinition() == typeof(IEnumerable<>) - ? dbType + Type sourceEnumerableInterface = dbType.IsGenericType && dbType.GetGenericTypeDefinition() == typeof(IEnumerable<>) + ? dbType : dbType.GetInterfaces().FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); - Type[] sourceGenericArgs = sourceEnumerableInterface != null + Type[] sourceGenericArgs = sourceEnumerableInterface != null ? sourceEnumerableInterface.GetTypeInfo().GetGenericArguments() : dbType.GetTypeInfo().GetGenericArguments(); if (pocoType.IsArray && sourceEnumerableInterface != null) @@ -302,13 +302,13 @@ private Delegate FindFromDbConverter() { var targetGenericType = pocoType.GetTypeInfo().GetGenericTypeDefinition(); var targetGenericArgs = pocoType.GetTypeInfo().GetGenericArguments(); - - Type sourceDictionaryInterface = dbType.IsGenericType && dbType.GetGenericTypeDefinition() == typeof(IDictionary<,>) - ? dbType + + Type sourceDictionaryInterface = dbType.IsGenericType && dbType.GetGenericTypeDefinition() == typeof(IDictionary<,>) + ? dbType : dbType.GetInterfaces().FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); - - sourceGenericArgs = sourceDictionaryInterface != null + + sourceGenericArgs = sourceDictionaryInterface != null ? sourceDictionaryInterface.GetTypeInfo().GetGenericArguments() : sourceGenericArgs; @@ -351,7 +351,7 @@ private Delegate ConvertFromIDictionary(Type targetGenericType, Type[] sourceGen return ConvertToDictionaryMethod.MakeGenericMethod(sourceGenericArgs).CreateDelegateLocal(); } return ConvertToDictionaryFromDbMethod - .MakeGenericMethod(sourceGenericArgs[0], sourceGenericArgs[1], targetGenericArgs[0], + .MakeGenericMethod(sourceGenericArgs[0], sourceGenericArgs[1], targetGenericArgs[0], targetGenericArgs[1]).CreateDelegateLocal(this); } return null; @@ -425,16 +425,16 @@ private Delegate FindToDbConverter() return converter; } - Type pocoType = typeof (TPoco); - Type dbType = typeof (TDatabase); + Type pocoType = typeof(TPoco); + Type dbType = typeof(TDatabase); if (typeof(TPoco) == typeof(TDatabase)) { Func func = d => d; return func; } - - if (pocoType.GetTypeInfo().IsGenericType + + if (pocoType.GetTypeInfo().IsGenericType && pocoType.GetGenericTypeDefinition() == typeof(Nullable<>) && !dbType.GetTypeInfo().IsValueType) { @@ -451,7 +451,7 @@ private Delegate FindToDbConverter() { if (d != null) { - return (TDatabase) deleg.DynamicInvoke(d); + return (TDatabase)deleg.DynamicInvoke(d); } if (default(TDatabase) != null) @@ -467,7 +467,7 @@ private Delegate FindToDbConverter() } // Support enum/nullable enum => string conversion - if (dbType == typeof (string)) + if (dbType == typeof(string)) { if (pocoType.GetTypeInfo().IsEnum) { @@ -485,31 +485,31 @@ private Delegate FindToDbConverter() if (dbType == typeof(Guid) && pocoType == typeof(TimeUuid)) { Guid TimeUuidConverter(TimeUuid a) => a.ToGuid(); - return (Func) TimeUuidConverter; + return (Func)TimeUuidConverter; } if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(dbType) && dbType.GetTypeInfo().IsGenericType) { Type dbGenericType = dbType.GetTypeInfo().GetGenericTypeDefinition(); Type[] dbTypeGenericArgs = dbType.GetTypeInfo().GetGenericArguments(); Type[] pocoTypeGenericArgs = null; - + if (pocoType.GetTypeInfo().IsArray) { - pocoTypeGenericArgs = new [] { pocoType.GetTypeInfo().GetElementType() }; + pocoTypeGenericArgs = new[] { pocoType.GetTypeInfo().GetElementType() }; } else if (pocoType.GetTypeInfo().IsGenericType) { pocoTypeGenericArgs = pocoType.GetTypeInfo().GetGenericArguments(); } - if (pocoTypeGenericArgs == null - || (dbType.GetTypeInfo().IsAssignableFrom(pocoType) + if (pocoTypeGenericArgs == null + || (dbType.GetTypeInfo().IsAssignableFrom(pocoType) && pocoTypeGenericArgs.SequenceEqual(dbTypeGenericArgs))) { Func changeTypeDelegate = ChangeType; return changeTypeDelegate; } - + if (pocoType.GetTypeInfo().IsArray || dbGenericType == typeof(IEnumerable<>)) { // Its a list or a set but the child types doesn't match @@ -547,7 +547,7 @@ private Func TryFindToDbConverter() return ChangeType; } - + private IEnumerable ConvertIEnumerableToDbType(IEnumerable items) { return items?.Select(TryFindToDbConverter()); @@ -610,7 +610,7 @@ private TDictionaryResult ConvertToSortedDictionaryFromDb { dictionary.Add(keyConverter(kv.Key), valueConverter(kv.Value)); } - return (TDictionaryResult) (object) dictionary; + return (TDictionaryResult)(object)dictionary; } private static HashSet ConvertToHashSet(IEnumerable set) @@ -632,7 +632,7 @@ private HashSet ConvertToHashSetFromDb(IEnumerable(setFromDatabase.Select(TryGetFromDbConverter())); } - + private HashSet ConvertIEnumerableToSetDb(IEnumerable set) { if (set == null) @@ -652,7 +652,7 @@ private static SortedSet ConvertToSortedSet(IEnumerable set) if (set is SortedSet) { - return (SortedSet) set; + return (SortedSet)set; } return new SortedSet(set); } @@ -665,7 +665,7 @@ private TSetResult ConvertToSortedSetFromDb( return default(TSetResult); } - return (TSetResult) (object) new SortedSet( + return (TSetResult)(object)new SortedSet( setFromDatabase.Select(TryGetFromDbConverter())); } @@ -678,7 +678,7 @@ private static List ConvertToList(IEnumerable list) if (list is List) { - return (List) list; + return (List)list; } return new List(list); } @@ -690,10 +690,10 @@ private TListResult ConvertToListFromDb(IEnumerab return default(TListResult); } - return (TListResult) (object) new List( + return (TListResult)(object)new List( itemsDatabase.Select(TryGetFromDbConverter())); } - + private TResult[] ConvertToArrayFromDb(IEnumerable listFromDatabase) { if (listFromDatabase == null) @@ -734,7 +734,7 @@ public static Delegate CreateDelegateLocal(this MethodInfo method, object sender } var delegateType = Expression.GetFuncType( method.GetParameters().Select(p => p.ParameterType) - .Concat(new [] { method.ReturnType }).ToArray()); + .Concat(new[] { method.ReturnType }).ToArray()); return method.CreateDelegate(delegateType, sender); } } diff --git a/src/Cassandra/Mapping/Utils/CqlIdentifierHelper.cs b/src/Cassandra/Mapping/Utils/CqlIdentifierHelper.cs index 06a989972..8e4494b37 100644 --- a/src/Cassandra/Mapping/Utils/CqlIdentifierHelper.cs +++ b/src/Cassandra/Mapping/Utils/CqlIdentifierHelper.cs @@ -31,7 +31,7 @@ public string EscapeIdentifierIfNecessary(IPocoData pocoData, string identifier) return "\"" + identifier + "\""; } - + public string EscapeTableNameIfNecessary(IPocoData pocoData, string keyspace, string table) { string name = null; @@ -43,7 +43,7 @@ public string EscapeTableNameIfNecessary(IPocoData pocoData, string keyspace, st name += EscapeIdentifierIfNecessary(pocoData, table); return name; } - + private static readonly HashSet ReservedKeywords = new HashSet { // See https://github.com/apache/cassandra/blob/trunk/doc/cql3/CQL.textile#appendixA diff --git a/src/Cassandra/Mapping/Utils/EnumerableExtensions.cs b/src/Cassandra/Mapping/Utils/EnumerableExtensions.cs index 071f8cc83..b60ae8a92 100644 --- a/src/Cassandra/Mapping/Utils/EnumerableExtensions.cs +++ b/src/Cassandra/Mapping/Utils/EnumerableExtensions.cs @@ -28,7 +28,7 @@ public static LookupKeyedCollection ToLookupKeyedCollection keySelector) { var keyedCollection = new LookupKeyedCollection(keySelector); - foreach(TValue value in values) + foreach (TValue value in values) keyedCollection.Add(value); return keyedCollection; diff --git a/src/Cassandra/Mapping/Utils/ICqlIdentifierHelper.cs b/src/Cassandra/Mapping/Utils/ICqlIdentifierHelper.cs index 96ddab093..eda18fd1a 100644 --- a/src/Cassandra/Mapping/Utils/ICqlIdentifierHelper.cs +++ b/src/Cassandra/Mapping/Utils/ICqlIdentifierHelper.cs @@ -22,7 +22,7 @@ namespace Cassandra.Mapping.Utils internal interface ICqlIdentifierHelper { string EscapeIdentifierIfNecessary(IPocoData pocoData, string identifier); - + string EscapeTableNameIfNecessary(IPocoData pocoData, string keyspace, string table); } } \ No newline at end of file diff --git a/src/Cassandra/Mapping/Utils/LookupKeyedCollection.cs b/src/Cassandra/Mapping/Utils/LookupKeyedCollection.cs index 09e1afcda..24c8818c4 100644 --- a/src/Cassandra/Mapping/Utils/LookupKeyedCollection.cs +++ b/src/Cassandra/Mapping/Utils/LookupKeyedCollection.cs @@ -33,7 +33,7 @@ public LookupKeyedCollection(Func getKeyFunc) _getKeyFunc = getKeyFunc; } - public LookupKeyedCollection(Func getKeyFunc, IEqualityComparer keyComparer) + public LookupKeyedCollection(Func getKeyFunc, IEqualityComparer keyComparer) : base(keyComparer) { _getKeyFunc = getKeyFunc; diff --git a/src/Cassandra/MaterializedViewMetadata.cs b/src/Cassandra/MaterializedViewMetadata.cs index 23738f2b7..df556f017 100644 --- a/src/Cassandra/MaterializedViewMetadata.cs +++ b/src/Cassandra/MaterializedViewMetadata.cs @@ -28,7 +28,7 @@ public class MaterializedViewMetadata : DataCollectionMetadata protected MaterializedViewMetadata() { - + } internal MaterializedViewMetadata(string name, string whereClause) diff --git a/src/Cassandra/Metadata.cs b/src/Cassandra/Metadata.cs index 63960cae1..cc44745a1 100644 --- a/src/Cassandra/Metadata.cs +++ b/src/Cassandra/Metadata.cs @@ -43,7 +43,7 @@ public class Metadata : IDisposable private volatile ConcurrentDictionary _keyspaces = new ConcurrentDictionary(); private volatile ISchemaParser _schemaParser; private readonly int _queryAbortTimeout; - private volatile CopyOnWriteDictionary> _resolvedContactPoints = + private volatile CopyOnWriteDictionary> _resolvedContactPoints = new CopyOnWriteDictionary>(); public event HostsEventHandler HostsEvent; @@ -614,19 +614,19 @@ internal async Task WaitForSchemaAgreementAsync(IConnection connection) while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds) { var serializer = ControlConnection.Serializer.GetCurrentSerializer(); - var schemaVersionLocalQuery = + var schemaVersionLocalQuery = new QueryRequest( - serializer, - Metadata.SelectSchemaVersionLocal, + serializer, + Metadata.SelectSchemaVersionLocal, QueryProtocolOptions.Default, - false, + false, null); - var schemaVersionPeersQuery = + var schemaVersionPeersQuery = new QueryRequest( - serializer, - Metadata.SelectSchemaVersionPeers, + serializer, + Metadata.SelectSchemaVersionPeers, QueryProtocolOptions.Default, - false, + false, null); var queries = new[] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) }; // ReSharper disable once CoVariantArrayConversion diff --git a/src/Cassandra/MetadataHelpers/DatacenterReplicationFactor.cs b/src/Cassandra/MetadataHelpers/DatacenterReplicationFactor.cs index 8b6cde97d..1259f1009 100644 --- a/src/Cassandra/MetadataHelpers/DatacenterReplicationFactor.cs +++ b/src/Cassandra/MetadataHelpers/DatacenterReplicationFactor.cs @@ -32,7 +32,7 @@ public DatacenterReplicationFactor(string datacenter, ReplicationFactor replicat public string Datacenter { get; } public ReplicationFactor ReplicationFactor { get; } - + public override bool Equals(object obj) { if (obj == null) @@ -40,7 +40,7 @@ public override bool Equals(object obj) return false; } - return obj.GetType() == GetType() + return obj.GetType() == GetType() && Equals((DatacenterReplicationFactor)obj); } @@ -63,7 +63,7 @@ private static int ComputeHashCode(string datacenter, ReplicationFactor replicat public int CompareTo(DatacenterReplicationFactor other) { var dcComparison = string.Compare(Datacenter, other.Datacenter, StringComparison.Ordinal); - return dcComparison != 0 + return dcComparison != 0 ? dcComparison : ReplicationFactor.CompareTo(other.ReplicationFactor); } diff --git a/src/Cassandra/MetadataHelpers/EverywhereStrategy.cs b/src/Cassandra/MetadataHelpers/EverywhereStrategy.cs index 850472ed9..c82687f2a 100644 --- a/src/Cassandra/MetadataHelpers/EverywhereStrategy.cs +++ b/src/Cassandra/MetadataHelpers/EverywhereStrategy.cs @@ -31,7 +31,7 @@ private EverywhereStrategy() public static IReplicationStrategy Instance { get; } = new EverywhereStrategy(); public Dictionary> ComputeTokenToReplicaMap( - IReadOnlyList ring, + IReadOnlyList ring, IReadOnlyDictionary primaryReplicas, int numberOfHostsWithTokens, IReadOnlyDictionary datacenters) diff --git a/src/Cassandra/MetadataHelpers/IReplicationStrategy.cs b/src/Cassandra/MetadataHelpers/IReplicationStrategy.cs index 12fc255b1..147e8dc33 100644 --- a/src/Cassandra/MetadataHelpers/IReplicationStrategy.cs +++ b/src/Cassandra/MetadataHelpers/IReplicationStrategy.cs @@ -22,7 +22,7 @@ namespace Cassandra.MetadataHelpers internal interface IReplicationStrategy : IEquatable { Dictionary> ComputeTokenToReplicaMap( - IReadOnlyList ring, + IReadOnlyList ring, IReadOnlyDictionary primaryReplicas, int numberOfHostsWithTokens, IReadOnlyDictionary datacenters); diff --git a/src/Cassandra/MetadataHelpers/IReplicationStrategyFactory.cs b/src/Cassandra/MetadataHelpers/IReplicationStrategyFactory.cs index 47b85f576..cedd05549 100644 --- a/src/Cassandra/MetadataHelpers/IReplicationStrategyFactory.cs +++ b/src/Cassandra/MetadataHelpers/IReplicationStrategyFactory.cs @@ -21,7 +21,7 @@ namespace Cassandra.MetadataHelpers internal interface IReplicationStrategyFactory { IReplicationStrategy Create( - string strategyClass, + string strategyClass, IReadOnlyDictionary replicationOptions); } } \ No newline at end of file diff --git a/src/Cassandra/MetadataHelpers/LocalStrategy.cs b/src/Cassandra/MetadataHelpers/LocalStrategy.cs index e0500ba3d..ff0b38c5f 100644 --- a/src/Cassandra/MetadataHelpers/LocalStrategy.cs +++ b/src/Cassandra/MetadataHelpers/LocalStrategy.cs @@ -31,7 +31,7 @@ private LocalStrategy() public static IReplicationStrategy Instance { get; } = new LocalStrategy(); public Dictionary> ComputeTokenToReplicaMap( - IReadOnlyList ring, + IReadOnlyList ring, IReadOnlyDictionary primaryReplicas, int numberOfHostsWithTokens, IReadOnlyDictionary datacenters) diff --git a/src/Cassandra/MetadataHelpers/NetworkTopologyStrategy.cs b/src/Cassandra/MetadataHelpers/NetworkTopologyStrategy.cs index dcf29b895..5a2b8da79 100644 --- a/src/Cassandra/MetadataHelpers/NetworkTopologyStrategy.cs +++ b/src/Cassandra/MetadataHelpers/NetworkTopologyStrategy.cs @@ -85,9 +85,9 @@ private Dictionary> ComputeTokenToReplicaNetwork( } private ISet ComputeReplicasForToken( - IReadOnlyList ring, - IReadOnlyDictionary primaryReplicas, - IReadOnlyDictionary datacenters, + IReadOnlyList ring, + IReadOnlyDictionary primaryReplicas, + IReadOnlyDictionary datacenters, int i) { var context = new NetworkTopologyTokenMapContext(ring, primaryReplicas, datacenters); diff --git a/src/Cassandra/MetadataHelpers/NetworkTopologyTokenMapContext.cs b/src/Cassandra/MetadataHelpers/NetworkTopologyTokenMapContext.cs index 15225c922..fe9615e38 100644 --- a/src/Cassandra/MetadataHelpers/NetworkTopologyTokenMapContext.cs +++ b/src/Cassandra/MetadataHelpers/NetworkTopologyTokenMapContext.cs @@ -22,8 +22,8 @@ namespace Cassandra.MetadataHelpers internal struct NetworkTopologyTokenMapContext { public NetworkTopologyTokenMapContext( - IReadOnlyList ring, - IReadOnlyDictionary primaryReplicas, + IReadOnlyList ring, + IReadOnlyDictionary primaryReplicas, IReadOnlyDictionary datacenters) { Ring = ring; diff --git a/src/Cassandra/MetadataHelpers/ReplicationFactor.cs b/src/Cassandra/MetadataHelpers/ReplicationFactor.cs index 5a4b94f84..ff86dcafb 100644 --- a/src/Cassandra/MetadataHelpers/ReplicationFactor.cs +++ b/src/Cassandra/MetadataHelpers/ReplicationFactor.cs @@ -56,7 +56,7 @@ public static ReplicationFactor Parse(string rf) var transientPart = rf.Substring(slashIndex + 1); var parsedAllPart = ReplicationFactor.ParseNumberOfReplicas(allPart); var parsedTransientPart = ReplicationFactor.ParseNumberOfReplicas(transientPart); - + return new ReplicationFactor(parsedAllPart, parsedTransientPart); } @@ -82,7 +82,7 @@ public bool Equals(ReplicationFactor other) return true; } - return AllReplicas == other.AllReplicas + return AllReplicas == other.AllReplicas && TransientReplicas == other.TransientReplicas; } @@ -109,8 +109,8 @@ public int CompareTo(ReplicationFactor other) } var allReplicasComparison = AllReplicas.CompareTo(other.AllReplicas); - return allReplicasComparison != 0 - ? allReplicasComparison + return allReplicasComparison != 0 + ? allReplicasComparison : TransientReplicas.CompareTo(other.TransientReplicas); } } diff --git a/src/Cassandra/MetadataHelpers/ReplicationStrategyFactory.cs b/src/Cassandra/MetadataHelpers/ReplicationStrategyFactory.cs index 688474902..2a3aa8b5c 100644 --- a/src/Cassandra/MetadataHelpers/ReplicationStrategyFactory.cs +++ b/src/Cassandra/MetadataHelpers/ReplicationStrategyFactory.cs @@ -43,17 +43,17 @@ public IReplicationStrategy Create( : null; } - if (strategyClass.Equals(ReplicationStrategies.NetworkTopologyStrategy, StringComparison.OrdinalIgnoreCase)) + if (strategyClass.Equals(ReplicationStrategies.NetworkTopologyStrategy, StringComparison.OrdinalIgnoreCase)) { return new NetworkTopologyStrategy(replicationOptions); } - if (strategyClass.Equals(ReplicationStrategies.LocalStrategy, StringComparison.OrdinalIgnoreCase)) + if (strategyClass.Equals(ReplicationStrategies.LocalStrategy, StringComparison.OrdinalIgnoreCase)) { return LocalStrategy.Instance; } - if (strategyClass.Equals(ReplicationStrategies.EverywhereStrategy, StringComparison.OrdinalIgnoreCase)) + if (strategyClass.Equals(ReplicationStrategies.EverywhereStrategy, StringComparison.OrdinalIgnoreCase)) { return EverywhereStrategy.Instance; } diff --git a/src/Cassandra/MetadataHelpers/SimpleStrategy.cs b/src/Cassandra/MetadataHelpers/SimpleStrategy.cs index f4ed78298..3516e74b9 100644 --- a/src/Cassandra/MetadataHelpers/SimpleStrategy.cs +++ b/src/Cassandra/MetadataHelpers/SimpleStrategy.cs @@ -29,7 +29,7 @@ public SimpleStrategy(ReplicationFactor replicationFactor) } public Dictionary> ComputeTokenToReplicaMap( - IReadOnlyList ring, + IReadOnlyList ring, IReadOnlyDictionary primaryReplicas, int numberOfHostsWithTokens, IReadOnlyDictionary datacenters) @@ -49,7 +49,7 @@ public override bool Equals(object obj) public bool Equals(SimpleStrategy other) { - return other != null + return other != null && _replicationFactor.Equals(other._replicationFactor); } @@ -62,8 +62,8 @@ public override int GetHashCode() /// Converts token-primary to token-replicas /// private Dictionary> ComputeTokenToReplicaSimple( - int numberOfHostsWithTokens, - IReadOnlyList ring, + int numberOfHostsWithTokens, + IReadOnlyList ring, IReadOnlyDictionary primaryReplicas) { var rf = Math.Min(_replicationFactor.FullReplicas, numberOfHostsWithTokens); @@ -77,12 +77,12 @@ private Dictionary> ComputeTokenToReplicaSimple( // circle back if necessary var nextReplicaIndex = (i + j) % ring.Count; var nextReplica = primaryReplicas[ring[nextReplicaIndex]]; - + // not necessary to check if already added this replica, // because it's an HashSet and Equals + GetHashCode are overriden in Host class replicas.Add(nextReplica); } - + tokenToReplicas.Add(token, replicas); } return tokenToReplicas; diff --git a/src/Cassandra/MetadataSyncOptions.cs b/src/Cassandra/MetadataSyncOptions.cs index 12fe7b130..5244571a8 100644 --- a/src/Cassandra/MetadataSyncOptions.cs +++ b/src/Cassandra/MetadataSyncOptions.cs @@ -33,13 +33,13 @@ public class MetadataSyncOptions /// Also check the api reference for for a more thorough explanation. /// public long RefreshSchemaDelayIncrement { get; private set; } = 1000; - + /// /// Use to set this value. The default value is 10000. /// Also check the api reference for for a more thorough explanation. /// public long MaxTotalRefreshSchemaDelay { get; private set; } = 10000; - + /// /// /// The default value is true. @@ -54,7 +54,7 @@ public MetadataSyncOptions SetMetadataSyncEnabled(bool metadataSyncEnabled) MetadataSyncEnabled = metadataSyncEnabled; return this; } - + /// /// /// The default value is 1000. @@ -72,7 +72,7 @@ public MetadataSyncOptions SetRefreshSchemaDelayIncrement(long refreshSchemaDela RefreshSchemaDelayIncrement = refreshSchemaDelayIncrement; return this; } - + /// /// /// The default value is 10000. diff --git a/src/Cassandra/Metrics/Abstractions/IDriverCounter.cs b/src/Cassandra/Metrics/Abstractions/IDriverCounter.cs index 8f5eb5a4f..75a7a9e4a 100644 --- a/src/Cassandra/Metrics/Abstractions/IDriverCounter.cs +++ b/src/Cassandra/Metrics/Abstractions/IDriverCounter.cs @@ -22,7 +22,7 @@ namespace Cassandra.Metrics.Abstractions public interface IDriverCounter : IDriverMetric { void Increment(); - + void Increment(long value); } } \ No newline at end of file diff --git a/src/Cassandra/Metrics/Abstractions/IDriverMetricsProvider.cs b/src/Cassandra/Metrics/Abstractions/IDriverMetricsProvider.cs index bb89b10f5..76d276331 100644 --- a/src/Cassandra/Metrics/Abstractions/IDriverMetricsProvider.cs +++ b/src/Cassandra/Metrics/Abstractions/IDriverMetricsProvider.cs @@ -29,28 +29,28 @@ public interface IDriverMetricsProvider /// Implementations can call to test if is a particular or . /// IDriverTimer Timer(string bucket, IMetric metric); - + /// /// Creates a meter metric. will contain the prefix configured with , /// session name and node's address. Node's address will only be in the bucket name when is a . /// Implementations can call to test if is a particular or . /// IDriverMeter Meter(string bucket, IMetric metric); - + /// /// Creates a counter metric. will contain the prefix configured with , /// session name and node's address. Node's address will only be in the bucket name when is a . /// Implementations can call to test if is a particular or . /// IDriverCounter Counter(string bucket, IMetric metric); - + /// /// Creates a gauge metric. will contain the prefix configured with , /// session name and node's address. Node's address will only be in the bucket name when is a . /// Implementations can call to test if is a particular or . /// IDriverGauge Gauge(string bucket, IMetric metric, Func valueProvider); - + /// /// Shutdowns/Disposes metrics created with the provided . This is especially useful to stop gauges which are supposed to run on a loop. /// diff --git a/src/Cassandra/Metrics/DriverMetricsOptions.cs b/src/Cassandra/Metrics/DriverMetricsOptions.cs index 542f3a0c7..e9bed0538 100644 --- a/src/Cassandra/Metrics/DriverMetricsOptions.cs +++ b/src/Cassandra/Metrics/DriverMetricsOptions.cs @@ -34,7 +34,7 @@ public class DriverMetricsOptions /// See for more information. Defaults to . /// public IEnumerable EnabledSessionMetrics { get; private set; } = SessionMetric.DefaultSessionMetrics; - + /// /// See for more information. /// @@ -46,7 +46,7 @@ public class DriverMetricsOptions public DriverMetricsOptions() { } - + /// /// Enables specific node metrics. The available node metrics can be found as static readonly properties in /// the class, e.g., . @@ -59,7 +59,7 @@ public DriverMetricsOptions SetEnabledNodeMetrics(IEnumerable enable EnabledNodeMetrics = enabledNodeMetrics; return this; } - + /// /// Enables specific session metrics. The available session metrics can be found as static readonly properties in /// the class, e.g., . diff --git a/src/Cassandra/Metrics/IDriverMetrics.cs b/src/Cassandra/Metrics/IDriverMetrics.cs index 28a4632ab..ab5be0775 100644 --- a/src/Cassandra/Metrics/IDriverMetrics.cs +++ b/src/Cassandra/Metrics/IDriverMetrics.cs @@ -29,7 +29,7 @@ public interface IDriverMetrics /// Exposes session metrics for the session from which this instance was retrieved. See . /// IMetricsRegistry SessionMetrics { get; } - + /// /// Exposes node metrics for the hosts used in requests executed by the session /// from which this instance was retrieved. See . @@ -42,7 +42,7 @@ public interface IDriverMetrics /// /// This exception is thrown if the metric object can not be cast to . TMetricType GetNodeMetric(Host host, NodeMetric nodeMetric) where TMetricType : class, IDriverMetric; - + /// /// Gets a specific session metric. can be any type in the /// inheritance tree of the metric object returned by the . diff --git a/src/Cassandra/Metrics/IMetricsRegistry.cs b/src/Cassandra/Metrics/IMetricsRegistry.cs index 93e8bc292..2032fae46 100644 --- a/src/Cassandra/Metrics/IMetricsRegistry.cs +++ b/src/Cassandra/Metrics/IMetricsRegistry.cs @@ -30,12 +30,12 @@ public interface IMetricsRegistry where TMetric : IMetric /// Dictionary with counter metrics. /// IReadOnlyDictionary Counters { get; } - + /// /// Dictionary with gauge metrics. /// IReadOnlyDictionary Gauges { get; } - + /// /// Dictionary with meter metrics. /// diff --git a/src/Cassandra/Metrics/Internal/IMetricsManager.cs b/src/Cassandra/Metrics/Internal/IMetricsManager.cs index fd66d0b95..1591817a4 100644 --- a/src/Cassandra/Metrics/Internal/IMetricsManager.cs +++ b/src/Cassandra/Metrics/Internal/IMetricsManager.cs @@ -47,7 +47,7 @@ internal interface IMetricsManager : IDriverMetrics, IDisposable /// Whether SessionMetrics of type Timer are enabled. /// bool AreSessionTimerMetricsEnabled { get; } - + /// /// Whether NodeMetrics of type Timer are enabled. /// diff --git a/src/Cassandra/Metrics/Internal/MetricsManager.cs b/src/Cassandra/Metrics/Internal/MetricsManager.cs index 704a669b2..45f8ed648 100644 --- a/src/Cassandra/Metrics/Internal/MetricsManager.cs +++ b/src/Cassandra/Metrics/Internal/MetricsManager.cs @@ -56,10 +56,10 @@ public MetricsManager(IDriverMetricsProvider driverMetricsProvider, DriverMetric /// public IMetricsRegistry SessionMetrics => _sessionMetrics.MetricsRegistry; - + /// public IReadOnlyDictionary> NodeMetrics => _nodeMetricsRegistryCollection; - + /// public bool AreMetricsEnabled => _metricsEnabled; @@ -124,10 +124,10 @@ public void RemoveNodeMetrics(Host host) /// public bool AreSessionTimerMetricsEnabled => !_disabledSessionTimerMetrics; - + /// public bool AreNodeTimerMetricsEnabled => !_disabledNodeTimerMetrics; - + /// public ISessionMetrics GetSessionMetrics() { diff --git a/src/Cassandra/Metrics/NodeMetric.cs b/src/Cassandra/Metrics/NodeMetric.cs index 3c08d94fc..49693cc7e 100644 --- a/src/Cassandra/Metrics/NodeMetric.cs +++ b/src/Cassandra/Metrics/NodeMetric.cs @@ -34,7 +34,7 @@ static NodeMetric() Gauges.OpenConnections, Gauges.InFlight, - + Counters.SpeculativeExecutions, Counters.AuthenticationErrors, Counters.ConnectionInitErrors, @@ -59,7 +59,7 @@ static NodeMetric() Counters.IgnoresOnWriteTimeout, Counters.Ignores }; - + NodeMetric.AllNodeMetrics = NodeMetric.DefaultNodeMetrics.Union(new[] { NodeMetric.Timers.CqlMessages }).ToList(); } @@ -137,22 +137,22 @@ public static class Counters /// Connection authentication errors. /// public static readonly NodeMetric AuthenticationErrors = new NodeMetric("errors.connection.auth"); - + /// /// Retried attempts on read timeouts due to the retry policy. /// public static readonly NodeMetric RetriesOnReadTimeout = new NodeMetric("retries.read-timeout"); - + /// /// Retried attempts on write timeouts due to the retry policy. /// public static readonly NodeMetric RetriesOnWriteTimeout = new NodeMetric("retries.write-timeout"); - + /// /// Retried attempts on unavailable errors due to the retry policy. /// public static readonly NodeMetric RetriesOnUnavailable = new NodeMetric("retries.unavailable"); - + /// /// Retried attempts on errors other than read timeouts, write timeouts and unavailable errors due to the retry policy. /// @@ -162,62 +162,62 @@ public static class Counters /// Total retry attempts due to the retry policy. /// public static readonly NodeMetric Retries = new NodeMetric("retries.total"); - + /// /// Ignored read timeouts due to the retry policy. /// public static readonly NodeMetric IgnoresOnReadTimeout = new NodeMetric("ignores.read-timeout"); - + /// /// Ignored write timeouts due to the retry policy. /// public static readonly NodeMetric IgnoresOnWriteTimeout = new NodeMetric("ignores.write-timeout"); - + /// /// Ignored unavailable errors due to the retry policy. /// public static readonly NodeMetric IgnoresOnUnavailable = new NodeMetric("ignores.unavailable"); - + /// /// Ignored errors other than read timeouts, write timeouts and unavailable errors due to the retry policy. /// public static readonly NodeMetric IgnoresOnOtherError = new NodeMetric("ignores.other"); - + /// /// Total ignored errors due to the retry policy. /// public static readonly NodeMetric Ignores = new NodeMetric("ignores.total"); - + /// /// Number of server side read timeout errors. /// public static readonly NodeMetric ReadTimeouts = new NodeMetric("errors.request.read-timeouts"); - + /// /// Number of server side write timeout errors. /// public static readonly NodeMetric WriteTimeouts = new NodeMetric("errors.request.write-timeouts"); - + /// /// Number of server side unavailable errors. /// public static readonly NodeMetric UnavailableErrors = new NodeMetric("errors.request.unavailables"); - + /// /// Number of server side errors other than Unavailable, ReadTimeout or WriteTimeout. /// public static readonly NodeMetric OtherErrors = new NodeMetric("errors.request.others"); - + /// /// Number of failed requests without a server response. /// public static readonly NodeMetric AbortedRequests = new NodeMetric("errors.request.aborted"); - + /// /// Number of requests that failed before being sent to the server. /// public static readonly NodeMetric UnsentRequests = new NodeMetric("errors.request.unsent"); - + /// /// Number of failed requests due to socket timeout. /// @@ -251,7 +251,7 @@ public static class Meters /// Meter that tracks the number/rate of bytes sent. /// public static readonly NodeMetric BytesSent = new NodeMetric("bytes-sent"); - + /// /// Meter that tracks the number/rate of bytes received. /// diff --git a/src/Cassandra/Metrics/Providers/Null/NullDriverCounter.cs b/src/Cassandra/Metrics/Providers/Null/NullDriverCounter.cs index 70808e5b1..cf53f17a0 100644 --- a/src/Cassandra/Metrics/Providers/Null/NullDriverCounter.cs +++ b/src/Cassandra/Metrics/Providers/Null/NullDriverCounter.cs @@ -25,11 +25,11 @@ internal class NullDriverCounter : IDriverCounter private NullDriverCounter() { } - + public void Increment(long value) { } - + public void Increment() { } diff --git a/src/Cassandra/Metrics/Providers/Null/NullDriverMeter.cs b/src/Cassandra/Metrics/Providers/Null/NullDriverMeter.cs index 933c4d707..94f3ceab9 100644 --- a/src/Cassandra/Metrics/Providers/Null/NullDriverMeter.cs +++ b/src/Cassandra/Metrics/Providers/Null/NullDriverMeter.cs @@ -25,7 +25,7 @@ internal class NullDriverMeter : IDriverMeter private NullDriverMeter() { } - + public void Mark(long amount) { } diff --git a/src/Cassandra/Metrics/Providers/Null/NullDriverMetricsProvider.cs b/src/Cassandra/Metrics/Providers/Null/NullDriverMetricsProvider.cs index 3d46f5e1e..c3d1f9706 100644 --- a/src/Cassandra/Metrics/Providers/Null/NullDriverMetricsProvider.cs +++ b/src/Cassandra/Metrics/Providers/Null/NullDriverMetricsProvider.cs @@ -26,7 +26,7 @@ public IDriverTimer Timer(string bucket, IMetric metric) { return NullDriverTimer.Instance; } - + public IDriverMeter Meter(string bucket, IMetric metric) { return NullDriverMeter.Instance; diff --git a/src/Cassandra/Metrics/Providers/Null/NullDriverTimer.cs b/src/Cassandra/Metrics/Providers/Null/NullDriverTimer.cs index 6b12b612c..2d35920bc 100644 --- a/src/Cassandra/Metrics/Providers/Null/NullDriverTimer.cs +++ b/src/Cassandra/Metrics/Providers/Null/NullDriverTimer.cs @@ -26,7 +26,7 @@ internal class NullDriverTimer : IDriverTimer private NullDriverTimer() { } - + public void Record(long elapsedNanoseconds) { } diff --git a/src/Cassandra/Metrics/Registries/IInternalMetricsRegistry.cs b/src/Cassandra/Metrics/Registries/IInternalMetricsRegistry.cs index 2bd295ba5..8349320a3 100644 --- a/src/Cassandra/Metrics/Registries/IInternalMetricsRegistry.cs +++ b/src/Cassandra/Metrics/Registries/IInternalMetricsRegistry.cs @@ -27,7 +27,7 @@ namespace Cassandra.Metrics.Registries internal interface IInternalMetricsRegistry : IMetricsRegistry where TMetric : IMetric { IDriverTimer Timer(string bucket, TMetric metric); - + IDriverMeter Meter(string bucket, TMetric metric); IDriverCounter Counter(string bucket, TMetric metric); diff --git a/src/Cassandra/Metrics/Registries/INodeMetrics.cs b/src/Cassandra/Metrics/Registries/INodeMetrics.cs index 1a8764f2b..d5d8d1ebe 100644 --- a/src/Cassandra/Metrics/Registries/INodeMetrics.cs +++ b/src/Cassandra/Metrics/Registries/INodeMetrics.cs @@ -35,7 +35,7 @@ internal interface INodeMetrics : IDisposable IDriverTimer CqlMessages { get; } IDriverGauge OpenConnections { get; } - + IDriverGauge InFlight { get; } IRequestErrorMetrics Errors { get; } diff --git a/src/Cassandra/Metrics/Registries/ISessionMetrics.cs b/src/Cassandra/Metrics/Registries/ISessionMetrics.cs index a14934d4f..f8f520bac 100644 --- a/src/Cassandra/Metrics/Registries/ISessionMetrics.cs +++ b/src/Cassandra/Metrics/Registries/ISessionMetrics.cs @@ -35,7 +35,7 @@ internal interface ISessionMetrics : IDisposable IDriverMeter BytesReceived { get; } IDriverGauge ConnectedNodes { get; } - + /// /// Internal MetricsRegistry used to create metrics internally. /// diff --git a/src/Cassandra/Metrics/Registries/InternalMetricsRegistry.cs b/src/Cassandra/Metrics/Registries/InternalMetricsRegistry.cs index 1d202e64c..63edda85a 100644 --- a/src/Cassandra/Metrics/Registries/InternalMetricsRegistry.cs +++ b/src/Cassandra/Metrics/Registries/InternalMetricsRegistry.cs @@ -50,7 +50,7 @@ public InternalMetricsRegistry(IDriverMetricsProvider driverMetricsProvider, IEn /// public IReadOnlyDictionary Gauges => _gauges; - + /// public IReadOnlyDictionary Meters => _meters; @@ -73,7 +73,7 @@ public IDriverTimer Timer(string bucket, TMetric metric) _metrics.Add(metric, timer); return timer; } - + public IDriverMeter Meter(string bucket, TMetric metric) { ThrowIfInitialized(); diff --git a/src/Cassandra/Metrics/Registries/NodeMetrics.cs b/src/Cassandra/Metrics/Registries/NodeMetrics.cs index 32446736f..d66b423ca 100644 --- a/src/Cassandra/Metrics/Registries/NodeMetrics.cs +++ b/src/Cassandra/Metrics/Registries/NodeMetrics.cs @@ -77,7 +77,7 @@ private void InitializeMetrics() OpenConnections = MetricsRegistry.Gauge( _bucketName, NodeMetric.Gauges.OpenConnections, () => _hostConnectionPool?.OpenConnections); - + InFlight = MetricsRegistry.Gauge( _bucketName, NodeMetric.Gauges.InFlight, () => _hostConnectionPool?.InFlight); diff --git a/src/Cassandra/Metrics/SessionMetric.cs b/src/Cassandra/Metrics/SessionMetric.cs index bfd779606..851bd057c 100644 --- a/src/Cassandra/Metrics/SessionMetric.cs +++ b/src/Cassandra/Metrics/SessionMetric.cs @@ -36,7 +36,7 @@ static SessionMetric() Gauges.ConnectedNodes }; - + SessionMetric.AllSessionMetrics = SessionMetric.DefaultSessionMetrics.Union(new[] { SessionMetric.Timers.CqlRequests }).ToList(); } @@ -88,7 +88,7 @@ private bool StrictEqualsNotNull(SessionMetric other) { return string.Equals(Name, other.Name); } - + /// /// A collection with all session metrics including Timers. /// @@ -113,7 +113,7 @@ public static class Meters /// Tracks the number/rate of bytes sent. /// public static readonly SessionMetric BytesSent = new SessionMetric("bytes-sent"); - + /// /// Tracks the number/rate of bytes received. /// diff --git a/src/Cassandra/MonitorReportingOptions.cs b/src/Cassandra/MonitorReportingOptions.cs index 59a195bc6..c571c3551 100644 --- a/src/Cassandra/MonitorReportingOptions.cs +++ b/src/Cassandra/MonitorReportingOptions.cs @@ -26,14 +26,14 @@ public sealed class MonitorReportingOptions internal const long DefaultStatusEventDelayMilliseconds = 300000L; internal const bool DefaultMonitorReportingEnabled = true; - + internal long StatusEventDelayMilliseconds { get; private set; } = MonitorReportingOptions.DefaultStatusEventDelayMilliseconds; /// /// This property is used to determine whether Monitor Reporting is enabled or not. /// public bool MonitorReportingEnabled { get; private set; } = MonitorReportingOptions.DefaultMonitorReportingEnabled; - + /// /// Determines whether or not events are sent to the connected cluster for monitor reporting. /// @@ -50,6 +50,6 @@ internal MonitorReportingOptions SetStatusEventDelayMilliseconds(long delay) { StatusEventDelayMilliseconds = delay; return this; - } + } } } \ No newline at end of file diff --git a/src/Cassandra/NoneAuthProvider.cs b/src/Cassandra/NoneAuthProvider.cs index d14adc15a..35c69f11a 100644 --- a/src/Cassandra/NoneAuthProvider.cs +++ b/src/Cassandra/NoneAuthProvider.cs @@ -31,7 +31,7 @@ public class NoneAuthProvider : IAuthProviderNamed public IAuthenticator NewAuthenticator(IPEndPoint host) { - if (_name == NoneAuthProvider.DseAuthenticator) + if (_name == NoneAuthProvider.DseAuthenticator) { // Try to use transitional mode return new TransitionalModePlainTextAuthenticator(); @@ -53,7 +53,8 @@ public void SetName(string name) /// would still send an AUTHENTICATE response. This Authenticator handles this situation /// by sending back a dummy credential. /// - private class TransitionalModePlainTextAuthenticator : PlainTextAuthProvider.PlainTextAuthenticator { + private class TransitionalModePlainTextAuthenticator : PlainTextAuthProvider.PlainTextAuthenticator + { public TransitionalModePlainTextAuthenticator() : base(string.Empty, string.Empty) { diff --git a/src/Cassandra/NullTypeAdapter.cs b/src/Cassandra/NullTypeAdapter.cs index 77c1af67e..247650e4e 100644 --- a/src/Cassandra/NullTypeAdapter.cs +++ b/src/Cassandra/NullTypeAdapter.cs @@ -23,7 +23,7 @@ public class NullTypeAdapter : ITypeAdapter { public Type GetDataType() { - return typeof (byte[]); + return typeof(byte[]); } public object ConvertFrom(byte[] decimalBuf) @@ -34,7 +34,7 @@ public object ConvertFrom(byte[] decimalBuf) public byte[] ConvertTo(object value) { TypeSerializer.CheckArgument(value); - return (byte[]) value; + return (byte[])value; } } } \ No newline at end of file diff --git a/src/Cassandra/Observers/Composite/CompositeRequestObserver.cs b/src/Cassandra/Observers/Composite/CompositeRequestObserver.cs index 3b890cfc5..140a89871 100644 --- a/src/Cassandra/Observers/Composite/CompositeRequestObserver.cs +++ b/src/Cassandra/Observers/Composite/CompositeRequestObserver.cs @@ -36,7 +36,7 @@ public CompositeRequestObserver(IRequestObserver o1, IRequestObserver o2) public async Task OnNodeRequestErrorAsync( RequestErrorType errorType, RetryDecision.RetryDecisionType decision, - SessionRequestInfo r, + SessionRequestInfo r, NodeRequestInfo nodeRequestInfo, Exception ex) { diff --git a/src/Cassandra/Observers/RequestTracker/RequestTrackerObserver.cs b/src/Cassandra/Observers/RequestTracker/RequestTrackerObserver.cs index 95468a5bc..fcebf6628 100644 --- a/src/Cassandra/Observers/RequestTracker/RequestTrackerObserver.cs +++ b/src/Cassandra/Observers/RequestTracker/RequestTrackerObserver.cs @@ -34,7 +34,7 @@ public RequestTrackerObserver(IRequestTracker requestTracker) public Task OnNodeRequestErrorAsync( RequestErrorType errorType, RetryDecision.RetryDecisionType decision, - SessionRequestInfo r, + SessionRequestInfo r, NodeRequestInfo nodeRequestInfo, Exception ex) { diff --git a/src/Cassandra/Outputs/OutputPrepared.cs b/src/Cassandra/Outputs/OutputPrepared.cs index 0d1f93a59..f4cc45210 100644 --- a/src/Cassandra/Outputs/OutputPrepared.cs +++ b/src/Cassandra/Outputs/OutputPrepared.cs @@ -41,7 +41,7 @@ internal OutputPrepared(ProtocolVersion protocolVersion, FrameReader reader) VariablesRowsMetadata = new RowSetMetadata(reader, protocolVersion.SupportsPreparedPartitionKey()); ResultRowsMetadata = new RowSetMetadata(reader, false); } - + // for testing internal OutputPrepared(byte[] queryId, RowSetMetadata rowSetVariablesRowsMetadata, RowSetMetadata resultRowsMetadata) { diff --git a/src/Cassandra/Outputs/OutputReadTimeout.cs b/src/Cassandra/Outputs/OutputReadTimeout.cs index d5cb8b78a..b17546bb0 100644 --- a/src/Cassandra/Outputs/OutputReadTimeout.cs +++ b/src/Cassandra/Outputs/OutputReadTimeout.cs @@ -40,7 +40,7 @@ internal OutputReadTimeout(bool isFailure) protected override void Load(FrameReader reader) { - _consistency = (ConsistencyLevel) reader.ReadInt16(); + _consistency = (ConsistencyLevel)reader.ReadInt16(); _received = reader.ReadInt32(); _blockFor = reader.ReadInt32(); diff --git a/src/Cassandra/Outputs/OutputRows.cs b/src/Cassandra/Outputs/OutputRows.cs index b96532cf6..edf78e3d5 100644 --- a/src/Cassandra/Outputs/OutputRows.cs +++ b/src/Cassandra/Outputs/OutputRows.cs @@ -33,7 +33,7 @@ internal class OutputRows : IOutput public RowSet RowSet { get; set; } public Guid? TraceId { get; private set; } - + public RowSetMetadata ResultRowsMetadata { get; } internal OutputRows(FrameReader reader, ResultMetadata resultMetadata, Guid? traceId) diff --git a/src/Cassandra/Outputs/OutputUnavailableException.cs b/src/Cassandra/Outputs/OutputUnavailableException.cs index 9dda1f54f..5741b25a5 100644 --- a/src/Cassandra/Outputs/OutputUnavailableException.cs +++ b/src/Cassandra/Outputs/OutputUnavailableException.cs @@ -24,7 +24,7 @@ internal class OutputUnavailableException : OutputError protected override void Load(FrameReader cb) { - _consistency = (ConsistencyLevel) cb.ReadInt16(); + _consistency = (ConsistencyLevel)cb.ReadInt16(); _required = cb.ReadInt32(); _alive = cb.ReadInt32(); } diff --git a/src/Cassandra/Outputs/OutputWriteTimeout.cs b/src/Cassandra/Outputs/OutputWriteTimeout.cs index 68ac83467..1b4b61ab8 100644 --- a/src/Cassandra/Outputs/OutputWriteTimeout.cs +++ b/src/Cassandra/Outputs/OutputWriteTimeout.cs @@ -36,7 +36,7 @@ internal OutputWriteTimeout(bool isFailure) protected override void Load(FrameReader reader) { - _consistencyLevel = (ConsistencyLevel) reader.ReadInt16(); + _consistencyLevel = (ConsistencyLevel)reader.ReadInt16(); _received = reader.ReadInt32(); _blockFor = reader.ReadInt32(); if (_isFailure) diff --git a/src/Cassandra/Policies/AesColumnEncryptionPolicy.cs b/src/Cassandra/Policies/AesColumnEncryptionPolicy.cs index 72795c2c6..0d0e883f1 100644 --- a/src/Cassandra/Policies/AesColumnEncryptionPolicy.cs +++ b/src/Cassandra/Policies/AesColumnEncryptionPolicy.cs @@ -185,7 +185,7 @@ private static void Validate(byte[] key, byte[] iv) if (iv != null && iv.Length != IVLength) { throw new ArgumentException("invalid IV size: " + iv.Length + ". Has to be 16 bytes."); - } + } try { using (var aes = Aes.Create()) diff --git a/src/Cassandra/Policies/AtomicMonotonicTimestampGenerator.cs b/src/Cassandra/Policies/AtomicMonotonicTimestampGenerator.cs index 518084914..ed62e5936 100644 --- a/src/Cassandra/Policies/AtomicMonotonicTimestampGenerator.cs +++ b/src/Cassandra/Policies/AtomicMonotonicTimestampGenerator.cs @@ -65,10 +65,10 @@ public class AtomicMonotonicTimestampGenerator : ITimestampGenerator /// milliseconds. Use 0 to disable. Default: 1000. /// public AtomicMonotonicTimestampGenerator( - int warningThreshold = DefaultWarningThreshold, + int warningThreshold = DefaultWarningThreshold, int minLogInterval = DefaultMinLogInterval) : this(warningThreshold, minLogInterval, Logger) { - + } /// @@ -97,7 +97,7 @@ protected virtual long GetTimestamp() { return (DateTime.UtcNow.Ticks - UnixEpochTicks) / TicksPerMicrosecond; } - + /// public long Next() { @@ -137,7 +137,7 @@ private void OnDrift(long timestamp, long lastTimestamp) // It drifted but not enough to log a warning return; } - var warningTimestamp = DateTime.UtcNow.Ticks/TimeSpan.TicksPerMillisecond; + var warningTimestamp = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; var lastWarning = Volatile.Read(ref _lastWarning); if (warningTimestamp - lastWarning <= _minLogInterval) { diff --git a/src/Cassandra/Policies/AtomicMonotonicWinApiTimestampGenerator.cs b/src/Cassandra/Policies/AtomicMonotonicWinApiTimestampGenerator.cs index 6fe569861..a17c52be8 100644 --- a/src/Cassandra/Policies/AtomicMonotonicWinApiTimestampGenerator.cs +++ b/src/Cassandra/Policies/AtomicMonotonicWinApiTimestampGenerator.cs @@ -29,12 +29,12 @@ public class AtomicMonotonicWinApiTimestampGenerator : AtomicMonotonicTimestampG { [DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)] private static extern void GetSystemTimePreciseAsFileTime(out long filetime); - + protected sealed override long GetTimestamp() { GetSystemTimePreciseAsFileTime(out long preciseTime); var timestamp = DateTime.FromFileTimeUtc(preciseTime); - return (timestamp.Ticks - UnixEpochTicks)/TicksPerMicrosecond; + return (timestamp.Ticks - UnixEpochTicks) / TicksPerMicrosecond; } /// @@ -53,7 +53,7 @@ public AtomicMonotonicWinApiTimestampGenerator( int warningThreshold = DefaultWarningThreshold, int minLogInterval = DefaultMinLogInterval) : this(warningThreshold, minLogInterval, Logger) { - + } internal AtomicMonotonicWinApiTimestampGenerator(int warningThreshold, int minLogInterval, Logger logger) diff --git a/src/Cassandra/Policies/BaseColumnEncryptionPolicy.cs b/src/Cassandra/Policies/BaseColumnEncryptionPolicy.cs index 64078de74..4bf07e6b1 100644 --- a/src/Cassandra/Policies/BaseColumnEncryptionPolicy.cs +++ b/src/Cassandra/Policies/BaseColumnEncryptionPolicy.cs @@ -25,7 +25,7 @@ namespace Cassandra /// /// The type of the "key" object that is used by the implementations of this class. See an example of this in . /// This is only meant to provide some compile time type safety since the base interface works with the basic "object" type. - public abstract class BaseColumnEncryptionPolicy: IColumnEncryptionPolicy + public abstract class BaseColumnEncryptionPolicy : IColumnEncryptionPolicy { private readonly ConcurrentDictionary _colData = new ConcurrentDictionary(); diff --git a/src/Cassandra/Policies/ConstantSpeculativeExecutionPolicy.cs b/src/Cassandra/Policies/ConstantSpeculativeExecutionPolicy.cs index 3303a0d6f..6f6edc340 100644 --- a/src/Cassandra/Policies/ConstantSpeculativeExecutionPolicy.cs +++ b/src/Cassandra/Policies/ConstantSpeculativeExecutionPolicy.cs @@ -51,12 +51,12 @@ public ConstantSpeculativeExecutionPolicy(long delay, int maxSpeculativeExecutio public void Dispose() { - + } public void Initialize(ICluster cluster) { - + } public ISpeculativeExecutionPlan NewPlan(string keyspace, IStatement statement) diff --git a/src/Cassandra/Policies/DCAwareRoundRobinPolicy.cs b/src/Cassandra/Policies/DCAwareRoundRobinPolicy.cs index 0129f3083..d59d38698 100644 --- a/src/Cassandra/Policies/DCAwareRoundRobinPolicy.cs +++ b/src/Cassandra/Policies/DCAwareRoundRobinPolicy.cs @@ -37,7 +37,7 @@ public class DCAwareRoundRobinPolicy : ILoadBalancingPolicy "The usedHostsPerRemoteDc parameter will be removed in the next major release of the driver. " + "DC failover should not be done in the driver, which does not have the necessary context to know " + "what makes sense considering application semantics. See https://datastax-oss.atlassian.net/browse/CSHARP-722"; - + private static readonly Logger Logger = new Logger(typeof(DCAwareRoundRobinPolicy)); private string _localDc; diff --git a/src/Cassandra/Policies/DefaultLoadBalancingPolicy.cs b/src/Cassandra/Policies/DefaultLoadBalancingPolicy.cs index 4d2b8939a..c37fb3f0a 100644 --- a/src/Cassandra/Policies/DefaultLoadBalancingPolicy.cs +++ b/src/Cassandra/Policies/DefaultLoadBalancingPolicy.cs @@ -41,7 +41,7 @@ internal DefaultLoadBalancingPolicy(ILoadBalancingPolicy childPolicy) { ChildPolicy = childPolicy ?? throw new ArgumentNullException(nameof(childPolicy)); } - + /// /// Creates a new datacenter aware round robin policy given the name of the local /// datacenter.

The name of the local datacenter provided must be the local @@ -55,7 +55,7 @@ public DefaultLoadBalancingPolicy(string localDc) } internal ILoadBalancingPolicy ChildPolicy { get; } - + ///

/// Return the HostDistance for the provided host. This policy consider nodes /// in the local datacenter as Local and the rest diff --git a/src/Cassandra/Policies/ExponentialReconnectionPolicy.cs b/src/Cassandra/Policies/ExponentialReconnectionPolicy.cs index 06109c791..227015368 100644 --- a/src/Cassandra/Policies/ExponentialReconnectionPolicy.cs +++ b/src/Cassandra/Policies/ExponentialReconnectionPolicy.cs @@ -71,7 +71,7 @@ public ExponentialReconnectionPolicy(long baseDelayMs, long maxDelayMs) // Maximum number of attempts after which we overflow (which is kind of theoretical anyway, you'll' // die of old age before reaching that but hey ...) int ceil = (baseDelayMs & (baseDelayMs - 1)) == 0 ? 0 : 1; - _maxAttempts = 64 - LeadingZeros(long.MaxValue/baseDelayMs) - ceil; + _maxAttempts = 64 - LeadingZeros(long.MaxValue / baseDelayMs) - ceil; } /// @@ -114,7 +114,7 @@ public long NextDelayMs() if (_attempts >= _policy._maxAttempts) return _policy._maxDelayMs; - return Math.Min(_policy._baseDelayMs*(1L << _attempts++), _policy._maxDelayMs); + return Math.Min(_policy._baseDelayMs * (1L << _attempts++), _policy._maxDelayMs); } } } diff --git a/src/Cassandra/Policies/IExtendedRetryPolicy.cs b/src/Cassandra/Policies/IExtendedRetryPolicy.cs index c5d25e89e..200f970b4 100644 --- a/src/Cassandra/Policies/IExtendedRetryPolicy.cs +++ b/src/Cassandra/Policies/IExtendedRetryPolicy.cs @@ -88,7 +88,7 @@ public WrappedExtendedRetryPolicy(IRetryPolicy policy, IExtendedRetryPolicy defa public IExtendedRetryPolicy DefaultPolicy { get; } - public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, + public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { return Policy.OnReadTimeout(query, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry); diff --git a/src/Cassandra/Policies/IReconnectionSchedule.cs b/src/Cassandra/Policies/IReconnectionSchedule.cs index e16fa3006..785ff5906 100644 --- a/src/Cassandra/Policies/IReconnectionSchedule.cs +++ b/src/Cassandra/Policies/IReconnectionSchedule.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace Cassandra +namespace Cassandra { /// /// Schedules reconnection attempts to a node. diff --git a/src/Cassandra/Policies/IRetryPolicy.cs b/src/Cassandra/Policies/IRetryPolicy.cs index 8c4452dc0..f889f6b78 100644 --- a/src/Cassandra/Policies/IRetryPolicy.cs +++ b/src/Cassandra/Policies/IRetryPolicy.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace Cassandra +namespace Cassandra { /// /// A policy that defines a default behavior to adopt when a request returns a diff --git a/src/Cassandra/Policies/LoggingRetryPolicy.cs b/src/Cassandra/Policies/LoggingRetryPolicy.cs index fb164c097..24d63f6ef 100644 --- a/src/Cassandra/Policies/LoggingRetryPolicy.cs +++ b/src/Cassandra/Policies/LoggingRetryPolicy.cs @@ -27,7 +27,7 @@ namespace Cassandra /// public class LoggingRetryPolicy : IExtendedRetryPolicy { - private readonly Logger _logger = new Logger(typeof (LoggingRetryPolicy)); + private readonly Logger _logger = new Logger(typeof(LoggingRetryPolicy)); private readonly IExtendedRetryPolicy _extendedPolicy; @@ -122,7 +122,7 @@ public RetryDecision OnRequestError(IStatement statement, Configuration config, switch (decision.DecisionType) { case RetryDecision.RetryDecisionType.Ignore: - _logger.Info("Ignoring on request error(retries: {0}, exception: {1})", nbRetry, ex); + _logger.Info("Ignoring on request error(retries: {0}, exception: {1})", nbRetry, ex); break; case RetryDecision.RetryDecisionType.Retry: _logger.Info("Retrying on request error (retries: {0}, exception: {1})", nbRetry, ex); diff --git a/src/Cassandra/Policies/NoSpeculativeExecutionPolicy.cs b/src/Cassandra/Policies/NoSpeculativeExecutionPolicy.cs index 500aa96e7..561071c2a 100644 --- a/src/Cassandra/Policies/NoSpeculativeExecutionPolicy.cs +++ b/src/Cassandra/Policies/NoSpeculativeExecutionPolicy.cs @@ -28,17 +28,17 @@ public class NoSpeculativeExecutionPolicy : ISpeculativeExecutionPolicy private NoSpeculativeExecutionPolicy() { - + } public void Dispose() { - + } public void Initialize(ICluster cluster) { - + } public ISpeculativeExecutionPlan NewPlan(string keyspace, IStatement statement) diff --git a/src/Cassandra/Policies/Policies.cs b/src/Cassandra/Policies/Policies.cs index c996c3e46..9190da7a8 100644 --- a/src/Cassandra/Policies/Policies.cs +++ b/src/Cassandra/Policies/Policies.cs @@ -36,7 +36,7 @@ public class Policies /// with as child policy. /// /// - public static ILoadBalancingPolicy DefaultLoadBalancingPolicy => + public static ILoadBalancingPolicy DefaultLoadBalancingPolicy => new DefaultLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy())); /// @@ -65,7 +65,7 @@ public static IReconnectionPolicy DefaultReconnectionPolicy return new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000); } } - + /// /// The default retry policy.The default retry policy is /// @@ -76,7 +76,7 @@ public static IRetryPolicy DefaultRetryPolicy return new DefaultRetryPolicy(); } } - + /// /// The default extended retry policy.The default extended retry policy is /// diff --git a/src/Cassandra/Policies/RetryLoadBalancingPolicy.cs b/src/Cassandra/Policies/RetryLoadBalancingPolicy.cs index 1cbd7c079..c7eaa8ee1 100644 --- a/src/Cassandra/Policies/RetryLoadBalancingPolicy.cs +++ b/src/Cassandra/Policies/RetryLoadBalancingPolicy.cs @@ -61,7 +61,7 @@ public IEnumerable NewQueryPlan(string keyspace, IStatement query) break; } else - Thread.Sleep((int) schedule.NextDelayMs()); + Thread.Sleep((int)schedule.NextDelayMs()); } } } diff --git a/src/Cassandra/Policies/RetryLoadBalancingPolicyEventArgs.cs b/src/Cassandra/Policies/RetryLoadBalancingPolicyEventArgs.cs index 00a6079c3..1ac828255 100644 --- a/src/Cassandra/Policies/RetryLoadBalancingPolicyEventArgs.cs +++ b/src/Cassandra/Policies/RetryLoadBalancingPolicyEventArgs.cs @@ -14,7 +14,7 @@ // limitations under the License. // -using System; +using System; namespace Cassandra { diff --git a/src/Cassandra/Policies/RoundRobinPolicy.cs b/src/Cassandra/Policies/RoundRobinPolicy.cs index 990839ead..85e2199fc 100644 --- a/src/Cassandra/Policies/RoundRobinPolicy.cs +++ b/src/Cassandra/Policies/RoundRobinPolicy.cs @@ -14,7 +14,7 @@ // limitations under the License. // -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading; using System.Linq; diff --git a/src/Cassandra/PreparedStatement.cs b/src/Cassandra/PreparedStatement.cs index b8fb97ddc..33d6d1152 100644 --- a/src/Cassandra/PreparedStatement.cs +++ b/src/Cassandra/PreparedStatement.cs @@ -70,7 +70,7 @@ public RowSetMetadata Variables { get { return _variablesRowsMetadata; } } - + /// /// Gets metadata on the columns that will be returned for this prepared statement. /// diff --git a/src/Cassandra/ProtocolEvents/ProtocolEventDebouncer.cs b/src/Cassandra/ProtocolEvents/ProtocolEventDebouncer.cs index d780d6e8d..c068680f7 100644 --- a/src/Cassandra/ProtocolEvents/ProtocolEventDebouncer.cs +++ b/src/Cassandra/ProtocolEvents/ProtocolEventDebouncer.cs @@ -99,7 +99,7 @@ public async Task HandleEventAsync(ProtocolEvent ev, bool processNow) { var callback = new TaskCompletionSource(); var sent = await _enqueueBlock.SendAsync(new Tuple, ProtocolEvent, bool>(callback, ev, processNow)).ConfigureAwait(false); - + if (!sent) { throw new DriverInternalError("Could not schedule event in the ProtocolEventDebouncer."); diff --git a/src/Cassandra/ProtocolEvents/SlidingWindowExclusiveTimer.cs b/src/Cassandra/ProtocolEvents/SlidingWindowExclusiveTimer.cs index cca05ff95..b535c25f6 100644 --- a/src/Cassandra/ProtocolEvents/SlidingWindowExclusiveTimer.cs +++ b/src/Cassandra/ProtocolEvents/SlidingWindowExclusiveTimer.cs @@ -44,7 +44,7 @@ public SlidingWindowExclusiveTimer(ITimerFactory timerFactory, TimeSpan delayInc { throw new ArgumentException("delayIncrement can not be greater than maxDelay"); } - + var scheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler; var taskFactory = new TaskFactory( CancellationToken.None, @@ -67,7 +67,7 @@ public void Dispose() { _timer?.Dispose(); } - + public void SlideDelay(bool processNow) { SlideDelayAsync(processNow).Forget(); @@ -137,12 +137,12 @@ private void CancelExistingTimer() { _timer?.Cancel(); } - + private void Fire() { // this method can't be async otherwise exclusive scheduler is pointless // this is already running inside the exclusive scheduler - + if (_isRunning) { _act(); diff --git a/src/Cassandra/ProtocolOptions.cs b/src/Cassandra/ProtocolOptions.cs index d6456a8c9..b20230b96 100644 --- a/src/Cassandra/ProtocolOptions.cs +++ b/src/Cassandra/ProtocolOptions.cs @@ -29,7 +29,7 @@ public class ProtocolOptions /// /// Maximum length of a frame according to the protocol /// - internal const int MaximumFrameLength = 256*1024*1024; + internal const int MaximumFrameLength = 256 * 1024 * 1024; /// /// The default value for : 10. @@ -84,7 +84,7 @@ public IFrameCompressor CustomCompressor /// /// Gets the maximum time to wait for schema agreement before returning from a DDL query. /// - public int MaxSchemaAgreementWaitSeconds + public int MaxSchemaAgreementWaitSeconds { get { return _maxSchemaAgreementWaitSeconds; } } @@ -110,7 +110,7 @@ public int MaxSchemaAgreementWaitSeconds /// public byte? MaxProtocolVersion { - get { return (byte?) _maxProtocolVersion; } + get { return (byte?)_maxProtocolVersion; } } internal ProtocolVersion? MaxProtocolVersionValue diff --git a/src/Cassandra/ProtocolVersion.cs b/src/Cassandra/ProtocolVersion.cs index ad29d3cd4..1a771dc36 100644 --- a/src/Cassandra/ProtocolVersion.cs +++ b/src/Cassandra/ProtocolVersion.cs @@ -151,8 +151,8 @@ public static ProtocolVersion GetHighestCommon(this ProtocolVersion version, Con { // Anything 4.0.0+ has a max protocol version of V5 and requires at least V3. v3Requirement = true; - maxVersion = config.AllowBetaProtocolVersions - ? Math.Min((byte)ProtocolVersion.V5, maxVersion) + maxVersion = config.AllowBetaProtocolVersions + ? Math.Min((byte)ProtocolVersion.V5, maxVersion) : Math.Min((byte)ProtocolVersion.V4, maxVersion); maxVersionWith3OrMore = maxVersion; } @@ -194,7 +194,7 @@ public static ProtocolVersion GetHighestCommon(this ProtocolVersion version, Con maxVersion = maxVersionWith3OrMore; } - return (ProtocolVersion) maxVersion; + return (ProtocolVersion)maxVersion; } /// @@ -223,7 +223,7 @@ public static bool SupportsTimestamp(this ProtocolVersion version) { return version >= ProtocolVersion.V3; } - + /// /// Determines whether the protocol supports flags in BATCH requests. /// diff --git a/src/Cassandra/QueryOptions.cs b/src/Cassandra/QueryOptions.cs index 9a9c130d4..d1bc7b64d 100644 --- a/src/Cassandra/QueryOptions.cs +++ b/src/Cassandra/QueryOptions.cs @@ -65,7 +65,7 @@ public class QueryOptions /// is obtained. /// /// - public bool RetryOnTimeout { get { return _retryOnTimeout; }} + public bool RetryOnTimeout { get { return _retryOnTimeout; } } /// /// Sets the default consistency level to use for queries. @@ -112,7 +112,7 @@ public QueryOptions SetSerialConsistencyLevel(ConsistencyLevel serialConsistency _serialConsistency = serialConsistencyLevel; return this; } - + /// /// The default serial consistency level used by queries. /// diff --git a/src/Cassandra/QueryProtocolOptions.cs b/src/Cassandra/QueryProtocolOptions.cs index 7d92017a7..8f4873013 100644 --- a/src/Cassandra/QueryProtocolOptions.cs +++ b/src/Cassandra/QueryProtocolOptions.cs @@ -38,12 +38,12 @@ public enum QueryFlags WithKeyspace = 0x80 } - public static readonly QueryProtocolOptions Default = + public static readonly QueryProtocolOptions Default = new QueryProtocolOptions(ConsistencyLevel.One, null, false, QueryOptions.DefaultPageSize, null, ConsistencyLevel.Any, null, null, null); public readonly int PageSize; public readonly ConsistencyLevel SerialConsistency; - + private readonly string _keyspace; public bool SkipMetadata { get; } @@ -58,7 +58,7 @@ public DateTimeOffset? Timestamp { get { - return RawTimestamp == null ? (DateTimeOffset?) null : + return RawTimestamp == null ? (DateTimeOffset?)null : TypeSerializer.UnixStart.AddTicks(RawTimestamp.Value * 10); } } @@ -81,7 +81,7 @@ internal QueryProtocolOptions(ConsistencyLevel consistency, byte[] pagingState, ConsistencyLevel serialConsistency, long? timestamp, - string keyspace, + string keyspace, RowSetMetadata variablesMetadata) { Consistency = consistency; @@ -137,7 +137,7 @@ internal static QueryProtocolOptions CreateFromQuery( query.PagingState, requestOptions.GetSerialConsistencyLevelOrDefault(query), timestamp, - query.Keyspace, + query.Keyspace, variablesMetadata); } @@ -205,11 +205,11 @@ internal void Write(FrameWriter wb, bool isPrepared) wb.WriteUInt16((ushort)Consistency); if (protocolVersion.Uses4BytesQueryFlags()) { - wb.WriteInt32((int) flags); + wb.WriteInt32((int)flags); } else { - wb.WriteByte((byte) flags); + wb.WriteByte((byte)flags); } } diff --git a/src/Cassandra/QueryTrace.cs b/src/Cassandra/QueryTrace.cs index 1c082f8de..8900cbd17 100644 --- a/src/Cassandra/QueryTrace.cs +++ b/src/Cassandra/QueryTrace.cs @@ -223,7 +223,7 @@ private void DoFetchTrace() } finally { - _isDisconnected = false; + _isDisconnected = false; } } diff --git a/src/Cassandra/RPToken.cs b/src/Cassandra/RPToken.cs index 5850382d8..6b4ec38fe 100644 --- a/src/Cassandra/RPToken.cs +++ b/src/Cassandra/RPToken.cs @@ -44,7 +44,7 @@ public override bool Equals(object obj) if (obj == null || GetType() != obj.GetType()) return false; - return _value == ((RPToken) obj)._value; + return _value == ((RPToken)obj)._value; } public override int GetHashCode() @@ -67,23 +67,23 @@ public override IToken Parse(string tokenStr) } [System.Diagnostics.CodeAnalysis.SuppressMessage( - "Security", - "CA5351:Do Not Use Broken Cryptographic Algorithms", + "Security", + "CA5351:Do Not Use Broken Cryptographic Algorithms", Justification = "Support for Cassandra's RandomPartitioner")] public override IToken Hash(byte[] partitionKey) { - if (_md5 == null) + if (_md5 == null) _md5 = MD5.Create(); - + var hash = _md5.ComputeHash(partitionKey); - + var reversedHash = new byte[hash.Length]; - for(int x = hash.Length - 1, y = 0; x >= 0; --x, ++y) + for (int x = hash.Length - 1, y = 0; x >= 0; --x, ++y) { reversedHash[y] = hash[x]; } var bigInteger = BigInteger.Abs(new BigInteger(reversedHash)); - + return new RPToken(bigInteger); } } diff --git a/src/Cassandra/RecyclableMemoryStream.cs b/src/Cassandra/RecyclableMemoryStream.cs index a7290e1b0..f5b04ba09 100644 --- a/src/Cassandra/RecyclableMemoryStream.cs +++ b/src/Cassandra/RecyclableMemoryStream.cs @@ -276,7 +276,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - + /// /// Equivalent to Dispose /// @@ -840,7 +840,7 @@ public IList> GetBufferList() if (largeBuffer != null) { return new ArrayBackedList>( - new[] { new ArraySegment(largeBuffer, 0, length)} + new[] { new ArraySegment(largeBuffer, 0, length) } ); } if (blocks.Count == 1) diff --git a/src/Cassandra/ReplicationStrategies.cs b/src/Cassandra/ReplicationStrategies.cs index 6658b8abb..268792785 100644 --- a/src/Cassandra/ReplicationStrategies.cs +++ b/src/Cassandra/ReplicationStrategies.cs @@ -30,7 +30,7 @@ public static class ReplicationStrategies // these two are internal because users shouldn't use these internal const string EverywhereStrategy = "EverywhereStrategy"; internal const string LocalStrategy = "LocalStrategy"; - + /// /// Returns replication property for SimpleStrategy. /// @@ -38,7 +38,7 @@ public static class ReplicationStrategies /// a dictionary of replication property sub-options. public static Dictionary CreateSimpleStrategyReplicationProperty(int replicationFactor) { - return new Dictionary {{"class", SimpleStrategy}, {"replication_factor", replicationFactor.ToString(CultureInfo.InvariantCulture)}}; + return new Dictionary { { "class", SimpleStrategy }, { "replication_factor", replicationFactor.ToString(CultureInfo.InvariantCulture) } }; } @@ -51,7 +51,7 @@ public static Dictionary CreateSimpleStrategyReplicationProperty public static Dictionary CreateNetworkTopologyStrategyReplicationProperty( Dictionary datacentersReplicationFactors) { - var result = new Dictionary {{"class", NetworkTopologyStrategy}}; + var result = new Dictionary { { "class", NetworkTopologyStrategy } }; if (datacentersReplicationFactors.Count <= 0) { return result; @@ -74,7 +74,7 @@ public static Dictionary CreateNetworkTopologyStrategyReplicatio /// a dictionary of replication property sub-options. public static Dictionary CreateReplicationProperty(string strategyClass, Dictionary subOptions) { - var result = new Dictionary {{"class", strategyClass}}; + var result = new Dictionary { { "class", strategyClass } }; if (subOptions.Count <= 0) { return result; diff --git a/src/Cassandra/Requests/BaseRequest.cs b/src/Cassandra/Requests/BaseRequest.cs index 94cf04e25..c2e5c38f1 100644 --- a/src/Cassandra/Requests/BaseRequest.cs +++ b/src/Cassandra/Requests/BaseRequest.cs @@ -24,7 +24,7 @@ namespace Cassandra.Requests internal abstract class BaseRequest : IRequest { private readonly HeaderFlags _headerFlags; - + /// /// Constructor that forces a specific serializer, i.e., protocol version. /// @@ -33,7 +33,7 @@ protected BaseRequest(ISerializer serializer, bool tracingEnabled, IDictionary /// Constructor that doesn't specify the serializer, will use the connection one. /// diff --git a/src/Cassandra/Requests/BatchRequest.cs b/src/Cassandra/Requests/BatchRequest.cs index 6fb8678e9..03e4d7c1d 100644 --- a/src/Cassandra/Requests/BatchRequest.cs +++ b/src/Cassandra/Requests/BatchRequest.cs @@ -38,7 +38,7 @@ internal class BatchRequest : BaseRequest, ICqlRequest public ConsistencyLevel Consistency { get; set; } protected override byte OpCode => BatchRequest.BatchOpCode; - + /// public override ResultMetadata ResultMetadata => null; @@ -71,7 +71,7 @@ public BatchRequest( // if flags are not supported, then the following additional parameters aren't either return; } - + SerialConsistency = requestOptions.GetSerialConsistencyLevelOrDefault(statement); _batchFlags |= QueryProtocolOptions.QueryFlags.WithSerialConsistency; @@ -126,7 +126,7 @@ protected override void WriteBody(FrameWriter wb) // then it doesn't support the following optional parameters either return; } - + if (protocolVersion.Uses4BytesQueryFlags()) { wb.WriteInt32((int)_batchFlags); diff --git a/src/Cassandra/Requests/BatchType.cs b/src/Cassandra/Requests/BatchType.cs index 1d8fd8455..6fd63f66a 100644 --- a/src/Cassandra/Requests/BatchType.cs +++ b/src/Cassandra/Requests/BatchType.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace Cassandra +namespace Cassandra { /// /// The type of batch to use diff --git a/src/Cassandra/Requests/ExecuteRequest.cs b/src/Cassandra/Requests/ExecuteRequest.cs index 93ad96622..01d99c039 100644 --- a/src/Cassandra/Requests/ExecuteRequest.cs +++ b/src/Cassandra/Requests/ExecuteRequest.cs @@ -31,8 +31,8 @@ internal class ExecuteRequest : BaseRequest, IQueryRequest, ICqlRequest private readonly byte[] _id; private readonly QueryProtocolOptions _queryOptions; - public ConsistencyLevel Consistency - { + public ConsistencyLevel Consistency + { get => _queryOptions.Consistency; set => _queryOptions.Consistency = value; } @@ -46,18 +46,18 @@ public byte[] PagingState public int PageSize => _queryOptions.PageSize; public ConsistencyLevel SerialConsistency => _queryOptions.SerialConsistency; - + public bool SkipMetadata => _queryOptions.SkipMetadata; /// public override ResultMetadata ResultMetadata { get; } public ExecuteRequest( - ISerializer serializer, + ISerializer serializer, byte[] id, - ResultMetadata resultMetadata, + ResultMetadata resultMetadata, QueryProtocolOptions queryOptions, - bool tracingEnabled, + bool tracingEnabled, IDictionary payload, bool isBatchChild) : base(serializer, tracingEnabled, payload) { @@ -85,7 +85,7 @@ public ExecuteRequest( ResultMetadata = resultMetadata; } - if (queryOptions.SerialConsistency != ConsistencyLevel.Any + if (queryOptions.SerialConsistency != ConsistencyLevel.Any && queryOptions.SerialConsistency.IsSerialConsistencyLevel() == false) { throw new RequestInvalidException("Non-serial consistency specified as a serial one."); @@ -110,7 +110,7 @@ protected override void WriteBody(FrameWriter wb) _queryOptions.Write(wb, true); } - + public void WriteToBatch(FrameWriter wb) { wb.WriteByte(1); //prepared query diff --git a/src/Cassandra/Requests/GraphTypeSerializerFactory.cs b/src/Cassandra/Requests/GraphTypeSerializerFactory.cs index b77d5917a..8a73b9bd9 100644 --- a/src/Cassandra/Requests/GraphTypeSerializerFactory.cs +++ b/src/Cassandra/Requests/GraphTypeSerializerFactory.cs @@ -34,7 +34,7 @@ internal class GraphTypeSerializerFactory : IGraphTypeSerializerFactory private readonly GraphSON1TypeSerializer _graphSon1TypeSerializer = new GraphSON1TypeSerializer(); - private readonly IThreadSafeDictionary _graphTypeSerializers = + private readonly IThreadSafeDictionary _graphTypeSerializers = new CopyOnWriteDictionary(); /// @@ -138,9 +138,9 @@ public IGraphTypeSerializer CreateSerializer( private struct CacheKey : IEquatable { public CacheKey( - GraphProtocol protocol, - IReadOnlyDictionary serializers, - IReadOnlyDictionary deserializers, + GraphProtocol protocol, + IReadOnlyDictionary serializers, + IReadOnlyDictionary deserializers, bool deserializeGraphNodes) { GraphProtocol = protocol; @@ -148,7 +148,7 @@ public CacheKey( Deserializers = deserializers; DeserializeGraphNodes = deserializeGraphNodes; } - + private GraphProtocol GraphProtocol { get; } private IReadOnlyDictionary Serializers { get; } @@ -159,9 +159,9 @@ public CacheKey( public bool Equals(CacheKey other) { - return GraphProtocol == other.GraphProtocol - && object.ReferenceEquals(Serializers, other.Serializers) - && object.ReferenceEquals(Deserializers, other.Deserializers) + return GraphProtocol == other.GraphProtocol + && object.ReferenceEquals(Serializers, other.Serializers) + && object.ReferenceEquals(Deserializers, other.Deserializers) && DeserializeGraphNodes == other.DeserializeGraphNodes; } @@ -173,7 +173,7 @@ public override bool Equals(object obj) public override int GetHashCode() { return Utils.CombineHashCodeWithNulls( - (int) GraphProtocol, Serializers, Deserializers, DeserializeGraphNodes); + (int)GraphProtocol, Serializers, Deserializers, DeserializeGraphNodes); } } } diff --git a/src/Cassandra/Requests/IGraphTypeSerializerFactory.cs b/src/Cassandra/Requests/IGraphTypeSerializerFactory.cs index 7f4161615..0d749d6de 100644 --- a/src/Cassandra/Requests/IGraphTypeSerializerFactory.cs +++ b/src/Cassandra/Requests/IGraphTypeSerializerFactory.cs @@ -33,7 +33,7 @@ internal interface IGraphTypeSerializerFactory /// See for an explanation. /// GraphProtocol GetDefaultGraphProtocol(IInternalSession session, IGraphStatement statement, GraphOptions options); - + /// /// Gets the serializer according to the protocol version. /// diff --git a/src/Cassandra/Requests/IReprepareHandler.cs b/src/Cassandra/Requests/IReprepareHandler.cs index da2d93e13..ad6f20f02 100644 --- a/src/Cassandra/Requests/IReprepareHandler.cs +++ b/src/Cassandra/Requests/IReprepareHandler.cs @@ -35,12 +35,12 @@ Task ReprepareOnSingleNodeAsync( KeyValuePair poolKvp, PreparedStatement ps, IRequest request, SemaphoreSlim sem, bool throwException); Task ReprepareOnSingleNodeAsync( - IRequestObserver observer, - SessionRequestInfo sessionRequestInfo, - KeyValuePair poolKvp, - PreparedStatement ps, - IRequest request, - SemaphoreSlim sem, + IRequestObserver observer, + SessionRequestInfo sessionRequestInfo, + KeyValuePair poolKvp, + PreparedStatement ps, + IRequest request, + SemaphoreSlim sem, bool throwException); } } \ No newline at end of file diff --git a/src/Cassandra/Requests/IRequestHandler.cs b/src/Cassandra/Requests/IRequestHandler.cs index 7039efd88..7921ca8e2 100644 --- a/src/Cassandra/Requests/IRequestHandler.cs +++ b/src/Cassandra/Requests/IRequestHandler.cs @@ -50,7 +50,7 @@ internal interface IRequestHandler Task SetNoMoreHostsAsync(NoHostAvailableException ex, IRequestExecution execution); bool HasCompleted(); - + /// /// Gets the next valid host for the purpose of obtaining a connection. /// diff --git a/src/Cassandra/Requests/IRequestHandlerFactory.cs b/src/Cassandra/Requests/IRequestHandlerFactory.cs index 0c223e360..8188af3d0 100644 --- a/src/Cassandra/Requests/IRequestHandlerFactory.cs +++ b/src/Cassandra/Requests/IRequestHandlerFactory.cs @@ -28,7 +28,7 @@ internal interface IRequestHandlerFactory Task CreateAsync(IInternalSession session, ISerializer serializer, IStatement statement, IRequestOptions options); Task CreateAsync(IInternalSession session, ISerializer serializer); - + IGraphRequestHandler CreateGraphRequestHandler(IInternalSession session, IGraphTypeSerializerFactory graphTypeSerializerFactory); } } \ No newline at end of file diff --git a/src/Cassandra/Requests/InternalPrepareRequest.cs b/src/Cassandra/Requests/InternalPrepareRequest.cs index 3c39b235e..090adff7c 100644 --- a/src/Cassandra/Requests/InternalPrepareRequest.cs +++ b/src/Cassandra/Requests/InternalPrepareRequest.cs @@ -43,7 +43,7 @@ internal enum PrepareFlags /// The CQL string to be prepared /// public string Query { get; set; } - + /// public override ResultMetadata ResultMetadata => null; @@ -58,11 +58,11 @@ public InternalPrepareRequest( { // if the keyspace parameter is not supported then prepare flags aren't either _prepareFlags = null; - + // and also no other optional parameter is supported return; } - + if (keyspace != null) { _prepareFlags |= PrepareFlags.WithKeyspace; diff --git a/src/Cassandra/Requests/PrepareHandler.cs b/src/Cassandra/Requests/PrepareHandler.cs index db075dda6..400c32ea0 100644 --- a/src/Cassandra/Requests/PrepareHandler.cs +++ b/src/Cassandra/Requests/PrepareHandler.cs @@ -94,7 +94,7 @@ private async Task SendRequestToOneNode( await observer.OnNodeStartAsync(info, nodeRequestInfo).ConfigureAwait(false); var result = await connection.Send(request).ConfigureAwait(false); responseReceived = true; - var prepareResult = new PrepareResult + var prepareResult = new PrepareResult { PreparedStatement = await GetPreparedStatement(result, request, request.Keyspace ?? connection.Keyspace, session.Cluster).ConfigureAwait(false), TriedHosts = triedHosts, @@ -107,7 +107,7 @@ private async Task SendRequestToOneNode( { await observer.OnNodeRequestErrorAsync( responseReceived ? RequestError.CreateClientError(ex, false) : RequestError.CreateServerError(ex), - info, + info, nodeRequestInfo).ConfigureAwait(false); if (PrepareHandler.CanBeRetried(ex)) @@ -185,11 +185,11 @@ private async Task GetPreparedStatement( } var prepared = (OutputPrepared)output; var ps = new PreparedStatement( - prepared.VariablesRowsMetadata, - prepared.QueryId, + prepared.VariablesRowsMetadata, + prepared.QueryId, new ResultMetadata(prepared.ResultMetadataId, prepared.ResultRowsMetadata), - request.Query, - keyspace, + request.Query, + keyspace, _serializerManager) { IncomingPayload = resultResponse.CustomPayload diff --git a/src/Cassandra/Requests/QueryRequest.cs b/src/Cassandra/Requests/QueryRequest.cs index 3351973aa..a1c86a9d3 100644 --- a/src/Cassandra/Requests/QueryRequest.cs +++ b/src/Cassandra/Requests/QueryRequest.cs @@ -54,7 +54,7 @@ public ConsistencyLevel SerialConsistency { get { return _queryOptions.SerialConsistency; } } - + /// public override ResultMetadata ResultMetadata => null; diff --git a/src/Cassandra/Requests/ReprepareHandler.cs b/src/Cassandra/Requests/ReprepareHandler.cs index bedae36ef..326634817 100644 --- a/src/Cassandra/Requests/ReprepareHandler.cs +++ b/src/Cassandra/Requests/ReprepareHandler.cs @@ -35,8 +35,8 @@ public async Task ReprepareOnAllNodesWithExistingConnections( var pools = session.GetPools(); var hosts = session.InternalCluster.AllHosts(); var poolsByHosts = pools.Join( - hosts, po => po.Key, - h => h.Address, + hosts, po => po.Key, + h => h.Address, (pair, host) => new { host, pair.Value }).ToDictionary(k => k.host, k => k.Value); if (poolsByHosts.Count == 0) @@ -58,8 +58,8 @@ public async Task ReprepareOnAllNodesWithExistingConnections( if (prepareResult.TriedHosts.ContainsKey(poolKvp.Key.Address)) { PrepareHandler.Logger.Warning( - $"An error occured while attempting to prepare query on {{0}}:{Environment.NewLine}{{1}}", - poolKvp.Key.Address, + $"An error occured while attempting to prepare query on {{0}}:{Environment.NewLine}{{1}}", + poolKvp.Key.Address, prepareResult.TriedHosts[poolKvp.Key.Address]); continue; } @@ -71,13 +71,13 @@ public async Task ReprepareOnAllNodesWithExistingConnections( await Task.WhenAll(tasks).ConfigureAwait(false); } } - + private static Task GetConnectionFromHostAsync( IHostConnectionPool pool, PreparedStatement ps, IDictionary triedHosts) { return GetConnectionFromHostInternalAsync(pool, ps, triedHosts, true); } - + private static async Task GetConnectionFromHostInternalAsync( IHostConnectionPool pool, PreparedStatement ps, IDictionary triedHosts, bool retry) { @@ -171,8 +171,8 @@ await observer.OnNodeRequestErrorAsync( if (observer != null) { await observer.OnNodeRequestErrorAsync( - RequestError.CreateServerError(ex), - sessionRequestInfo, + RequestError.CreateServerError(ex), + sessionRequestInfo, nodeRequestInfo).ConfigureAwait(false); } LogOrThrow( diff --git a/src/Cassandra/Requests/RequestExecution.cs b/src/Cassandra/Requests/RequestExecution.cs index 9aff936f8..c10edbe8b 100644 --- a/src/Cassandra/Requests/RequestExecution.cs +++ b/src/Cassandra/Requests/RequestExecution.cs @@ -47,7 +47,7 @@ internal class RequestExecution : IRequestExecution /// Host that was queried last in this execution. It can be null in case there was no attempt to send the request yet. /// private volatile Host _host; - + public RequestExecution(IRequestHandler parent, IInternalSession session, IRequest request, IRequestObserver requestObserver, SessionRequestInfo sessionRequestInfo) { _parent = parent; @@ -76,7 +76,7 @@ public Host Start(bool currentHostRetry) // fail fast: try to choose a host before leaving this thread var validHost = _parent.GetNextValidHost(_triedHosts); - SendToNextHostAsync(validHost).Forget(); + SendToNextHostAsync(validHost).Forget(); return validHost.Host; } @@ -171,7 +171,7 @@ private async Task SendAsync(IRequest request, Host host, Func callback(error, response, nodeRequestInfo), timeoutMillis); @@ -463,7 +463,7 @@ private Task ObserveNodeRequestErrorAsync( return TaskHelper.Completed; } - + /// /// Gets the retry decision based on the request error /// @@ -490,10 +490,10 @@ internal static RetryDecisionWithReason GetRetryDecisionWithReason( { return new RetryDecisionWithReason( policy.OnReadTimeout( - statement, - e.ConsistencyLevel, - e.RequiredAcknowledgements, - e.ReceivedAcknowledgements, + statement, + e.ConsistencyLevel, + e.RequiredAcknowledgements, + e.ReceivedAcknowledgements, e.WasDataRetrieved, retryCount), RequestErrorType.ReadTimeOut @@ -504,10 +504,10 @@ internal static RetryDecisionWithReason GetRetryDecisionWithReason( { return new RetryDecisionWithReason( policy.OnWriteTimeout( - statement, - e1.ConsistencyLevel, - e1.WriteType, - e1.RequiredAcknowledgements, + statement, + e1.ConsistencyLevel, + e1.WriteType, + e1.RequiredAcknowledgements, e1.ReceivedAcknowledgements, retryCount), RequestErrorType.WriteTimeOut @@ -600,7 +600,7 @@ async Task ResponseHandler(IRequestError error, Response response, NodeRequestIn } RequestExecution.ValidateResult(response); - var output = ((ResultResponse) response).Output; + var output = ((ResultResponse)response).Output; if (!(output is OutputPrepared outputPrepared)) { var ex = new DriverInternalError("Expected prepared response, obtained " + output.GetType().FullName); @@ -636,7 +636,7 @@ await _requestObserver.OnNodeRequestErrorAsync( if (_parent.SetNodeExecutionCompleted(nodeRequestInfo.ExecutionId)) { - await _requestObserver.OnNodeSuccessAsync( _sessionRequestInfo, nodeRequestInfo).ConfigureAwait(false); + await _requestObserver.OnNodeSuccessAsync(_sessionRequestInfo, nodeRequestInfo).ConfigureAwait(false); } await SendAsync(_request, nodeRequestInfo.Host, HandleResponseAsync).ConfigureAwait(false); diff --git a/src/Cassandra/Requests/RequestHandler.cs b/src/Cassandra/Requests/RequestHandler.cs index 4ec526b50..be1044f5e 100644 --- a/src/Cassandra/Requests/RequestHandler.cs +++ b/src/Cassandra/Requests/RequestHandler.cs @@ -179,17 +179,17 @@ internal static IRequest GetRequest(IStatement statement, ISerializer serializer if (statement is BoundStatement s2) { // set skip metadata only when result metadata id is supported because of CASSANDRA-10786 - var skipMetadata = - serializer.ProtocolVersion.SupportsResultMetadataId() + var skipMetadata = + serializer.ProtocolVersion.SupportsResultMetadataId() && s2.PreparedStatement.ResultMetadata.ContainsColumnDefinitions(); var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s2, requestOptions, skipMetadata, s2.PreparedStatement.Variables); request = new ExecuteRequest( - serializer, + serializer, s2.PreparedStatement.Id, - s2.PreparedStatement.ResultMetadata, + s2.PreparedStatement.ResultMetadata, options, - s2.IsTracing, + s2.IsTracing, s2.OutgoingPayload, false); } @@ -424,7 +424,7 @@ private static async Task GetConnectionFromHostInternalAsync( Host host, HostDistance distance, IInternalSession session, IDictionary triedHosts, bool retry) { var hostPool = session.GetOrCreateConnectionPool(host, distance); - + try { return await hostPool.GetConnectionFromHostAsync(triedHosts, () => session.Keyspace).ConfigureAwait(false); diff --git a/src/Cassandra/Requests/StartupOptionsFactory.cs b/src/Cassandra/Requests/StartupOptionsFactory.cs index 6290fba84..db28ed058 100644 --- a/src/Cassandra/Requests/StartupOptionsFactory.cs +++ b/src/Cassandra/Requests/StartupOptionsFactory.cs @@ -27,7 +27,7 @@ internal class StartupOptionsFactory : IStartupOptionsFactory public const string NoCompactOption = "NO_COMPACT"; public const string DriverNameOption = "DRIVER_NAME"; public const string DriverVersionOption = "DRIVER_VERSION"; - + public const string ApplicationNameOption = "APPLICATION_NAME"; public const string ApplicationVersionOption = "APPLICATION_VERSION"; public const string ClientIdOption = "CLIENT_ID"; @@ -46,7 +46,7 @@ public StartupOptionsFactory(Guid clusterId, string appVersion, string appName) _appVersion = appVersion; _clusterId = clusterId; } - + public IReadOnlyDictionary CreateStartupOptions(ProtocolOptions options) { var startupOptions = new Dictionary @@ -78,7 +78,7 @@ public IReadOnlyDictionary CreateStartupOptions(ProtocolOptions startupOptions.Add(StartupOptionsFactory.DriverNameOption, AssemblyHelpers.GetAssemblyTitle(typeof(StartupOptionsFactory))); startupOptions.Add( StartupOptionsFactory.DriverVersionOption, AssemblyHelpers.GetAssemblyInformationalVersion(typeof(StartupOptionsFactory))); - + if (_appName != null) { startupOptions[StartupOptionsFactory.ApplicationNameOption] = _appName; @@ -88,7 +88,7 @@ public IReadOnlyDictionary CreateStartupOptions(ProtocolOptions { startupOptions[StartupOptionsFactory.ApplicationVersionOption] = _appVersion; } - + startupOptions[StartupOptionsFactory.ClientIdOption] = _clusterId.ToString(); return startupOptions; } diff --git a/src/Cassandra/Requests/ValidHost.cs b/src/Cassandra/Requests/ValidHost.cs index 3b7fd77f0..f9c243cc1 100644 --- a/src/Cassandra/Requests/ValidHost.cs +++ b/src/Cassandra/Requests/ValidHost.cs @@ -40,7 +40,7 @@ public static ValidHost New(Host host, HostDistance distance) // We should not use an ignored host return null; } - + if (!host.IsUp) { // The host is not considered UP by the driver. diff --git a/src/Cassandra/Responses/Response.cs b/src/Cassandra/Responses/Response.cs index 3867d5bf7..1e7608358 100644 --- a/src/Cassandra/Responses/Response.cs +++ b/src/Cassandra/Responses/Response.cs @@ -62,12 +62,12 @@ internal Response(Frame frame) Reader.Read(buffer, 0, 16); TraceId = new Guid(TypeSerializer.GuidShuffle(buffer)); } - + if (frame.Header.Flags.HasFlag(HeaderFlags.Warning)) { Warnings = Reader.ReadStringList(); } - + if (frame.Header.Flags.HasFlag(HeaderFlags.CustomPayload)) { CustomPayload = Reader.ReadBytesMap(); diff --git a/src/Cassandra/Responses/ResultResponse.cs b/src/Cassandra/Responses/ResultResponse.cs index 519d38d46..326b9799c 100644 --- a/src/Cassandra/Responses/ResultResponse.cs +++ b/src/Cassandra/Responses/ResultResponse.cs @@ -48,7 +48,7 @@ public enum ResultResponseKind internal ResultResponse(Frame frame) : base(frame) { - Kind = (ResultResponseKind) Reader.ReadInt32(); + Kind = (ResultResponseKind)Reader.ReadInt32(); switch (Kind) { case ResultResponseKind.Void: diff --git a/src/Cassandra/RoutingKey.cs b/src/Cassandra/RoutingKey.cs index e421ccb46..ad734554f 100644 --- a/src/Cassandra/RoutingKey.cs +++ b/src/Cassandra/RoutingKey.cs @@ -62,13 +62,13 @@ internal static RoutingKey Compose(params RoutingKey[] components) res[idx] = 0; idx++; } - return new RoutingKey {RawRoutingKey = res}; + return new RoutingKey { RawRoutingKey = res }; } private static void PutShortLength(byte[] bb, int idx, int length) { - bb[idx] = ((byte) ((length >> 8) & 0xFF)); - bb[idx + 1] = ((byte) (length & 0xFF)); + bb[idx] = ((byte)((length >> 8) & 0xFF)); + bb[idx + 1] = ((byte)(length & 0xFF)); } } } diff --git a/src/Cassandra/RowPopulators/ExecutionInfo.cs b/src/Cassandra/RowPopulators/ExecutionInfo.cs index ff708b945..360b7e147 100644 --- a/src/Cassandra/RowPopulators/ExecutionInfo.cs +++ b/src/Cassandra/RowPopulators/ExecutionInfo.cs @@ -60,7 +60,7 @@ public ExecutionInfo() /// /// public IDictionary IncomingPayload { get; internal set; } - + /// /// Retrieves the coordinator that responded to the request /// @@ -123,7 +123,7 @@ internal void SetAchievedConsistency(ConsistencyLevel achievedConsistency) AchievedConsistency = achievedConsistency; } - internal void SetSchemaInAgreement(bool schemaAgreement) + internal void SetSchemaInAgreement(bool schemaAgreement) { IsSchemaInAgreement = schemaAgreement; } diff --git a/src/Cassandra/RowPopulators/RowSetMetadata.cs b/src/Cassandra/RowPopulators/RowSetMetadata.cs index 7ae3db2fa..81a498532 100644 --- a/src/Cassandra/RowPopulators/RowSetMetadata.cs +++ b/src/Cassandra/RowPopulators/RowSetMetadata.cs @@ -83,7 +83,7 @@ public class CustomColumnInfo : IColumnInfo public CustomColumnInfo() { - + } public CustomColumnInfo(string name) @@ -228,7 +228,7 @@ public override int GetHashCode() var hash = 19; foreach (var elem in Elements) { - hash = hash * 31 + + hash = hash * 31 + (elem.TypeCode.GetHashCode() ^ (elem.TypeInfo != null ? elem.TypeInfo.GetHashCode() : 0)); } return hash; @@ -289,7 +289,7 @@ public class RowSetMetadata /// It returns null when partition keys were not parsed. ///
internal int[] PartitionKeys { get; private set; } - + /// /// Whether the new_metadata_id was set. /// @@ -307,7 +307,7 @@ internal RowSetMetadata(FrameReader reader, bool parsePartitionKeys = false) //Allow to be created for unit tests return; } - var flags = (RowSetMetadataFlags) reader.ReadInt32(); + var flags = (RowSetMetadataFlags)reader.ReadInt32(); var columnLength = reader.ReadInt32(); if (parsePartitionKeys) @@ -321,7 +321,7 @@ internal RowSetMetadata(FrameReader reader, bool parsePartitionKeys = false) string gKsname = null; string gTablename = null; - + if ((flags & RowSetMetadataFlags.HasMorePages) == RowSetMetadataFlags.HasMorePages) { PagingState = reader.ReadBytes(); @@ -331,7 +331,7 @@ internal RowSetMetadata(FrameReader reader, bool parsePartitionKeys = false) { NewResultMetadataId = reader.ReadShortBytes(); } - + if ((flags & RowSetMetadataFlags.NoMetadata) == RowSetMetadataFlags.NoMetadata) { return; @@ -359,7 +359,7 @@ internal RowSetMetadata(FrameReader reader, bool parsePartitionKeys = false) col.Table = gTablename; } col.Name = reader.ReadString(); - col.TypeCode = (ColumnTypeCode) reader.ReadUInt16(); + col.TypeCode = (ColumnTypeCode)reader.ReadUInt16(); col.TypeInfo = GetColumnInfo(reader, col.TypeCode); col.Type = reader.Serializer.GetClrType(col.TypeCode, col.TypeInfo); Columns[i] = col; @@ -374,16 +374,16 @@ private IColumnInfo GetColumnInfo(FrameReader reader, ColumnTypeCode code) switch (code) { case ColumnTypeCode.List: - innercode = (ColumnTypeCode) reader.ReadUInt16(); + innercode = (ColumnTypeCode)reader.ReadUInt16(); return new ListColumnInfo { ValueTypeCode = innercode, ValueTypeInfo = GetColumnInfo(reader, innercode) }; case ColumnTypeCode.Map: - innercode = (ColumnTypeCode) reader.ReadUInt16(); + innercode = (ColumnTypeCode)reader.ReadUInt16(); IColumnInfo kci = GetColumnInfo(reader, innercode); - var vinnercode = (ColumnTypeCode) reader.ReadUInt16(); + var vinnercode = (ColumnTypeCode)reader.ReadUInt16(); IColumnInfo vci = GetColumnInfo(reader, vinnercode); return new MapColumnInfo { @@ -393,7 +393,7 @@ private IColumnInfo GetColumnInfo(FrameReader reader, ColumnTypeCode code) ValueTypeInfo = vci }; case ColumnTypeCode.Set: - innercode = (ColumnTypeCode) reader.ReadUInt16(); + innercode = (ColumnTypeCode)reader.ReadUInt16(); return new SetColumnInfo { KeyTypeCode = innercode, @@ -414,7 +414,7 @@ private IColumnInfo GetColumnInfo(FrameReader reader, ColumnTypeCode code) var dataType = new ColumnDesc { Name = reader.ReadString(), - TypeCode = (ColumnTypeCode) reader.ReadUInt16(), + TypeCode = (ColumnTypeCode)reader.ReadUInt16(), }; dataType.TypeInfo = GetColumnInfo(reader, dataType.TypeCode); @@ -422,20 +422,20 @@ private IColumnInfo GetColumnInfo(FrameReader reader, ColumnTypeCode code) } return udtInfo; case ColumnTypeCode.Tuple: - { - var tupleInfo = new TupleColumnInfo(); - var elementLength = reader.ReadInt16(); - for (var i = 0; i < elementLength; i++) { - var dataType = new ColumnDesc + var tupleInfo = new TupleColumnInfo(); + var elementLength = reader.ReadInt16(); + for (var i = 0; i < elementLength; i++) { - TypeCode = (ColumnTypeCode) reader.ReadUInt16(), - }; - dataType.TypeInfo = GetColumnInfo(reader, dataType.TypeCode); - tupleInfo.Elements.Add(dataType); + var dataType = new ColumnDesc + { + TypeCode = (ColumnTypeCode)reader.ReadUInt16(), + }; + dataType.TypeInfo = GetColumnInfo(reader, dataType.TypeCode); + tupleInfo.Elements.Add(dataType); + } + return tupleInfo; } - return tupleInfo; - } default: return null; } diff --git a/src/Cassandra/SSLOptions.cs b/src/Cassandra/SSLOptions.cs index 6c09e6088..b2aef4ea8 100644 --- a/src/Cassandra/SSLOptions.cs +++ b/src/Cassandra/SSLOptions.cs @@ -14,7 +14,7 @@ // limitations under the License. // -using System; +using System; using System.Net; using System.Net.Security; using System.Security.Authentication; @@ -27,7 +27,7 @@ namespace Cassandra ///
public class SSLOptions { - private readonly static Logger _logger = new Logger(typeof (SSLOptions)); + private readonly static Logger _logger = new Logger(typeof(SSLOptions)); private RemoteCertificateValidationCallback _remoteCertValidationCallback = ValidateServerCertificate; private SslProtocols _sslProtocol = SslProtocols.Tls; private bool _checkCertificateRevocation; diff --git a/src/Cassandra/SchemaParser.cs b/src/Cassandra/SchemaParser.cs index 6d2fd5b3b..4be6108a4 100644 --- a/src/Cassandra/SchemaParser.cs +++ b/src/Cassandra/SchemaParser.cs @@ -33,7 +33,7 @@ internal abstract class SchemaParser : ISchemaParser private const int TraceAttemptDelay = 400; private const string SelectTraceSessions = "SELECT * FROM system_traces.sessions WHERE session_id = {0}"; private const string SelectTraceEvents = "SELECT * FROM system_traces.events WHERE session_id = {0}"; - + protected readonly IMetadataQueryProvider Cc; protected readonly Metadata Parent; protected abstract string SelectAggregates { get; } @@ -201,7 +201,7 @@ public override Task> GetKeyspacesAsync(bool retry .QueryAsync(SelectKeyspaces, retry) .ContinueSync(rs => rs.Select(ParseKeyspaceRow)); } - + public override async Task> GetKeyspacesNamesAsync() { var rs = await Cc.QueryAsync(SelectKeyspacesNames, true).ConfigureAwait(false); @@ -538,7 +538,7 @@ internal class SchemaParserV2 : SchemaParser protected override string SelectTables => "SELECT table_name FROM system_schema.tables WHERE keyspace_name='{0}'"; protected override string SelectUdts => "SELECT * FROM system_schema.types WHERE keyspace_name='{0}' AND type_name = '{1}'"; - + internal SchemaParserV2(Metadata parent, Func> udtResolver) : base(parent) { @@ -579,7 +579,7 @@ public override async Task> GetKeyspacesAsync(bool var rs = await Cc.QueryAsync(SelectKeyspaces, retry).ConfigureAwait(false); return rs.Select(ParseKeyspaceRow); } - + public override async Task> GetKeyspacesNamesAsync() { var rs = await Cc.QueryAsync(SelectKeyspacesNames, true).ConfigureAwait(false); @@ -984,7 +984,7 @@ public override async Task> GetKeyspacesAsync(bool // Yield the keyspaces followed by the virtual keyspaces return keyspaces.Concat(virtualKeyspaces); } - + public override async Task> GetKeyspacesNamesAsync() { // Start the task to get the keyspace names in parallel diff --git a/src/Cassandra/Serialization/CollectionSerializer.cs b/src/Cassandra/Serialization/CollectionSerializer.cs index 4d2635bae..8a7c2fdab 100644 --- a/src/Cassandra/Serialization/CollectionSerializer.cs +++ b/src/Cassandra/Serialization/CollectionSerializer.cs @@ -50,7 +50,7 @@ public override IEnumerable Deserialize(ushort protocolVersion, byte[] buffer, i if (childTypeCode == null) { throw new DriverInternalError(string.Format("CollectionSerializer can not deserialize CQL values of type {0}", - typeInfo == null ? "null" : typeInfo.GetType().FullName)); + typeInfo == null ? "null" : typeInfo.GetType().FullName)); } var count = DecodeCollectionLength((ProtocolVersion)protocolVersion, buffer, ref offset); var childType = GetClrType(childTypeCode.Value, childTypeInfo); @@ -78,7 +78,7 @@ public override IEnumerable Deserialize(ushort protocolVersion, byte[] buffer, i childType = nullableType; isNullable = true; } - + result.SetValue(null, i); } else @@ -109,7 +109,7 @@ internal Type GetClrTypeForSet(IColumnInfo typeInfo) var openType = typeof(IEnumerable<>); return openType.MakeGenericType(valueType); } - + internal Type GetClrTypeForGraphSet(IColumnInfo typeInfo) { var valueType = GetClrTypeForGraph(((SetColumnInfo)typeInfo).KeyTypeCode, ((SetColumnInfo)typeInfo).KeyTypeInfo); diff --git a/src/Cassandra/Serialization/DataTypeParser.cs b/src/Cassandra/Serialization/DataTypeParser.cs index 465140af9..a9dde8aac 100644 --- a/src/Cassandra/Serialization/DataTypeParser.cs +++ b/src/Cassandra/Serialization/DataTypeParser.cs @@ -126,7 +126,7 @@ internal static ColumnDesc ParseFqTypeName(string typeName, int startIndex, int TypeCode = ColumnTypeCode.Custom }; var trimmedTypeName = typeName.Trim(); - length -= typeName.Length-trimmedTypeName.Length; + length -= typeName.Length - trimmedTypeName.Length; typeName = trimmedTypeName; if (length > ReversedTypeName.Length && typeName.IndexOf(ReversedTypeName, startIndex, comparison) == startIndex) { diff --git a/src/Cassandra/Serialization/DictionarySerializer.cs b/src/Cassandra/Serialization/DictionarySerializer.cs index 0e675eaa4..8c323d107 100644 --- a/src/Cassandra/Serialization/DictionarySerializer.cs +++ b/src/Cassandra/Serialization/DictionarySerializer.cs @@ -29,7 +29,7 @@ public override ColumnTypeCode CqlType public override IDictionary Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo) { - var mapInfo = (MapColumnInfo) typeInfo; + var mapInfo = (MapColumnInfo)typeInfo; var keyType = GetClrType(mapInfo.KeyTypeCode, mapInfo.KeyTypeInfo); var valueType = GetClrType(mapInfo.ValueTypeCode, mapInfo.ValueTypeInfo); var count = DecodeCollectionLength((ProtocolVersion)protocolVersion, buffer, ref offset); diff --git a/src/Cassandra/Serialization/DurationSerializer.cs b/src/Cassandra/Serialization/DurationSerializer.cs index 35ade7ce8..56f109a8c 100644 --- a/src/Cassandra/Serialization/DurationSerializer.cs +++ b/src/Cassandra/Serialization/DurationSerializer.cs @@ -21,8 +21,8 @@ namespace Cassandra.Serialization { internal class DurationSerializer : TypeSerializer { - private static readonly ThreadLocal EncodingBuffers = - new ThreadLocal(() => new [] { new byte[9] , new byte[9], new byte[9]}); + private static readonly ThreadLocal EncodingBuffers = + new ThreadLocal(() => new[] { new byte[9], new byte[9], new byte[9] }); public DurationSerializer(bool asCustomType) { diff --git a/src/Cassandra/Serialization/GenericSerializer.cs b/src/Cassandra/Serialization/GenericSerializer.cs index 50d013fb7..06f53364d 100644 --- a/src/Cassandra/Serialization/GenericSerializer.cs +++ b/src/Cassandra/Serialization/GenericSerializer.cs @@ -26,7 +26,7 @@ namespace Cassandra.Serialization { internal class GenericSerializer : IGenericSerializer { - private static readonly Logger Logger = new Logger(typeof (GenericSerializer)); + private static readonly Logger Logger = new Logger(typeof(GenericSerializer)); private readonly IDictionary _primitiveDeserializers = new Dictionary { @@ -52,7 +52,7 @@ internal class GenericSerializer : IGenericSerializer { ColumnTypeCode.Varchar, TypeSerializer.PrimitiveStringSerializer }, { ColumnTypeCode.Varint, TypeSerializer.PrimitiveBigIntegerSerializer } }; - + private readonly IEnumerable _defaultCustomTypeSerializers = new ITypeSerializer[] { new DateRangeSerializer(), @@ -103,18 +103,18 @@ public object Deserialize(ProtocolVersion version, byte[] buffer, int offset, in switch (typeCode) { case ColumnTypeCode.Custom: - { - if (typeInfo is VectorColumnInfo) - { - return _vectorSerializer.Deserialize((byte)version, buffer, offset, length, typeInfo); - } - if (_customDeserializers.Count == 0 || !_customDeserializers.TryGetValue(typeInfo, out typeSerializer)) { - // Use byte[] by default - typeSerializer = TypeSerializer.PrimitiveByteArraySerializer; + if (typeInfo is VectorColumnInfo) + { + return _vectorSerializer.Deserialize((byte)version, buffer, offset, length, typeInfo); + } + if (_customDeserializers.Count == 0 || !_customDeserializers.TryGetValue(typeInfo, out typeSerializer)) + { + // Use byte[] by default + typeSerializer = TypeSerializer.PrimitiveByteArraySerializer; + } + return typeSerializer.Deserialize((byte)version, buffer, offset, length, typeInfo); } - return typeSerializer.Deserialize((byte)version, buffer, offset, length, typeInfo); - } case ColumnTypeCode.Udt: return _udtSerializer.Deserialize((byte)version, buffer, offset, length, typeInfo); case ColumnTypeCode.List: @@ -137,7 +137,7 @@ public Type GetClrType(ColumnTypeCode typeCode, IColumnInfo typeInfo) } return clrTypeHandler(typeInfo); } - + public Type GetClrTypeForGraph(ColumnTypeCode typeCode, IColumnInfo typeInfo) { if (!_defaultGraphTypes.TryGetValue(typeCode, out Func clrTypeHandler)) @@ -217,7 +217,7 @@ public ColumnTypeCode GetCqlType(Type type, out IColumnInfo typeInfo) IColumnInfo valueTypeInfo; ColumnTypeCode valueTypeCode; var interfaces = type.GetTypeInfo().GetInterfaces(); - if (typeof(IDictionary).GetTypeInfo().IsAssignableFrom(type) && + if (typeof(IDictionary).GetTypeInfo().IsAssignableFrom(type) && interfaces.Any(t => IntrospectionExtensions.GetTypeInfo(t).IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>))) { var keyTypeCode = GetCqlType(type.GetTypeInfo().GetGenericArguments()[0], out IColumnInfo keyTypeInfo); @@ -454,7 +454,7 @@ public byte[] Serialize(ProtocolVersion version, object value) } if (Utils.IsTuple(type)) { - return _tupleSerializer.Serialize((byte)version, (IStructuralEquatable) value); + return _tupleSerializer.Serialize((byte)version, (IStructuralEquatable)value); } var buffer = _udtSerializer.Serialize((byte)version, value); if (buffer != null) @@ -473,7 +473,7 @@ public void SetSpecificSerializers(IEnumerable typeSerializers) { typeSerializers = new List(0); } - + var defined = new HashSet(); foreach (var ts in typeSerializers) { @@ -516,7 +516,7 @@ public void SetSpecificSerializers(IEnumerable typeSerializers) { throw new DriverInternalError("Expected custom type serializers only."); } - + if (_customDeserializers.ContainsKey(defaultCustomSerializer.TypeInfo) || _customSerializers.ContainsKey(defaultCustomSerializer.Type)) { diff --git a/src/Cassandra/Serialization/Geometry/LineStringSerializer.cs b/src/Cassandra/Serialization/Geometry/LineStringSerializer.cs index 7ffc05d49..94baa853d 100644 --- a/src/Cassandra/Serialization/Geometry/LineStringSerializer.cs +++ b/src/Cassandra/Serialization/Geometry/LineStringSerializer.cs @@ -38,7 +38,7 @@ public override LineString Deserialize(ushort protocolVersion, byte[] buffer, in } var isLe = IsLittleEndian(buffer, offset); offset++; - var type = (GeometryType) EndianBitConverter.ToInt32(isLe, buffer, offset); + var type = (GeometryType)EndianBitConverter.ToInt32(isLe, buffer, offset); if (type != GeometryType.LineString) { throw new ArgumentException("Binary representation was not a LineString"); @@ -51,7 +51,7 @@ public override LineString Deserialize(ushort protocolVersion, byte[] buffer, in throw new ArgumentException(string.Format("Buffer length does not match: {0} < {1}", buffer.Length, offset + pointsLength * 16)); } var points = new Point[pointsLength]; - for (var i = 0; i < pointsLength; i++) + for (var i = 0; i < pointsLength; i++) { points[i] = new Point( EndianBitConverter.ToDouble(isLe, buffer, offset), diff --git a/src/Cassandra/Serialization/Geometry/PointSerializer.cs b/src/Cassandra/Serialization/Geometry/PointSerializer.cs index 90d2d470d..2e19b225a 100644 --- a/src/Cassandra/Serialization/Geometry/PointSerializer.cs +++ b/src/Cassandra/Serialization/Geometry/PointSerializer.cs @@ -37,13 +37,13 @@ public override Point Deserialize(ushort protocolVersion, byte[] buffer, int off throw new ArgumentException("2D Point buffer should contain 21 bytes"); } var isLe = IsLittleEndian(buffer, offset); - var type = (GeometryType) EndianBitConverter.ToInt32(isLe, buffer, offset + 1); + var type = (GeometryType)EndianBitConverter.ToInt32(isLe, buffer, offset + 1); if (type != GeometryType.Point2D) { throw new ArgumentException("Binary representation was not a point"); } return new Point( - EndianBitConverter.ToDouble(isLe, buffer, offset + 5), + EndianBitConverter.ToDouble(isLe, buffer, offset + 5), EndianBitConverter.ToDouble(isLe, buffer, offset + 13)); } diff --git a/src/Cassandra/Serialization/Geometry/PolygonSerializer.cs b/src/Cassandra/Serialization/Geometry/PolygonSerializer.cs index fd6780cb5..468e2b43a 100644 --- a/src/Cassandra/Serialization/Geometry/PolygonSerializer.cs +++ b/src/Cassandra/Serialization/Geometry/PolygonSerializer.cs @@ -79,12 +79,12 @@ public override IColumnInfo TypeInfo public override byte[] Serialize(ushort protocolVersion, Polygon value) { - var totalRingsLength = value.Rings.Sum(r => 4 + r.Count*16); + var totalRingsLength = value.Rings.Sum(r => 4 + r.Count * 16); var buffer = new byte[9 + totalRingsLength]; var isLittleEndian = UseLittleEndianSerialization(); buffer[0] = isLittleEndian ? (byte)1 : (byte)0; var offset = 1; - EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, (int)GeometryType.Polygon ); + EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, (int)GeometryType.Polygon); offset += 4; EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, value.Rings.Count); offset += 4; @@ -96,7 +96,7 @@ public override byte[] Serialize(ushort protocolVersion, Polygon value) { EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, point.X); EndianBitConverter.SetBytes(isLittleEndian, buffer, offset + 8, point.Y); - offset += 16; + offset += 16; } } return buffer; diff --git a/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1Converter.cs b/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1Converter.cs index db38ba6c0..8edfc662e 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1Converter.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1Converter.cs @@ -42,7 +42,7 @@ internal class GraphSON1Converter : GraphSONConverter }; internal static readonly GraphSON1Converter Instance = new GraphSON1Converter(); - + private readonly Dictionary _readers; private GraphSON1Converter() diff --git a/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1TypeSerializer.cs b/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1TypeSerializer.cs index c49726131..8c2348fd0 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1TypeSerializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON1/GraphSON1TypeSerializer.cs @@ -22,7 +22,7 @@ namespace Cassandra.Serialization.Graph.GraphSON1 { internal class GraphSON1TypeSerializer : IGraphTypeSerializer { - private static readonly Func RowParser = + private static readonly Func RowParser = row => new GraphNode(new GraphSON1Node(row.GetValue("gremlin"), false)); public bool DefaultDeserializeGraphNodes => true; diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/GraphTypeSerializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/GraphTypeSerializer.cs index 57b850673..71c3b8014 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/GraphTypeSerializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/GraphTypeSerializer.cs @@ -291,7 +291,7 @@ private bool TryConvertFromMap(JToken token, Type type, string typeName, bool de elementType = typeof(object); } - var dictionary = FromMapToDictionary((JArray) token[GraphSONTokens.ValueKey], keyType, elementType, deserializeGraphNodes); + var dictionary = FromMapToDictionary((JArray)token[GraphSONTokens.ValueKey], keyType, elementType, deserializeGraphNodes); if (convertToElementMap) { @@ -447,7 +447,7 @@ private bool ConvertToElementMap(IDictionary map, out dynamic properties[key] = kvp.Value; } - + result = new ElementMap(id, label, properties); return true; } diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/StringBasedSerializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/StringBasedSerializer.cs index cf2919dd2..fc065e4a4 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/StringBasedSerializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/StringBasedSerializer.cs @@ -30,7 +30,7 @@ protected StringBasedSerializer(string prefix, string typeKey) _typeKey = typeKey; _prefix = prefix; } - + public Dictionary Dictify(dynamic objectData, IGraphSONWriter writer) { return GraphSONUtil.ToTypedValue(_typeKey, objectData == null ? null : ToString(objectData), _prefix); @@ -51,7 +51,7 @@ protected virtual string TokenToString(JToken token) { return token.ToObject(); } - + protected abstract string ToString(dynamic obj); protected abstract dynamic FromString(string str); diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/EdgeDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/EdgeDeserializer.cs index cf7196608..3ff139a27 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/EdgeDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/EdgeDeserializer.cs @@ -35,8 +35,8 @@ internal class EdgeDeserializer : BaseStructureDeserializer, IGraphSONStructureD { private const string Prefix = "g"; private const string TypeKey = "Edge"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(EdgeDeserializer.Prefix, EdgeDeserializer.TypeKey); public dynamic Objectify(JToken token, Func factory, IGraphSONReader reader) diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PathDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PathDeserializer.cs index 92c44efc6..fd3f8f978 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PathDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PathDeserializer.cs @@ -35,8 +35,8 @@ internal class PathDeserializer : BaseStructureDeserializer, IGraphSONStructureD { private const string Prefix = "g"; private const string TypeKey = "Path"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(PathDeserializer.Prefix, PathDeserializer.TypeKey); public dynamic Objectify(JToken token, Func factory, IGraphSONReader reader) diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertyDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertyDeserializer.cs index 32696ed69..5e2d14350 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertyDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertyDeserializer.cs @@ -33,8 +33,8 @@ internal class PropertyDeserializer : BaseStructureDeserializer, IGraphSONStruct { private const string Prefix = "g"; private const string TypeKey = "Property"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(PropertyDeserializer.Prefix, PropertyDeserializer.TypeKey); public dynamic Objectify(JToken token, Func factory, IGraphSONReader reader) diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertySerializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertySerializer.cs index 82706f40d..afb7753b3 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertySerializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/PropertySerializer.cs @@ -61,7 +61,7 @@ private dynamic CreateElementDict(IGraphNode graphNode, IGraphSONWriter writer) { return null; } - + var serializedElement = writer.ToDict(graphNode); Dictionary elementDict = serializedElement; if (elementDict.ContainsKey(GraphSONTokens.ValueKey)) diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/VertexPropertyDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/VertexPropertyDeserializer.cs index 6b48dd313..ba96e355c 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Structure/VertexPropertyDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Structure/VertexPropertyDeserializer.cs @@ -34,8 +34,8 @@ internal class VertexPropertyDeserializer : BaseStructureDeserializer, IGraphSON { private const string Prefix = "g"; private const string TypeKey = "VertexProperty"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(VertexPropertyDeserializer.Prefix, VertexPropertyDeserializer.TypeKey); public dynamic Objectify(JToken token, Func factory, IGraphSONReader reader) @@ -43,7 +43,7 @@ public dynamic Objectify(JToken token, Func factory, IGraphSO var graphNode = ToGraphNode(factory, token); return new VertexProperty( - graphNode.Get("id", true), + graphNode.Get("id", true), graphNode.Get("label"), graphNode.Get("value", true), graphNode.Get("vertex"), diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopDateDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopDateDeserializer.cs index d1a16ce8d..3cd31bca1 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopDateDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopDateDeserializer.cs @@ -31,9 +31,9 @@ internal class TinkerpopDateDeserializer : IGraphSONDeserializer { private const string Prefix = "g"; private const string TypeKey = "Date"; - + private static readonly DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); - + public static string TypeName => GraphSONUtil.FormatTypeName(TinkerpopDateDeserializer.Prefix, TinkerpopDateDeserializer.TypeKey); diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopTimestampDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopTimestampDeserializer.cs index 928235dac..00e4d1f04 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopTimestampDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TinkerpopTimestampDeserializer.cs @@ -31,7 +31,7 @@ internal class TinkerpopTimestampDeserializer : IGraphSONDeserializer { private const string Prefix = "g"; private const string TypeKey = "Timestamp"; - + private static readonly DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); public static string TypeName => diff --git a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TraverserDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TraverserDeserializer.cs index 96ea6f713..cdb57af5c 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TraverserDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON2/Tinkerpop/TraverserDeserializer.cs @@ -34,8 +34,8 @@ internal class TraverserDeserializer : BaseStructureDeserializer, IGraphSONStruc { private const string Prefix = "g"; private const string TypeKey = "Traverser"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(TraverserDeserializer.Prefix, TraverserDeserializer.TypeKey); public dynamic Objectify(JToken graphsonObject, Func factory, IGraphSONReader reader) diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/CustomGraphSON3Reader.cs b/src/Cassandra/Serialization/Graph/GraphSON3/CustomGraphSON3Reader.cs index 5dbe0a80e..6317db18e 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/CustomGraphSON3Reader.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/CustomGraphSON3Reader.cs @@ -48,7 +48,7 @@ static CustomGraphSON3Reader() CustomGraphSON3Reader.AddGraphSON3Deserializers(CustomGraphSON3Reader.Deserializers); CustomGraphSON3Reader.AddGraphSON3StructureDeserializers(CustomGraphSON3Reader.StructureDeserializers); } - + protected static void AddGraphSON3Deserializers(IDictionary dictionary) { foreach (var kv in CustomGraphSON3Reader.CustomGraphSON3SpecificDeserializers) @@ -56,7 +56,7 @@ protected static void AddGraphSON3Deserializers(IDictionary dictionary) { foreach (var kv in CustomGraphSON3Reader.CustomGraphSON3SpecificStructureDeserializers) @@ -66,21 +66,21 @@ protected static void AddGraphSON3StructureDeserializers(IDictionary graphNodeFactory, - IReadOnlyDictionary customDeserializers, - IGraphSONReader reader) + Func graphNodeFactory, + IReadOnlyDictionary customDeserializers, + IGraphSONReader reader) : base( - CustomGraphSON3Reader.Deserializers, - CustomGraphSON3Reader.StructureDeserializers, - graphNodeFactory, - customDeserializers, + CustomGraphSON3Reader.Deserializers, + CustomGraphSON3Reader.StructureDeserializers, + graphNodeFactory, + customDeserializers, reader) { } - + private static Dictionary Deserializers { get; } = new EmptyGraphSON2Reader().GetDeserializers(); - + private static Dictionary StructureDeserializers { get; } = new Dictionary(); } diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/ComplexTypeDefinitionHelper.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/ComplexTypeDefinitionHelper.cs index c5d045f10..f7504ca63 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/ComplexTypeDefinitionHelper.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/ComplexTypeDefinitionHelper.cs @@ -39,11 +39,11 @@ public static Dictionary GetUdtTypeDefinition( public static Dictionary GetDefinitionByValue( IGenericSerializer genericSerializer, dynamic obj) { - var objType = (Type) obj.GetType(); + var objType = (Type)obj.GetType(); var typeCode = genericSerializer.GetCqlType(objType, out var typeInfo); return GetDefinitionByType(new Dictionary(), genericSerializer, typeCode, typeInfo); } - + private static Dictionary GetDefinitionByType( IGenericSerializer genericSerializer, ColumnTypeCode typeCode, IColumnInfo typeInfo) { diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/Duration3Serializer.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/Duration3Serializer.cs index 4a85e7f69..83917b2e7 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/Duration3Serializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/Duration3Serializer.cs @@ -37,16 +37,16 @@ public Dictionary Dictify(dynamic objectData, IGraphSONWriter w { "nanos", writer.ToDict(d.Nanoseconds) } }; return GraphSONUtil.ToTypedValue( - Duration3Serializer.TypeKey, - value, + Duration3Serializer.TypeKey, + value, Duration3Serializer.Prefix); } public dynamic Objectify(JToken graphsonObject, IGraphSONReader reader) { - var months = (int) reader.ToObject(graphsonObject["months"]); - var days = (int) reader.ToObject(graphsonObject["days"]); - var nanos = (long) reader.ToObject(graphsonObject["nanos"]); + var months = (int)reader.ToObject(graphsonObject["months"]); + var days = (int)reader.ToObject(graphsonObject["days"]); + var nanos = (long)reader.ToObject(graphsonObject["nanos"]); return new Duration(months, days, nanos); } } diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/TupleGraphSONSerializer.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/TupleGraphSONSerializer.cs index ba63d0dc5..62e194055 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/TupleGraphSONSerializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/TupleGraphSONSerializer.cs @@ -60,8 +60,8 @@ public bool TryDictify( var dict = new Dictionary { { "cqlType", "tuple" }, - { - "definition", + { + "definition", data.Select(elem => ComplexTypeDefinitionHelper.GetDefinitionByValue(genericSerializer, elem)) }, { "value", data.Select(d => serializer.ToDict(d)) } }; diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/UdtGraphSONDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/UdtGraphSONDeserializer.cs index c50a1466c..03e9500be 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Dse/UdtGraphSONDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Dse/UdtGraphSONDeserializer.cs @@ -33,7 +33,7 @@ public dynamic Objectify( { var keyspace = serializer.FromDb(graphsonObject["keyspace"]); var name = serializer.FromDb(graphsonObject["name"]); - var values = (JArray) graphsonObject["value"]; + var values = (JArray)graphsonObject["value"]; var targetTypeIsDictionary = false; Type elementType = null; @@ -72,10 +72,10 @@ public dynamic Objectify( } } - var obj = readToDictionary - ? ToDictionary(serializer, elementType, (JArray) graphsonObject["definition"], values) + var obj = readToDictionary + ? ToDictionary(serializer, elementType, (JArray)graphsonObject["definition"], values) : ToObject(serializer, udtMap, values); - + if (!serializer.ConvertFromDb(obj, type, out var result)) { throw new InvalidOperationException($"Could not convert UDT from type {obj.GetType().FullName} to {type.FullName}"); @@ -83,7 +83,7 @@ public dynamic Objectify( return result; } - + internal object ToObject(IGraphTypeSerializer serializer, UdtMap map, IEnumerable valuesArr) { var obj = Activator.CreateInstance(map.NetType); @@ -94,7 +94,7 @@ internal object ToObject(IGraphTypeSerializer serializer, UdtMap map, IEnumerabl { break; } - + var field = map.Definition.Fields[i]; i++; @@ -104,18 +104,18 @@ internal object ToObject(IGraphTypeSerializer serializer, UdtMap map, IEnumerabl { continue; } - + var convertedValue = serializer.FromDb(value, prop.PropertyType, false); prop.SetValue(obj, convertedValue, null); } return obj; } - + internal object ToDictionary( IGraphTypeSerializer serializer, Type elementType, IEnumerable definitions, IEnumerable valuesArr) { - var fieldNames = definitions.Select(def => (string) def["fieldName"]).ToArray(); + var fieldNames = definitions.Select(def => (string)def["fieldName"]).ToArray(); var newDictionary = (IDictionary)Activator.CreateInstance(typeof(Dictionary<,>).MakeGenericType(typeof(string), elementType)); var elementIsGraphNode = elementType == typeof(GraphNode) || elementType == typeof(IGraphNode); diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Structure/Path3Deserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Structure/Path3Deserializer.cs index 6dd59515d..66c0f8639 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Structure/Path3Deserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Structure/Path3Deserializer.cs @@ -37,8 +37,8 @@ internal class Path3Deserializer : BaseStructureDeserializer, IGraphSONStructure { private const string Prefix = "g"; private const string TypeKey = "Path"; - - public static string TypeName => + + public static string TypeName => GraphSONUtil.FormatTypeName(Path3Deserializer.Prefix, Path3Deserializer.TypeKey); public dynamic Objectify(JToken graphsonObject, Func factory, IGraphSONReader reader) @@ -51,26 +51,26 @@ public dynamic Objectify(JToken graphsonObject, Func factory, labels = ParseLabels(jObj); objects = ParseObjects(jObj, factory); } - + return new Path(labels, objects); } private ICollection> ParseLabels(JObject tokenObj) { - if (tokenObj["labels"] is JObject labelsObj + if (tokenObj["labels"] is JObject labelsObj && labelsObj[GraphTypeSerializer.ValueKey] is JArray labelsArray) { return labelsArray .Select(node => { - if (node is JObject nodeObj - && nodeObj[GraphTypeSerializer.ValueKey] is JArray nodeArray) - { - return new HashSet(nodeArray.Select(n => n.ToString())); - } + if (node is JObject nodeObj + && nodeObj[GraphTypeSerializer.ValueKey] is JArray nodeArray) + { + return new HashSet(nodeArray.Select(n => n.ToString())); + } - throw new InvalidOperationException($"Cannot create a Path from {tokenObj}"); - }) + throw new InvalidOperationException($"Cannot create a Path from {tokenObj}"); + }) .ToArray(); } @@ -79,7 +79,7 @@ private ICollection> ParseLabels(JObject tokenObj) private ICollection ParseObjects(JObject tokenObj, Func factory) { - if (tokenObj["objects"] is JObject objectsObj + if (tokenObj["objects"] is JObject objectsObj && objectsObj[GraphTypeSerializer.ValueKey] is JArray objectsArray) { return objectsArray.Select(jt => ToGraphNode(factory, jt)).ToArray(); diff --git a/src/Cassandra/Serialization/Graph/GraphSON3/Tinkerpop/ByteBufferDeserializer.cs b/src/Cassandra/Serialization/Graph/GraphSON3/Tinkerpop/ByteBufferDeserializer.cs index 2438e2ccd..d1e42543f 100644 --- a/src/Cassandra/Serialization/Graph/GraphSON3/Tinkerpop/ByteBufferDeserializer.cs +++ b/src/Cassandra/Serialization/Graph/GraphSON3/Tinkerpop/ByteBufferDeserializer.cs @@ -31,7 +31,7 @@ internal class ByteBufferDeserializer : IGraphSONDeserializer { private const string Prefix = "gx"; private const string TypeKey = "ByteBuffer"; - + public static string TypeName => GraphSONUtil.FormatTypeName(ByteBufferDeserializer.Prefix, ByteBufferDeserializer.TypeKey); diff --git a/src/Cassandra/Serialization/Graph/IGraphTypeSerializer.cs b/src/Cassandra/Serialization/Graph/IGraphTypeSerializer.cs index f14469f8c..bb04d6b85 100644 --- a/src/Cassandra/Serialization/Graph/IGraphTypeSerializer.cs +++ b/src/Cassandra/Serialization/Graph/IGraphTypeSerializer.cs @@ -61,7 +61,7 @@ internal interface IGraphTypeSerializer /// . /// object FromDb(JToken token, Type type, bool deserializeGraphNodes); - + /// /// Generic version of /// diff --git a/src/Cassandra/Serialization/Graph/INode.cs b/src/Cassandra/Serialization/Graph/INode.cs index f6f10bcf5..7cb827137 100644 --- a/src/Cassandra/Serialization/Graph/INode.cs +++ b/src/Cassandra/Serialization/Graph/INode.cs @@ -113,7 +113,7 @@ internal interface INode bool TryGetMember(GetMemberBinder binder, out object result); void WriteJson(JsonWriter writer, JsonSerializer serializer); - + void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context); } diff --git a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ClassSerializer.cs b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ClassSerializer.cs index bb588860f..a1c1a669a 100644 --- a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ClassSerializer.cs +++ b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ClassSerializer.cs @@ -31,7 +31,7 @@ internal class ClassSerializer : IGraphSONSerializer { public Dictionary Dictify(dynamic objectData, IGraphSONWriter writer) { - var type = (Type) objectData; + var type = (Type)objectData; return writer.ToDict(Activator.CreateInstance(type)); } } diff --git a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Reader.cs b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Reader.cs index 617686c76..3bab8eef8 100644 --- a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Reader.cs +++ b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Reader.cs @@ -36,16 +36,16 @@ internal class GraphSON2Reader : GraphSONReader /// public GraphSON2Reader() { - + } /// /// Creates a new instance of . /// - public GraphSON2Reader(IReadOnlyDictionary deserializerByGraphSONType) : + public GraphSON2Reader(IReadOnlyDictionary deserializerByGraphSONType) : base(deserializerByGraphSONType) { - + } } } \ No newline at end of file diff --git a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Writer.cs b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Writer.cs index a3bdf5dc5..250a830d7 100644 --- a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Writer.cs +++ b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/GraphSON2Writer.cs @@ -37,16 +37,16 @@ internal class GraphSON2Writer : GraphSONWriter /// public GraphSON2Writer() { - + } - + /// /// Creates a new instance of . /// - public GraphSON2Writer(IReadOnlyDictionary customSerializerByType) : + public GraphSON2Writer(IReadOnlyDictionary customSerializerByType) : base(customSerializerByType) { - + } } } \ No newline at end of file diff --git a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ListSerializer.cs b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ListSerializer.cs index 40521d979..432573d54 100644 --- a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ListSerializer.cs +++ b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/ListSerializer.cs @@ -30,7 +30,7 @@ namespace Cassandra.Serialization.Graph.Tinkerpop.Structure.IO.GraphSON internal class ListSerializer : IGraphSONDeserializer, IGraphSONSerializer { private static readonly IReadOnlyList EmptyList = new object[0]; - + public dynamic Objectify(JToken graphsonObject, IGraphSONReader reader) { var jArray = graphsonObject as JArray; diff --git a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/MapSerializer.cs b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/MapSerializer.cs index 4ae232c20..19be965e2 100644 --- a/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/MapSerializer.cs +++ b/src/Cassandra/Serialization/Graph/Tinkerpop/Structure/IO/GraphSON/MapSerializer.cs @@ -46,7 +46,7 @@ public dynamic Objectify(JToken graphsonObject, IGraphSONReader reader) // IDictionary return result; } - + public Dictionary Dictify(dynamic objectData, IGraphSONWriter writer) { var map = objectData as IDictionary; diff --git a/src/Cassandra/Serialization/LegacyTypeSerializer.cs b/src/Cassandra/Serialization/LegacyTypeSerializer.cs index c0e768dc6..ae36d1952 100644 --- a/src/Cassandra/Serialization/LegacyTypeSerializer.cs +++ b/src/Cassandra/Serialization/LegacyTypeSerializer.cs @@ -37,7 +37,7 @@ public IColumnInfo TypeInfo get { return null; } } - public ColumnTypeCode CqlType + public ColumnTypeCode CqlType { get { return _typeCode; } } @@ -54,7 +54,7 @@ public object Deserialize(ushort protocolVersion, byte[] buffer, int offset, int buffer = Utils.SliceBuffer(buffer, offset, length); if (_reverse) { - Array.Reverse(buffer); + Array.Reverse(buffer); } return _adapter.ConvertFrom(buffer); } diff --git a/src/Cassandra/Serialization/Primitive/BooleanSerializer.cs b/src/Cassandra/Serialization/Primitive/BooleanSerializer.cs index 32bb85330..193aceefe 100644 --- a/src/Cassandra/Serialization/Primitive/BooleanSerializer.cs +++ b/src/Cassandra/Serialization/Primitive/BooleanSerializer.cs @@ -30,7 +30,7 @@ public override bool Deserialize(ushort protocolVersion, byte[] buffer, int offs public override byte[] Serialize(ushort protocolVersion, bool value) { - return new [] { (byte)(value ? 1 : 0) }; + return new[] { (byte)(value ? 1 : 0) }; } } } diff --git a/src/Cassandra/Serialization/Primitive/DecimalSerializer.cs b/src/Cassandra/Serialization/Primitive/DecimalSerializer.cs index 60c39ed1b..3eb311363 100644 --- a/src/Cassandra/Serialization/Primitive/DecimalSerializer.cs +++ b/src/Cassandra/Serialization/Primitive/DecimalSerializer.cs @@ -52,13 +52,13 @@ internal static decimal ToDecimal(BigInteger unscaledValue, int scale) { try { - return (decimal) (unscaledValue*BigInteger.Pow(new BigInteger(10), Math.Abs(scale))); + return (decimal)(unscaledValue * BigInteger.Pow(new BigInteger(10), Math.Abs(scale))); } catch (OverflowException) { throw new ArgumentOutOfRangeException( "unscaledValue", - unscaledValue*BigInteger.Pow(new BigInteger(10), Math.Abs(scale)), + unscaledValue * BigInteger.Pow(new BigInteger(10), Math.Abs(scale)), "Value can not be represented as a CLR Decimal"); } } diff --git a/src/Cassandra/Serialization/Search/DateRangeSerializer.cs b/src/Cassandra/Serialization/Search/DateRangeSerializer.cs index a105ea213..8ead5d183 100644 --- a/src/Cassandra/Serialization/Search/DateRangeSerializer.cs +++ b/src/Cassandra/Serialization/Search/DateRangeSerializer.cs @@ -22,7 +22,7 @@ namespace Cassandra.Serialization.Search internal class DateRangeSerializer : TypeSerializer { private readonly IColumnInfo _typeInfo = new CustomColumnInfo("org.apache.cassandra.db.marshal.DateRangeType"); - + /// /// The byte length of the serialized DateRange with a single boundary: byte + long + byte /// @@ -49,7 +49,7 @@ public override DateRange Deserialize(ushort protocolVersion, byte[] buffer, int { throw new ArgumentException("DateRange serialized value must have at least 1 byte"); } - var type = (RangeType) buffer[offset++]; + var type = (RangeType)buffer[offset++]; switch (type) { case RangeType.SingleValue: @@ -71,7 +71,7 @@ public override DateRange Deserialize(ushort protocolVersion, byte[] buffer, int private DateRangeBound ReadDateRangeBound(byte[] buffer, int offset) { var millis = EndianBitConverter.ToInt64(false, buffer, offset); - return new DateRangeBound(UnixStart.AddMilliseconds(millis), (DateRangePrecision) buffer[offset + 8]); + return new DateRangeBound(UnixStart.AddMilliseconds(millis), (DateRangePrecision)buffer[offset + 8]); } public override byte[] Serialize(ushort protocolVersion, DateRange value) @@ -91,7 +91,7 @@ public override byte[] Serialize(ushort protocolVersion, DateRange value) } // byte + long + byte buffer = new byte[10]; - buffer[0] = (byte) RangeType.OpenRangeLow; + buffer[0] = (byte)RangeType.OpenRangeLow; WriteDateRangeBound(buffer, 1, value.UpperBound.Value); return buffer; } @@ -123,24 +123,24 @@ private static int WriteDateRangeBound(byte[] buffer, int offset, DateRangeBound var millisecondsDiff = ticksDiff / (decimal)TimeSpan.TicksPerMillisecond; var millis = Convert.ToInt64(Math.Floor(millisecondsDiff)); EndianBitConverter.SetBytes(false, buffer, offset, millis); - buffer[offset + 8] = (byte) value.Precision; + buffer[offset + 8] = (byte)value.Precision; return offset + 9; } private enum RangeType : byte { - // single value as in "2001-01-01" - SingleValue = 0, - // closed range as in "[2001-01-01 TO 2001-01-31]" - ClosedRange = 1, - // open range high as in "[2001-01-01 TO *]" - OpenRangeHigh = 2, - // - 0x03 - open range low as in "[* TO 2001-01-01]" - OpenRangeLow = 3, - // - 0x04 - both ranges open as in "[* TO *]" - OpenBoth = 4, - // - 0x05 - single open range as in "[*]" - OpenSingle = 5 + // single value as in "2001-01-01" + SingleValue = 0, + // closed range as in "[2001-01-01 TO 2001-01-31]" + ClosedRange = 1, + // open range high as in "[2001-01-01 TO *]" + OpenRangeHigh = 2, + // - 0x03 - open range low as in "[* TO 2001-01-01]" + OpenRangeLow = 3, + // - 0x04 - both ranges open as in "[* TO *]" + OpenBoth = 4, + // - 0x05 - single open range as in "[*]" + OpenSingle = 5 } } } diff --git a/src/Cassandra/Serialization/SerializerManager.cs b/src/Cassandra/Serialization/SerializerManager.cs index 06483efe0..1d3caed5b 100644 --- a/src/Cassandra/Serialization/SerializerManager.cs +++ b/src/Cassandra/Serialization/SerializerManager.cs @@ -62,7 +62,7 @@ public byte[] Serialize(ProtocolVersion version, object value) { return _genericSerializer.Serialize(version, value); } - + public void SetUdtMap(string name, UdtMap map) { _genericSerializer.SetUdtMap(name, map); diff --git a/src/Cassandra/Serialization/TupleSerializer.cs b/src/Cassandra/Serialization/TupleSerializer.cs index c6b2bad46..e0d757282 100644 --- a/src/Cassandra/Serialization/TupleSerializer.cs +++ b/src/Cassandra/Serialization/TupleSerializer.cs @@ -66,7 +66,7 @@ internal Type GetClrType(IColumnInfo typeInfo) return genericTupleType.MakeGenericType( tupleInfo.Elements.Select(s => GetClrType(s.TypeCode, s.TypeInfo)).ToArray()); } - + internal Type GetClrTypeForGraph(IColumnInfo typeInfo) { var tupleInfo = (TupleColumnInfo)typeInfo; diff --git a/src/Cassandra/Serialization/TypeSerializer.cs b/src/Cassandra/Serialization/TypeSerializer.cs index 48e8813f9..1976884d3 100644 --- a/src/Cassandra/Serialization/TypeSerializer.cs +++ b/src/Cassandra/Serialization/TypeSerializer.cs @@ -55,9 +55,9 @@ internal static byte[] GuidShuffle(byte[] b, int offset = 0) { return new[] { - b[offset + 3], b[offset + 2], b[offset + 1], b[offset + 0], - b[offset + 5], b[offset + 4], - b[offset + 7], b[offset + 6], + b[offset + 3], b[offset + 2], b[offset + 1], b[offset + 0], + b[offset + 5], b[offset + 4], + b[offset + 7], b[offset + 6], b[offset + 8], b[offset + 9], b[offset + 10], b[offset + 11], b[offset + 12], b[offset + 13], b[offset + 14], b[offset + 15] }; } @@ -165,7 +165,7 @@ public Type Type /// public virtual IColumnInfo TypeInfo { - get { return null;} + get { return null; } } /// @@ -219,7 +219,7 @@ internal Type GetClrType(ColumnTypeCode typeCode, IColumnInfo typeInfo) } return _serializer.GetClrType(typeCode, typeInfo); } - + internal Type GetClrTypeForGraph(ColumnTypeCode typeCode, IColumnInfo typeInfo) { if (_serializer == null) diff --git a/src/Cassandra/Serialization/TypeSerializerDefinitions.cs b/src/Cassandra/Serialization/TypeSerializerDefinitions.cs index 43e3b21f3..372e16770 100644 --- a/src/Cassandra/Serialization/TypeSerializerDefinitions.cs +++ b/src/Cassandra/Serialization/TypeSerializerDefinitions.cs @@ -71,7 +71,7 @@ public TypeSerializerDefinitions Define(TypeSerializer typeSerializer) _definitions.Add(typeSerializer); return this; } - + /// /// Adds the serializer if there is none defined yet with the same type. /// Checks the serializer type (serializer.GetType()) not the CRL or CQL types) diff --git a/src/Cassandra/SessionManagement/IInternalCluster.cs b/src/Cassandra/SessionManagement/IInternalCluster.cs index 7e66100cc..529a2e11b 100644 --- a/src/Cassandra/SessionManagement/IInternalCluster.cs +++ b/src/Cassandra/SessionManagement/IInternalCluster.cs @@ -46,7 +46,7 @@ internal interface IInternalCluster : ICluster /// In case the statement was already in the prepared statements cache, logs an warning but prepares it anyway. /// Task Prepare(IInternalSession session, ISerializerManager serializerManager, InternalPrepareRequest request); - + IReadOnlyDictionary> GetResolvedEndpoints(); /// diff --git a/src/Cassandra/SessionManagement/IInternalSession.cs b/src/Cassandra/SessionManagement/IInternalSession.cs index 6a70eaca8..fba8e2143 100644 --- a/src/Cassandra/SessionManagement/IInternalSession.cs +++ b/src/Cassandra/SessionManagement/IInternalSession.cs @@ -68,7 +68,7 @@ internal interface IInternalSession : ISession new string Keyspace { get; set; } IInternalCluster InternalCluster { get; } - + /// /// Fetches the request options that were mapped from the provided execution profile's name. /// diff --git a/src/Cassandra/SessionRequestInfo.cs b/src/Cassandra/SessionRequestInfo.cs index e15377a74..914ea0dde 100644 --- a/src/Cassandra/SessionRequestInfo.cs +++ b/src/Cassandra/SessionRequestInfo.cs @@ -56,6 +56,6 @@ internal SessionRequestInfo(InternalPrepareRequest prepareRequest, string sessio /// Returns the session's current keyspace (if it was set). /// public string SessionKeyspace { get; } - + } } diff --git a/src/Cassandra/SessionState.cs b/src/Cassandra/SessionState.cs index d3cb4faa3..e4c4eeecd 100644 --- a/src/Cassandra/SessionState.cs +++ b/src/Cassandra/SessionState.cs @@ -88,7 +88,7 @@ internal class HostStateInfo public int OpenConnections { get; } public int InFlightQueries { get; } - + public HostStateInfo(IHostConnectionPool pool) { OpenConnections = pool.OpenConnections; diff --git a/src/Cassandra/SocketOptions.cs b/src/Cassandra/SocketOptions.cs index dbce0f7fb..aff65ae3b 100644 --- a/src/Cassandra/SocketOptions.cs +++ b/src/Cassandra/SocketOptions.cs @@ -44,7 +44,7 @@ public class SocketOptions private bool _useStreamMode; private int _readTimeoutMillis = DefaultReadTimeoutMillis; private int _defunctReadTimeoutThreshold = DefaultDefunctReadTimeoutThreshold; - private int _metadataAbortTimeout = 5 * 60000; + private int _metadataAbortTimeout = 5 * 60000; /// /// Gets the number of milliseconds to wait for the socket to connect diff --git a/src/Cassandra/Statement.cs b/src/Cassandra/Statement.cs index 050bea267..03b54183a 100644 --- a/src/Cassandra/Statement.cs +++ b/src/Cassandra/Statement.cs @@ -259,7 +259,7 @@ internal virtual IQueryRequest CreateBatchRequest(ISerializer serializer) { throw new InvalidOperationException("Cannot insert this query into the batch"); } - + /// public IStatement SetIdempotence(bool value) { diff --git a/src/Cassandra/TableMetadata.cs b/src/Cassandra/TableMetadata.cs index eb83edb2f..bd3b4dc23 100644 --- a/src/Cassandra/TableMetadata.cs +++ b/src/Cassandra/TableMetadata.cs @@ -22,7 +22,7 @@ namespace Cassandra /// /// Describes a Cassandra table /// - public class TableMetadata: DataCollectionMetadata + public class TableMetadata : DataCollectionMetadata { private static readonly IDictionary EmptyIndexes = new ReadOnlyDictionary(new Dictionary()); @@ -39,7 +39,7 @@ public class TableMetadata: DataCollectionMetadata protected TableMetadata() { - + } internal TableMetadata(string name, IDictionary indexes, bool isVirtual = false) diff --git a/src/Cassandra/Tasks/HashedWheelTimer.cs b/src/Cassandra/Tasks/HashedWheelTimer.cs index 8236c58a5..13d84300b 100644 --- a/src/Cassandra/Tasks/HashedWheelTimer.cs +++ b/src/Cassandra/Tasks/HashedWheelTimer.cs @@ -112,7 +112,7 @@ private void SetTimer() //the _timer might already have been disposed of } } - + /// /// Starts the timer explicitly. /// Calls to will internally call this method. diff --git a/src/Cassandra/Tasks/TaskHelper.cs b/src/Cassandra/Tasks/TaskHelper.cs index 144ecb242..f4d47e88c 100644 --- a/src/Cassandra/Tasks/TaskHelper.cs +++ b/src/Cassandra/Tasks/TaskHelper.cs @@ -94,10 +94,10 @@ public static Task FromException(Exception exception) /// public static T WaitToComplete(Task task, int timeout = Timeout.Infinite) { - TaskHelper.WaitToComplete((Task) task, timeout); + TaskHelper.WaitToComplete((Task)task, timeout); return task.Result; } - + /// /// Increments session client timeout counter in case of timeout. /// @@ -125,7 +125,7 @@ public static void WaitToCompleteWithMetrics(IMetricsManager manager, Task task, /// public static T WaitToCompleteWithMetrics(IMetricsManager manager, Task task, int timeout = Timeout.Infinite) { - TaskHelper.WaitToCompleteWithMetrics(manager, (Task) task, timeout); + TaskHelper.WaitToCompleteWithMetrics(manager, (Task)task, timeout); return task.Result; } @@ -217,7 +217,7 @@ public static void TrySet(this TaskCompletionSource tcs, Exception ex, T r tcs.TrySetResult(result); } } - + /// /// Attempts to transition the underlying Task to RanToCompletion or Faulted state. /// diff --git a/src/Cassandra/TimeUuid.cs b/src/Cassandra/TimeUuid.cs index 47d725267..9f26a97fb 100644 --- a/src/Cassandra/TimeUuid.cs +++ b/src/Cassandra/TimeUuid.cs @@ -27,10 +27,10 @@ public struct TimeUuid : IEquatable, IComparable //Reuse the random generator to avoid collisions private static readonly Random RandomGenerator = new Random(); private static readonly object RandomLock = new object(); - private static readonly byte[] MinNodeId = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80}; - private static readonly byte[] MinClockId = {0x80, 0x80}; - private static readonly byte[] MaxNodeId = {0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f}; - private static readonly byte[] MaxClockId = {0x7f, 0x7f}; + private static readonly byte[] MinNodeId = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }; + private static readonly byte[] MinClockId = { 0x80, 0x80 }; + private static readonly byte[] MaxNodeId = { 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f }; + private static readonly byte[] MaxClockId = { 0x7f, 0x7f }; private readonly Guid _value; @@ -163,7 +163,7 @@ public override string ToString() { return _value.ToString(); } - + /// /// Returns a string representation /// diff --git a/src/Cassandra/TokenMap.cs b/src/Cassandra/TokenMap.cs index 2d81ebacf..3872627e7 100644 --- a/src/Cassandra/TokenMap.cs +++ b/src/Cassandra/TokenMap.cs @@ -39,12 +39,12 @@ internal class TokenMap : IReadOnlyTokenMap private static readonly Logger Logger = new Logger(typeof(ControlConnection)); internal TokenMap( - TokenFactory factory, - IReadOnlyDictionary>> tokenToHostsByKeyspace, - List ring, - IReadOnlyDictionary primaryReplicas, - IReadOnlyDictionary>> keyspaceTokensCache, - IReadOnlyDictionary datacenters, + TokenFactory factory, + IReadOnlyDictionary>> tokenToHostsByKeyspace, + List ring, + IReadOnlyDictionary primaryReplicas, + IReadOnlyDictionary>> keyspaceTokensCache, + IReadOnlyDictionary datacenters, int numberOfHostsWithTokens) { Factory = factory; @@ -72,7 +72,7 @@ public void UpdateKeyspace(KeyspaceMetadata ks) sw.Stop(); TokenMap.Logger.Info( - "Finished updating TokenMap for the '{0}' keyspace. It took {1:0} milliseconds.", + "Finished updating TokenMap for the '{0}' keyspace. It took {1:0} milliseconds.", ks.Name, sw.Elapsed.TotalMilliseconds); } @@ -154,20 +154,20 @@ public static TokenMap Build(string partitioner, ICollection hosts, IColle sw.Stop(); TokenMap.Logger.Info( - "Finished building TokenMap for {0} keyspaces and {1} hosts. It took {2:0} milliseconds.", - keyspaces.Count, - hosts.Count, + "Finished building TokenMap for {0} keyspaces and {1} hosts. It took {2:0} milliseconds.", + keyspaces.Count, + hosts.Count, sw.Elapsed.TotalMilliseconds); return new TokenMap(factory, tokenToHosts, ring, primaryReplicas, ksTokensCache, datacenters, numberOfHostsWithTokens); } private static void UpdateKeyspace( KeyspaceMetadata ks, - IDictionary>> tokenToHostsByKeyspace, - IReadOnlyList ring, - IReadOnlyDictionary primaryReplicas, - IDictionary>> keyspaceTokensCache, - IReadOnlyDictionary datacenters, + IDictionary>> tokenToHostsByKeyspace, + IReadOnlyList ring, + IReadOnlyDictionary primaryReplicas, + IDictionary>> keyspaceTokensCache, + IReadOnlyDictionary datacenters, int numberOfHostsWithTokens) { IReadOnlyDictionary> replicas; diff --git a/src/Cassandra/UdtMap.cs b/src/Cassandra/UdtMap.cs index 1b2bce180..0ef95ddf8 100644 --- a/src/Cassandra/UdtMap.cs +++ b/src/Cassandra/UdtMap.cs @@ -102,7 +102,7 @@ public abstract class UdtMap protected UdtMap(Type netType, string udtName) : this(netType, udtName, null) { } - + protected UdtMap(Type netType, string udtName, string keyspace) { NetType = netType ?? throw new ArgumentNullException("netType"); diff --git a/src/Cassandra/Utils.cs b/src/Cassandra/Utils.cs index a6b4216d6..a2e03ad92 100644 --- a/src/Cassandra/Utils.cs +++ b/src/Cassandra/Utils.cs @@ -65,7 +65,7 @@ public static IDictionary ConvertStringToMapInt(string source) var map = new SortedDictionary(); if (source != "{}") - { + { foreach (string elem in elements) { if (int.TryParse(elem.Split(':')[1].Replace("\"", ""), out int value)) @@ -355,7 +355,7 @@ public static object ToCollectionType(Type collectionType, Type valueType, Array public static object ToVectorType(Type valueType, Array value) { var vectorType = typeof(CqlVector<>).MakeGenericType(valueType); - var vector = (IInternalCqlVector) Activator.CreateInstance(vectorType); + var vector = (IInternalCqlVector)Activator.CreateInstance(vectorType); vector.SetArray(value); return vector; }