Wednesday, June 13, 2012

Using Apache Cassandra with .NET - Part 2


One major difference between Cassandra and a traditional relational database is that Cassandra supports a variable amount of columns per rows in any given column family. In this post we will insert a column to the column family, "Tweets" The tweet column family is of contains one row with the text “sample tweet text1”. We will also see the test case for a null value insert exception.

[TestMethod]
public void InsertOnSubmitInsertsANewValueToTheColumnFamily()
{
    var key = "1".ToCassandraByte();
    const string columnName = "text";
    const string value = "sample tweet text 1";

    using (var context = new CassandraContext("localhost", 9160, "Twitter"))
    {
        context.Column.DeleteOnSubmit(x => x.ColumnFamily == "Tweets" && x.Key == key);
        context.SubmitChanges();

        var column = new Column().SetNameValue(columnName, value);
        context.InsertOnSubmit("Tweets", key, column);

        context.SubmitChanges();

        var tweet = (from x in context.ColumnList
                        .Where(x => x.ColumnFamily == "Tweets" && x.Key == key)
                    select x.ToObject<Tweet>()).FirstOrDefault();

        Assert.AreEqual(value, tweet.text);

        context.Column.DeleteOnSubmit(x => x.ColumnFamily == "Tweets" && x.Key == key);
        context.SubmitChanges();
    }
}

[TestMethod]
[ExpectedException(typeof(Thrift.TApplicationException))]
public void InsertNullValueTest()
{
    var key = "1".ToCassandraByte();
    const string columnName = "text";

    using (var context = new CassandraContext("localhost", 9160, "Twitter"))
    {
        var column = new Column()
            .SetNameValue(columnName, null);
        context.InsertOnSubmit("Tweet", key, column);

        context.SubmitChanges();
    }
}

2 comments:

Fabio Rogerio said...

Hi,

I am working with Apache Cassandra to C# (Cassandraemon) but I am problem with Datetime.
How are you working with Datetime?
In my Class the atributes are Datetime.
Tranks!

Prajeesh Prathap said...

Hi Fabio,
Try the GetDateTime method.
http://cassandraemon.codeplex.com/workitem/32