Thursday, July 24, 2014

NoSQL - MongoDB; Querying Data

Intro

In Part 1 of the series on NoSQL we were introduced to some of the general concepts behind this movement and how some of the technologies work in a general sense. In Part 2 we setup a MongoDB instance and wrote some C# code to insert data into the DB. Here in the final installment of the series we'll cover getting our data back out of the MongoDB instance.

To the Code!

Let's jump on into some code. Open back up the solution file you created back in Part 2, BlogMongo. If you named your stuff the same I did, you can open up default.aspx and default.aspx.cs also as that's where we'll put our code. I'm adding a new button to the form called btnQuery and giving it a new click event, which I'll leave empty for the moment. Now, do you remember this function from last week?

        private MongoCollection GetMongoCollection()
        {
            var client = new MongoClient("mongodb://localhost");
            var server = client.GetServer();
            var database = server.GetDatabase("BlogMongo");
            return database.GetCollection<Stuff>("stuffses");
        }


This is the function we used last week to connect to our database and our collection (table), using the Mongo C# driver. Now let's pull some data out of it; you'll be surprised just how easy this is:

        
        private void QueryStuff()
        {
            var collection = GetMongoCollection();
            var singleQuery = Query<Stuff>.EQ(e => e.SomeInt, 3);
            var stuff = collection.FindOneAs<Stuff>(singleQuery);
            var serializer = new JavaScriptSerializer();
            Response.Write(serializer.Serialize(stuff));
        }


This method pulls a single document/object out of the database and collection and spits it out in the response. The first line of the method just opens up a connection to the database and retrieves a reference to our collection. The second line creates a Mongo query object (you'll have to add a using statement to MongoDB.Driver.Builders). The query object should return object(s) of type Stuff, and the query shall look for an item with a value of 3 for the property SomeInt. The 3rd line tells the collection to pull back a single item of type Stuff that matches the query we created in the previous line. Line 4 creates a javascript serialization object that we're just using to display some friendly output, and line 5 spits out our serialized JSON object to the browser. Yes that's right, 3 lines of code (which we could easily condense further) pulls a specific object out of the database for us. Nifty! Go ahead and call this new method in the click event of your query button so you can see the output. Just in case you're not coding along with me, here's what the output looks like:

{"Id":"d639cae8-906a-4d7c-ab6d-553319a8a70e","SomeInt":3,"SomeString":"yeah, a string","ListOfStrings":["0","1","2"]}

Ok that was some really cool stuff. Almost as cool as an iceberg hitting you in the face! But how do we create some niftier, more complicated queries? Well as it turns out, the Mongo C# driver supports quite a few LINQ operations for data querying so you can have some real fun here! Let's see another example of querying MongoDB data, this time with LINQ:

        private void QueryStuff()
        {
            var collection = GetMongoCollection();
            var singleQuery = Query<Stuff>.EQ(e => e.SomeInt, 3);
            var stuff = collection.FindOneAs<Stuff>(singleQuery);
            var serializer = new JavaScriptSerializer();
            Response.Write(serializer.Serialize(stuff));
            var linqQuery = from item in collection.AsQueryable<Stuff>()
                            where item.SomeString == "yeah, a string"
                            select item;
            foreach (var item in linqQuery)
                Response.Write(serializer.Serialize(item));
        }



Our new code starts on line 6, beneath the prior junk. Line 6 sets up our LINQ query. I'm assuming you're familiar enough with LINQ to either create LINQ queries or google around to figure out how to make them so I won't go into detail on it, but as you can see this query is meant to select all the items from our collection who have a SomeString property with the value "yeah, a string". (Note: you'll need to add 2 more using statements. MongoDB.Driver.Linq and System.Linq). The foreach below it is just our output generation code. Easy, simple, and powerful, that's the best kind of code there is! Here is the new output (note that it includes the prior line of output too, so there's 1 extra object of type Stuff here):

{"Id":"d639cae8-906a-4d7c-ab6d-553319a8a70e","SomeInt":3,"SomeString":"yeah, a string","ListOfStrings":["0","1","2"]}{"Id":"d639cae8-906a-4d7c-ab6d-553319a8a70e","SomeInt":3,"SomeString":"yeah, a string","ListOfStrings":["0","1","2"]}{"Id":"494be80b-5f1a-48c4-9a15-3c01f89d2216","SomeInt":4,"SomeString":"yeah, a string","ListOfStrings":["0","1","2","3"]}{"Id":"a089f1bd-c33b-43ae-9f25-894e0c5e31c2","SomeInt":5,"SomeString":"yeah, a string","ListOfStrings":["0","1","2","3","4"]}{"Id":"097c8d4f-fff4-4daa-a535-75d38fe87199","SomeInt":3,"SomeString":"yeah, a string","ListOfStrings":["0","1","2"]}

