Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 496 lines (375 sloc) 13.78 kb
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
using System;
using System.Linq;
using FluentCassandra.Connections;
using FluentCassandra.Types;
using FluentCassandra.Linq;
using System.Collections.Generic;
using System.Configuration;


namespace FluentCassandra.Sandbox
{
internal class Program
{
public static readonly string KeyspaceName = ConfigurationManager.AppSettings["TestKeySpace"];
public static readonly Server Server = new Server(ConfigurationManager.AppSettings["TestServer"]);


#region Setup

private static void SetupKeyspace()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
if (db.KeyspaceExists(KeyspaceName))
db.DropKeyspace(KeyspaceName);

var keyspace = new CassandraKeyspace(new CassandraKeyspaceSchema
{
Name = KeyspaceName,
}, db);

keyspace.TryCreateSelf();

// create column family using CQL
db.ExecuteNonQuery(@"
CREATE COLUMNFAMILY Posts (
KEY ascii PRIMARY KEY,
Title text,
Body text,
Author text,
PostedOn timestamp
);");

// create column family using API
keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema
{
FamilyName = "Tags",
KeyValueType = CassandraType.AsciiType,
ColumnNameType = CassandraType.Int32Type,
DefaultColumnValueType = CassandraType.UTF8Type
});

// create super column family using API
keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema
{
FamilyName = "Comments",
FamilyType = ColumnType.Super,
KeyValueType = CassandraType.AsciiType,
SuperColumnNameType = CassandraType.DateType,
ColumnNameType = CassandraType.UTF8Type,
DefaultColumnValueType = CassandraType.UTF8Type
});
}
}

#endregion

#region Console Helpers

private static void ConsoleHeader(string header)
{
Console.WriteLine(@"
************************************************
** " + header + @"
************************************************");
}

#endregion

#region Create Post

private static void CreateFirstPost()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";

var postFamily = db.GetColumnFamily("Posts");
var tagsFamily = db.GetColumnFamily("Tags");

// create post
ConsoleHeader("create post");
dynamic post = postFamily.CreateRecord(key: key);
post.Title = "My First Cassandra Post";
post.Body = "Blah. Blah. Blah. about my first post on how great Cassandra is to work with.";
post.Author = "Nick Berardi";
post.PostedOn = DateTimeOffset.Now;


// create tags
ConsoleHeader("create post tags");
dynamic tags = tagsFamily.CreateRecord(key: key);
tags[0] = "Cassandra";
tags[1] = ".NET";
tags[2] = "Database";
tags[3] = "NoSQL";

// attach the post to the database
ConsoleHeader("attaching record");
db.Attach(post);
db.Attach(tags);

// save the changes
ConsoleHeader("saving changes");
db.SaveChanges();
}
}

private static void CreateSecondPost()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "second-blog-post";

var postFamily = db.GetColumnFamily("Posts");
var tagsFamily = db.GetColumnFamily("Tags");

// create post
ConsoleHeader("create post");
dynamic post = postFamily.CreateRecord(key: key);
post.Title = "My Second Cassandra Post";
post.Body = "Blah. Blah. Blah. about my second post on how great Cassandra is to work with.";
post.Author = "Nick Berardi";
post.PostedOn = DateTimeOffset.Now;

// create tags
ConsoleHeader("create post tags");
dynamic tags = tagsFamily.CreateRecord(key: key);
tags[0] = "Cassandra";
tags[1] = ".NET";
tags[2] = "Database";
tags[3] = "NoSQL";

// attach the post to the database
ConsoleHeader("attaching record");
db.Attach(post);
db.Attach(tags);

// save the changes
ConsoleHeader("saving changes");
db.SaveChanges();
}
}

#endregion

#region Read Post

private static void ReadFirstPost()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";

var postFamily = db.GetColumnFamily("Posts");
var tagsFamily = db.GetColumnFamily("Tags");

// get the post back from the database
ConsoleHeader("getting 'first-blog-post'");

// query using API
dynamic post = postFamily.Get(key).FirstOrDefault();

// query using CQL-LINQ
dynamic tags = (
from t in tagsFamily
where t.Key == key
select t).FirstOrDefault();

// show details
ConsoleHeader("showing post");
Console.WriteLine(
String.Format("=={0} by {1}==\n{2}",
post.Title,
post.Author,
post.Body
));

// show tags
ConsoleHeader("showing tags");
foreach (var tag in tags)
Console.WriteLine(String.Format("{0}:{1}", tag.ColumnName, tag.ColumnValue));
}
}

