Browsing:

Tag: ASP.NET MVC

ASP.NET Web API, Angularjs and MongoDb part 5

This is the sequel to this.

You can find the finished application here: https://github.com/jacqinthebox/AddressBook

angular

When I was creating this I was really confused about 'the double MVC' setup. The one that comes with ASP.NET and the one that comes with Angularjs.

It felt like what I was doing was bloathed and wrong.

I decided to start again from scratch, but this time with Node as the backend.

node


Getting started with ASP.NET API with MongoLab part 3

This is the sequel to this post
We will be using MongoLab as a backend for our Web Api.

We are using the AddressBook again in this example, but for clarity we're building it from scratch.

Creating the MongoLab database

Head over to MongoLab and create an account!

  • First create a new database. Make sure you choose the free plan. Name the database 'addressbook'.
  • Click to create a new user.
  • Add a new collection (equivalent for a table) named persons.

Please take note of the connectionstring:

2013-11-01 08_12_03-MongoLab_ MongoDB-as-a-Service

Setting up the Web Api project in Visual Studio

Fire up Visual Studio 2013 and hit File -> New -> Project.
Choose Empty ASP.NET Web Application with a Web API and name the project AddressBook.

2013-11-01 08_07_48-New ASP.NET Project - AddressBook

We must install the Mongo Csharp Driver:

Install-Package MongoCsharpDriver

Now open App_Start\WebApiConfig.cs and add json formatting to it (see my previous post why):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace AddressBook
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

//This section you need to add:
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
}

Connecting to the MongoLab

Let's not reinvent the wheel if you don't have to. This article is a great introduction to Mongo and C#. I borrowed their MongoConnectionHandler.

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddressBook
{
    public class MongoConnectionHandler
    {
        public MongoCollection MongoCollection { get; private set; }

 public MongoConnectionHandler()
        {
            const string connectionString = "mongodb://:@ds031108.mongolab.com:31108/addressbook";
            //const string connectionString = "mongodb://localhost:27017";
            //// Get a thread-safe client object by using a connection string
            var mongoClient = new MongoClient(connectionString);

            //// Get a reference to a server object from the Mongo client object
            var mongoServer = mongoClient.GetServer();

            //// Get a reference to the database object 
            //// from the Mongo server object
            const string databaseName = "persons";
            var db = mongoServer.GetDatabase(databaseName);

            //// Get a reference to the collection object from the Mongo database object
            //// The collection name is the type converted to lowercase + "s"
            MongoCollection = db.GetCollection(typeof(T).Name.ToLower() + "s");
        }
    }
}

The Person class

I want the Person_Id to be the same as the document id, so I can retrieve documents easily. I'm not sure though if this is best practice. But it works.

public class Person 
    {
        public Person()
        {
            Person_Id = ObjectId.GenerateNewId().ToString();
        }

        [BsonId]
        public string Person_Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Blog { get; set; }
        public string Facebook { get; set; }
        public string Twitter { get; set; }
        public string LinkedIn { get; set; }
        public string Googleplus { get; set; }
    }

And here's the POST method:

public class PersonController : ApiController
    {
        public MongoConnectionHandler collection = new MongoConnectionHandler();

        public HttpResponseMessage Post([FromBody] Person person)
        {
            collection.MongoCollection.Insert(person);
            var response = Request.CreateResponse(HttpStatusCode.Created, person);

          
            string uri = Url.Link("DefaultApi", new { id = person.Person_Id });
            response.Headers.Location = new Uri(uri);
            return response;

        }


    }
      

You can use the API with Fiddler.

2013-11-01 14_33_36-Fiddler Web Debugger

Look at the results it has returned:

2013-11-01 14_35_25-Fiddler Web Debugger

It returned the new URI with the new Id as you can see.

Now let's check MongoLab, and lo and behold:

2013-11-01 14_39_53-MongoLab_ MongoDB-as-a-Service

Here's the remainder of the CRUD methods:

        public IEnumerable Get()
        {
            return collection.MongoCollection.FindAll().AsEnumerable();

        }


        public Person Get(string id) {

            //var query = Query.EQ(p => p.Person_Id, id);
            return collection.MongoCollection.FindOne(Query.EQ("_id", id));

        }

        public void Delete(string id)
        {
            collection.MongoCollection.Remove(Query.EQ("_id", id));

        }

        public HttpResponseMessage Put([FromBody] Person person)
        {
            
            var p = collection.MongoCollection.FindOne(Query.EQ("_id", person.Person_Id));

            if (p != null)
            {
                collection.MongoCollection.Save(person);
            }
           
            return Request.CreateResponse(HttpStatusCode.OK, person);
        }

So, that works.
Next time, let's consume this WebApi with Angularjs.

And here's all the code: here

I have changed 'Person' to 'Contact' in the sourcecode


Castle Windsor ASP.NET MVC 3 Baby Example part 2

This is part 1. The sourcecode is here.
This article is based on this tutorial.

So I created an IStoryTeller interface, with one method that returns a string. GoodMorning.
Very sophisticated, no?
Next, I created 2 classes that implement the IStoryTeller interface. A French and a Dutch. I'm pretty sure you know where this is going:

