RavenDB.NET Client API

Exclusive offer: get 50% off this eBook here
RavenDB 2.x Beginner’s Guide

RavenDB 2.x Beginner’s Guide — Save 50%

Build high performance NoSQL .NET-based applications quickly and efficiently with this book and ebook

$29.99    $15.00
by Khaled Tannir | September 2013 | Beginner's Guides Open Source

In this article, by Khalid Tanner, author RavenDB 2.x Beginner's Guide we learn some of the RavenDB Client API. RavenDB is written in C# that runs on the Microsoft .NET Framework. The .NET Client API exposes all aspects of the RavenDB server to your application in a seamless manner and can be accessed from any .NET language. In this article, you will learn step-by-step how to connect to RavenDB to interact with the server by writing some C# code and perform various basic operations such as loading, inserting, and updating documents from the RavenDB server.

In this article, we will learn how to use the RavenDB Client API for:

  • Setting up your development environment
  • Connecting to RavenDB
  • Loading a document
  • Creating a document
  • Inserting a new document
  • Updating a document

(For more resources related to this topic, see here.)

The RavenDB .NET Client API

RavenDB provides a set of .NET client libraries for interacting with it, which can be accessed from any .NET-based programming languages. By using these libraries, you can manage RavenDB, construct requests, send them to the server, and receive responses.

The .NET Client API exposes all aspects of the RavenDB and allows developers to easily integrate RavenDB services into their own applications.

The .NET Client API is involved with loading and saving the data, and it is responsible for integrating with the .NET System.Transactions namespace. With System.Transactions, there is already a general way to work transactionally across different resources. Also the .NET Client API is responsible for batching requests to the server, caching, and more.

The .NET Client API is easy to use and uses several conventions to control how it works. These conventions can be modified by the user to meet its application needs.

It is not recommended to use System.Transactions. In fact, it is recommended to avoid it. System.Transactions is supported in RavenDB mostly to allow integration while using collaboration tools between services for example, NServiceBus.

Setting up your development environment

Before you can start developing an application for RavenDB, you must first set up your development environment. This setup involves installing the following software packages on your development computer:

  • Visual Studio 2012 (required)
  • RavenDB Client (required)
  • NuGet Package Manager (optional)

You may download and install the latest Visual Studio version from the Microsoft website: http://msdn.microsoft.com/En-us/library/vstudio/e2h7fzkw.aspx

In order to use RavenDB in your own .NET application, you have to add a reference to the Raven.Client.Lightweight.dll and the Raven.Abstractions.dll files, (which you can find in the ~\Client folder of the distribution package) into your Visual Studio project.

The easiest way to add a reference to these DLLs is by using the NuGet Package Manager, which you may use to add the RavenDB.Client package.

NuGet Package Manager is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET framework.

You can find more information on the NuGet Package Manager extension by visiting the official website at http://nuget.org/.

Time for action – installing NuGet Package Manager

The NuGet Package Manager extension is the easiest way to add the RavenDB Client library to a Visual Studio project. If you do not have NuGet Package Manager already installed, you can install it as follows:

  1. Start Visual Studio.
  2. From the TOOLS menu, click on Extensions and Updates....
  3. In the Extensions and Updates... dialog, click on Online.
  4. If you don’t see NuGet Package Manager, type nuget package manager in the search box.
  5. Select the NuGet Package Manager extension and click on Download.
  6. After the download completes, you will be prompted to install the package.
  7. After the installation completes, you might be prompted to restart Visual Studio.

What just happened?

We installed the NuGet Package Manager extension to Visual Studio, which you will use to add RavenDB Client to your Visual Studio project.

Creating a simple application

Let’s write a simple application to learn how to interact with RavenDB.

Time for action – adding RavenDB Client to a Visual Studio project

Let’s go ahead and create a new Visual Studio project. You will add the RavenDB Client using the Nuget Package Manager extension to this project to be able to connect to RavenDB and begin using it:

  1. Start Visual Studio and click on New Project from the Start page or from the File menu, navigate to New and then Project.
  2. In the Templates pane, click on Installed and then click on Templates and expand the Visual C# node. Under Visual C#, click on Windows. In the list of project templates, select Console Application. Name the project as RavenDB_Ch03 and click on OK.

  3. From the TOOLS menu, click on Library Package Manager.

    If you do not see this menu item, make sure that the NuGet Package Manager extension has been installed correctly.

  4. Click on Manage NuGet Packages for Solution....
  5. In the Manage NugGet Packages dialog, select Online.
  6. In the search box, type ravendb.
  7. Select the package named RavenDB Client.

  8. Click on Install and accept the license.
  9. After the package installs, click on Close to close the dialog box.

