Browsing:

Tag: C#

Entity Framework from scratch Part 3 EF4 Database

How to connect your existing database  to a new entity Framework driven app.  I was surprised about the ease of connecting the database to the app. It takes just 5 steps to realise the connection with any available database. EF supports all sorts of databases.

Here we go: First open your project and right click Shoeshoedata

Then we  select Ado.net Entity Data Model and name it Myshoes.edmx

Choose your excisting datamodel

Choose your data Connection, in this case we use the  excisting' Shoe' database

Select which tables (or views)  you'll need for your EF app

and the database is connected to your new EF4 project. See that was easy.

Now the project is ready to use your database.

And now for the Multiple solution config in EF4

Is this yet another famous Microsoft workaround!? Since the new EF4 app couldn’t find his connection string.

We we're looking for a solution to get our App.config to communicate with the console reference. this problem only occurs  when you work with multiple project solutions, he can't seem to find the correct references.

We found out it doesnt work when you just change the .config properties to Copy always, you also need to copy the app.config file to the console app.  as soon as this is done, it works. Maybe there is another solution for this problem, but i have not yet found it.


Entity Framework from scratch Part 2 EF4 release

A lot has happened since the last blog where we introduced the entity framework and tried to explain the possible benefits it could have over the other NoSQL.
Microsoft has released a new EF4 that builds us cleaner code, “Code First Development”

They have kept their eyes out on the other NoSQL movements and learned, In this post we are going to introduce 2 new types, the DbContext and the DbSet that EF4 brought us.
At first I was puzzled as in why two new types, and not just remake the ObjectContext and ObjectSet.
But there is a logica behind this, as you can read on the Msdn blog. They are no replacement, they are just simplified. Now you can always choose to use the more advanced types. DBSet has full compatibility with the excisting EF’s and to switch to the ObjectContext and ObjectSet.

We are going to build a standard console app.
First, make sure you're on .Net version 4, or the entity framework 4 will not work.

Dwnload the new EF4 features here and install them.

Fire up your visual studio and choose the console app, and name it ShoeShoe. Now add a using statement on top of the program.cs

using System.Data.Entity;

Now define the two classes we need for our data, namely ShoeShoe a class that describes the shoes in my closet and second the type of shoes i have collected.

public class ShoeCat
{
    public string ShoeCatId { get; set; }
    public string Name { get; set; }

    public virtual ICollection Shoe { get; set; }
}

public class ShoeShoe
{
    public int ShoeShoeId { get; set; }
    public string Name { get; set; }
    public string CategoryId { get; set; }