Now I have to create an installer for the StoryTeller. Here is where I tell Castle Windsor which StoryTeller to implement:

Now I can create the controller and add the IStoryTeller to the constructor:

Run, Forest!

And now if I change the Installer and inject the FrenchStoryTeller I get:

So this is how easy this is.


Castle Windsor and ASP.NET MVC 3 extremely simple example part 1

Castle Windsor is an Inversion of Control Container which has excellent documentation, written by Krzysztof Koźmic. Krzysztof has written a perfect tutorial on ASP.NET MVC 3, which I thought I would follow. And then I found that Castle Windsor is extremely easy and transparent to use. And it has a cool name at that.

What again is Inversion of Control and why ever would I use it?

Suppose you develop a member administration tool and the customer wants to use an MySQL database. But you coded the app with Linq to SQL. Wouldn't it be nice if you could just change your ORM from L2S to EF? Or Nhibernate?
Or, what if you coded your app with an object database, and then later you find that the customer has a DBA who is absolutely against NoSQL?
The same goes for the logging framework. Which one? Log4Net or Elmah?

With IOC you can just pick and choose which framework you plug in. When you start with one choice of a product, you are not bound to it.

It's called Inversion of Control because it's an inverted API. With an API, you use the methods it exposes. With IOC, you let your application choose which API to use. Huh? Yeah. Because when your app spins up, it uses reflection to get all the dependencies you configured within your container. Now, does that make any sense?

A simple example

Here's how the principle works.
In an ASP.NET MVC architecture, there is a Model, a View and a Controller. The Controller sits between the Model and the View, so the Controller would be a good place where we can inject some dependencies. How to inject these dependencies? Well, by their constructor.
The default controllerfactory has a parameterless constructor, so we need to override that, by creating a new class. E.g. WindsorControllerFactory. And we let our controllerfactory inherit from DefaultControllerFactory.
We need to override two methods: ReleaseController (so that he Windsor Controller is released) and getControllerInstance (which returns a Windsor Controller). This bit of plumbing code just provides the MVC runtime with new instances of the controller type for each request and when the request ends, it releases the controller.

Next, we need to register the controllers in to the container with an Installer, like this:

This is how we register types in the container, so there will me more of these classes later.

Now we need to bootstrap this in global.asax:

And then we are ready to roll.

In part 2 I will show how to create some interfaces and inject them in the controller.

Here is the complete example.


Back to basics: db4o and ASP.NET MVC 3

Let's write an app with Db4o and ASP.NET MVC again! Check out this post first.

We've kept it simple & stupid: a model with two entities and a one-to-many relationship. It should set a base for most apps though:

A little background: in a data centre there are serverracks, with blade enclosures or blade chassis. In these enclosures, you can put servers. So, bladeservers go into one blade chassis. Here is the typical one to many relationship!

This is how I set up the solution in Visual Studio:

  • Core contains the business entities
  • Tasks is a console app to get things done quick and dirty
  • Test is for the Unit tests
  • Web is the ASP.NET MVC3 application (Empty) with Razor

So, just create a new class in Core and make it look like this:

Now go to the Db4o website quickly to grab db4o for .NET 4.0, version 8.0.160.14822 MSI. You may have to register first. Install the software.

Now open (add to the solution if you did not yet do so) the Web application and add some references:

I created the following folder structure:

Let's first create the interface for the Unit of Work:

And since we'll be using Db4o for our objectpersistence, let's create a Db4oSession, that derives from ISession.

Next, we need to set up the mechanism that handles the connection to the database for us. This is the SessionFactory:

Now, we are ready to write our first tests:

I can run them successfully in Nunit, which is awesome.

And yes, this all is based on the weblog of my hero Rob Conery. I am so sorry.

Well, we're almost there. We can actually write our controller methods now. Let's add a BladeChassisController and add the Index method:

public ActionResult Index()
        {
            var chassis = SessionFactory.Current.All<BladeChassis>();
            return View(chassis);
            
        }

And this would be our Edit method (that retrieves an instance of the bladechassis to edit):

public ActionResult Edit(int id)
        {
            string cid = id.ToString();
            var chassis = SessionFactory.Current.Single<BladeChassis>(x => x.ChassisID == cid);
            return View(chassis);
        }

And this is the actual altering the 'record' in the 'database':

[HttpPost]
        public ActionResult Edit(int id, FormCollection values)
        {
            try
            {
                // TODO: Add update logic here
                string cid = id.ToString();
                var c = SessionFactory.Current.Single<BladeChassis>(x => x.ChassisID == cid);
                
                UpdateModel(c);
                SessionFactory.Current.Save(c);
                SessionFactory.Current.CommitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

And here is the delete method:

public ActionResult Delete(int id)
        {
            try
            {
                string cid = id.ToString();
                var chassis = SessionFactory.Current.Single<BladeChassis>(x => x.ChassisID == cid);
                SessionFactory.Current.Delete(chassis);
                return RedirectToAction("Index");
            }
            catch
            {
                return View("Index");
            }
        }

It's insanely simple. (Until you need to fill a DropDownList, but that's a separate article).

You can download the example here.
Don't forget to run the Console App in Tasks first, because it adds some data to the app.