What just happened?

We created the RavenDB_Ch03 Visual Studio project and added the RavenDB Client to get connected to the RavenDB server.

Once the RavenDB Client is installed, by expanding the References node of your project in Visual Studio, you can see the RavenDB DLLs (Raven.Abstractions, Raven.Client.Lightweight) added automatically to your project by the Nuget Package Manager extension.

You should ensure that the RavenDB Client version matches the server version you are running. This can lead to some really frustrating runtime errors when the versions don’t match.

You can also install RavenDB Client using the Package Manager console (Visual Studio | Tools | Library Package Manager | Package Manager Console). To install the latest RavenDB Client, run the following command in the Package Manager console: Install-Package RavenDB.Client or Install-Package RavenDB.Client–Version {version number} to add a specific version.

Connecting to RavenDB

To begin using RavenDB we need to get a new instance of the DocumentStore object, which points to the server and acts as the main communication channel manager.

Once a new instance of DocumentStore has been created, the next step is to create a new session against that Document Store. The session object is responsible for implementing the Unit of Work pattern. A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.

The session object is used to interact with RavenDB and provides a fully transactional way of performing database operations, and allows the consumer to store data into the database, and load it back when necessary using queries or by document ID.

In order to perform an action against the RavenDB store, we need to ensure that we have an active and valid RavenDB session before starting the action, and dispose it off once it ends.

Basically, before disposing of the session, we will call the SaveChanges() method on the session object to ensure that all changes will be persisted.

To create a new RavenDB session, we will call the OpenSession() method on the DocumentStore object, which will return a new instance of the IDocumentSession object.

Time for action – connecting to RavenDB

Your Visual Studio project now has a reference to all needed RavenDB Client DLLs and is ready to get connected to the RavenDB server. You will add a new class and necessary code to create a communication channel with the RavenDB server:

  1. Open the RavenDB_Ch03 project.
  2. Modify the Main() method (in Program.cs class) to look like the following code snippet:

  3. Press Ctrl + Shift + S to save all files in the solution.

What just happened?

We just added the DocumentStore object initialization code to the Main() method of the RavenDB_Ch03 project.

Within the Main() method, you create a new instance of the DocumentStore object, which is stored in the DocumentStore variable. The DocumentStore object basically acts as the connection manager and must be created only once per application.

It is important to point out that this is a heavyweight and thread safe object. Note that, when you create many of these your application will run slow and will have a larger memory footprint.

To create an instance of the DocumentStore object, you need to specify the URL that points to the RavenDB server. The URL has to include the TCP port number (8080 is the default port number) on which RavenDB server is listening (line 17 in the previous code snippet).

In order to point to the Orders database, you set the value of DefaultDatabase to Orders, which is the name of our database (line 18).

To get the new instance of the IDocumentStore object, you have to call the Initialize() method on the DocumentStore object. With this instance, you can establish the connection to the RavenDB server (line 19).

The whole DocumentStore initialization code is surrounded by a using statement. This is used to specify when resources should be released. Basically, the using statement calls the Dispose() method of each object for which the resources should be released.

Interacting with RavenDB using the .NET Client API

RavenDB stores documents in JSON format. It converts the .NET objects into their JSON equivalent when storing documents, and back again by mapping the .NET object property names to the JSON property names and copies the values when loading documents. This process that makes writing and reading data structures to and from a document file extremely easy is called Serialization and Deserialization.

Interacting with RavenDB is very easy. You might create a new DocumentStore object and then open a session, do some operations, and finally apply the changes to the RavenDB server.

The session object will manage all changes internally, but changes will be committed to the underlying document database only when the SaveChanges() method is called. This is important to note because all changes to the document will be discarded if this method is not invoked.

