Programming
MongoDB Driver for C#/.NET
MongoDB is a NoSQL database. In this post, I will explain how to use the C#/.NET driver for MongoDB. The MongoDB C# Driver is the 10gen-supported.
Installing MongoDB ( Windows )
You can download MongoDb from the link: http://www.mongodb.org/downloads
After you install, go to INSTALL_DIR/bin directory and run “mongod.exe”. This will start the database.
Now start “mongo.exe” which is in the same directory. A javascript shell will be opened. By default a database named ‘test’ is created by MongoDB installation.
Some helpfull commands:
> show dbs
…
> show collections
…
> db.MyNewDatabaseName.insert( { name: “John”, age: 12 } )
//MyNewDatabaseName is created automatically and the object with name = ‘John’ and age = 12 inserted into it.
> db.MyNewDatabaseName.find()
//This command returns all documents in our database in json format.
C#/.NET Driver
You can install the driver from http://github.com/mongodb/mongo-csharp-driver/downloads
Add reference to the “MongoDB.Bson.dll” and “MongoDB.Driver.dll” .
The API docs is available on web: http://api.mongodb.org/csharp/current/
We are ready to connect our MongoDB server(s) do some CRUD operations.
Creating a MongoServer object: ( by default the port 27017 is used by MongoDB )
string url = “mongodb://localhost:27017”;
MongoServer server = MongoServer.Create(url);
MongoDatabase testDb = server[“test”, SafeMode.True];
MongoCollection<BsonDocument> collection = testDb[“MyNewDatabase”, SafeMode.True];
From now on we are just going to do operations on the collection object. We connect to the “MyNewDatabase” with safe mode on. This feature is needed if you want to check whether your operation has succeeded or failed. When SafeMode=true, driver queries the database for LastErrorMessage. Otherwise, It does not make this query after your operation completed.
Our collection object is BsonDocument type. So we are going to insert BsonDocuments into it:
SafeModeResult result = collection.Insert(new BsonDocument { { “Name”, “John”}, { “Age”, 15 } } );
After you insert some more documents to the database try the following query:
var query = Query.Or(Query.EQ(“Name”, “John”), Query.GTE(“Age”, 20));
var cursor = collection.Find(query);
foreach (var item in cursor)
{ //do something with item
}
The examples were for BsonDocument objects. How about our custom objects. Let us have Person objects and we want to store and query them in MongoDB.
MongoCollection<Person> collection = testDb.GetCollection<Person>(“MyPersonDatabase”, SafeMode.True);
collection.Insert(new Person(“John”, 38));
That’s it. We do not need to add any attribute to Person class. It just have two fields name and age.
We inserted our object successfully. We can check this by running “mongo.exe” and type:
>db. MyPersonDatabase.find()
{ “_id”: Objectid(“4f296e1e2d4ce5510645ac61”), “Name” : “John”, “Age” : 38 }
The “_id” field is generated and inserted as objectid of our object. If you try to select this record from database:
Person p = collection.FindOne();
You get an error says “_id” field is missing and it can not deserialize the Person object.
I come up with a quick solution which is to add _id field to our Person object. There can be other solutions.
Updating objects is also simple:
Person p = collection.FindOne();
p.Age++;
collection.Save(p);
You can also use GridFS feature of MongoDB from the driver API. You can download/upload files or streams to MongoDB server.
var gridFileSystem = test1.GridFS;
//Upload . stream is source
var fileInfo = gridFileSystem.Upload(stream, remoteFileName);
//Download. stream is destination
gridFileSystem.Download(stream, remoteFileName);
References:
http://www.slideshare.net/mongodb
https://www.10gen.com/presentations#programming_lang__dotnet
https://www.10gen.com/presentations/mongosf-2011/c-sharp-development-with-mongodb
R programming for those coming from other languages
AI Challenge 2011 (Ants) post mortem by xathis
WCF Rest Services
WCF REST Starter Kit provides easy way to create rest web services. Visual studio has project templates for rest WCF services. First you need to go download “WCF REST Starter Kit Preview 2” from codeplex. http://aspnet.codeplex.com/releases/view/24644
Then Open a new project from installed templates tab Visual C#->Web->WCF Rest Service Application.
In the global.asax file you can specify the routing with RegisterRoutes() method. By changing the first argument of the ServiceRoute:
RouteTable.Routes.Add(new ServiceRoute(“RestServiceTest”, new WebServiceHostFactory(), typeof(HelloService)));
you can deploy your rest service with the url: http://localhost:58944/RestServiceTest (port will not be same in your localhost). It uses ASP.NET routing.
OperationContract is optional in Rest web services. In the template project you will see the SampleItem.cs file.
public class SampleItem
{
public int Id { get; set; }
public string StringValue { get; set; }
}
You can return objects of this type , or a collection of this type.
Service1.cs has some unimplemented method declerations. These will guide you to implement your own services. I will give some additional examples for service methods and how they can be called by a client.
[WebGet(UriTemplate = “GetItems”)]
public List<SampleItem> GetItems() {
//your code
}
If you implement the above method in your service, it will be available at http://localhost:58944/RestServiceTest/GetItems , because we specified UriTemplate=”GetItems” in the method template.
You can also call methods with argumens. An example call for the method
public int Square(int number) { return number*number; }
is
http://localhost:58944/RestServiceTest/Square/number
Then the number you typed ine the above url will be mapped to the argument of the method. This is the beauty of rest services.
Now we will switch our topic to the type of response. WCF WebHttp Services returns an XML response as default. If you need JSON response then a little modification is needed. We need automaticFormatSelectionEnabled = true for changing the format of response. An example web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/>
<standardEndpoints>
<webHttpEndpoint>
<!–
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
–>
<standardEndpoint name=”” helpEnabled=”true” automaticFormatSelectionEnabled=”true”/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
We can switch our web service to return json format for every request or we can give that flexibility to the client.
[WebGet(UriTemplate = “GetItems?Format={format}”)]
public List<GetItems> GetItems(string format) { // your code }
If the format sepcified by the client is json we can set the reponse format to json in the method:
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
An Http request with correct format will be enough to call this method and it will return a json string as response. WCF REST Starter Kit Preview 2 assemblies provides a method to read json object: response.Content.ReadAsJsonDataContract<T>()
References:
http://blogs.msdn.com/b/endpoint/archive/2010/01/06/introducing-wcf-webhttp-services-in-net-4.aspx
Turkish: http://www.buraksenyurt.com/archive.aspx#WCF-WebHttp-Services
Modifying web.config file – Web setup project
In my previous post I talked about how to open a web setup project and add custom actions and user interfaces to it. Now I will give some examples of how to modify the web.config file that is copied in the virtual directory by our installer.
Most setups need to change the content of the web.config file for many reasons such as target machine properties, link updates etc. Setups may also require additional information from user to update the web.config accordingly.
For gathering input from user, there are several ways:
- Using Web Setup Project’s User Interfaces
If a few text boxes are enough for you, the provided User Interfaces will satisfy your needs. You can pass the user entered parameters to your installer class.(Explained in previous post)
‘targetdir’ parameter keeps the web.config file path.
An important note: You should not try to modify the web.config during installation process. Use the AfterInstall event handler to make your updates.
- Creating Your Own Forms Applciation
You can create a windows forms project and run it as a process at AfterInstall event handler.
To do this, you need to add the project output of the forms application you created to the web setup. After doing this, web setup will copy your executable to the target directory and you will be able to run it there.
The forms application can modify the web.config anyway you like.
- ASP.Net configuration
Visual Studio Web Setup Project
Web setup project is simply a visual studio setup project that helps web projects to be installed on a target machine’s IIS. Setup project and Web Setup project templates are available in Visual Studio.
After you open a web setup project. Click on the project on solution explorer and press f4. Title of installer, icon, version, manufacter etc. can be set here.
Since we are creating a web setup, we should have web project that is going to be published under IIS. Add an existing web project of yours in the web setup solution. After that right click on the web setup project Add->Project Output. In the pop-up dialog select your web project from the combo box at the top and select both ‘Primary Output’ and ‘Content Files’ in the list box. Note that only the dlls that are referenced by your web project will be copied into virtual directory.
Other dlls in your bin directory that are copied by a postbuid event or a manual copy/paste, will not be available in the VirtualDirectory/bin folder. A quick solution is to add reference to these dlls in your web project so that they will be recognized by web setup project as dependency and copied to target virtual directory.
User Interface :
Right click on the project on solution explorer and navigate to View->User Interace.
There are some template dialogs you can add to your installer. Right click on the Start and click Add Dialog.
Choose the template that fits your purpose and begin to edit the dialog through Properties window.
Set visibility of fields to false that are not needed. Edit#Property is the variable that is assigned with user’s input. We are going to use these values in next part.
this configuration will look like that
Custom Actions:
Custom actions are user defined executables, dlls or scripts which run by installer. I will show a C# example custom action.
Right click on the solution and Add -> New Project -> Class Library. You can add an existing project too.
We need to have reference to System.Configuration.dll & System.Configuration.Install.dll. Now you can create your own Installer class and play with it. Inherit Installer class and don’t forget the RunInstaller attribute.
Now we need to add the project output to the setup project. Right click on the setup project Add -> Project Output. Select the Class library project and select Primary Output then click OK.
To add this class library project as a custom action to our web setup project. Right click on setup project View->CustomActions then Add Custom Action to Install. And press f4 after adding the custom action. You will see something like:
We have a installer class and we need user inputs in that class. To provide these parameters write your parameters in the Custom Action Box above. In my case it is :
/targetdir=”[TARGETDIR]\” /targetvdir=”[TARGETVDIR]” /targetsite=”[TARGETSITE]” /sql=”[SQL_SERVERNAME]” /sqldbname=”[SQL_DB_NAME]” /sqluser=”[SQL_USERNAME]” /sqlpw=”[SQL_PASSWORD]” /
Retrieve these in your installer class :
That is a brief introduction to web setup projects. I will talk about specific problems I encountered in my next posts.
Taylan









