Programming Languages on Power

 View Only

Connecting .NET applications to Apache Cassandra on Power: A step-by-step guide

By Janani Janakiraman posted Wed July 12, 2023 07:52 AM

  

Updated: May 06, 2024
IBM®, Microsoft®, and Red Hat® have announced the availability of .NET 8, with delivery included in RHEL 8.9, RHEL 9.3, and Red Hat OpenShift. This release also provides support for Linux on Power (ppc64le) and IBM Z systems (s390x).

You can find more .NET on Power resources here.

===============================================================================

Since Microsoft unveiled .NET 7 in November 2022, one standout feature that has been widely discussed is the support for running .NET applications on Power. Ever since this announcement, we have been exploring the ability of .NET applications to establish connections with diverse database servers on IBM Power.

In this blog post, I will guide you through the process of creating a sample C# application called ‘Hello DB’, which showcases the ability to connect with a NoSQL Database Server - Apache Cassandra. Get ready to embark on this technical journey and expand your knowledge in the realm of .NET application development!

What is Apache Cassandra?

Apache Cassandra is an open source NoSQL distributed database that has gained the trust of numerous companies due to its remarkable scalability, high availability, and uncompromising performance. Additionally, apart from the free open source version, there are multiple distributions of Cassandra available, one of which is provided by IBM's OEM partner, DataStax.

DataStax's distribution of Apache Cassandra is particularly noteworthy as it is distributed and supported by the very team that played a major role in developing Cassandra's codebase. Furthermore, IBM and DataStax collaborate to offer DataStax Enterprise with IBM, empowering enterprises to build and manage modern data applications in hybrid and multi-cloud environments.

Apache Cassandra use cases

Apache Cassandra has proven to be a valuable asset for numerous renowned brands such as Netflix, Uber, Instagram, Reddit, SoundCloud, and many others. Its versatility and robustness make it an ideal choice for various brands.

Here are some common scenarios where Apache Cassandra shines:

  • E-commerce and inventory management.
  • Personalization, recommendations, and customer experience.
  • Internet of Things (IoT) and edge computing.
  • Fraud detection and authentication.
  • Financial services and payments.
  • Messaging.
  • Playlists.
  • Logistics and asset management.
  • Content management systems.
  • Transaction logging.
  • Tracking of all kinds, including packages and orders.
  • Digital and media management.

Connect to Apache Cassandra from a .Net sample application

Before you begin, ensure you have a Power Virtual Machine (VM) with RHEL 8 or RHEL 9. Install the .NET SDK and an Apache Cassandra server on the VM. In this example, I installed both on the same VM.

This example is a simplified configuration focused on showcasing the connectivity of .NET applications to Apache Cassandra database.

Apache Cassandra is a distributed database. To get the maximum benefit out of Apache Cassandra, you must run it on multiple machines.

Connecting to Apache Cassandra from a .NET sample application involves a series of steps. Let's break it down:

Step 1: Set up the Apache Cassandra database server

This section deals with how to install, configure, and start the Apache Cassandra database server and to create a sample keyspace and a table inside it.