RavenDB is safe by default. This unique feature means that the database is configured to stop users querying for large amount of data. It is never a good idea to have a query that returns thousands of records, which is inefficient and may take a long time to process.

By default, RavenDB limits the number of documents on the client side to 128 (this is a configurable option) if you don't make use of the Take() method on the Query object.

Basically, if you need to get data beyond the 128 documents limit, you need to page your query results (by using Take() and Skip() methods). RavenDB also has a very useful option to stop you from creating the dreaded SELECT N+1 scenario—this feature stops after 30 requests are sent to the server per session, (which also is a configurable option).

The recommended practice is to keep the ratio of SaveChanges() calls to session instance at 1:1. Reaching the limit of 30 remote calls while maintaining the 1:1 ratio is typically a symptom of a significant N+1 problem.

To retrieve or store documents, you might create a class type to hold your data document and use the session instance to save or load that document, which will be automatically serialized to JSON.

Loading a document

To load a single document from a RavenDB database, you need to invoke the Load() method on the Session object you got from the DocumentStore instance. Then you need to specify the type of the document you will load from the RavenDB database.

Time for action – loading a document

You will create the Order class to hold the order data information and will add the LoadOrder()method, which you will call to load an Order document from the RavenDB server:

  1. Open the RavenDB_Ch03 project, add a new class and name it Order.
  2. Add the following code snippet to the Order class:

  3. Add the DisplayOrder() method to the Program class using the following code snippet:

  4. Add the Load<Order>() method to the Program class using the following code snippet:

  5. Save all the files and press F6 to build the solution.
  6. Switch to Windows Explorer and go to the RavenDB installation folder and launch RavenDB server using the Start.cmd command file.
  7. Return to Visual Studio, once the RavenDB server is running, press F5 to run RavenDB_Ch03 to see the document information in the output console window.

What just happened?

You just wrote the necessary code to load your first document from the RavenDB server. Let’s take a look at the code you added to the RavenDB_Ch03 project.

You added the Order class to the project. This class will hold the data information for the Order document you will load from the server. It contains six fields (lines 11 to 16 in the previous code snippet) that will be populated with values from the JSON Order document stored on the server.

By adding a field named Id, RavenDB will automatically populate this field with the document ID when the document is retrieved from the server.

You added the DisplayOrder() method to the Program class. This method is responsible for displaying the Order field’s values to the output window.

You also added the Load<Order>() method (lines 26 to 30) to the Program class. This method is surrounded by a using statement to ensure that the resources will be disposed at the end of execution of this method.

To open a RavenDB session you call the OpenSession() method on the IDocumentStore object. This session is handled by the session variable (line 26).

The Load() method is a generic method. It will load a specific entity with a specific ID, which you need to provide when calling the method. So in the calling code to the Load() method (line 28), you provide the Order entity and the document ID that we want to retrieve from the server which is Orders/A179854.

Once the Order document with the Id field as Orders/A179854 is retrieved from the server, you send it to the DisplayOrder() method to be displayed (line 29).

Finally, you build and run the RavenDB_Ch03 project.

Have a go hero – loading multiple documents

You know now how to load any single document from the RavenDB server using the Load() method. What if you have more than one document to load? You can use the Load() method to load more than one document in a single call. It seems easy to do. Well give it a go!

Arrays are very useful!

RavenDB 2.x Beginner’s Guide Build high performance NoSQL .NET-based applications quickly and efficiently with this book and ebook
Published: September 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Inserting a new Document

To insert a new document into a RavenDB database, you need to create a new instance of the object that will hold your data information and then invoke the Store() method on the session object, which you got from the DocumentStore object.

Time for action – inserting a new document

You will add necessary code to the Main() method in the Program class to create a new Order object and insert it into the Orders database:

  1. Add the following code snippet to the Main() method:

  2. Save all the files, build and run the solution.
  3. Switch to your Management Studio, and click on the Documents tab to display documents of the Orders database and view the newly inserted document.

What just happened?

We just wrote the necessary code to insert a new order into the Orders database. Let’s take a look at the code we added to the RavenDB_Ch03 project.

You begin by opening a RavenDB session (line 33 in the previous code snippet). Again, the code is surrounded by the using statement in order to release resources when method execution ends.

