Connect to Cassandra with C#
In this article, we will introduce how to connect to Cassandra by using C#. We will start to install C# development environment and then provide simple demo code for connecting remote server (Cassandra) and local program.
Download Visual Studio Community
Go to visualstudio and choose Community Version to install.
Install Visual Studio
Follow the instructions and install.
Create a new project
Choose Console Project and click Next.
Enter Project Name and click Create
Install Cassandra C# driver
In the left side of your development window, Open Solution View and notice that there is a folder called Packages.
Right-click Packages and click Add Packages…
Find out CassandraCSharpDriver in the window, and click Add Package.
If you unfold the Packages folder, you will see that a list of libraries has been installed in your local project.
Write sample code
Replace public IP, username, and password with your real settings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using Cassandra; namespace Instaclustr.Cassandra.ConnectionSample { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello Cassandra!"); var cluster = Cluster.Builder() .AddContactPoints(<PUBLIC IP1>, <PUBLIC IP2>, <PUBLIC IP3>,..) .WithPort(9042) .WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy("AWS_VPC_AP_SOUTHEAST_2")) .WithAuthProvider(new PlainTextAuthProvider(<Username>, <Password>)) .Build(); // Connect to the nodes using a keyspace var session = cluster.Connect("system_distributed"); // Get name of a Cluster Console.WriteLine("The cluster's name is: " + cluster.Metadata.ClusterName); // Execute a query on a connection synchronously var rs = session.Execute("SELECT * FROM repair_history"); // Iterate through the RowSet foreach (var row in rs) { var value = row.GetValue<string>("keyspace_name"); Console.WriteLine(value); // Do something with the value } } } } |
Click Run and Start without Debugging, we can see the result as the following
Hello I tried connecting AWS keyspace but getting error
‘All hosts tried for query failed (tried 3.83.170.153:9142: OperationTimedOutException ‘The host 3.83.170.153:9142 did not reply before timeout 5000ms
Hi Virendra, While AWS Keyspace is largely Cassandra-compatible there are some significant differences and Keyspace is not our area of expertise so we can’t help there sorry. You might have more luck trying one of our Apache Cassandra clusters on a free trial!
How do we add and send SSL certificate over here