I'll demonstrate the steps to install the open source version of Apache Cassandra on the same RHEL machine with the .NET SDK. However, you can install Apache Cassandra on any machine or OS of your choice.

  1. Build a docker image of Apache Cassandra database server and .NET .

    Ensure that the latest version of Java is installed on your machine.

    Download Apache Cassandra - for this example, I used version 4.1.1. If it's no longer available, you can get the latest version from the official Apache Cassandra website.

    Run the following command to install your Apache Cassandra server.

    # Download Dockerfile and licensing.txt for Apache Cassandra from the buildscript repo.
    wget https://raw.githubusercontent.com/ppc64le/build-scripts/master/c/cassandra/Dockerfiles/4.1.x-ubi8/Dockerfile
    wget https://raw.githubusercontent.com/ppc64le/build-scripts/master/c/cassandra/Dockerfiles/4.1.x-ubi8/licensing.txt
    
    # Include the command to install dotnet in the Dockerfile
    sed -i '25i \\nRUN yum install -y dotnet libicu vim\n' Dockerfile
    
    # Build the cassdb image using this Dockerfile
    docker build --pull --no-cache -t cassdb --build-arg VERSION=4.1.3 .
    
    
  2. Create the container from the just created cassdb image.

    docker run -ti localhost/cassdb /bin/bash
    [cassandra@153804e28654 cassandra]$ //inside container 153804e28654
  3. Start the server.

    Run the following command to start your Apache Cassandra server, it may take a little while for the server to fully start up.

    cassandra -R
  4. Verify your connection and create a table.

    Use the ‘cqlsh’ command to connect to the Cassandra server. In this example I created a sample keyspace and table called cycling.cyclist_alt_stats that will later be referenced in the .NET program.

    cqlsh
    Connected to Cassandra Cluster at 127.0.0.1:9042
    [cqlsh 6.1.0 | Cassandra 4.1.1 | CQL spec 3.4.6 | Native protocol v5]
    Use HELP for help.
    cqlsh> CREATE KEYSPACE IF NOT EXISTS cycling WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 };
    
    Warnings :
    Your replication factor 3 for keyspace cycling is higher than the number of nodes 1 for datacenter datacenter1
    
    cqlsh> USE cycling;
    cqlsh:cycling> CREATE TABLE cycling.cyclist_alt_stats ( id UUID PRIMARY KEY, lastname text, birthday timestamp, nationality text, weight text, height text );

Step 2: Build a .NET C# application to connect to the Apache Cassandra server

Now that the database server is set up, let's move on to creating a sample .NET application that connects to it. Run the following inside the Docker container.

  1. Create a sample .NET console application.

    Use the ‘dotnet new console’ command to create a new console application.

    # Create a dotnet console app in the cassDB directory
    dotnet new console -o cassDB

    Add the CassandraCSharpDriver package, a feature-rich and highly tunable C# client library for Apache Cassandra and DataStax Enterprise.

    # Add the CassandraCSharpDriver
    cd cassDB/
    dotnet add package CassandraCSharpDriver
  2. Build the C# code.

    Below is a sample C# program that connects to the Cassandra database server and retrieves information about keyspaces and tables in the ‘cycling’ keyspace that was created during the database setup.

    Note: Provide the details of your database server in this program.

    # cat cassDB/Program.cs
    using System;
    using Cassandra;
    namespace Instaclustr.Cassandra.ConnectionSample
    {
        class CassandraConnectSample
        {
            public static void Main(string[] args)
            {
                Console.WriteLine("Hello Cassandra!");
                Cluster cluster = Cluster
                         .Builder()
                     .AddContactPoints("<<DB IP Address/Hostname>>","127.0.0.1")
                                     .WithPort(9042)
                                     .Build()
                     ;
            var session = cluster.Connect();
                Console.WriteLine("Connected to cluster: " + cluster.Metadata.ClusterName);
                var keyspaceNames = session
                    .Execute("SELECT * FROM system_schema.keyspaces")
                    .Select(row => row.GetValue<string>("keyspace_name"));
                Console.WriteLine("Found keyspaces:");
                foreach (var name in keyspaceNames)
                {
                    Console.WriteLine("- {0}", name);
                }
            // Note: Substitute Select statements with information from your database server
            var tableNames = session
                .Execute("SELECT table_name FROM system_schema.tables WHERE keyspace_name = 'cycling'").Select(row => row.GetValue<string>("table_name"));
            Console.WriteLine("TableNames:");
                foreach (var name in tableNames)
                {
                    Console.WriteLine("- {0}", name);
                }
        }
        }
    }
  3. Run the Program.

    Run the program using the dotnet run command, and you should see the output displaying the connected cluster name, keyspaces, and table names.

    # dotnet run
    
    Hello Cassandra!
    
    Connected to cluster: Cassandra Cluster
    
    Found keyspaces:
    - cycling
    - system_auth
    - system_schema
    - system_distributed
    - system
    - system_traces
    
    TableNames:
    - cyclist_alt_stats

Congratulations! You have successfully set up a .NET C# application to connect and interact with the Apache Cassandra database server.

Conclusion

This blog is all about creating a sample C# application that interacts with Apache Cassandra database server. From here, you can explore more advanced use cases and functionalities to leverage the power of .NET with Apache Cassandra in your applications. Feel free to experiment further and build upon this foundation to create even more sophisticated interactions with your data in the Cassandra database server. Happy coding!

Permalink