That's pretty much all we're going to cover folks! These are just the basics of querying a MongoDB instance, but this will get you pretty far. Here's the complete code file in case you need it:

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using MongoDB.Driver.Linq;

namespace BlogMongo
{
    public class Stuff
    {
        public Guid Id { get; set; }
        public int SomeInt { get; set; }
        public string SomeString { get; set; }
        public IList<string> ListOfStrings { get; set; }
        public Stuff()
        {
            ListOfStrings = new List<string>();
        }
    }

    public partial class Default : System.Web.UI.Page
    {
        private Stuff GenerateStuff()
        {
            var stuff = new Stuff() { Id = Guid.NewGuid(), SomeInt = new Random().Next(0, 10), SomeString = "yeah, a string" };
            for (int i = 0; i < stuff.SomeInt; i++)
                stuff.ListOfStrings.Add(i.ToString());
            return stuff;
        }

        private MongoCollection GetMongoCollection()
        {
            var client = new MongoClient("mongodb://localhost");
            var server = client.GetServer();
            var database = server.GetDatabase("BlogMongo");
            return database.GetCollection<Stuff>("stuffses");
        }

        private void SaveStuff()
        {
            var stuff = GenerateStuff();
            var collection = GetMongoCollection();
            collection.Save(stuff);
        }

        private void QueryStuff()
        {
            var collection = GetMongoCollection();
            var singleQuery = Query<Stuff>.EQ(e => e.SomeInt, 3);
            var stuff = collection.FindOneAs<Stuff>(singleQuery);
            var serializer = new JavaScriptSerializer();
            Response.Write(serializer.Serialize(stuff));
            var linqQuery = from item in collection.AsQueryable<Stuff>()
                            where item.SomeString == "yeah, a string"
                            select item;
            foreach (var item in linqQuery)
                Response.Write(serializer.Serialize(item));
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryStuff();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveStuff();
        }

    }
}


What's Next

There are plenty of other ways to query a MongoDB instance. Play around with it and see what you can find, and read the resource links below. The Mongo C# LINQ tutorial and the Mongo C# Driver Getting Started pages are both very handy. This is my last blog on NoSQL (at least for now) though, so we'll be on to a different topic next week. If you want further NoSQL knowledge, then you're on your own buddy!

Resources

MongoDB C# Driver LINQ Tutorial
MongoDB Getting Started With the C# Driver

Thursday, July 17, 2014

NoSQL - MongoDB; Setup and Saving Data

Intro

In the previous post in this series I covered the basics of NoSQL data stores. I briefly mentioned MongoDB and its home in the NoSQL world as a document store. This week I'll go over some of the basics of using MongoDB in your c# code. Hold onto yer hats folks, we're in for a ride!

Setting up Mongo Locally

Go to the MongoDB download page, download and setup the correct version of Mongo for your OS. The instructions on their site are better than anything I can write, so do what they say and you'll be fine :). Be sure to actually run the MongoDB system after you install it (there are instructions for running the program on their website too), as it's pretty tough to connect to a database that isn't running.

A Free MongoDB GUI

MongoDB does not come with a GUI. If you've got a SQL Server background you've probably become accustomed to visualizing your data using SQL Server Management Studio, as it's a very handy GUI for navigating around your data. Mongo does have a couple options, they just don't come with MongoDB. For this tutorial, I'll be using MongoVue, which I suggest you download too for your own usage. I won't get into general usage of this program as it's pretty easy and it's detailed nicely on their website.

A Quick Bit of Mongo Terminology

If you have a SQL background you're well on your way to understanding how a MongoDB server is organized. The only thing that may throw you off initially is Mongo doesn't use tables. The closes thing they have is a Collection, which is roughly akin to a table. You're supposed to store only a single type of object within each collection, though it's not enforced. Still, it's a good idea as it keeps your data organized.

Saving Data

OK then cool cats, it's time to fire up Visual Studio and play with Mongo. Create yourself a new webforms project. I called mine BlogMongo, but call yours whatever you like. Now go into NuGet package manager and install the package "mongocsharpdriver" into your project. This NuGet package contains everything you need to read and write data using MongoDB and C#. It's the official package listed on the MongoDB site, so it's my preferred option though there are others out there.

Drop a server-side button on your webform.Call the button btnSave. Add a click() event to it.Add a couple using statements too; one for MongoDB.Bson and one for MongoDB.Driver. Now I'll work a little coding magic, paste it in here, and discuss below:

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;

namespace BlogMongo
{
    public class Stuff
    {
        public Guid Id { get; set; }
        public int SomeInt { get; set; }
        public string SomeString { get; set; }
        public IList<string> ListOfStrings { get; set; }
        public Stuff()
        {
            ListOfStrings = new List<string>();
        }
    }