    public virtual ShoeCat Category { get; set; }

Now we are gonna add context using the new DbContext DbSet type from EF4

public class ShoeShoeCatalog : DbContext
{
    public DbSet Categories { get; set; }
    public DbSet Products { get; set; }
}

To get your console app to recognize the Dbset statement, we need to add 2 references:
The Microsoft.Data.Entity.CTP
microsoft.data.entity
and the system.data.entity.

this is all the code needed to start the process of storing and retrieving data.

Now let’s put some data in the app and build a program class

class Program
{
    static void Main(string[] args)
    {
        using (var context = new ShoeShoeCatalog())
        {
            var Pump = new ShoeCat { ShoeCatId = "Pump", Name = "Sexy" };
            context.Categories.Add(Pump);
            int recordsAffected = context.SaveChanges();

            Console.WriteLine(
                "Succesfully Saved {0} row(s) to the database, press any key to exit.",
                recordsAffected);

            Console.ReadKey();
        }
    }
}

Now we successfully added shoeshoe data.
This is ofcourse just the beginning of our shoeshoe app, but i hope you are bit more familiar with the 2 new types EF4 has provided us.

Enjoy ! Next we are going to build extra features in ourShoeShoe console application.


ASP.NET MVC and MongoDb Part 2

In the former blogpost we've explored MongoDb and we've created a very basic MVC application with the norm.dll. We created a User and a Bug class, but we've only implemented some CR (and not UD) for the User class.
In this post I will explore how to deal with a one-to-many relationship in a document based database, i.e. a non relational database.
classdiagram

One user can submit more bugs, so there is a one to many relationship between the user and the bugs. But how to implement that in an app where there is no relational database and where there are no constraints?

This were the ViewModel pattern comes in.

Below I created a new class, the BugViewModel class, which is a combination of attributes or fields from the Bug and the User class:

namespace BugBase.ViewModels
{
    public class BugViewModel
    {
        public ObjectId Id { get; set; }
        public ObjectId UserId { get; set; }
        public string ShortDescription { get; set; }
        public string LongDescription { get; set; }
        public DateTime? Date { get; set; }
        public bool Status { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
    }
}

So, that's great. Thank you Framework! But however do I map those attributes to the User and Bug classes?
There is AutoMapper, an object to object mapper by Jimmy Bogard, available here. But I think Automapper is a bit complex to use. For simple scenario's, like BugBase, there is a solution in the ASP.NET MVC futures assembly. This assembly provides a static class, the ModelCopier, that can also use for copying values between View Model objects and Domain model objects. It's available here at Codeplex. The dll is called Microsoft.Web.Mvc.dll. Add a reference to it in BugBase and you're good to go.

The controller create method, would look like this:

[HttpPost]
 public ActionResult Create(BugViewModel bugviewmodel)
   {
       var bug = new Bug();
       ModelCopier.CopyModel(bugviewmodel, bug);

       using (var session = new MongoSession())
        {
         string username = bugviewmodel.UserName;
            var user = session.users
              .Where(u => u.UserName == username)
                  .FirstOrDefault();

                bug.User = user;
                session.Save(bug);                
         }
      return RedirectToAction("Index");
      }
 }

You see how easy it is to add a user to a bug using the ViewModel Pattern and copy the viewmodel to the original domain class.

Next time we'll spice up the userinterface and we'll add some jQuery and Ajax.


(Another) ASP.NET MVC 2.0 app with MongoDb Part 1

I have been fiddling around with Db4o and well.. I did not finish my app. Which probably means that it is time to try out yet another document based database. So. Let's cover MongoDb this time.

I will now create a webapplication where users can submit bugs for a certain software project. Let's call it BugBase.

The first step is to create the folders c:\data and c:\data\db. These are the default folders that you can override if you wish. The next step is to download the Mongo binaries and extract them in c:\data\db.

As with many nosql databases they're obscenely trivial to install. Click on mongod.exe in the bin folder and the Mongo server is running:

mongodb

Let's see if this works. Let's create a bug record for "unable to save" in a database.

C:\data\db\bin>mongo
MongoDB shell version: 1.4.2
url: test
connecting to: test
type "exit" to exit
type "help" for help
> b = { description : "unable to save" };
{ "description" : "unable to save" }
> b = { bugtext : "unable to save the records"};
{ "bugtext" : "unable to save the records" }
> db.bugbase.save(b);
> db.bugbase.find();
{ "_id" : ObjectId("4c03a7fa0e6c000000004226"), "bugtext" : "unable to save the
records" }
>

mongocli

Apparently it does work 😉
I inserted a record in a document (ie table) and Mongo created a unique identifier for me. Cool.

Put Mongo in an ASP.NET MVC 2 app

First step is to create an MVC2 app in Visual Studio 2010 and get rid of all the standard stuff from the template.

Did somebody actually write a MongoDb to Linq provider? But yes of course! My hero Rob Conery did. And Andrew Theken took it further and hosts the project on Github.

What a surprise, only yesterday Andrew uploaded a new version. Wherever would I be without the efforts of these brilliant people? Download the latest Norm project (should I use Github) and compile it in Visual Studio. Grab the norm.dll from the bin folder and add a reference to it in the BugBase project.

Next I need an example as of how to use this dll. At Codeplex Shiju Varghese wrote an example application, which I will use as a reference. But you don't need to check out all these examples. It's just to give the credits to the people that made all this possible.

For BugBase we need at least 2 classes. Bug and User. Create them in the Models folder.

 public class User
    {
        [MongoIdentifier]
        public ObjectId Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public List Bugs { get; set; }

        public User() {
            Bugs = new List();
        }
    }
public class Bug
    {
        [MongoIdentifier]
        public ObjectId Id { get; set; }
        public string ShortDescription { get; set; }
        public string LongDescription { get; set; }
        public DateTime? Date { get; set; }
        public bool Status { get; set; }
        public User User { get; set; } 
    }

Now, let's add a folder called Infrastructure to put all the data layer stuff in. Create a new class called MongoSession.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Norm;
using Norm.Collections;
using Norm.Linq;
using Norm.Responses;
using BugBase.Models;

namespace BugBase.Infrastructure
{
    internal class MongoSession : IDisposable
    {
        private readonly MongoQueryProvider provider;

        public MongoSession()
        {
            var mongo = new Mongo("BugBase", "localhost", "27017", "");
            this.provider = new MongoQueryProvider(mongo);
        }

        public IQueryable Bugs
        {
            get { return new MongoQuery(this.provider); }
        }
        public IQueryable users
        {
            get { return new MongoQuery(this.provider); }
        }
        public MongoQueryProvider Provider
        {
            get { return this.provider; }
        }

        public void Add(T item) where T : class, new()
        {
            this.provider.DB.GetCollection().Insert(item);
        }

        public void Dispose()
        {
            this.provider.Server.Dispose(); 
        }
        public void Delete(T item) where T : class, new()
        {
            this.provider.DB.GetCollection().Delete(item);
        }

        public void Drop()
        {
            this.provider.DB.DropCollection(typeof(T).Name);
        }

        public void Save(T item) where T : class,new()
        {
            this.provider.DB.GetCollection().Save(item);            
        }
    }    
  }

We've got the models in place and the datalayer, so let's create a UserController.

usercontroller

Let's create a view.

usercreateview

Create a strongly typed view with the BugBase.Models.User View Data Class and Create as View Content.

Now let's add the controllermethods to create a user and list them:

 public ActionResult Index()
        {
            using (var session = new MongoSession())
            {
                var userlist = session.users.AsEnumerable();
                return View(userlist);
            }
        }
 [HttpPost]
        public ActionResult Create(User user)
        {
            using (var session = new MongoSession())
            {
                session.Save(user);
            }
            return new RedirectResult("/User");
        }

Compile the project and behold the result:

usercreate

And the list: (OK, never mind the poor security of this app)

userlist

Next time let's implement the bugs. You can download the very beta beta beta BugBase App here.


Db4o and ASP.NET MVC 2 part 2

In the last article I explained how to set up an ASP.NET MVC 2 project with a Db4o backend to create a weblog application. In the spirit of Domain Driven Design we created a single entity 'Story'. We managed to create a separate class for database access. We did not however, implement the Unit of Work or the Repository pattern. We'll get to that later. Let's have a working application first and we'll build in the abstractions later.

So, we created a StoryController in the Controllers folder and we implemented the Create method. After clicking Submit the method takes us to Index:

datienaarindex

So we need to go to line 19 and right click on Index and click Add View, just like before:

datienaarindexview

And then we can scaffold the Index View like this:

index

Here is the code to list all the Story entries in the database:

public ActionResult Index()
        {
            //instantiate the db4o objectcontainer:
            IObjectContainer db = MySingleInstance.Instance().
                OpenDataBase();

            try
            {
                //this is the tricky part.
                //We select all the Story objects from the db:
                var query = from Story s in db select s;
                //And we'll add that to a list:
                List allStories = new List();
                foreach (Story story in query)
                {
                    allStories.Add(story);
                }
                //We'll present the List to the View
                return View(allStories);
            }
            finally
            {
                //Close the database.
                db.Close();
            }
        }

Why am I copying the query result to a List? The answer is, if I don't, the database closes before the page is displayed, so the page remains empty and we'll get a DataBaseClosed Exception.

Now run the application (hit F5) and browse to http://localhost:portnr/Story.

List

And we see all our entries. If you click Create New, you'll be directed to the form we made in part 1 and you can add another blog article. So basically the weblog application is ready, right?

The only thing is, it looks like shit. And I am no designer. So let's grab a nice minimalist CSS template from the web. I googled 'minimalist elegant css' and came across Inkcover. The css of this site is a bit cluttered and it's derived from a templating engine from Coldfusion I believe. But with a little hacking it came out quite nice.

Ik Zeg..

I'll think I'll have to notify the designers.

Next time I will cover validation at last. And perhaps upload the code.