private static void ReadAllPosts()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";

var tagsFamily = db.GetColumnFamily("Tags");

// get the post back from the database
ConsoleHeader("getting 'first-blog-post'");

// query using CQL
var posts = db.ExecuteQuery("SELECT * FROM Posts LIMIT 25");

// query using API
dynamic tags = tagsFamily.Get(key).FirstOrDefault();

// show details
ConsoleHeader("showing post");
foreach (dynamic post in posts)
{
Console.WriteLine(
String.Format("=={0} by {1}==\n{2}",
post.Title,
post.Author,
post.Body
));
}

// show tags
ConsoleHeader("showing tags");
foreach (var tag in tags)
Console.WriteLine(String.Format("{0}:{1}", tag.ColumnName, tag.ColumnValue));
}
}

#endregion

#region Update Post

private static void UpdateFirstPost()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";

var postFamily = db.GetColumnFamily("Posts");

// get the post back from the database
ConsoleHeader("getting 'first-blog-post' for update");

// query using API
dynamic post = postFamily.Get(key).FirstOrDefault();

post.Title = post.Title + "(updated)";
post.Body = post.Body + "(updated)";
post.Author = post.Author + "(updated)";
post.PostedOn = DateTimeOffset.Now;

// attach the post to the database
ConsoleHeader("attaching record");
db.Attach(post);

// save the changes
ConsoleHeader("saving changes");
db.SaveChanges();
}
}

#endregion

#region Create Comments

private static void CreateComments()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";

// get the comments family
var commentsFamily = db.GetSuperColumnFamily("Comments");

ConsoleHeader("create comments");
var postComments = commentsFamily.CreateRecord(key: key);

// lets attach it to the database before we add the comments
db.Attach(postComments);

var dt = new DateTime(2010, 11, 29, 5, 03, 00, DateTimeKind.Local);

// add 5 comments
for (int i = 0; i < 5; i++)
{
var comment = postComments.CreateSuperColumn();
comment["Name"] = "Nick Berardi";
comment["Email"] = "nick@coderjournal.com";

// you can also use it as a dynamic object
dynamic dcomment = comment;
dcomment.Website = "www.coderjournal.com";
dcomment.Comment = "Wow fluent cassandra is really great and easy to use.";

var commentPostedOn = dt;
postComments[commentPostedOn] = comment;

Console.WriteLine("Comment " + (i + 1) + " Posted On " + commentPostedOn.ToLongTimeString());
dt = dt.AddMinutes(2);
}

// save the comments
db.SaveChanges();
}
}

#endregion

#region Read Comments

private static void ReadComments()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{
var key = "first-blog-post";
var lastDate = DateTime.Now;

// get the comments family
var commentsFamily = db.GetSuperColumnFamily("Comments");

for (int page = 0; page < 2; page++)
{
// lets back the date off by a millisecond so we don't get paging overlaps
lastDate = lastDate.AddMilliseconds(-1D);

ConsoleHeader("showing page " + page + " of comments starting at " + lastDate.ToLocalTime());

// query using API
var comments = commentsFamily.Get(key)
.ReverseColumns()
.StartWithColumn(lastDate)
.TakeColumns(3)
.FirstOrDefault();

foreach (dynamic comment in comments)
{
var dateTime = (DateTime)comment.ColumnName;

Console.WriteLine(String.Format("{0:T} : {1} ({2} - {3})",
dateTime.ToLocalTime(),
comment.Name,
comment.Email,
comment.Website
));

lastDate = dateTime;
}
}
}
}

#endregion

#region CreateColumnFamilyWithUUIDOperator
private static void CreateColumnFamilyWithUUIDOperator()
{

using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{

db.ExecuteNonQuery("CREATE TABLE TestCF (KEY text PRIMARY KEY) WITH comparator=uuid AND default_validation=text;");

Guid columnName1 = GuidGenerator.GenerateTimeBasedGuid(DateTime.Now);

Guid columnName2 = GuidGenerator.GenerateTimeBasedGuid(DateTime.Now);

db.ExecuteNonQuery(string.Format("INSERT INTO TestCF (KEY, {0}, {1}) VALUES ('Key1', 'Value1', 'Value2')", columnName1, columnName2));

List<ICqlRow> rows = db.ExecuteQuery("SELECT * FROM TestCF WHERE KEY = 'Key1'").ToList();

Guid value = rows[0].Columns[1].ColumnName.GetValue<Guid>();

ConsoleHeader("Returned data from db");
ConsoleHeader(value.ToString());
}
}
#endregion