    public partial class Default : System.Web.UI.Page
    {
        private Stuff GenerateStuff()
        {
            var stuff = new Stuff() { Id = Guid.NewGuid(), SomeInt = new Random().Next(0, 10), SomeString = "yeah, a string" };
            for (int i = 0; i < stuff.SomeInt; i++)
                stuff.ListOfStrings.Add(i.ToString());
            return stuff;
        }

        private MongoCollection GetMongoCollection()
        {
            var client = new MongoClient("mongodb://localhost");
            var server = client.GetServer();
            var database = server.GetDatabase("BlogMongo");
            return database.GetCollection<Stuff>("stuffses");
        }

        private void SaveStuff()
        {
            var stuff = GenerateStuff();
            var collection = GetMongoCollection();
            collection.Save(stuff);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveStuff();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}



You'll see after the using statements, the first thing we've done is add a class called Stuff. This is just our POCO (plain old CLR object) that we'll store in the database. The GenerateStuff() method within our page merely creates an object of type Stuff and puts some data in it.

GetMongoCollection() is where things start to get interesting. The first line in the function gets us a reference to an MongoClient object, which is how you connect to a Mongo database. The code is connecting to the local installation we did up above. Line 2 of the method gets a reference to the Mongo server. In this case it's the same machine, but hey we need an object. Line 3 gets a reference to a database named BlogMongo within the Mongo server. Those of you reading carefully might be thinking "uh...Pete, forget something? Like maybe creating the database?". Nay friends, nay! I forgot no such thing! Call it a feature or call it a piece of kryptonite, but Mongo will create a database automatically the first time you save some data into it. So, even though this database doesn't yet exist, we can reference it. Neato! Line 4 retrieves from the database a collection (or table if you'd rather) named stuffses. Note that this collection doesn't exist yet either; the same rule for database creation applies to collection creation.

The next interesting method is SaveStuff(). It's pretty compact at 3 lines, and the 3rd line is the only really new bit of awesome. This uses our collection reference that we created above and calls its Save() method in order to save our stuff object which is of type Stuff. The Save() method is used for an upsert. There are separate Insert() and Update() methods, but I prefer to use this multipurpose method.

Now, just to prove the magic is still alive in my relationship with the code, I ran this little fella and clicked the button 4 times. Here is the representation of our data in MongoVUE:


A quick note on the storage behind MongoDB: MongoDB stores its data in BSON format, which is Binary JSON. It's just a flavor of JSON with a little bit of extra bells and whistles. That's why, in the above screenshot of MongoVue, I elected to show you the JSON representation of our stored objects. JSON is a pretty universal communication mechanism these days, so getting used to seeing it an using it can only benefit you.

Ok one last quick note, then I'm done noting. Really: See how there is no field named Id in my stored objects in that MongoVue screenshot, even though there is a field in the class Stuff named Id? This is because the Mongo C# driver will automatically use any field named Id as your primary key/id field, which is how documents are identified within the MongoDB database. MongoDB however stores such fields with a name of _id unless you specify otherwise, so in this case the field Id (which is a useful standard, so name your Id fields this if you can) maps to _id in the MongoDB database.

What's Next?

Next week will be the final installment of NoSQL/Mongo. I'll show you guys how to query data. Maybe a few other tricks too if I have the time and we have enough space on the blog post.

I encourage you to read up on using the Mongo C# driver using the link in the resources section below.We only scratched the surface this week, and we'll lightly gouge it next week. There's still plenty we won't have time for though, so if you like MongoDB and you want to learn more, their website is the best place to get into it.

Resources

MongoDB-Getting Started With the C# Driver

Thursday, July 10, 2014

NoSQL - A Brief Introduction

Intro

What is a NoSQL Database? It's generally considered to be a data storage system that doesn't use relational tables and isn't accessed by structured query language. For decades now SQL and relational tables have been the standard for data storage. SQL storage, or more generally speaking relational storage, is driven by the concept of denormalization of data to reduce redundancy. You have many tables representing a structure of objects/entities, and you can join those many tables together to bring back the entire picture of your data and objects.

Why has NoSQL Become Big News?

Some larger companies such as Facebook, Twitter, and many others have found that modeling their data using a relational database system just wasn't fast enough and didn't scale well with load, and it is quite complex to the casual observer. And, the part I've found most tiresome in my own work, a relational database enforces a rigid scheme. Have you ever spent much time mapping a huge object tree to the tables and columns behind it? It's not terribly fun.

The big relational database systems have spent a lot of time and money optimizing their systems, but at a certain point they become constrained by the disk system behind them. Once your disks are your bottleneck, the only options are to get more expensive and faster storage subsystems (ie faster drives or a faster/better SAN-type system). Plus, if you have a complicated object hierarchy with many levels and relations to model, you have more and more tables to model which means more joining of tables and more processing/disk hits to get your data. There are coding frameworks for dealing with the mapping side of things, such as Entity Framework, but the complexity of the mapping is still there; the tedium is just automated for you.

Types of NoSQL Databases

NoSQL systems have been created with the idea of tackling these problems in various ways. Now this doesn't mean that relational databases are obsolete; rather, with the growing maturity and popularity of various NoSQL platforms, you have more options available to research and choose from. As with many technologies, the more you learn the better decisions you can make so I encourage you to keep reading and see if you can think of some ideas of how you might use NoSQL in your own projects.

There are many different types of NoSQL databases, but I will only give a brief overview of three of them:

  1. Document Store: The general concept behind a document store is that objects/entities are represented in the underlying storage mechanism with a "document". Generally speaking you are encouraged to store your entire object (and all it's children, and all it's children, etc) in a single document. These documents are in various formats depending on the vendor. You might see JSON with one vendor, BSON with another, XML, etc. If you've ever exported an object to JSON, you can visualize a document store roughly as a collection of JSON exports (serialized objects) on a disk system, that you can query with some sort of vendor-proprietary query language. 
    1. Benefits: The perceived benefits of a document store over a relational store are, of course, dependent on how you use the system. Imagine if you have a fairly simple base storage object (a Chair) with 7 child objects (5 wheels, a single bolt, and a single arm; not a comfortable chair I know). Now mentally compare loading this from a relational database with loading it as a single JSON document. To load from a relational database you have to join together (or query separately) 8 different tables. This means at least 8 separate hits to your underlying disk storage system, probably more with indexing. To load the same object from a document store? The object and all of its children are stored in a single document, so you have 1 disk operation. Oh and did I mention that it almost eliminates object-->storage mapping problems? Because you are, for the most part, just serializing your object to some form of document and saving that whole thing, you don't really care what's in that document. It's all taken care of for you. No mapping!
    2. Pitfalls: These can of course vary based on the vendor, but in general you have to have a good idea up-front of what you are going to want to do with your data further down the road or you will end up with a lot of duplicated data that is hard to maintain. Let's say for example that within the arm sub-object of the chair you store the name of the arm's manufacturer. If you have 20 chairs in your database, that's ~20 references to the name of this manufacturer (assuming all 20 chairs use the same type of chair arm) in your storage system. What if the manufacturer changes its name? You now have to go and modify all 20 of the chairs/arms in your storage system. In a relational system with a normalized structure, you modify the one chair arm entry as it's just a single row in a table of chair arms. So, a general rule with document stores is they're best-used when your top-level object is what you care about. If you care about treating lower-level objects as primary citizens of your project ecosystem, you should consider other alternatives. (tip: you can in fact have multiple types of collections of objects in a document store and relate them to each other, but that's a topic for another day).
  2. Graph: The big idea behind a graph database is that it allows for a more efficient modeling of relationships between objects. Every element has a direct link to adjacent elements, and through some magic I don't quite understand this means you don't need to have foreign keys and indexes on them. Thus, lookups of relationships are quite fast. Where might this be useful? Social relationship mapping (I'm talkin bout you Facebook), transportation, etc. 
    1. Benefits: Clearly the benefit here is for representing entities/objects that are tightly related and need to be referenced together with their relations. The specific improvement here is speed. A side effect of the better performance is that they will also scale better (continue to have good performance) even as the data set grows much larger.
    2. Pitfalls: Relational databases are, in general, going to be better at performing summary/group calculations and updates of large amounts of data at the same time. Be sure you're using the right tool for what your system needs to accomplish.
  3. Key-Value Store: As the name implies, a key value store represents the stored entities as a list of key/value pairs. For those of you familiar with the .net world, think of the dictionary class. The key is some sort of value that uniquely identifies the data/value, and the value is whatever you want it to be. Serialized object, an int, whatever. A Key-Value store is almost like an even simpler version of a document store. With a document store the database doesn't care what the structure of your document is, but the document does have a structure and the database can (most of the time) query against it. With a key-value store, the database doesn't know or care what's in there and you can't query on it. You can only pull up a value by key, that's it. Nothing fancy.
    1. Benefits: Very simple and very flexible in terms of what you can store. Because there is no structure whatsoever to the data, you can put whatever you feel like in the value portion of a key-value store.
    2. Drawbacks: Inflexible in terms of how you retrieve data. You'd better be sure you don't need to write any ad-hoc queries on your data, because you can only load a value or not; that's it.


My Experience


I myself have a very limited exposure to NoSQL databases. In fact, I've never used one in production, and I've only spent a few hours developing with them on personal projects. So far my experience with NoSQL has been limited to two specific document store databases, Couchbase and MongoDB.

In general, I have to say I have found both of them quite easy to develop with. Querying data from them is relatively straightfoward, though if you're used to SQL you will have to learn new syntax and all that jazz; sorry. Setup is usually pretty easy, though due to a rather nasty bug at the time I was using Couchbase, MongoDB proved much easier to get up and running consistently in a Windows development environment.

The most useful piece of advice I can give regarding NoSQL databases is: read up about them through some google-fu, learn how they work, and research how others have used them with both good and bad results. Then see if and how you can apply them to what you do. They do have their uses, but be careful and ask for advice before implementing.


Resources


NoSQL
Document Oriented Database
Graph Database
Key-Value Store

Thursday, June 26, 2014

Dynamic and ExpandoObject

Intro

Ahh, dynamic types. For those who love anarchy, disorder, and a total lack of type-safe compile-time code wrangling, dynamic types are quite a boon. There are many languages out there that facilitate such things, JavaScript being one of the largest among them. And while I consider myself to be firmly in the camp of "type-safety is good!", I do recognize that there are a few valid uses for dynamic types in my cozy little type-safe bubble that is c#.

As you can guess from the title of this post and the preceding paragraph, this post is going to be about dynamic and ExpandoObject. I won't get into the nitty gritty details of either, as I prefer the 30,000 ft view here. We'll cover how to use them and what you might do with them, but without opening up the hood too much. If you wish to dig further you can read the links towards the bottom of the blog.

When to Use

Have you ever had to interact with type-unsafe services and languages? For example, have you ever integrated a c# app with Facebook, Twitter, or any other such 3rd party service that returns a JSON object? Or, have you perhaps written a JSON Web API yourself? Being the client of such a service will almost invariably involve either you creating proxy classes that represent the data returned so that you can parse the JSON into your friendly object structure, or hey, we will soon see how to do such things with dynamic objects!

I'm sure there are other uses too, but this is the main one I've run into and I've run into it multiple times so I assume it must be fairly common. After all, a sample size of 1 among the millions of programmers in the wold has to be statistically significant.

How to Use

Our first sample will be a simple one; we're just going to create a dynamic object and add some properties and a method to it, without declaring the object type ahead of time. Let's jump right in:

        
        public string DoStuff()
        {
            dynamic myDynamicVariable = new ExpandoObject();
            myDynamicVariable.Name = "Fred";
            myDynamicVariable.Age = 34;
            myDynamicVariable.ToString = new Func<string>(() => { return myDynamicVariable.Name + "::" + myDynamicVariable.Age; });
            return myDynamicVariable.ToString();
        }



In the above code, we first declare a variable named myDynamicVariable of type dynamic, and initialize it to a new instance of ExpandoObject. The combination of dynamic and ExpandoObject is the magic sauce that makes the code below it function properly. Notice how we never declared or used some special class that has a Name or Age property, or a ToString method? Yet, through the awesomeness of dynamics the value we want is returned by the method DoStuff.The return statement returns the result of a call to the ToString method of myDynamicVariable, and in this case returns the string "Fred::34". When I first saw code similar to this, I was amazed it even compiled much less ran! All we had to do was declare our type and start putting new properties and values into our class, and we can even declare methods inline. Groovy! What would happen if you tried the same thing with an object of type "Object"? If you guessed compiler error, treat yourself to a hearty pat on the back, because you're right! Dynamic types give you the power to modify object properties with a clean syntax, without declaring the type ahead of time.

For our second sample we'll be using the JSON.Net NuGet package to import a JSON string into a dynamic object. In my opinion, this is the best type of usage for dynamic objects. Let's look at the sample code before I get ahead of myself here:

        public KeyValuePair<string, int> DoJsonStuff()
        {
            string json = "{ 'SomeStringProp': 'Hey, a string!', 'SomeIntProp': 42  }";
            dynamic deserializedObject = JsonConvert.DeserializeObject<dynamic>(json);
            return new KeyValuePair<string, int>((string)deserializedObject.SomeStringProp, (int)deserializedObject.SomeIntProp);
        }



The first line sets the JSON value we are going to parse. The 2nd line uses JSON.Net to deserialize the JSON string into a dynamic object using the call JSONConvert.DeserializeObject. The 3rd line returns our KeyValuePair, which as you have guessed contains the values "Hey, a string!" and 42.

Now imagine you have just called the Twitter API to retrieve a user's feed. Twitter responds with a JSON list of object that is fairly large in many cases, and contains lots and lots of properties and sub-object. Do you want to go map what comes back to statically typed classes? Well I do actually, but hey it's not everyone's cup of queso and as you can see, dynamics aren't hard to work with in .Net.


What's Next?

  • Read up more on the dynamic keyword
  • Read up more on ExpandoObject
  •  Learn how to create anonymous methods using the Func type (and others!)
  • Go hog-wild and read up on JSON.Net

Thursday, June 19, 2014

Extension Methods

Intro

What is the airspeed velocity of an unladen swallow? African AND European.

Oh wait, wrong question. What I meant was, what are extension methods? Extension methods allow you, the humble developer, to add methods to existing types. You can do this without inheritance and without modifying the source class.

Example

I think the best way to illustrate the concept is with an example. We will extend the int class for the sake of dice rolling. Specifically, I want to be able to roll 2 x-sided die at the same time. I know this seems like a waste of effort to use an extension method, but too bad; it's my blog! So, we'll extend Integer to have a DoubleDieRoll() method which returns a Tuple<int, int> that is 2 rolls of a die with x sides, where x is the source integer. So for example, if I were to call 6.DoubleDieRoll(); I would expect to receive a 2-part result tuple that contains 2 random numbers between 1 and 6. Believe it or not, this is quite easy to do in .net. Fire up a .net project of your favorite type (winforms, xaml, webforms, mvc, whatever) and add a class called GameExtensions. In the sample code below I've created an mvc project ccalled BlogExtensionMethods. Create yourself a new class named "GameExtensions" (note that this name is purposely meaningless, to illustrate that the name of the class doesn't matter). Here's the code for my class:

using System;

namespace BlogExtensionMethods
{
    public static class GameExtensions
    {
        public static Tuple<int, int> DoubleDieRoll(this int val)
        {
            Random rnd = new Random();
            var roll1 = rnd.Next(1, val);
            var roll2 = rnd.Next(1, val);
            return new Tuple<int, int>(roll1, roll2);
        }
    }
}


As you can see, we have a single static class name GameExtensions. Within this class we have a single static method named DoubleDieRoll. The key part of the method is the parameter. the parameter "this int val" means that our method DoubleDieRoll will work on the int class. The body of the method is nothing special, but it does illustrate returning a tuple of int, int. So, key points:
  1. static class
  2. static method
  3. single parameter with the keyword this, the data type we're extending, and a name for the parameter (name doesn't matter).

Now let's see how to call the spiffy new method:

        public string Roll2Die()
        {
            var dieRolls = 20.DoubleDieRoll();
            return String.Format("die roll1: {0}, die roll2: {1}", dieRolls.Item1, dieRolls.Item2);
        }



Cool huh? You can call this on any old int value. In the above code we're calling 20.DoubleDieRoll(). It's pretty fun, and you even get intellisense on your call within the IDE! You'll get back 2 random rolls of a 20-sided die with the above code.

Pitfalls

This stuff is pretty fun, but guess what? There are a lot of people that recommend you use extension methods very judiciously if at all. The reasoning is that it can get kind of confusing if in some projects you have methods on pre-canned classes that don't exist in other projects, such as the odd DoubleDieRoll we defined above for the int class. I must confess that I've never used extension methods, partially for this reason. However like any other tool, I'm sure it has it's uses and if you try hard enough you just might find one yourself.

Resources

Extension Methods, from the c# Programming Guide on MSDN

Thursday, June 12, 2014

LINQ - LINQ to SQL

Intro w/Recap

In part 1, part 2, and part 3 we discussed LINQ basics, some more advanced techniques for dealing with objects in LINQ, and LINQ to XML. Here in our final post of the series we'll discuss LINQ to SQL, and briefly discuss Entity Framework in order to give some context to LINQ to SQL. What is LINQ to SQL? As you can guess, it is the usage of LINQ with data stored in a sql-compatible database such as MS SQL Server. For the purposes of our discussion we will be using SQL Express 2008 R2, though these samples will work fine with newer versions as well.

Entity Framework Basics

At this point hopefully you're wondering why I plan on discussing Entity Framework (EF). The reason is that LINQ to SQL works directly with Entity Framework objects. Entity Framework is MS's Object Relational Mapper (ORM) that helps save you time by linking your Plain-Old-CLR-Objects (POCO's) to your database. If you've ever had to link objects with database tables/fields you know it can be very tedious and time-consuming work, and ORM's help automate much of this tedium.

As part of today's LINQ lesson I'll walk you through how to get a database all setup and ready to map with EF, then I'll show you how to have EF automatically create your tables/fields based on object(s) that you've created in code.

Let's start with setting up the database. If you don't already have it, go download sql server express edition. You can find it here. Install that little sucker (get the one called "SQL Server Express With Tools") and then return. If you need help with installation, please post a reply here in the blog so that everyone can benefit from the shared knowledge. After you have completed installation, you're done! Yeah EF is so cool that it creates your database, tables, and columns for you. Can't get much easier than that. But hey we haven't done that yet so keep reading.

Code-First DB Setup w/EF

That's it for the database for now. We're going to use something called code-first setup of our EF, meaning we'll write our storage classes first and we'll use some spiffery to automatically create the tables for us.

I've created a couple classes myself for storage; Animal and Show. Here is the code for both:

using System.ComponentModel.DataAnnotations;
namespace BlogLinq
{
    public class Animal
    {
        [Key]
        public string name { get; set; }
        public string animalType { get; set; }
    }
}


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BlogLinq
{
    public class Show
    {
        [Key]
        public string name { get; set; }
        public virtual List<Animal> animals { get; set; }
    }
}

As you can see, we have an Animal with 2 properties (name and animalType), and a Show with 2 properties (name and animals, which is a list of type Animal). We use the Key attribute to denote which field is the primary key for our class/table, so that EF can avoid creating a heap table. Trust me (or ask Bobby, my resident DBA, they're bad). The only other oddity here is that I made the animals property of the Show class virtual. This is necessary for EF to load such a list at runtime from a SQL data source.

Next you need to install the EntityFramework package from NuGet. If you don't, your code won't compile as that namespace and the Key attribute I used above are from EF. I'm assuming you know how to work with NuGet package manager, but if that's not the case feel free to ask in the comments below. Now you need to create a "Context" class, which is just a fancy way of saying that you need something that ties LINQ to your database table(s) and classes. Create a class called ZooContext. Here's the code of my ZooContext:

using System.Data.Entity;

namespace BlogLinq
{
    public class ZooContext : DbContext
    {
        public DbSet<Show> Shows { get; set; }
        public DbSet<Animal> Animals { get; set; }
    }
}

Because this blog post isn't about EntityFramework (let me know if you want to see such a beast!) I won't go into any further detail on this ZooContext class, so we'll just say for now that this class as defined above will let us use LINQ to query the database rather than having to roll our own SQL queries.



Inserting Data With EF

What fun is querying data when there's no data? none at all! We're going to write a quick method here that will insert data into our database and tables for us. "But Pete", you say, "We don't have a database, or tables, or columns!". Yeah I know that, and so does EF. Trust me, it will create this crap for you. Write a function like this:

        protected void btnEFInsert_Click(object sender, EventArgs e)
        {
            var zooContext = new ZooContext();
            var show = new Show() { name = "Early", animals = new List<Animal>() };
            show.animals.Add(new Animal() { animalType = "Bird", name = "George" });
            var show2 = new Show() { name = "Late", animals = new List<Animal>() };
            show2.animals.Add(new Animal() { animalType = "Ferret", name = "Fred" });
            show2.animals.Add(new Animal() { animalType = "Bear", name = "Bear" });
            zooContext.Shows.Add(show);
            zooContext.Shows.Add(show2);
            zooContext.SaveChanges();
        }



In the first line of our function we create an instance of our ZooContext class that links EF to our POCO's. We then proceed to create some shows, add animals to them, and add our shows (which contain the animals) to the zooContext. Then we call zooContext.SaveChanges(), and voila! EF created a database for us, a few tables, setup our columns, and even created primary and foreign keys for us. That's so darn cool I could pinch myself. Here's a screenshot full of awesomesauce:



Querying Data With LINQ to SQL

Back to LINQ...now that we have a little bit of data in our database our foray into pure EF is over, so let's query that data using LINQ. This should look pretty familiar by now:

        protected void btnLinqSqlSelect_Click(object sender, EventArgs e)
        {
            var zooContext = new ZooContext();
            var query = from show in zooContext.Shows
                        where show.name.Equals("Late", StringComparison.OrdinalIgnoreCase)
                        select show;
            foreach (var show in query)
            {
                Response.Write("show: " + show.name);
                foreach (var animal in show.animals)
                    Response.Write(String.Format("<br / >    {0} the {1} is in the {2} show!", animal.name, animal.animalType, show.name));
            }
        }



We start by creating a ZooContext object in order to pull junk from the database, then it's all just standard-looking LINQ from there. In the above LINQ query we retrieve all the shows (there's just 1) named "Late", and EF/LINQ goes and pulls all the shows and their child animals from the database for us. Simple and powerful stuff here!

Here's the output in case you don't trust me about the code working:
show: Late
    Bear the Bear is in the Late show!
    Fred the Ferret is in the Late show!




Drawbacks

With great power comes great headaches. The cool time-saving and readability afforded by LINQ comes with a price. Ask your local DBA what they think about ORM's and you'll get a good first-person ear-blasting about the evils of auto-generated queries. Fine-tuning a SQL database really is a profession unto itself, which is part of why the DBA was invented. EF and LINQ generate some decent SQL, but in many cases it's not optimized. This isn't much of a concern with small apps, but if you expect to scale, dig further into LINQ/EF and see what all options you can find for optimization.


What's Next?

  • You could spend some time cozying up to Entity Framework. Learn things like changing the name of the database your data gets plopped in, view the sql queries it generates (it's still using sql behind the scenes), how to add new fields to your classes and have them added to the table(s), etc.

Resources

My Code (Created Using VS Express 2013)!
Entity Framework
SQL Express

Thursday, June 5, 2014

LINQ - LINQ to XML

Intro


This week we'll build on the foundation we learned in part 1 and part 2, adding LINQ to XML to our repertoire. As you have probably surmised, LINQ to XML technology lets you use the LINQ query syntax, with which you've now familiarized yourself, to query data from an in-memory representation of XML data. To an extent, this frees you from learning even more technology for XML parsing such as XPath, so you can have a common framework of knowledge (LINQ) to query many different types of things (objects, XML, and next week SQL data). Perhaps I should have stated and emphasized this better up-front in part 1 to drum up more interest in LINQ, but learning LINQ is almost like a 3-for-1 deal. You learn LINQ, and you get to query 3 types of data. It saves code and saves time, and what else can you ask for in the world of coding? No it won't write your code for you. I know you were gonna ask :)

Loading XML

Step 1 in our journey today is loading an XML string from memory. There are other ways to get XML into a LINQ to XML object such as loading from disk, creating the xml object tree ourselves, etc, but this is the simplest. Note that you'll need to add System.Xml.Linq to your using clause. Here is how to load XML from a string:

private XElement ZooXml
        {
            get 
            {
                return XElement.Parse("<zoo><show name='Early'><animal name='Simba' animalType='lion'></animal><animal name='Bill' animalType='baboon'></animal></show><show name='Lunch'><animal name='Bjork' animalType='baboon'>Bjork says bye!</animal></show><show name='Evening'><animal name='Pete' animalType='panda'></animal></show></zoo>");
            }
        }



The only thing noteworthy here is XElement.Parse. XElement is the class you'll work with most frequently in LINQ to XML as it represents an XML element. The parse method parses the string that you pass in and returns a new object of type XElement. Pretty simple stuff so far.


Querying Basic Data

I know you all paid the price of admission to see the real show, so let's start querying the data. What I want is to pull a list of all the shows and display the names of all the shows. Here's our first example:

        protected void btnLinqXmlMultipleElements_Click(object sender, EventArgs e)
        {
            XElement zooElement = ZooXml;
            var shows = from show in zooElement.Elements("show")
                        select show;
            foreach (var show in shows)
                Response.Write("< br />" + show.Attribute("name").Value);
        }


and here's the output:
Early
Lunch
Evening

Pretty simple code huh? The .Elements() method will return all matching elements of the specified element/node (in this case zooElement, which is the root element). We specify that we only want elements named show in this case, so we only get back show elements. Then we loop through the result set and display the name of each show.

Elements Containing Specific Sub-Elements

What if we wanted only shows that have a baboon in them?

        protected void btnLinqXmlShowsWithBaboons_Click(object sender, EventArgs e)
        {
            XElement zooElement = ZooXml;
            var shows = from show in zooElement.Elements("show")
                        where show.Elements("animal").Any(animal => animal.Attribute("animalType").Value.Equals("baboon", StringComparison.OrdinalIgnoreCase))
                        select show;
            foreach (var show in shows)
                Response.Write("< br />" + show.Attribute("name").Value);
        }



And our output (hey, it's even correct!) is as follows:
Early
Lunch

As you can see above, the where clause is what's different. We tell the compiler that we want all show elements who contain an element named "animal" which have an attribute "animalType" with the value "baboon". There's nothing complicated here, with a little practice you can get the hang of it quite easily.

Getting Element Value(s)

Scroll back up near the top for a moment where we defined the property ZooXml. Notice how Bjork the baboon has a value within her xml element, with the value "Bjork says bye!"? Putting values into xml tags is common so let's see filter on and use them:

        protected void btnLinqXmlElementWithValue_Click(object sender, EventArgs e)
        {
            XElement zooElement = ZooXml;
            var elements = from element in zooElement.Descendants()
                            where !String.IsNullOrWhiteSpace(element.Value) && element.Name.ToString().Equals("animal", StringComparison.OrdinalIgnoreCase)
                            select element;
            foreach (var element in elements)
                Response.Write("< br />" + element.Name + "::" + element.Attribute("animalType").Value + "::" + element.Attribute("name").Value + "::" + element.Value);
        }



Output:
animal::baboon::Bjork::Bjork says bye! 

The first thing you'll notice different is that we used Descendants() this time instead of Elements(). What's the diff yo? Elements are just the direct children of where we're looking. For our prior queries that was good enough. For this query, we know that an animal is what has a value, and an animal is not a direct child of the root zoo element. Rather, animals are children of the show in which they perform, so we need to use the Descendants method().

The next difference is our use of element.Value. This isn't voodoo or anything, it's exactly what you think; the element value. We use it in our where clause to pull only those elements that have a value.

What's Next?

There are lots more things that you can do with LINQ to XML. We don't have time to cover all of them, but take a look on MSDN; there's lots to read.
  • Other methods such as Ancestors(), ElementsAfterSelf(), etc.
  • XNode: look it up! It's powerful. Finer level of detail than XElement, though you won't often need it's functionality.
  • Manipulate and save XML.
  • Create an XML tree entirely in code.
  • Peek ahead to LINQ to SQL which will be next week's post.
  • Experiment with last week's topics while playing with LINQ to XML. Joins, ordering, grouping, projections. This is by far the best thing you could do, as you'll put the pieces of the puzzle together and learn them as a whole.

Resources

LINQ to XML on MSDN