Home > BigData > How to connect Cassandra and .Net Framework 3.5

How to connect Cassandra and .Net Framework 3.5

Share on TwitterSubmit to reddit

I’ve recently worked in a project with Cassandra and .Net Framework 3.5. Unfortunately most of the latest version of Cassandra clients for .Net only compile with Framework 4.0, it’s the case for:

So we chose the client:

Which official description is: “Cassandra-sharp is a .NET client for Apache Cassandra. It features connection strategies to adapt to cluster topology and client constraints. Overall, cassandra-sharp aims at simplicity and robustness in a small library compatible with .NET 3.5 and 4.0.”

In our case we have implemented the cassandra-sharp client within a VB.Net 3.5 (it would work in C# as well) project in Microsoft Visual Basic 2008 Express edition. Considering you already have a Cassandra server up and running (more info: http://www.datastax.com/products/community) a CQL query from .Net 3.5 can be easily executed with the following example:

  • Download cassandra-sharp client from http://code.google.com/p/cassandra-sharp/
  • Create a new project as a “Console Application”
  • Include into your project the libraries “cassandra-sharp.dll” and “log4net.dll” from the cassandra-sharp package.
  • Create a new file in your project called “app.config”, and add the following code where the <Server> tag contains the IP address of your Cassandra server:
<?xml version="1.0"?>
<configuration>

  <configSections>
    <section name="CassandraSharp" type="CassandraSharp.SectionHandler, cassandra-sharp"/>
  </configSections>

  <CassandraSharp>
    <Cluster name="TestCassandra">
      <Behavior maxRetries="3" keyspace="samples" readCL="ONE" writeCL="LOCAL_QUORUM"/>

      <Transport type="Framed" port="9160" poolSize="1"/>

      <Endpoints>
        <Server>127.0.0.1</Server>
      </Endpoints>
    </Cluster>
  </CassandraSharp>

  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>
  • Edit your main file “Main.vb” (or the name you have used) and include the following code:
Imports CassandraSharp
Imports System.Text
Imports CassandraSharp.Config
Imports CassandraSharp.MadeSimple
Imports Apache.Cassandra

Module Main

    Sub Main()

        ' Loading Cassandra configuration...
        XmlConfigurator.Configure()
        Dim cluster As ICluster = ClusterManager.GetCluster("TestCassandra")

        ' Define your query
        Dim queryString As String = "select * from table"

        'Execute your query in Cassandra
        Dim res As CqlResult = cluster.ExecuteCql(queryString)

        ' Connection release
        ClusterManager.Shutdown()

        ' Get results. In this example integer, date and double types
        '
        'getId(res.Rows.ElementAt(i).Columns.ElementAt(0).Value
        'getDate(res.Rows.ElementAt(i).Columns.ElementAt(j).Name)
        'getDouble(res.Rows.ElementAt(i).Columns.ElementAt(j).Value))  

    End Sub
End Module
  • The variable “res” contains the result of the query. Remember that the data from Cassandra (row id, column name, column value) has a byte array format, so you would have to transform it to a data type such as String, int, double, Datetime, etc. As an example here is the code of some helper functions to transform to Int, Double and DateTime:
Public Function getId(ByVal value As Byte()) As Integer
        Dim buffer As Byte() = New Byte(value.Length - 1) {}
        value.CopyTo(buffer, 0)
        Array.Reverse(buffer)
        Dim result As Integer = BitConverter.ToInt32(buffer, 0)
        Return result
    End Function

    Public Function getDate(ByVal value As Byte()) As DateTime
        Dim buffer As Byte() = New Byte(value.Length - 1) {}
        value.CopyTo(buffer, 0)
        Array.Reverse(buffer)
        Dim ticks As Long = BitConverter.ToInt64(buffer, 0)
        Dim dateTime As New System.DateTime(1970, 1, 1, 0, 0, 0, _
             0)

        dateTime = dateTime.AddMilliseconds(ticks)
        Return dateTime
    End Function

    Public Function getDouble(ByVal value As Byte()) As Double
        Dim buffer As Byte() = New Byte(value.Length - 1) {}
        value.CopyTo(buffer, 0)
        Array.Reverse(buffer)
        Dim result As Double = BitConverter.ToDouble(buffer, 0)
        Return result
    End Function

The code is also available in GitHub:

Hope it helps!

Thanks for visiting semoru.com

Share on TwitterSubmit to reddit

9 thoughts on “How to connect Cassandra and .Net Framework 3.5

  1. Hi semoru,

    I would like to know of you why theses confiration (KeySpce more specifically) isn’t supported in Cassandra-Sharp…
    Well, I got it work specifying the KeySpace in the query, like this:

    string query = “select * from \”KeySpace\”.ColumnFamily”;

    Note that I had to put the \”\” between the KeySpace name, because if i don’t do it, I got a exception saying: “the KeySpace *name* does not exist”.

    Well, it wasn’t very easy to discover this \”KeySpace\” (doesn’t see that in any documentation, well, i didn’t see many documentation sincerely), so, do you know some Cassandra-Sharp documentation where these things are addressed?

    Thanks!

  2. Hi Lucas,

    you shouldn’t specify the KeySpace in the query. This parameter is set in the config file, under the XML-node “Behavior”:

    <?xml version="1.0"?>
    <configuration>
    
      <configSections>
        <section name="CassandraSharp" type="CassandraSharp.SectionHandler, cassandra-sharp"/>
      </configSections>
    
      <CassandraSharp>
        <Cluster name="TestCassandra">
          <Behavior maxRetries="3" keyspace="your key space" readCL="ONE" writeCL="LOCAL_QUORUM"/>
    
          <Transport type="Framed" port="9160" poolSize="1"/>
    
          <Endpoints>
            <Server>127.0.0.1</Server>
          </Endpoints>
        </Cluster>
      </CassandraSharp>
    
      <startup>
        <supportedRuntime version="v2.0.50727"/>
      </startup>
    </configuration>

    So then, when you prepare the query, you only have to specifiy the ColumnFamily.

    Hope it helps!

  3. Hello,

    there are several things that do not quite work when I have copied, converted to c# and paste the code.

    using CassandraSharp.MadeSimple;
    using Apache.Cassandra;

    It cannot find MadeSimple and Apache. (Other using statements are OK after adding reference to cassandra library).

    CqlResult res = cluster.ExecuteCql(queryString);
    CqlResults and ExecuteCql cannot be found.

    Could you give me some guidelines where it may result from?
    The rest of code is OK.

    Thanks in advance!

  4. Hi johnyjj2, thanks for your message.

    Normally if you include the references in your project you should’t have problems to find the classes MadeSimple, Apache, CQLResults and ExecuteCql. Which version of cassandra-sharp are you using? remember that only version 0.6.4 is working in .net 3.5

    Hope it helps!

  5. Hello,
    thanks for your reply. The only what I have done was including in Solution Explorer in Referencews section CassandraSharp (cassandra-sharp-bin-2.3.2\CassandraSharp.dll). I use .NET Framework 4 Client Profile.
    Things like using CassandraSharp; and using CassandraSharp.Config; are accepted by VS.
    Regards!

  6. Hi,

    i added the keyspace in behaviour section as discussed above.still i am getting the same error.

    Do we need to add additional logic to read the same or cassandra takes care of it as in the case of endpoint.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


+ 1 = eight

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>