### Install Cassandra C# Driver Source: https://github.com/datastax/csharp-driver/blob/master/README.md Use the NuGet Package Manager to install the Cassandra C# Driver. ```bash PM> Install-Package CassandraCSharpDriver ``` -------------------------------- ### Install App.Metrics Provider via NuGet Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/metrics/app-metrics/README.md Use the Package Manager Console to install the required NuGet package. ```powershell PM> Install-Package CassandraCSharpDriver.AppMetrics ``` -------------------------------- ### Restore and Build All Projects Source: https://github.com/datastax/csharp-driver/wiki/Building-and-running-tests Use these commands to restore dependencies and build the entire solution. Ensure you have .NET Core 2.1 SDK installed. ```bash dotnet restore src dotnet build src/Cassandra.sln ``` -------------------------------- ### Basic Cluster and Session Configuration Source: https://github.com/datastax/csharp-driver/blob/master/README.md Configure the cluster builder with your cluster's contact points and connect to the nodes using a keyspace. This example demonstrates synchronous query execution and iterating through the results. ```csharp // Configure the builder with your cluster's contact points var cluster = Cluster.Builder() .AddContactPoints("host1") .Build(); // Connect to the nodes using a keyspace var session = cluster.Connect("sample_keyspace"); // Execute a query on a connection synchronously var rs = session.Execute("SELECT * FROM sample_table"); // Iterate through the RowSet foreach (var row in rs) { var value = row.GetValue("sample_int_column"); // Do something with the value } ``` -------------------------------- ### Prepared Statements for Performance Source: https://github.com/datastax/csharp-driver/blob/master/README.md Prepare a statement once and bind different parameters to it for optimal performance. This example shows preparing an UPDATE statement and then executing it with specific parameters. ```csharp // Prepare a statement once var ps = session.Prepare("UPDATE user_profiles SET birth=? WHERE key=?"); // ...bind different parameters every time you need to execute var statement = ps.Bind(new DateTime(1942, 11, 27), "hendrix"); // Execute the bound statement with the provided parameters session.Execute(statement); ``` -------------------------------- ### Insert Statement Example Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/speculative-retries/README.md Example of an INSERT statement. Consider using timestamps with queries to avoid issues with speculative executions. ```cql insert into my_table (k, v) values (1, 1); ``` -------------------------------- ### Configure Driver Metrics Options Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/metrics/README.md Examples of enabling specific session metrics using DriverMetricsOptions and LINQ operations. ```csharp // Enable all session metrics builder.WithMetrics(provider, new DriverMetricsOptions().SetEnabledSessionMetrics(SessionMetric.AllSessionMetrics)); // Enable default session metrics (same effect as not calling the method at all) builder.WithMetrics(provider, new DriverMetricsOptions().SetEnabledSessionMetrics(SessionMetric.DefaultSessionMetrics)); // Enable default session metrics except "bytes-sent", using LINQ builder.WithMetrics(provider, new DriverMetricsOptions() .SetEnabledSessionMetrics(SessionMetric.DefaultSessionMetrics.Except(new [] { SessionMetric.Meters.BytesSent }))); // Enable default session metrics and 'cql-requests' timer metric, using LINQ builder.WithMetrics(provider, new DriverMetricsOptions() .SetEnabledSessionMetrics(SessionMetric.DefaultSessionMetrics.Union(new [] { SessionMetric.Timers.CqlRequests }))); ``` -------------------------------- ### Delete Statement Example Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/speculative-retries/README.md Example of a DELETE statement. This query might be affected by the ordering of speculative executions if not handled properly. ```cql delete from my_table where k = 1; ``` -------------------------------- ### Create and Insert Geospatial Data in CQL Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/geotypes/README.md Example CQL commands to define a table with a PointType column and insert a point using WKT format. ```cql cqlsh> CREATE TABLE points_of_interest(name text PRIMARY KEY, coords 'PointType'); cqlsh> INSERT INTO points_of_interest (name, coords) VALUES ('Eiffel Tower', 'POINT(48.8582 2.2945)'); ``` -------------------------------- ### Create Table with PointType in cqlsh Source: https://github.com/datastax/csharp-driver/blob/master/README.md Example of creating a table with a 'PointType' column using cqlsh. ```cql CREATE TABLE points_of_interest(name text PRIMARY KEY, coords 'PointType'); INSERT INTO points_of_interest (name, coords) VALUES ('Eiffel Tower', 'POINT(48.8582 2.2945)'); ``` -------------------------------- ### Register UDT mapping Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/udts/README.md Registering UDT mappings at the session level. Includes an example for specifying a keyspace. ```csharp await session.UserDefinedTypes.DefineAsync( UdtMap.For() .Map(v => v.Alias, "alias") .Map(v => v.CountryCode, "country_code") .Map(v => v.Number, "number")).ConfigureAwait(false); ``` ```csharp await session.UserDefinedTypes.DefineAsync( UdtMap.For(keyspace: "keyspace") .Map(v => v.Alias, "alias") .Map(v => v.CountryCode, "country_code") .Map(v => v.Number, "number")).ConfigureAwait(false); ``` -------------------------------- ### Trace Class - OnStartAsync Implementation Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Starts a new Cassandra activity and adds it to the request items using a predefined key. This method is part of the `IRequestTracker` implementation. ```csharp private static readonly string otelActivityKey = "otel_activity"; public Task OnStartAsync(RequestTrackingInfo request) { (...) var activity = ActivitySource.StartActivity("cassandra", ActivityKind.Client); request.Items.TryAdd(otelActivityKey, activity); (...) } ``` -------------------------------- ### Configure Encryption Policy Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/column-encryption/README.md Define an encryption policy and add columns to it, specifying the keys and type codes for encryption. This setup is required for both prepared and simple statements. ```csharp var policy = new AesColumnEncryptionPolicy(); policy.AddColumn("ks", "table", "encrypted", KEY, TYPECODE); ``` -------------------------------- ### Get Vertex Properties by Name Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/graph-support/README.md Retrieve specific properties from a vertex object using the `GetProperty()` method. This example demonstrates accessing string and integer properties by their names. ```csharp var vertex = session.ExecuteGraph(new SimpleGraphStatement("g.V()")).First().To(); // Assuming that vertex with properties: name:string, and age:int Console.WriteLine(vertex.GetProperty("name").Value.ToString()); Console.WriteLine(vertex.GetProperty("age").Value.ToInt32()); ``` -------------------------------- ### On-the-fly Re-preparation on Execution Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/core/statements/prepared/README.md Demonstrates the scenario where the driver attempts to execute a statement, finds that the coordinator does not recognize it, and then re-prepares the statement on the fly. This process involves an initial execute attempt, followed by a prepare and a subsequent execute, all transparent to the client but incurring extra roundtrips. ```ditaa client driver node1 --+-------------------------------+------------------------------+-- | | | |session.execute(boundStatement)| | +------------------------------>| | | | EXECUTE(id, values) | | |----------------------------->| | | | | | UNPREPARED | | |<-----------------------------| | | | | | | | | PREPARE(query) | | |----------------------------->| | | | | | PREPARED(id) | | |<-----------------------------| | | | | | | | | EXECUTE(id, values) | | |----------------------------->| | | | | | ROWS | | |<-----------------------------| | | | |<------------------------------| | ``` -------------------------------- ### Creating CqlVector instances Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/vectors/README.md Demonstrates various ways to initialize CqlVector objects, including direct instantiation, factory methods, and conversion extensions. ```csharp // these 2 are equivalent var vector = new CqlVector(1, 2, 3); var vector = CqlVector.New(new int[] { 1, 2, 3 }); // CqlVector.New requires an array but you prefer using other types such as List // you can call the IEnumerable extension method .ToArray() - note that it performs a copy var vector = CqlVector.New(new List { 1, 2, 3 }.ToArray()); // create a vector with the specified number of dimensions (this is similar to creating an array - new int[dimensions]) var vector = CqlVector.New(3); // Converting an array to a CqlVector without copying var vector = new int[] { 1, 2, 3 }.AsCqlVector(); // Converting an IEnumerable to a CqlVector (calls .ToArray() internally so it performs a copy) var vector = new int[] { 1, 2, 3 }.ToCqlVector(); ``` -------------------------------- ### Execute Graph Statement with Guid and IPAddress Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/graph-support/README.md Construct and execute a graph statement that includes parameters of type `Guid` and `IPAddress`. Ensure these types are correctly mapped or supported by the driver. ```csharp var traversal = new SimpleGraphStatement( "g.addV('sample').property('uid', uid).property('ip_address', address)", new { uid = Guid.NewGuid(), address = IPAddress.Parse("127.0.0.1") }); session.ExecuteGraph(traversal); ``` -------------------------------- ### Connect to Cassandra and execute a query Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/core/README.md Demonstrates the basic lifecycle of connecting to a cluster, creating a session, and iterating through query results. Ensure the Cluster and Session instances are shared throughout the application and disposed of properly to release resources. ```csharp var cluster = Cluster.Builder() .AddContactPoints("host1", "host2", "host3") .Build(); // (1) var session = cluster.Connect("sample_keyspace"); // (2) var rs = session.Execute("SELECT * FROM sample_table"); // (3) foreach (var row in rs) { var value = row.GetValue("sample_int_column"); // (4) //do something with the value } ``` -------------------------------- ### RequestHandler Result Propagation Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Example of passing tracking information to the result handler. ```csharp _requestResultHandler.TrySetResult(result, _requestTrackingInfo); ``` -------------------------------- ### Provide Client Certificate from File Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/tls/README.md Use `SSLOptions.SetCertificateCollection` to provide a collection of X509Certificate2 objects loaded from PFX files. Specify the password if the certificate is protected. ```csharp var cluster = Cluster.Builder() .AddContactPoints("...") .WithSSL(new SSLOptions() // set client certificate collection .SetCertificateCollection(new X509Certificate2Collection { // use the following constructor if the certificate is password protected new X509Certificate2(@"C:\path\to\client_cert.pfx", "cert_password"), // use the following constructor if the certificate is not password protected //new X509Certificate2(@"C:\path\to\client_cert.pfx") }) ) .Build(); ``` -------------------------------- ### Define a UDT in CQL Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/udts/README.md Example of a CQL statement to create a user-defined type. ```sql CREATE TYPE address ( street text, city text, zip int, phones list ); ``` -------------------------------- ### Iterate Observers in CompositeRequestObserver Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Example implementation of triggering multiple observers on request success. ```csharp public void OnRequestSuccess(RequestTrackingInfo r) { foreach (var observer in this.observers) { observer.OnRequestSuccess(r); } } ``` -------------------------------- ### TcsMetricsRequestResultHandler Constructor Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Constructor implementation that initializes tracking and notifies the observer of request start. ```csharp public TcsMetricsRequestResultHandler( IRequestObserver requestObserver, RequestTrackingInfo requestTrackingInfo) { _requestObserver = requestObserver; _taskCompletionSource = new TaskCompletionSource(); _requestObserver.OnRequestStart(requestTrackingInfo); } ``` -------------------------------- ### Initialize Mapper with Global Mappings Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/mapper/batch/README.md Define global mapping configurations and create an IMapper instance. Ensure the session object is properly initialized. ```csharp MappingConfiguration.Global.Define(); var mapper = new Mapper(session); ``` -------------------------------- ### Enable Metrics with App.Metrics Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/metrics/app-metrics/README.md Initialize the driver metrics provider using an existing App.Metrics IMetricsRoot instance. ```csharp var metricsRoot = new App.Metrics.MetricsBuilder().Build(); var cluster = Cluster .Builder() .AddContactPoint("127.0.0.1") .WithMetrics(metricsRoot.CreateDriverMetricsProvider()) .Build(); ``` -------------------------------- ### Connect and Query with C# Ado.Net Driver Source: https://github.com/datastax/csharp-driver/blob/master/src/Cassandra/Data/README.rst Initializes a connection to a Cassandra cluster using the CqlProviderFactory and iterates through query results. ```csharp var provider = DbProviderFactories.GetFactory("Cassandra.Data.CqlProviderFactory"); var connection = provider.CreateConnection(); connection.ConnectionString = "Contact Points=cass1,cass2;Port=9042"; connection.Open(); var cmd = connection.CreateCommand(); var reader = cmd.ExecuteReader(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) Console.Write(reader.GetValue(i).ToString()+"|"); Console.WriteLine(); } ``` -------------------------------- ### Initialize MappingConfiguration and Table instances Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/linq/batch/README.md Register the mappings and create table instances required for LINQ operations. ```csharp MappingConfiguration.Global.Define(); var usersTable = new Table(session); var usersByNameTable = new Table(session); ``` -------------------------------- ### Advanced Linq Query Operations Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/linq/README.md Examples of filtering, limiting, projecting, and modifying data using both query and lambda syntax. ```csharp // First row or null using a query User user = ( from user in users where user.Group == "admin" select user.Name).FirstOrDefault().Execute(); // First row or null using lambda syntax User user = users.Where(u => u.UserId == "john") .FirstOrDefault() .Execute(); // Use Take() to limit your result sets server side var userAdmins = ( from user in users where user.Group == "admin" select user.Name).Take(100).Execute(); // Use Select() to project to a new form server side var userCoordinates = ( from user in users where user.Group == "admin" select new Tuple(user.X, user.Y)).Execute(); // Delete users.Where(u => u.UserId == "john") .Delete() .Execute(); // Delete If (Cassandra 2.1+) users.Where(u => u.UserId == "john") .DeleteIf(u => u.LastAccess == value) .Execute(); // Update users.Where(u => u.UserId == "john") .Select(u => new User { LastAccess = TimeUuid.NewId()}) .Update() .Execute(); ``` -------------------------------- ### Run Unit Tests with Detailed Output Source: https://github.com/datastax/csharp-driver/blob/master/CONTRIBUTING.md Runs unit tests with a Release configuration, targeting .NET 8, and provides detailed console output. This is useful for debugging test failures. ```bash dotnet test src/Cassandra.Tests/Cassandra.Tests.csproj -c Release -f net8 -l "console;verbosity=detailed" ``` -------------------------------- ### Handle UDT property mismatches Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/udts/README.md Examples of handling cases where CQL column names do not match C# class property names. ```sql CREATE TYPE address ( street text, city text, zip_code int, phones list ); ``` ```csharp public class Address { public string Street { get; set; } public string City { get; set; } public int ZipCode { get; set; } public IEnumerable Phones { get; set;} } ``` ```csharp session.UserDefinedTypes.Define( UdtMap.For
() .Map(a => a.Street, "street") .Map(a => a.City, "city") .Map(a => a.Zip, "zip") .Map(a => a.Phones, "phones") ); ``` ```csharp session.UserDefinedTypes.Define( UdtMap.For
() .Automap() .Map(a => a.Zipcode, "zip_code") ); ``` -------------------------------- ### Configure Metrics and Monitoring Source: https://context7.com/datastax/csharp-driver/llms.txt Enable and access driver metrics using the App.Metrics integration to monitor session and node performance. ```csharp using Cassandra; using Cassandra.Metrics; // Install package: CassandraCSharpDriver.AppMetrics // Enable default metrics var cluster1 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithMetrics(metricsProvider) .Build(); // Enable all metrics including timers var cluster2 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithMetrics(metricsProvider, new DriverMetricsOptions() .SetEnabledSessionMetrics(SessionMetric.AllSessionMetrics) .SetEnabledNodeMetrics(NodeMetric.AllNodeMetrics) .SetBucketPrefix("cassandra")) .Build(); // Access metrics programmatically var session = cluster2.Connect("my_keyspace"); IDriverMetrics metrics = session.GetMetrics(); // Get session-level metrics var sessionMetrics = metrics.SessionMetrics; // Get node-level metrics foreach (var host in session.Cluster.AllHosts()) { if (metrics.NodeMetrics.TryGetValue(host, out var nodeMetrics)) { Console.WriteLine($"Metrics for {host.Address}"); } } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/datastax/csharp-driver/wiki/Building-and-running-tests Execute unit tests for the driver. Ensure you are targeting the netcoreapp2.0 framework. Unit tests typically complete within 3 minutes. ```bash dotnet test src/Cassandra.Tests/Cassandra.Tests.csproj -f netcoreapp2.0 ``` -------------------------------- ### Convert All Graph Results to Specific Type in C# Source: https://github.com/datastax/csharp-driver/blob/master/README.md Apply the `To()` conversion to the entire `GraphResultSet` to get a sequence of the specified type, such as `IVertex`. ```csharp foreach (IVertex vertex in rs.To()) { Console.WriteLine(vertex.Label); } ``` -------------------------------- ### Execute CQL command using ADO.NET Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/adonet/README.md Demonstrates the standard open/close pattern for executing a command via CqlConnection. Note that this approach is synchronous and limited by ADO.NET design patterns. ```csharp var connection = new CqlConnection(connectionString); connection.Open(); try { var command = connection.CreateCommand(); command.CommandText = "UPDATE tbl SET val = 'z' WHERE id = 1"; command.ExecuteNonQuery(); } finally { connection.Close(); } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/datastax/csharp-driver/wiki/Building-and-running-tests Execute integration tests. This requires ccm and Simulacron to be installed and configured. The filter excludes long-running and memory-intensive tests. ```bash dotnet test src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj -f netcoreapp2.0 --filter "(TestCategory!=long)&(TestCategory!=memory)" ``` -------------------------------- ### Build Cluster with Legacy vs Execution Profile API Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/execution-profiles/README.md Compares building a Cluster instance using legacy configuration parameters versus the modern Execution Profile API. ```csharp var cluster2 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithQueryOptions( new QueryOptions() .SetConsistencyLevel(ConsistencyLevel.LocalQuorum) .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)) .WithLoadBalancingPolicy(lbp) .WithSpeculativeExecutionPolicy(sep) .WithRetryPolicy(rp) .Build(); ``` ```csharp var cluster2 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithExecutionProfiles(opts => opts .WithProfile("default", profile => profile .WithConsistencyLevel(ConsistencyLevel.LocalQuorum) .WithSerialConsistencyLevel(ConsistencyLevel.LocalSerial) .WithLoadBalancingPolicy(lbp) .WithSpeculativeExecutionPolicy(sep) .WithRetryPolicy(rp))) .Build(); ``` -------------------------------- ### Insert Statement with Timestamp Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/speculative-retries/README.md Example of an INSERT statement using a specific timestamp. This helps ensure predictable results when speculative executions are enabled. ```cql insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000; ``` -------------------------------- ### Executing prepared vector statements Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/vectors/README.md Demonstrates binding vector parameters to prepared statements for efficient execution. ```csharp var psInsert = await session.PrepareAsync("INSERT INTO table1 (i, j) VALUES (?, ?)"); var psSelect = await session.PrepareAsync("SELECT * FROM table1 ORDER BY j ANN OF ? LIMIT ?"); var boundInsert = psInsert.Bind(2, new CqlVector(5.0f, 6.0f, 7.0f)); await session.ExecuteAsync(boundInsert); var boundSelect = psSelect.Bind(new CqlVector(4.7f, 5.0f, 5.0f), 1); var rowSet = await session.ExecuteAsync(boundSelect); var row = rowSet.Single(); var i = row.GetValue("i"); var j = row.GetValue>("j"); ``` -------------------------------- ### IRequestTracker Interface Definition Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Defines the interface for tracking Cassandra request activity, including methods for start, success, error, and node-specific events. ```csharp public interface IRequestTracker { Task OnStartAsync(RequestTrackingInfo request); Task OnSuccessAsync(RequestTrackingInfo request); Task OnErrorAsync(RequestTrackingInfo request, Exception ex); Task OnNodeSuccessAsync(RequestTrackingInfo request, HostTrackingInfo hostInfo); Task OnNodeErrorAsync(RequestTrackingInfo request, HostTrackingInfo hostInfo, Exception ex); } ``` -------------------------------- ### Create IQueryable Table instance Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/linq/README.md Instantiate an IQueryable instance for your entity using the Table constructor and an existing ISession. ```csharp var users = new Table(session); ``` -------------------------------- ### Configure Default Load Balancing Policy Source: https://context7.com/datastax/csharp-driver/llms.txt Sets up the default token-aware and datacenter-aware load balancing policy for routing queries to replicas in the local datacenter. ```csharp using Cassandra; // Default load balancing (token-aware + DC-aware) var cluster1 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithLoadBalancingPolicy(Policies.NewDefaultLoadBalancingPolicy("datacenter1")) .Build(); ``` -------------------------------- ### Provide Client Certificate from Certificate Store Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/tls/README.md Obtain a collection of certificates from the X509 store (e.g., `LocalMachine` or `CurrentUser`) and provide it to `SSLOptions.SetCertificateCollection`. Ensure the certificate is accessible in the chosen store. ```csharp X509Certificate2Collection collection; using (var store = new X509Store(StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); collection = store.Certificates; } var cluster = Cluster.Builder() .AddContactPoints("...") .WithSSL(new SSLOptions().SetCertificateCollection(collection)) .Build(); ``` -------------------------------- ### Prepare a Statement Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/routing-queries/README.md Prepare an INSERT statement for the 'users' table. The driver will determine partition key composition from metadata. ```csharp PreparedStatement prepared = session.Prepare( "INSERT INTO users (id, name) VALUES (?, ?)"); ``` -------------------------------- ### Enable NLog logging in DataStax C# Driver Source: https://github.com/datastax/csharp-driver/blob/master/doc/faq/README.md Configure the driver to use NLog for logging by adding an NLogLoggerProvider before initializing the Cluster. Ensure NLog is installed in your project. ```csharp // Use the provider you prefer, in this case NLog ILoggerProvider provider = new NLogLoggerProvider(); // Add it before initializing the Cluster Cassandra.Diagnostics.AddLoggerProvider(provider); ``` -------------------------------- ### Run all integration tests Source: https://github.com/datastax/csharp-driver/blob/master/CONTRIBUTING.md Executes the full suite of integration tests, including all categories. ```bash dotnet test src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj -c Release -f net8 -l "console;verbosity=detailed" ``` -------------------------------- ### Configure Exponential Reconnection Policy Source: https://context7.com/datastax/csharp-driver/llms.txt Sets a custom reconnection policy with an exponential backoff strategy, starting with a 1-second delay and increasing up to a 60-second delay between reconnection attempts. ```csharp using Cassandra; // Custom reconnection policy var cluster3 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithReconnectionPolicy( new ExponentialReconnectionPolicy(1000, 60000)) // 1s to 60s backoff .Build(); ``` -------------------------------- ### Initial Preparation and Re-preparation Flow Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/core/statements/prepared/README.md Illustrates the process of preparing a statement initially and then re-preparing it on all remaining nodes. The prepared statement identifier is a hash of the query string, ensuring consistency across nodes. ```ditaa client driver node1 node2 node3 --+------------------------+----------------+--------------+------+--- | | | | | | session.prepare(query) | | | | |----------------------->| | | | | | PREPARE(query) | | | | |--------------->| | | | | | | | | | PREPARED(id) | | | | |<---------------| | | | | | | | | | | | | | | PREPARE(query) | | |------------------------------>| | | | | | | PREPARE(query) | | |------------------------------------->| | | | | |<-----------------------| | | ``` -------------------------------- ### Configure Constant Speculative Execution Policy Source: https://context7.com/datastax/csharp-driver/llms.txt Enables speculative execution for latency-sensitive queries, starting additional executions after a specified delay and limiting the maximum number of concurrent speculative executions. ```csharp using Cassandra; // Speculative execution for latency-sensitive queries var cluster4 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithSpeculativeExecutionPolicy( new ConstantSpeculativeExecutionPolicy( delay: 500, // Start speculative execution after 500ms maxSpeculativeExecutions: 2)) // At most 2 additional executions .Build(); var session = cluster4.Connect("my_keyspace"); // Mark statement as idempotent to enable speculative execution var statement = new SimpleStatement("SELECT * FROM users WHERE id = ?", userId); statement.SetIdempotence(true); var rs = await session.ExecuteAsync(statement); ``` -------------------------------- ### Build Specific Projects with Target Frameworks Source: https://github.com/datastax/csharp-driver/wiki/Building-and-running-tests Build individual projects targeting specific .NET frameworks like netstandard1.5 or netcoreapp2.0. This is useful for cross-platform development. ```bash dotnet build src/Cassandra/Cassandra.csproj -f netstandard1.5 ``` ```bash dotnet build src/Cassandra.Tests/Cassandra.Tests.csproj -f netcoreapp2.0 ``` ```bash dotnet build src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj -f netcoreapp2.0 ``` -------------------------------- ### Batching Statements for Atomic Operations Source: https://github.com/datastax/csharp-driver/blob/master/README.md Execute multiple statements (prepared or unprepared) in a batch to update or insert several rows atomically, even across different column families. This example prepares two statements and adds them to a batch. ```csharp // Prepare the statements involved in a profile update once var profileStmt = session.Prepare("UPDATE user_profiles SET email=? WHERE key=?"); var userTrackStmt = session.Prepare("INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)"); // ...you should reuse the prepared statement // Bind the parameters and add the statement to the batch batch var batch = new BatchStatement() .Add(profileStmt.Bind(emailAddress, "hendrix")) .Add(userTrackStmt.Bind("hendrix", "You changed your email", DateTime.Now)); // Execute the batch session.Execute(batch); ``` -------------------------------- ### Build Cluster with Logging Retry Policy Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/automatic-failover/README.md Illustrates building an ICluster instance with a retry policy that logs every retry decision at LogLevel.Info. Ensure you have configured logging for the driver to see these messages. ```csharp ICluster cluster = Cluster.Builder() .AddContactPoints("127.0.0.1", "127.0.0.2") .WithRetryPolicy(new LoggingRetryPolicy(new DefaultRetryPolicy())) .Build(); ISession session = cluster.Connect(); ``` -------------------------------- ### Implement Proxy Login Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/auth/README.md Configures the DsePlainTextAuthProvider to authenticate as one user while acting as another. ```csharp var authProvider = new DsePlainTextAuthProvider("ben", "ben", "alice"); var cluster = Cluster.builder() .AddContactPoint("host1") .WithAuthProvider(authProvider) .Build(); var session = cluster.Connect(); // All requests will be executed as 'alice' session.Execute(query); ``` -------------------------------- ### Configure and Use Mapper for Object Mapping Source: https://context7.com/datastax/csharp-driver/llms.txt Automates mapping between CQL rows and C# objects. Configure mappings once at application startup. ```csharp using Cassandra; using Cassandra.Mapping; // Define your POCO class public class User { public Guid UserId { get; set; } public string Name { get; set; } public string Email { get; set; } public DateTimeOffset CreatedAt { get; set; } } // Configure mappings (do once at startup) MappingConfiguration.Global.Define( new Map() .TableName("users") .PartitionKey(u => u.UserId) .Column(u => u.UserId, cm => cm.WithName("id")) .Column(u => u.Name, cm => cm.WithName("name")) .Column(u => u.Email, cm => cm.WithName("email")) .Column(u => u.CreatedAt, cm => cm.WithName("created_at"))); var session = cluster.Connect("my_keyspace"); var mapper = new Mapper(session); // Insert a new user var newUser = new User { UserId = Guid.NewGuid(), Name = "Alice Smith", Email = "alice@example.com", CreatedAt = DateTimeOffset.UtcNow }; await mapper.InsertAsync(newUser); // Fetch users with CQL IEnumerable users = mapper.Fetch("WHERE name = ?", "Alice Smith"); // Fetch single user User user = mapper.SingleOrDefault("WHERE id = ?", newUser.UserId); // Update user user.Email = "alice.smith@example.com"; mapper.Update(user); // Delete user mapper.Delete(user); // Fetch with automatic SELECT generation IEnumerable allUsers = mapper.Fetch(); // Fetch single column values IEnumerable emails = mapper.Fetch("SELECT email FROM users"); ``` -------------------------------- ### Initialize CompositeObserverFactoryBuilder in Configuration Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md Configures the builder with specific metrics and tracer observers. ```csharp internal Configuration(...) { (...) ObserverFactoryBuilder = new CompositeObserverFactoryBuilder( new MetricsObserverFactoryBuilder(MetricsEnabled), new TracerObserverFactoryBuilder(driverTracer)); (...) } ``` -------------------------------- ### Configure Derived Execution Profiles Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/execution-profiles/README.md Demonstrates creating execution profiles that inherit parameters from base profiles, including the use of WithDerivedProfile. ```csharp var cluster = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithExecutionProfiles(opts => opts .WithProfile("default", profile => profile .WithLoadBalancingPolicy(Policies.NewDefaultLoadBalancingPolicy("dc1")) .WithConsistencyLevel(ConsistencyLevel.LocalOne) .WithSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(delay: 50, maxSpeculativeExecutions: 1))) .WithProfile("local-quorum", profile => profile .WithConsistencyLevel(ConsistencyLevel.LocalQuorum) .WithSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(delay: 100, maxSpeculativeExecutions: 1))) .WithProfile("remote-one", profile => profile .WithLoadBalancingPolicy(Policies.NewDefaultLoadBalancingPolicy("dc2"))) .WithConsistencyLevel(ConsistencyLevel.LocalOne) .WithSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(delay: 2000, maxSpeculativeExecutions: 1))) .WithDerivedProfile("remote-quorum", "remote-one", profile => profile .WithConsistencyLevel(ConsistencyLevel.LocalQuorum) .WithSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(delay: 2500, maxSpeculativeExecutions: 1)))) .Build(); ``` -------------------------------- ### Execute Graph Queries Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/graph-support/README.md Demonstrates executing graph creation and data manipulation queries using SimpleGraphStatement. ```csharp session.ExecuteGraph("system.createGraph('demo').ifNotExist().build()"); GraphStatement s1 = new SimpleGraphStatement("g.addV(label, 'test_vertex')").SetGraphName("demo"); session.ExecuteGraph(s1); GraphStatement s2 = new SimpleGraphStatement("g.V()").SetGraphName("demo"); GraphResultSet rs = session.ExecuteGraph(s2); ``` -------------------------------- ### Execute Simple Statement with Routing Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/routing-queries/README.md Execute a simple INSERT statement. You must explicitly set the routing values corresponding to the partition key. ```csharp var id = Guid.NewGuid(); var query = new SimpleStatement( "INSERT INTO users (id, name) VALUES (?, ?)", id, "Franz Ferdinand"); // You must specify the values that compose the partition key query.SetRoutingValues(id); session.Execute(query); ``` -------------------------------- ### Enable Default TLS/SSL Encryption Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/tls/README.md Use the WithSSL method on the Cluster builder to enable default TLS/SSL encryption. ```csharp var cluster = Cluster.Builder() .AddContactPoints(...) .WithSSL() .Build(); ``` -------------------------------- ### Bind and Execute Prepared Statement Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/routing-queries/README.md Bind parameters to a prepared statement and execute it. The driver handles routing automatically. ```csharp BoundStatement bound = prepared.Bind(Guid.NewGuid(), "Franz Ferdinand"); session.Execute(bound); ``` -------------------------------- ### Execute Batch with Execution Profile Source: https://github.com/datastax/csharp-driver/blob/master/doc/upgrade-guide/README.md Use this method on IMapper to execute a batch of CQL statements with a specified execution profile. ```csharp void Execute(ICqlBatch batch, string executionProfile) ``` ```csharp Task ExecuteAsync(ICqlBatch batch, string executionProfile) ``` -------------------------------- ### Retrieve Metrics with AppMetrics Extensions Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/metrics/README.md Demonstrates retrieving specific host metrics using generic registries, provider-specific extension methods, and accessing metric values. ```csharp // Get a specific metric of a specific host using the generic registry and converting it to the provider's type IAppMetricsTimer cqlMessagesMetric = nodeMetrics.Timers[NodeMetric.Counters.Errors].ToAppMetricsTimer(); // Get a specific metric of a specific host (requires AppMetrics Provider) IAppMetricsCounter counterAppMetrics = metrics.GetNodeMetric(host, NodeMetric.Counters.Errors); // Get a specific metric of a specific host with AppMetrics extension method IAppMetricsCounter counterAppMetrics = metrics.GetNodeCounter(host, NodeMetric.Counters.Errors); // Get value of that metric (IAppMetricsCounter provides a GetValue() method) long bytesSent = counterAppMetrics.GetValue(); ``` -------------------------------- ### Enable OpenTelemetry Tracing in C# Driver Source: https://context7.com/datastax/csharp-driver/llms.txt Configure OpenTelemetry tracer provider and enable instrumentation on the driver. Optionally include database statements and batch child statements in traces. ```csharp using Cassandra; using Cassandra.OpenTelemetry; using OpenTelemetry; using OpenTelemetry.Trace; // Configure OpenTelemetry tracer provider using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(CassandraActivitySourceHelper.ActivitySourceName) .AddConsoleExporter() .Build(); // Enable OpenTelemetry instrumentation on the driver var cluster = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithOpenTelemetryInstrumentation() .Build(); // Include query text in traces (optional, disabled by default) var clusterWithStatements = Cluster.Builder() .AddContactPoint("127.0.0.1") .AddOpenTelemetryInstrumentation(options => { options.IncludeDatabaseStatement = true; options.BatchChildStatementLimit = 10; }) .Build(); var session = cluster.Connect("my_keyspace"); // Queries will now generate OpenTelemetry traces var rs = await session.ExecuteAsync(new SimpleStatement("SELECT * FROM users")); // Trace output includes: db.system, db.operation.name, db.namespace, server.address, server.port ``` -------------------------------- ### Define MyMappings for User and UserByName Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/mapper/batch/README.md Configure mappings for User and UserByName classes to specific keyspace and table names, including partition and column definitions. ```csharp public class MyMappings : Mappings { public MyMappings() { For() .KeyspaceName("ks_example") .TableName("users") .PartitionKey(u => u.UserId) .Column(u => u.UserId, cm => cm.WithName("id")) .Column(u => u.Name, cm => cm.WithName("name")); For() .KeyspaceName("ks_example") .TableName("users_by_name") .PartitionKey(u => u.UserId) .Column(u => u.UserId, cm => cm.WithName("id")) .Column(u => u.Name, cm => cm.WithName("name")); } } ``` -------------------------------- ### Configure cluster with AES encryption policy Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/column-encryption/README.md Initialize the C# driver cluster, applying the configured AESColumnEncryptionPolicy to enable client-side column encryption. ```csharp var policy = new AesColumnEncryptionPolicy(); policy.AddColumn("ks", "table", "id", idKey, ColumnTypeCode.Uuid); policy.AddColumn("ks", "table", "address", addressKey, ColumnTypeCode.Text); var cluster = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithColumnEncryptionPolicy(policy) .Build(); ``` -------------------------------- ### Enable OTLP Exporter Source: https://github.com/datastax/csharp-driver/blob/master/examples/OpenTelemetry/DistributedTracing/README.md Uncomment this line in Program.cs to enable an OTLP exporter for distributed tracing. This is useful for integrating with systems like Jaeger. ```csharp //.AddOtlpExporter(opt => opt.Endpoint = new Uri("http://localhost:4317")) // uncomment if you want to use an OTPL exporter like Jaeger ``` -------------------------------- ### Configure SSL with Custom Options Source: https://context7.com/datastax/csharp-driver/llms.txt Enables TLS/SSL encryption with custom options, specifically enabling certificate revocation checking. ```csharp using Cassandra; using System.Security.Cryptography.X509Certificates; // SSL with custom options var cluster2 = Cluster.Builder() .AddContactPoint("secure-host") .WithSSL(new SSLOptions() .SetCertificateRevocationCheck(true)) .Build(); ``` -------------------------------- ### Build Specific Project and Target Framework Source: https://github.com/datastax/csharp-driver/blob/master/CONTRIBUTING.md Builds a specific project within the solution against a designated .NET target framework. Useful for cross-platform builds or targeting specific runtimes. ```bash dotnet build src/Cassandra/Cassandra.csproj -f netstandard2.0 dotnet build src/Cassandra.Tests/Cassandra.Tests.csproj -f net8 dotnet build src/Cassandra.IntegrationTests/Cassandra.IntegrationTests.csproj -f net8 ``` -------------------------------- ### Executing simple vector statements Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/vectors/README.md Shows how to insert and query vector data using SimpleStatement. ```csharp await session.ExecuteAsync( new SimpleStatement( "INSERT INTO table1 (i, j) VALUES (?, ?)", 1, new CqlVector(1.0f, 2.0f, 3.0f))); var rowSet = await session.ExecuteAsync( new SimpleStatement( "SELECT * FROM table1 ORDER BY j ANN OF ? LIMIT ?", new CqlVector(0.6f, 0.5f, 0.9f), 1)); var row = rowSet.Single(); var i = row.GetValue("i"); var j = row.GetValue?>("j"); ``` -------------------------------- ### Configure SSL with Client Certificate Authentication Source: https://context7.com/datastax/csharp-driver/llms.txt Enables TLS/SSL encryption and configures client certificate authentication using a specified PFX certificate file and password. ```csharp using Cassandra; using System.Security.Cryptography.X509Certificates; // SSL with client certificate authentication var clientCert = new X509Certificate2(@"C:\certs\client.pfx", "password"); var cluster3 = Cluster.Builder() .AddContactPoint("secure-host") .WithSSL(new SSLOptions() .SetCertificateCollection(new X509Certificate2Collection { clientCert })) .Build(); ``` -------------------------------- ### Instantiate Mapper Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/mapper/README.md Create a new Mapper instance using an existing ISession. ```csharp IMapper mapper = new Mapper(session); ``` -------------------------------- ### Execute Prepared Statement in C# Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/core/statements/prepared/README.md Prepare a query string and bind values to create a bound statement for execution. ```csharp PreparedStatement prepared = session.Prepare("insert into product (sku, description) values (?, ?)"); BoundStatement bound = prepared.Bind("234827", "Mouse"); session.Execute(bound); ``` -------------------------------- ### Import Mapper namespace Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/mapper/README.md Include the necessary namespace to access Mapper functionality. ```csharp using Cassandra.Mapping; ``` -------------------------------- ### Define Purchase class and MyMappings Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/mapper/batch/README.md Define a Purchase class and its corresponding mappings for use in conditional batch statements. Note the use of AsStatic() for the balance column. ```csharp private class Purchase { public Guid UserId { get; set; } public Guid ExpenseId { get; set; } public int Amount { get; set; } public int Balance { get; set; } } private class MyMappings : Mappings { public MyMappings() { For() .KeyspaceName("ks_example") .TableName("purchases") .PartitionKey(u => u.UserId) .ClusteringKey(u => u.ExpenseId) .Column(u => u.UserId, cm => cm.WithName("user_id")) .Column(u => u.ExpenseId, cm => cm.WithName("expense_id")) .Column(u => u.Amount, cm => cm.WithName("amount")) .Column(u => u.Balance, cm => cm.WithName("balance").AsStatic()); } } ``` -------------------------------- ### Insert with Execution Profile and Options Source: https://github.com/datastax/csharp-driver/blob/master/doc/upgrade-guide/README.md Use this method on IMapper to insert a POCO object with optional query settings and a specified execution profile. ```csharp void Insert(T poco, string executionProfile, CqlQueryOptions queryOptions = null) ``` ```csharp Task InsertAsync(T poco, string executionProfile, CqlQueryOptions queryOptions = null) ``` -------------------------------- ### Prepare statement with per-query keyspace Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/components/core/statements/per_query_keyspace/README.md When preparing statements, you can specify the target keyspace as a parameter in the `Session.Prepare()` method. This is required for bound statements. ```csharp PreparedStatement pst = session.Prepare("SELECT * FROM foo WHERE k = ?", "test"); // Will query test.foo: BoundStatement bs = pst.Bind(1); ``` -------------------------------- ### Create Linq IQueryable Instance with Specific Configuration Source: https://github.com/datastax/csharp-driver/blob/master/doc/upgrade-guide/README.md Obtain an IQueryable instance for querying Cassandra using a specific mapping configuration. This allows for custom mapping definitions per query. ```csharp var config = new MappingConfiguration(); var users = new Table(session, config); ``` -------------------------------- ### Capture Cassandra Activity with Tracer Provider Source: https://github.com/datastax/csharp-driver/blob/master/proposals/open-telemetry/tracing-rfc.md When setting up the tracer provider, include the Cassandra source name to capture activity. The `CassandraInstrumentation.ActivitySourceName` is available in the `CassandraCSharpDriver.OpenTelemetry` package. ```csharp using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(CassandraInstrumentation.ActivitySourceName) .AddConsoleExporter() .Build(); ``` -------------------------------- ### Include OpenTelemetry Instrumentation in Cluster Builder Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/opentelemetry/README.md Add the `Cassandra.OpenTelemetry` package and use the `WithOpenTelemetryInstrumentation()` extension method when building your cluster to enable tracing. ```csharp var cluster = Cluster.Builder() .AddContactPoint(Program.ContactPoint) .WithOpenTelemetryInstrumentation() .Build(); ``` -------------------------------- ### Configure MacOS loopback aliases for Simulacron Source: https://github.com/datastax/csharp-driver/blob/master/CONTRIBUTING.md Run this script on MacOS to create loopback aliases required by Simulacron for multi-node simulation. ```bash #!/bin/bash for sub in {0..4}; do echo "Opening for 127.0.$sub" for i in {0..255}; do sudo ifconfig lo0 alias 127.0.$sub.$i up; done done ``` -------------------------------- ### Run Unit Tests for Specific Target Framework Source: https://github.com/datastax/csharp-driver/blob/master/CONTRIBUTING.md Executes unit tests for the specified project and target framework. The default target frameworks for tests are `net8` and `net481`. ```bash dotnet test src/Cassandra.Tests/Cassandra.Tests.csproj -f net8 ``` -------------------------------- ### Configure Plain Text Authentication Source: https://context7.com/datastax/csharp-driver/llms.txt Sets up plain text authentication using username and password credentials for connecting to a Cassandra cluster. ```csharp using Cassandra; using Cassandra.DataStax.Auth; // Plain text authentication (PasswordAuthenticator) var cluster1 = Cluster.Builder() .AddContactPoint("127.0.0.1") .WithCredentials("cassandra_user", "cassandra_password") .Build(); ``` -------------------------------- ### Create AesKeyAndIV objects Source: https://github.com/datastax/csharp-driver/blob/master/doc/features/column-encryption/README.md Instantiate AesKeyAndIV with a key, and optionally an IV. If no IV is provided, a new one is generated for each encryption operation. ```csharp var keyOnly = new AesColumnEncryptionPolicy.AesKeyAndIV(key, iv); var keyAndIv = new AesColumnEncryptionPolicy.AesKeyAndIV(key); ``` -------------------------------- ### Connect to DataStax Astra Cloud in C# Source: https://context7.com/datastax/csharp-driver/llms.txt Uses a secure connection bundle and credentials to connect to an Astra cloud database. ```csharp using Cassandra; // Connect to Astra using the secure connection bundle var session = Cluster.Builder() .WithCloudSecureConnectionBundle(@"C:\path\to\secure-connect-DATABASE_NAME.zip") .WithCredentials("client_id", "client_secret") .Build() .Connect(); // Execute queries normally var rs = session.Execute("SELECT * FROM system.local"); Console.WriteLine($"Connected to cluster: {rs.First().GetValue("cluster_name")}"); ```