Then, you create a new instance of the Order class and populate its fields with some values (lines 35 to 43). After that, we call the Store() method on the session object and pass to it the new Order object (line 44). The data will still be in memory until the SaveChanges() method on the session object is invoked (line 45).

Updating a document

Updating a document is also very simple in RavenDB, which is responsible for tracking changes you make for an object within your session. This is another reason why the session object is important.

To update a document you will load this document first using the Load() method on the session object, make changes you need to the document and then save the changes to the server using the SaveChanges() method on the session object. When updating a document, the entire document is sent to the server with the Id field set to the existing document value; this means that the existing document will be replaced in the DocumentStore object with the new one.

Time for action – updating a document

You will add necessary code to the Main() method in the Program class to update the Order document with the Id field as Orders/B279855, and save the changes to the Orders database.

  1. Add the following code snippet to the Main() method:

  2. Save all the files, build and run the solution.
  3. Switch to your Management Studio, and click on the Documents tab to display documents of the Orders database and view that the document has been updated.

What just happened?

You just wrote the necessary code to update the Order document with the Id as Orders/B279855 and save the changes to the Orders database.

You begin by opening a RavenDB session (line 49 in the previous code snippet). Then, you load the Order document with the Id field as Orders/B279855 by calling the Load() method (line 51). Then you modified its field values (lines 52 to 55).

After that you call the SaveChanges() method on the session object to persist changes on the server (line 55).

You don’t have to call the Store() method or track any changes by yourself. RavenDB will do all of that for you.

Summary

Thus, we learned how to connect to RavenDB to interact with the server by writing some C# code and perform various basic operations such as loading, inserting, and updating documents from the RavenDB server.

Resources for Article :


Further resources on this subject:


About the Author :


Khaled Tannir

Khaled Tannir has been working with computers since 1980. He began programming with the legendary Sinclair Zx81 and later with Commodore home computer products (Vic 20, Commodore 64, Commodore 128D, and Amiga 500).

He has a Bachelor's degree in Electronics, a Master's degree in System Information Architectures, in which he graduated with a professional thesis, and completed his education with a Master of Research degree.

He is a Microsoft Certified Solution Developer (MCSD) and has more than 20 years of technical experience leading the development and implementation of software solutions and giving technical presentations. He now works as an independent IT consultant and has worked as an infrastructure engineer, senior developer, and enterprise/solution architect for many companies in France and Canada.

With significant experience in Microsoft .Net, Microsoft Server Systems, and Oracle Java technologies, he has extensive skills in online/offline applications design, system conversions, and multilingual applications in both domains: Internet and Desktops.

He is always researching new technologies, learning about them, and looking for new adventures in France, North America, and the Middle-east. He owns an IT and electronics laboratory with many servers, monitors, open electronic boards such as Arduino, Netduino, RaspBerry Pi, and .Net Gadgeteer, and some smartphone devices based on Windows Phone, Android, and iOS operating systems.

In 2012, he contributed to the EGC 2012 (International Complex Data Mining forum at Bordeaux University, France) and presented, in a workshop session, his work on "how to optimize data distribution in a cloud computing environment". This work aims to define an approach to optimize the use of data mining algorithms such as k-means and Apriori in a cloud computing environment.

He is the author of RavenDB 2.x Beginner's Guide, Packt Publishing.

He aims to get a PhD in Cloud Computing and Big Data and wants to learn more and more about these technologies.

He enjoys taking landscape and night time photos, travelling, playing video games, creating funny electronic gadgets with Arduino/.Net Gadgeteer, and of course, spending time with his wife and family.

You can reach him at contact@khaledtannir.net.

Books From Packt


RavenDB High Performance
RavenDB High Performance

Getting Started with OrientDB
Getting Started with OrientDB

Ruby and MongoDB Web Development Beginner's Guide
Ruby and MongoDB Web Development Beginner's Guide

Instant InnoDB
Instant InnoDB

CouchDB and PHP Web Development Beginner's Guide
CouchDB and PHP Web Development Beginner's Guide

PHP and MongoDB Web Development Beginner’s Guide
PHP and MongoDB Web Development Beginner’s Guide

Apache Wicket Cookbook
Apache Wicket Cookbook

Cassandra High Performance Cookbook
Cassandra High Performance Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
6
7
L
j
4
e
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software