#region CreateColumnFamilyWithTimestampOperator
private static void CreateColumnFamilyWithTimestampOperator()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{

db.ExecuteNonQuery("CREATE TABLE TestCF2 (KEY text PRIMARY KEY) WITH comparator=timestamp AND default_validation=text;");

DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
DateTimeOffset TimeNow = DateTimeOffset.UtcNow;

var columnName2 = Convert.ToInt64(Math.Floor((TimeNow - UnixStart).TotalMilliseconds));
var columnName1 = columnName2 + 5000;

db.ExecuteNonQuery(string.Format("INSERT INTO TestCF2 (KEY, {0}, {1}) VALUES ('Key1', 'Value1', 'Value2')", columnName1, columnName2));

List<ICqlRow> rows = db.ExecuteQuery("SELECT * FROM TestCF2 WHERE KEY = 'Key1'").ToList();

DateTime value1 = rows[0].Columns[1].ColumnName.GetValue<DateTime>();
DateTime value2 = rows[0].Columns[2].ColumnName.GetValue<DateTime>();

ConsoleHeader("Returned data from db for timestamp comparator");
ConsoleHeader(value1.ToString());
ConsoleHeader(value2.ToString());

}
}
#endregion

#region TombstoneTest
private static void TombstoneTest()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{


db.ExecuteNonQuery("CREATE TABLE OfferReservation (KEY int PRIMARY KEY) WITH comparator = text AND default_validation = float");
db.ExecuteNonQuery("INSERT INTO OfferReservation (KEY, '25:100') VALUES (5, 0.25)");
db.ExecuteNonQuery("INSERT INTO OfferReservation (KEY, '25:101') VALUES (5, 0.25)");
db.ExecuteNonQuery("DELETE '25:100' FROM OfferReservation WHERE KEY = 5");

List<ICqlRow> rows = db.ExecuteQuery("SELECT '25:100' FROM OfferReservation WHERE KEY = 5").ToList();

}
}
#endregion

#region BigDecimalTest
private static void BigDecimalTest()
{
using (var db = new CassandraContext(keyspace: KeyspaceName, server: Server))
{

// arrange
db.ExecuteNonQuery("CREATE TABLE OfferReservation2 (KEY text PRIMARY KEY) WITH comparator = text AND default_validation = decimal");
db.ExecuteNonQuery("INSERT INTO OfferReservation2 (KEY, 'MyColumn') VALUES ('Key0', 1000000000000000000)");
db.ExecuteNonQuery("INSERT INTO OfferReservation2 (KEY, 'MyColumn') VALUES ('Key1', 0.25)");
db.ExecuteNonQuery("INSERT INTO OfferReservation2 (KEY, 'MyColumn') VALUES ('Key2', 2000000000000.1234)");
db.ExecuteNonQuery("INSERT INTO OfferReservation2 (KEY, 'MyColumn') VALUES ('Key3', -0.25)");
db.ExecuteNonQuery("INSERT INTO OfferReservation2 (KEY, 'MyColumn') VALUES ('Key4', -0.25122333)");

var actual = db.ExecuteQuery("SELECT * FROM OfferReservation2");

var results = actual.ToList();


var firstValue = (decimal)results.First(x => x.Key == "Key0")["MyColumn"];
var secondValue = (decimal)results.First(x => x.Key == "Key1")["MyColumn"];
var thirdValue = (decimal)results.First(x => x.Key == "Key2")["MyColumn"];
var fourthValue = (decimal)results.First(x => x.Key == "Key3")["MyColumn"];
var fifthValue = (decimal)results.First(x => x.Key == "Key4")["MyColumn"];

ConsoleHeader("Returned data from Big Decimal Test");
ConsoleHeader(firstValue.ToString());
ConsoleHeader(secondValue.ToString());
ConsoleHeader(thirdValue.ToString());
ConsoleHeader(fourthValue.ToString());
ConsoleHeader(fifthValue.ToString());
}
}
#endregion

private static void Main(string[] args)
{
SetupKeyspace();

CreateFirstPost();

CreateSecondPost();

ReadFirstPost();

ReadAllPosts();

UpdateFirstPost();

ReadFirstPost();

CreateComments();

CreateColumnFamilyWithUUIDOperator();

CreateColumnFamilyWithTimestampOperator();

ReadComments();

TombstoneTest();

BigDecimalTest();

Console.Read();
}
}
}
Something went wrong with that request. Please try again.