Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

Localizing an ASP.Net MVC 4.0 application

In this post I will demonstrate with a hands on demo how to localise your ASP.Net MVC applications.  

The most important thing to point out is that in this world we live in, we should expect our site to be visited by various people from different cultures and languages.So we must be prepared to have our site internationalised. Thankfully ASP.Net MVC simplifies the whole internationalisation/localisation process.

I would like to talk about the Thread.CurrentCulture property that impacts formatting. That means that this property instructs the runtime how it should display strings e.g the currency in ($ or  €) or how the date should be displayed.

The other imporant property is Thread.CurrentUICulture which is used by the Resource Manager to look up culture-specific resources at run-time.

I have installed VS 2012 Ultimate edition in my Windows 8 machine. Υou can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.

1) I am launching VS 2012 and I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application from the available templates. Choose C# as the development language and Internet Application. I will name my application MvcLocalization.All the necessary files are created

2) In the Ιndex.chstml  view in the Home folder add the following code

@{
  
    var mysalary = 2450.0m;
 
    var birthday = new DateTime(1980217); 
    
}
 
<div>
    @mysalary.ToString("c")
 
</div>
 
 
 
<br />
 
 
<div>
 
    @birthday.ToShortDateString()
 
</div>

I just declare two variables and output them back to the screen. I format the mysalary  value as currency.

3) Now we need to change our settings in the web.config file.In the <system.web> section add

<globalization culture="auto" uiCulture="auto"/>

 

4) Build and run your application and you should will see something like the picture below

 


 

My default culture in this machine is US English. So everything is formatted accordingly.

I go to Internet Explorer ( I view my app in IE ) -> Tools ->Languages->Set Language Preferences and add another language (Greek)

Now I run again my application. Now I see the new culture format is applied in both my strings.

Have a look at the picture below

 

 The way ASP.Net runtime managed to display everything in the new culture because it identified the Accept-Language HTTP Header and the globalization entry in the web.config.

5) Now let's move to the next step of localisation and localise some other strings.

To localise text I am going to use .resx files. These files are xml file and are capable of storing localised text per culture.

We need a .resx for every language we want to support.All these resources are compiled in strongly typed classes.

Ι change my language back to English.

I will add a string in the Index.cshml view

<div>Welcome</div>

Now I need to create my resource files.I go to Home (Views Folder) and I add a resource item - Resources.resx.

Now you will that there is Resources.resx.cs file created.Inside there, there is a strongly typed class. In the editor that pops up I will make a new entry.

Have a look at the picture below

Now I go back to the Index.cshtml file and

change this

<div>Welcome</div>

to

<div>@MvcLocalization.Views.Home.Resources.WelcomeText</div>

I add the namespace and then the name of the class (Resources) and the name of the string (WelcomeText).

Build and run your application. You will see the text "Welcome to you all!!!"

Now if I want to add another language I must add create another .resx file.Once more I go to Home (Views Folder) and I add a resource item - Resources.el.resx.

Then I add another entry for the greek language.

Have a look at the picture below

 

Now,I go to Internet Explorer ( I view my app in IE ) -> Tools ->Languages->Set Language Preferences and add another language (Greek)

I build and run my application. Now I see the localised text "Kαλώς Ήλθατε"

Hope it helps!!!

Using the Repository Pattern in an ASP.Net MVC 4.0 application

In this post I will demonstrate with a hands-on demo the importance of using patterns in an ASP.Net MVC application. I will use the Repository Pattern to create an additional abstract layer between my domain classes and the data layer.

For a more formal definition, I will use the definition that Martin Fowler has given to his book "Patterns of Enterprise Application Architecture".

"Repository Pattern mediates between the domain and the data mapping layers using a collection-like interface for accessing domain objects".

Basically what that means is that it is a layer to separate our application from the data storage technology. It is a pattern for data access.

I will explain more about this pattern as I build the application.

First I will build a small ASP.Net MVC 4.0 EF Code first application without using the repository pattern and then I will rewrite my code leveraging that pattern.

People who follow this blog have seen me in the past building an application first and then changing it a bit to demonstrate the post's main idea.

I will keep things simple. I will create a simple POCO class, Footballer, and then build an ASP.Net MVC application where one can create,edit and delete Footballer entities.

Also I will show you how to architecture properly your ASP.Net MVC 4.0 EF Code first application.

We should not have our domain classes, data access classes and views,controllers in the same project.

We should have them in 3 different projects.

That way our code is more extensible, maintainable and easy to reuse in other non web applications that might need to consume or use EF Code first data access layer.We have a clear separation of concerns.

 

I have installed VS 2012 Ultimate edition in my Windows 8 machine. Υou can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.

1)  I am launching VS 2012 and I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application from the available templates. Choose C# as the development language and Internet Application. I will name my application MvcRepository. This will be the startup project.

2) Now that we have our MVC project structure we will create another project in our solution. This will be a Windows Library project. I will name it MvcRepository.DomainClasses. In this project I will add only the definitions of the domain class Footballer. I delete the class1.cs class file.

I create a new class, Footballer.cs. The code follows

   public class Footballer
    {
        public int FootballerID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Weight { getset; }
        public double Height { getset; }
 
 
    }
My class is simple class and knows nothing about the Entity Framework.

3) I will add another project in this solution. This will be a Windows Library project. I will name it MvcRepository.DomainAccess.I delete the class1.cs class file.

In this class I will add classes that act at the data access layer that will interact with the ASP.Net MVC application and the SQL Server database that will be created.

I will add a reference to the MvcRepository.DomainClasses project as well.

Then we need to install Entity Framework 5.0. We will do that through Nuget packages. Make sure you do that.


Then we need to create a context class that inherits from DbContext.Add a new class to project. Name it TheFootballerDBContext.Now that we have the entity class created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows

 

 public class TheFootballerDBContext : DbContext
    {
 
 public DbSet<Footballer> Footballers { getset; }
 
    }

    Do not forget to add  (using System.Data.Entity;) in the beginning of the class file

 

4) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it , it will use a connection string in the web.config and will create the database based on the classes.I will use the LocalDb.

In my case the connection string inside the web.config, looks like this

      <add name="TheFootballerDBContext"
 connectionString="Data Source=(LocalDb)\v11.0;
 AttachDbFilename=|DataDirectory|\NewDBFootballers.mdf;
 Integrated Security=True"
 providerName="System.Data.SqlClient" />

 

5) Now we need to access our model from a controller.This is going to be a simple class that retrieves the footballers data.

I will add a reference to the MvcRepository.DomainClasses project.

Right-click the Controllers folder and create a new FootballerController controller. Have a look at the picture below to set the appropriate settings and then click Add.

Have a look at the picture below


 

 Visual Studio 2012 will create the following


A FootballerController.cs file in the project's Controllers folder.
A Footballer folder in the project's Views folder.
Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Footballer folder.

Then we need to make a small change to the _Layout.cshtml file. We will add this line of code to add another item in the menu so we can navigate to the Footballers page.

 

    <li>@Html.ActionLink("Footballers""Index""Footballer")</li>

 

6)  Build and run your application.Navigate to the localhost/youport/footballer

You have a UI ready for you to add,edit,delete footballers. I will add 2-3 entries.

7) Now we are ready to change our code to incorporate the Repository pattern.

I am going to show you the contents of the FootballerController.cs class, so you can see changes we will make to the controller later on, when we incorporate the Repository pattern.

 

    public class FootballerController : Controller
    {
        private TheFootballerDBContext db = new TheFootballerDBContext();
 
        //
        // GET: /Footballer/
 
        public ActionResult Index()
        {
 
        
            return View(db.Footballers.ToList());
        }
 
        //
        // GET: /Footballer/Details/5
 
        public ActionResult Details(int id = 0)
        {
            Footballer footballer = db.Footballers.Find(id);
            if (footballer == null)
            {
                return HttpNotFound();
            }
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Create
 
        public ActionResult Create()
        {
            return View();
        }
 
        //
        // POST: /Footballer/Create
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Footballer footballer)
        {
            if (ModelState.IsValid)
            {
                db.Footballers.Add(footballer);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
 
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Edit/5
 
        public ActionResult Edit(int id = 0)
        {
            Footballer footballer = db.Footballers.Find(id);
            if (footballer == null)
            {
                return HttpNotFound();
            }
            return View(footballer);
        }
 
        //
        // POST: /Footballer/Edit/5
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Footballer footballer)
        {
            if (ModelState.IsValid)
            {
                db.Entry(footballer).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Delete/5
 
        public ActionResult Delete(int id = 0)
        {
            Footballer footballer = db.Footballers.Find(id);
            if (footballer == null)
            {
                return HttpNotFound();
            }
            return View(footballer);
        }
 
        //
        // POST: /Footballer/Delete/5
 
        [HttpPostActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Footballer footballer = db.Footballers.Find(id);
            db.Footballers.Remove(footballer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
 
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
 public class FootballerController : Controller
    {
        private TheFootballerDBContext db = new TheFootballerDBContext();

I want to remind you that in an MVC application the View is my user interface and the Controller interacts with the view.

Ιn the line above I can see that I create an instance of the TheFootballerDBContext class that inherits from the DbContext class. That means that I work directly with EF.

I do not want that. I do not want to work with EF in all the layers of my application.

Have a look in some action methods in the FootballerController.cs class

        public ActionResult Index()
        {
            return View(db.Footballers.ToList());
        }
 
        //
        // GET: /Footballer/Details/5
 
        public ActionResult Details(int id = 0)
        {
            Footballer footballer = db.Footballers.Find(id);
            if (footballer == null)
            {
                return HttpNotFound();
            }
            return View(footballer);
        }

You can see that there are queries that talk directly to the data access layer.Not just the queries in those two methods but in all methods in the controller. That is not the ideal option.We need a new abstract layer between the Controller class and the DbContext class.

 

We will do that by adding another class.In that way our code facilitates unit testing and test driven development.

8) Now we will add another class file to the MvcRepository.DomainAccess project. I will name it IFootballerRepository.cs. The code follows

 

    public interface IFootballerRepository : IDisposable
    {
        IEnumerable<Footballer> GetFootballers();
        Footballer GetFootballerByID(int FootballerID);
        void InsertFootballer(Footballer footballer);
        void DeleteFootballer(int FootballerID);
        void UpdateFootballer(Footballer footballer);
        void Save();
    }

In this class we declare CRUD methods.We also have two read methods. The first one returns all Footballer entities, and the second one finds a single Footballer entity by ID.

Now we will add another class file to the MvcRepository.DomainAccess project. I will name it FootballerRepository.cs. It will implement the IFootballerRepository interface. Interfaces cannot be instantiated and the methods they declare cannot be implemented. You can inherit only from one base class but from multiple interfaces.

The code for the FootballerRepository.cs follows

    public class FootballerRepository : IFootballerRepositoryIDisposable
    {
        private TheFootballerDBContext context;
 
        public FootballerRepository(TheFootballerDBContext context)
        {
            this.context = context;
        }
 
        public IEnumerable<Footballer> GetFootballers()
        {
            return context.Footballers.ToList();
        }
 
        public Footballer GetFootballerByID(int id)
        {
            return context.Footballers.Find(id);
        }
 
        public void InsertFootballer(Footballer footballer)
        {
            context.Footballers.Add(footballer);
        }
 
        public void DeleteFootballer(int FootballerID)
        {
            Footballer footballer = context.Footballers.Find(FootballerID);
            context.Footballers.Remove(footballer);
        }
 
        public void UpdateFootballer(Footballer footballer)
        {
            context.Entry(footballer).State = EntityState.Modified;
        }
 
        public void Save()
        {
            context.SaveChanges();
        }
 
        private bool disposed = false;
 
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }
 
        public void Dispose()
        {
            Dispose(true);
       
        }
    }

The database context is defined in a class variable, and the constructor expects the calling object to pass in an instance of the context.

The implementation of the various methods is straightforward

       public void InsertFootballer(Footballer footballer)
        {
            context.Footballers.Add(footballer);
        }

In the simple method above, a footballer entity is passed from the calling application (controller) to the method and this is added to the collection of footballers.

Please run your application and place breakpoints so you can see what is going on.

We also implement the SaveChanges method so all the data that lives in the memory is saved back to the datastore in a transactional way.

        public void Save()
        {
            ctx.SaveChanges();
        }

We also implement the IDisposable and dispose the database context.

Now I will show you the complete code (with the changes made) to the FootballerController.cs class. I have used italics to highlight the changes.

 

    public class FootballerController : Controller
    {
        private IFootballerRepository footballerRepository = null;
 
    public FootballerController()
      
    {
this.footballerRepository=new FootballerRepository(new TheFootballerDBContext());
    }
 
    public FootballerController(IFootballerRepository footballerRepository)
    {
        this.footballerRepository = footballerRepository;
    }
 
        //
        // GET: /Footballer/
 
        public ActionResult Index()
        {
IEnumerable<Footballer> footballers=footballerRepository.GetFootballers();
            return View(footballers);
        }
 
        //
        // GET: /Footballer/Details/5
 
        public ViewResult Details(int id = 0)
        {
Footballer footballer = footballerRepository.GetFootballerByID(id);
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Create
 
        public ActionResult Create()
        {
            return View();
        }
 
        //
        // POST: /Footballer/Create
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Footballer footballer)
        {
            if (ModelState.IsValid)
            {
        footballerRepository.InsertFootballer(footballer);
        footballerRepository.Save();
        return RedirectToAction("Index");
            }
 
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Edit/5
 
        public ActionResult Edit(int id = 0)
        {
 Footballer footballer = footballerRepository.GetFootballerByID(id);
            if (footballer == null)
            {
                return HttpNotFound();
            }
            return View(footballer);
        }
 
        //
        // POST: /Footballer/Edit/5
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Footballer footballer)
        {
            if (ModelState.IsValid)
            {
     footballerRepository.UpdateFootballer(footballer);
     footballerRepository.Save();
     return RedirectToAction("Index");
            }
            return View(footballer);
        }
 
        //
        // GET: /Footballer/Delete/5
 
        public ActionResult Delete(int id = 0)
        {
  Footballer footballer = footballerRepository.GetFootballerByID(id);
 
            return View(footballer);
        }
 
        //
        // POST: /Footballer/Delete/5
 
        [HttpPost,ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
   Footballer footballer = footballerRepository.GetFootballerByID(id);
  footballerRepository.DeleteFootballer(id);
  footballerRepository.Save();
  return RedirectToAction("Index");
        }
 
        protected override void Dispose(bool disposing)
        {
            footballerRepository.Dispose();
            base.Dispose(disposing);
        }
    }

The controller declares a class variable for an object that implements the IFootballerRepository interface.

The default constructor creates a new context instance, and the other constructor allows the caller to pass in a context instance.

All the methods in the controller are very easy to understand.

Have a look at the method below.

Instead of working with the DbContext (EF) directly we now make calls to the Repository methods (footballerRepository.ΙnsertFootballer(footballer)) that are part of our data access layer (MvcRepository.DomainAccess) that talk with the TheFootballerDBContext that inherits from the DbContext = EF. But this time we have the controller talking to the repository that talks to the data access layer that talks to the database.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Footballer footballer)
        {
            if (ModelState.IsValid)
            {
   footballerRepository.InsertFootballer(footballer);
   footballerRepository.Save();
   return RedirectToAction("Index");
            }
 
            return View(footballer);
        }

 

Build and run your application. If you have understood and followed everything your ASP.Net MVC will work just fine. Try to add some more footballer entries.

 

Hope it helps!!!

Looking into Fluent API in an ASP.Net MVC 4.0 Code First application

In this post I will demonstrate with a hands-on example how to use the Fluent API to map  POCO classes (set configurations) to SQL Server tables without using the set of conventions Entity Framework Code First expects.

I will also give a short introduction to ASP.Net MVC and its main components. I will talk briefly about Entity Framework Code First, Database First and Model First.

Also I will show you how to architecture properly your ASP.Net MVC 4.0 EF Code first application.

We should not have our domain classes, data access classes and views,controllers in the same project.

We should have them in 3 different projects.

That way our code is more extensible, maintainable and easy to reuse in other non web applications that might need to consume or use EF Code first data access layer.We have a clear separation of concerns.

We can configure our POCO classes with Data Annotations. By using Data Annotations we can configure our domain-entity classes so that they can take best advantage of the EF.We can decorate our entity classes with declarative attributes.

If you want to find out how you can use Data Annotations have a look at this post.

Fluent API supports all the configurations that Data Annotations support and more.Data Annotations support only a subset of the configurations that Fluent API supports.

You can configure your classes not in a declarative way (Data Annotations) but you can create a new class and configure the entity classes through pure C# code and lambda expressions. This is the Fluent API way.Code purists prefer this way since we keep our domain classes without any other declarations.

Before I can go on I will explain that the EF Code First Model works with conventions.

  • The table names are derived from the entity class names
  • If have a entity key in entity e.f Customer (CustomerID) , this will be the Primary Key in the Customer table.How does EF do that? By default Code First will look either for a property with the name id to create the primary key.This is the default behavior. We can change that behavior with Fluent API.
  • All the string properties in my EF classes became nvarchar(max,null) .This is default behavior. We can change that behavior with Fluent API.

Through Fluent API, we can configure entities and properties in various ways.We can configure things like

  • Relationships between entities
  • The column name of an entity property
  • The column order of an entity property
  • The column type of an entity property
  • The precision of an entity property
  • If an entity property is required

We can also configure things like Inheritance Hierarchies, map an entity to multiple tables and a table to multiple entities.

I will demonstrate most of these configurations.

Let me give you a short introduction to ASP.Net MVC first. I suggest that you go through some of the videos and other learning resources from the official ASP.Net MVC site.

I will say a few words on how I understand ASP.Net MVC and what its main benefits/design goals are.

Obviously the first paradigm on building web applications on the web is Web Forms.

Web forms was the first and only way to build web application when ASP.Net was introduced to the world, nine years ago.

It replaced the classic ASP model by providing us with a strongly typed code that replaced scripting.We had/have languages that are compiled.Web forms feels like a form that you programmed with VB 6.0 for the desktop.

The main idea was to abstract the WEB. By that I mean HTML is abstracted in a way. Click events replaced "Post" operations.Since that time, web standards have strengthened and client side programming is on the rise. Developers wanted to have more control on the HTML.Web forms , as I said before handles HTML in an abstract way and is not the best paradigm for allowing full control on the HTML rendering.

ASP.Net MVC provide us with a new way of writing ASP.Net applications.It does not replace web forms. It is just an alternative project type.It still runs on ASP.Net and supports caching,sesions and master pages. In ASP.Net MVC applications we have no viewstate or page lifecycle. For more information on understanding the MVC application execution process have a look at this link .It is a highly extensible and testable model.

In order to see what features of ASP.Net are compatible in both Models have a look here.

MVC pattern has been around for decades and it has been used across many technologies as a design pattern to use when building UI. It is based on an architecture model that embraces the so called "seperation of concern pattern".

There are three main building blocks in the MVC pattern. The View talks to the Model. The Model has the data that the View needs to display.The View does not have much logic in them at all.

The Controller orchestrates everything.When we have an HTTP request coming in, that request is routed to the Controller. It is up to the Controller to talk to the file system,database and build the model.The routing mechanism in MVC is implemented through the System.Web.Routing assembly. Routes are defined during application startup.Have a look at the Global.asax file,when building an MVC application.

The Controller will select which View to use to display the Model to the client.It is clear that we have now a model that fully supports "separation of concerns".The Controller is responsible for building the Model and selecting the View.

The Controller does not save any data or state. The Model is responsible for that.The Controller selects the View but has nothing to do with displaying data to the client.This is the View's job.

The Controller component is basically a class file that we can write VB.Net or C# code. We do not have Page_Load event handler routines, just simple methods which are easy to test.No code behind files are associated with the Controller classes.All these classes should be under the Controllers folder in your application.Controller type name must end with Controller (e.g ProductController).

In the Views folder we should place the files responsible for displaying content to the client.Create subfolders for every Controller. Shared folder contains views used by multiple controllers.

In this post I will use the Razor View engine rather than the WebForms View. Razor View engine is designed with MVC in mind and it is the way (as far as I am concerned) to work with ASP.Net MVC.

Before we start I will give again a short introduction to Entity Framework. The stable version of Entity Framework as we speak is EF 5.0.It is available through Nuget and it is an open source project.

The .Net framework provides support for Object Relational Mapping through EF. So EF is a an ORM tool and it is now the main data access technology that microsoft works on. I use it quite extensively in my projects. Through EF we have many things out of the box provided for us. We have the automatic generation of SQL code.It maps relational data to strongly types objects.All the changes made to the objects in the memory are persisted in a transactional way back to the data store. 

You can search in my blog, because I have posted many posts regarding ASP.Net and EF. 

There are different approaches (paradigms) available using the Entity Framework, namely Database First, Code First, Model First. 

You can find in this post an example on how to use the Entity Framework to retrieve data from an SQL Server Database using the "Database/Schema First" approach.

In this approach we make all the changes at the database level and then we update the model with those changes. 

In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework.

This model was firstly introduced in EF version 4.0 and we could start with a blank model and then create a database from that model.When we made changes to the model , we could recreate the database from the new model. 

The Code First approach is the more code-centric than the other two. Basically we write POCO classes and then we persist to a database using something called DBContext.

In this application we will us the Code First approach when building our data-centric application with EF. 

Code First relies on DbContext. We create classes with properties and then these classes interact with the DbContext class.Then we can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests.

DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First).

I am running VS Studio 2012 Ultimate edition but you can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.

I will create an ASP.Net MVC application that has two entities, Department and Courses. They have one to many relationships between them.

1)  I am launching VS 2012 and I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application from the available templates. Choose C# as the development language and Internet Application. I will name my application FluentAPIMVC. This will be the startup project.

2) Now that we have our MVC project structure we will create another project in our solution. This will be a Windows Library project. I will name it FluentAPIMVC.DomainClasses. In this project I will add only the definitions of the two domain classes Course and Department. I delete the class1.cs.

I create a new class, Department.cs. The code follows

 

    public class Department
    {
        public int DepartmentId { getset; }
        public string Name { getset; }
        public decimal Budget { getset; }
        public DateTime StartDate { getset; }
        public virtual ICollection<Course> Courses { getset; }
    }

 I will add another class, Course.cs

public class Course
    {
        public int CourseID { getset; }
        public string Title { getset; }
        public int Credits { getset; }
        public int DepartmentID { getset; }
        public virtual Department Department { getset; }
    }

 

These are just two plain POCO classes that know nothing at all about Entity Framework.

 

3) I will add another project in this solution. This will be a Windows Library project. I will name it FluentAPIMVC.DomainAccess.

In this class I will add classes that act at the data access layer that will interact with the ASP.Net MVC application and the SQL Server database that will be created.

I will add references to System.Data.Entity

I will add a reference to the FluentAPIMVC.DomainClasses project as well.

Then we need to install Entity Framework 5.0. We will do that through Nuget packages. Make sure you do that.

I will add a class DepartmentDBContext to the project.

The contents of this class are:

 public class DepartmentDBContext:DbContext

    {
   
        public DbSet<Department> Departments { getset; }
        public DbSet<Course> Courses { getset; }
 
    }

This class inherits from DbContext. Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.

I will add more code to this class later on.

4) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it , it will use a connection string in the web.config and will create the database based on the classes.I will use the LocalDb

      <add name="DepartmentDBContext"
 connectionString="Data Source=(LocalDb)\v11.0;
 AttachDbFilename=|DataDirectory|\DepartmentCourses.mdf;
 Integrated Security=True"
 providerName="System.Data.SqlClient" />

 

 5) Now we can build our application to make sure everything works ok. Now I want to insert data , seed the database, to the tables.

I will add another class to the FluentAPIMVC.DomainAccess. I name it DepartmentCoursesInsert.

The contents of this class follow

 

 public class DepartmentCoursesInsert:
    DropCreateDatabaseAlways<DepartmentDBContext> {
        protected override void Seed(DepartmentDBContext context)
        {
            var departments = new List<Department>
            {
            new Department { 
                
     Name = "Physics",Budget=35500StartDate=DateTime.Parse("12/12/1999"),
     Courses = new List<Course>             
                { 
                
    new Course {Title = "Nuclear Physics"Credits= 45},
    new Course {Title = "Quantum Physics"Credits= 35}
 
                }
 
                            },
            
             new Department { 
                 
     Name = "Maths",Budget=45500StartDate=DateTime.Parse("12/12/2009"),
     Courses = new List<Course>             
                { 
                
     new Course {Title = "Trigonometry"Credits= 35},
     new Course {Title = "Analytic Geometry"Credits= 45}
 
                }
 
                            },
        
            };
 
     departments.ForEach(dep => context.Departments.Add(dep));
     base.Seed(context);
        }
    }

 

We need to add entries for the System.Data.Entity and the FluentAPIMVC.DomainClasses namespace for this class to compile.

In this class I inherit from the  DropCreateDatabaseAlways<DepartmentDBContext>

class and I will override the default behavior of that class with my class.

I will ovverride the Seed method with some data.Then I create 2 instances of the Department entity and 4 entities of the Course entity.

Then through a simple lambda expression I add the data to the database using these last lines of code.

   departments.ForEach(dep => context.Departments.Add(dep));
     base.Seed(context);

This is just a way to populate initially the database with some data. You could leave this step out and populate the database through the views.

There is another way to populate the database and you should not use DropCreateDatabaseAlways  in production databases.

We have Code First Migrations to insert data but I will not show that here. You can read about Code First Migration in this post.

Before the addition of Code First Migrations (4.1,4.2 versions), Code First database initialisation meant that Code First would create the database if it does not exist (the default behaviour - CreateDatabaseIfNotExists).

Another pattern is DropCreateDatabaseAlways which means that Code First will recreate the database every time one runs the application.

The other pattern we could use is DropCreateDatabaseIfModelChanges which means that Entity Framework, will drop the database if it realises that model has changes since the last time it created the database.

That is of course fine for the development database but totally unacceptable and catastrophic when you have a production database. We cannot lose our data because of the way that Code First works.

 

Now we need to make one more change.in the Global.asax.cs file to add a line of code


 Database.SetInitializer(new DepartmentCoursesInsert());

 

 We add this line of code to the Application_Start() method.

 

I will add references to System.Data.Entity

I will add a reference to the FluentAPIMVC.DomainAccess project as well.

 

6) Now I will create a new class in the in the FluentAPIMVC.DomainAccess project. I will name it CourseMap.

This is a configuration class that uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

public class CourseMap : EntityTypeConfiguration<Course>
    {
        public CourseMap()
        {
            // Primary Key
            this.HasKey(t => t.CourseID);
 
            // Properties
            this.Property(t => t.CourseID)
 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 
            this.Property(t => t.Title)
                .IsRequired()
                .HasMaxLength(70);
 
            this.Property(t => t.Credits)
               .IsRequired();
              
 
            // Table & Column Mappings
   this.ToTable("Course");
   this.Property(t => t.CourseID).HasColumnName("ID");
   this.Property(t => t.Title).HasColumnName("Title");
   this.Property(t => t.Credits).HasColumnName("CreditsForCourse");
   this.Property(t => t.DepartmentID).HasColumnName("DepID");
 
            // Relationships
      this.HasRequired(t => t.Department)
      .WithMany(t => t.Courses)
      .HasForeignKey(d => d.DepartmentID);
 
        }
    }

In the code above I define the primary key. I define that the primary key as an identity. Then I set that the Title property is non nullable and has a max length of 70. The entity property Credits is required.

Then I define the Table and Column mappings. The entity maps to a table called Course.Then I define the names for the column names.So I can change the entity name properties to different table column names.

Finally I define the one to many relationship.

7) Now I will create a new class in the in the FluentAPIMVC.DomainAccess project. I will name it DepartmentMap.

This is a configuration class that uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

public class DepartmentMap : EntityTypeConfiguration<Department>
    {
        public DepartmentMap()
        {
            // Primary Key
            this.HasKey(t => t.DepartmentId);
 
            // Properties
            this.Property(t => t.DepartmentId)
  .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 
            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(40);
 
            this.Property(t => t.Budget)
               .IsRequired()
               .HasColumnType("decimal")
               .HasPrecision(204)
               ;
 
            this.Property(t => t.StartDate)
           .IsOptional();
 
            // Table & Column Mappings
 this.ToTable("Department");
 this.Property(t => t.DepartmentId).HasColumnOrder(1).HasColumnName("ID");
 this.Property(t => t.Name).HasColumnOrder(2).HasColumnName("Dep Name");
 this.Property(t => t.Budget).HasColumnOrder(4).HasColumnName("Budget");
 this.Property(t=>t.StartDate).HasColumnOrder(3).HasColumnName("Start Date");
 
        }
    }

In the code above I define the primary key. I define that the primary key as an identity. Then I set that the Name property is non nullable and has a max length of 40. The entity property Budget is required (not null in the respective column) and its datatype will be decimal with a precision of (20,4).

The StartDate entity property is not required (allow null in the respective column in the table).

Then I define the Table and Column mappings. The entity maps to a table called Department.Then I define the names for the column names.So I can change the entity name properties to different table column names.I also change the order of the columns.

I am sure you have realised what Fluent API is and how we can use it to define mappings. I have just demonstrated some of the most common settings and configurations used in Fluent API.

8) Now I need to add some more code in the DepartmentDBContext class.

I need to override the OnModelCreating method so I can give the builder useful information before it goes on and builds the model.

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
   modelBuilder.Configurations.Add(new CourseMap());
   modelBuilder.Configurations.Add(new DepartmentMap());
   }

 The complete code for this class follows

    public class DepartmentDBContext:DbContext

    {
 
   
    public DbSet<Department> Departments { getset; }
   public DbSet<Course> Courses { getset; }
 
  
    
 
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
   modelBuilder.Configurations.Add(new CourseMap());
   modelBuilder.Configurations.Add(new DepartmentMap());
   }
 
    }

 9) Now I need to make some changes to the FluentAPIMVC project.

I will add a reference to the FluentAPIMVC.DomainClasses project.

I need to add a controller. I will name it DepartmentController

Have a look at the picture below.

 

Now we need to make a small change to the _Layout.cshtml file. We will add this line of code to add another item in the menu.

  <li>@Html.ActionLink("Departments""Index""Department")</li>

 

10) Build and run your application.

Navigate to the  your localhost/port/department, in my case (http://localhost:57958/Department).

Have a look at App_Data folder. You will see the DepartmentCourses.mdf localdb database.Τhis database was created from EF Code First.

Have a look at the picture below to see the table's definitions. If we go back to your configuration classes where we did the initial mapping you will see that all Fluent API configurations were honored.Have a look at the column names,types and order. Check which types allow nulls and which not.

 

Have a look at the picture below to see the department page.You can see the seeded data. You can edit existing departments,create new departments and delete them.

 

 

Hope it helps!!!

An introduction into Glimpse and how to use it in your ASP.Net applications

In this post I will provide a short introduction to Glimpse and why i think it is very important for any developer that builds ASP.Net sites (both Web Forms and MVC) to use it.

I am building ASP.Net applications and I have started using it.

Glimpse will show you valuable information about your ASP.Net application from within the browser. It will show you what is happening on the server where you ASP.Net application is hosted.

I have posted a post on Page Inspector herePage Inspector gives developers a very good/handy way to identify layout issues and to find out which part of server side code is responsible for that HTML snippet of code.

A short definition of Glimpse is that it is a diagnostics platform for the web.Gives us an opportunity to glimpse on the server side of things and your asp.net applications. It gathers very detailed information and diagnostics about the behavior and execution of our ASP.Net application and then sends back this information. We can see for example what kind of code was executed and how long it took.

The good news first. Glimpse is free and open source. That means that everyone can download it and install it and extend it by writing your own plugins.

As you will see from the screenshots I will provide, Glimpse looks a lot like Firebug or Chrome Dev tools but please bear in mind that those tools show you what happens on the browser while Glimpse shows you what is going on, on the server.

Firstly I will create a simple ASP.Net  MVC 4.0 application using Entity Framework 5.0 and Code first.Obviously we need some sort of ASP.net application to show off Glimpse.

Ι will show you how to get Glimpse (though Nuget) first and then how to install it in your application.


I have installed VS 2012 Ultimate edition in my Windows 8 machine. Υou can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.

1)  Create an ASP.Net MVC 4.0 application.Give it an appropriate name.

2) Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class.Place this class file in the Models folder.

The code follows


   public class Footballer
    {
        public int FootballerID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Weight { getset; }
        public double Height { getset; }
 
 
    }

3) Then we need to create a context class that inherits from DbContext.Add a new class to the Models folder.Name it TheFootballerDBContext.Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows

 

 public class TheFootballerDBContext:DbContext
    {
       
      public DbSet<Footballer> Footballers { getset; }
        
    }

    Do not forget to add  (using System.Data.Entity;) in the beginning of the class file

 

4) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it , it will use a connection string in the web.config and will create the database based on the classes.I will use the name "NewFootballers" for the database.

In my case the connection string inside the web.config, looks like this

 

   <connectionStrings>
 
   <add name="TheFootballerDBContext" 
connectionString="server=.;integrated security=true;
  database=NewFootballers" providerName="System.Data.SqlClient"/>
        
        
    </connectionStrings>

5) Now we need to access our model from a controller.This is going to be a simple class that retrieves the footballers data.


Right-click the Controllers folder and create a new FootballerController controller. Have a look at the picture below to set the appropriate settings and then click Add.

Have a look at the picture below


 

 Visual Studio 2012 will create the following


A FootballerController.cs file in the project's Controllers folder.
A Footballer folder in the project's Views folder.
Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Footballer folder.

 

6)  Build and run your application.Navigate to the localhost/youport/footballer

I will insert some data in the database through the interface. So now we have a working ASP.Net MVC 4.0 application using EF 5.0 and I am ready to examine it through Glimpse.

7) I will install Glimpse through Nuget.Select your project and then right-click on it and from the context menu select Manage Nuget Packages. Then in the search area search for Glimpse finf Glimpse Mvc4 and install it.Once you’ve done that, Glimpse will automatically add a few entries to your web.config for you.

Open your web.config file and search for Glimpse to see the added sections.If you have installed Glimpsed you will see the picture below


 

8) Now we must turn it on and that is very simple. Build and run your application again Navigate to the localhost/youport/glimpse.axd in my case (http://localhost:55139/glimpse.axd) and you will see the Glimpse page.

Then we just need to turn it on. Just click on the "Turn Glimpse On". We  set a cookie that will tell the Glimpse  running on the server to send you Glimpse data.

Have a look at the picture below

 

 

 

 

9) Now we have the basic setup of Glimpse ready and we can use it.

Navigate to the localhost/youport/footballer, in my case ( http://localhost:55139/footballer/ ) and you will see the Glimpse icon on the lower-right hand corner.

When you click it you will see something like the picture below. It resembles the Chrome Dev tool and Firebug. Have a look at the picture below.

 

10) Now I will explain what kind of information we can see in the various tabs.

There are 8 tabs in Glimpse. Configuration tab contains information from the web.config file. By all means have a look at it.You can see values that come from the machine.config as well.Click this tab and see for yourself.

There is also the Environment tab. In this tab we can see information like the server that handles the request. It provides the name of the server, the operating system that runs on the server and the version of the .Net framework installed. It also provides information on the version of the IIS.We can also see information the Application Assemblies.

The next tab is the Request tab.  In this tab we get information about the request and more specifically how the server received it.You can see information like the User Agent,the cookies, the Raw Url, the Query String,the current UI culture.

Next is the Route tab. In this tab we get information about all the routes that are registered and which route was actually used to service your request.

Next is the Server tab. In this tab we get information about all the web server variables that are available for the request for example APPL_PHYSICAL_PATH, HTTP_COOKIE,HTTP_REFERER,HTTP_USER_AGENT

Next is the Session tab. In this tab we get information about all the keys and values of the data that is stored in the user's Session.The session is for each user/browser and it is managed in the server.

Next is the Timeline tab. In this tab we get information about what was executed in the server and how much time it took, for that method in the controller to execute. We have events like Start Request, InvokeActionResult, RenderView.You can see the whole HTTP MVC Pipeline.

Next is the Trace tab. In this tab we get messages about any messages traced to the System.Diagnostics.Trace or System.Diagnostics.Debug.

So if you go to the Index method of the Footballer controller and type e.g

Trace.Write("this is a test");

Trace.TraceError("error");

these trace messages will show on the Trace tab.

These are the main tabs but we also have the Ajax Tab. In this tab we can get information about all the ajax requests made since the page was loaded.

If you add some Ajax code in your controller methods, you will see the data related with those Ajax requests in the Ajax tab.

We also have the History tab. In this tab we can see all the requests made to the server and we can inspect each request.We can see data under the Request URL, Method, Duration , Date/Time,Is Ajax headers.

Glimpse works well with mobile devices. It will count all requests from mobile devices like a mobile phone or a pad.

I am running again my application and I go to http://localhost:55139/footballer page.You should do that as well, having Glimple enabled.

I will show you some more tabs that are specific to ASP.Net MVC like Execution tab. The execution tab shows information about all the methods executed for the processing of the specific HTTP request. You can see the controller name, the action methods and the time elapsed.

Have a look at the picture below

 

Next we have the Model Binding Tab.This tab shows you what parameters were bound and with what values for the specific request. I Hit the Edit link (http://localhost:55139/footballer) and i move to the http://localhost:55139/footballer/Edit/1.

You will have to do the same for your own localhost/youport/footballer page request.

If you do that you will see something like the picture below

Next we can see the Metadata tab that shows the model medata ASP.Net MVC has used to display the view.

Next we can see the Views tab that shows information about the views ASP.Net MVC that has used and information about the views.

You can see how ASP.Net MVC works in regard with views.Once again I click on the Edit link-  http://localhost:55139/footballer/Edit/1.

We can see the View that rendered the request and the model type passed to that view from the Controller.

Have a look at the picture below

 

Hope it helps!!!

Looking into the LINQ Zip operator

In this rather short post I will be demonstrating with a hands-on example the usefulness of the Linq Zip operator.

You can find more information on Linq expressions and operators (both in query and method syntax) in this post.

I am going to use Visual Studio 2012 Ultimate edition (Visual Studio 2012 Express for Web edition) and I will create an ASP.Net 4.0 Web forms application

I can use LINQ queries not only against databases but against arrays, since the array of strings/integers implement the IENumerable interface.

Just to be absolutely clear you can query any form of data that implements the IENumerable interface.

The Zip operator merges the corresponding elements of two sequences using a specified selector function.

The Zip query operator was not included in LINQ. It was added later in .NET 4.0.

 

1) Fire up Visual Studio 2012.

2) Create an empty web site. Give it the name of your choice.Choose C# as the development language.

3) Add a web form item to your site. Leave the default name.

We will have two string arrays. One array will consist of football teams and another one will consist of their football nicknames.

We will merge those two arrays.

4) In the Page_Load event handling routine type

 

protected void Page_Load(object senderEventArgs e)
    {
string[] footballteamnames = { "Manchester United""Liverpool", 
                                 "Arsenal""Aston Villa" };
 
string[] footballnicknames = { "Red Devils""The Reds", 
                                 "Gunners""Villagers"};
 
var teamswithnicknames = footballteamnames.Zip
 (footballnicknames,(teamnickname=> team + " - " + nickname);
 
 
 
  foreach ( var item in teamswithnicknames )
  {
      Response.Write(item);
      Response.Write("<br/>");
  }
      
    }

 

We declare two string arrays footballteamnames and footballnicknames. We will match the football names with the nicknames.

We declare a variable teamswithnicknames and then we call the Zip operator on the first list,passing in the name of the second list. Then we have a lambda expression declaring how we want the lists zipped together.

So we say that we want the second array to be zipped with the first one and then we indicate through the delegate how they should be combined.

Build and run your application. You will see the following results.

 Manchester United - Red Devils
Liverpool - The Reds
Arsenal - Gunners
Aston Villa - Villagers

 

Hope it helps!!!!

Creating an Entity Data Model in an EF Code First application

In this blog post I will demonstrate with a hands-on example how to use EF Code First Workflow to create an entity data model, an .edmx file so I can visualise my POCO classes

I will follow the steps that I created in this post. In that post I managed to create POCO classes without actually writing the classes myself, but I had EF taking care of that by pointing to the right database.

Please note that what I am about to show will work just fine when one creates his own POCO classes. By that I mean is that you do not need to reverse engineer Code First classes from an existing database for the visualisation to work. You can create your POCO classes from scratch and still use Entity Framework Power Tools  to create the .edmx file.

I am going to re-create some of the steps of my other post in this one.

I am running VS Studio 2012 Ultimate edition but you can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.


1)  I am launching VS 2012 and I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application from the available templates.I will name my application CodeFirstExistingDatabase

2) Normally with Code First we create new classes and then EF knows how tο create the database from those classes. In this application we will do the reverse.

3) Before I create the database I need to download and install Entity Framework Power Tools Beta 3. Go to Tools -> Extensions and updates and search for Entity Framework Power Tools Beta 3 and then install it. Have a look at the picture below. I have already installed it.In you case it will say Install.

 

 

The good news is that Entity Framework Power Tools will be included in EF 6.0.

4) I have already created a sample database. It is called School. It has two tables with data, Course and Department. There is one to many relationship between Department and Course. A Department has many Course(s). This is the script ( SchoolDB.zip) that will install the database with the data in your SQL Server instance.Make sure you have the database installed.

5) Right-click on your project, then select Entity Framework -> Reverse Engineer Code First.Have a look at the picture below


6) In the next step we will be prompted to connect to the database. Connect to the SQL Server instance and the connect to the DB and hit OK.Have a look at the picture below

 

7) Now the Power Tools of EF have created the necessary classes. Have a look under the Models,Mapping folder to see the generated files.

Have a look at the picture below

 

Open web.config. EF has added a connection string to the database

<add name="schoolContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=school;
         Integrated Security=True;MultipleActiveResultSets=True"
      providerName="System.Data.SqlClient" />

The schoolContext.cs file has been created. There is a class in there schoolContext. It has the same name as the name in the name property of the connection string above (name=schoolContext).The schoolContext class derives from the DbContext. DbContext is a base class in EF and it is responsible for change tracking,persisting data back to the database and in general managing the entity objects during runtime. DbSet properties are also exposed and those properties represent collections of the specified entities in the context.

 public schoolContext()
            : base("Name=schoolContext")

Those two lines of code above tell EF that the connection information for this context should be loaded from web.config.

Τhese are the contents of the schoolContext.cs file

public partial class schoolContext : DbContext
    {
        static schoolContext()
        {
            Database.SetInitializer<schoolContext>(null);
        }
 
        public schoolContext()
            : base("Name=schoolContext")
        {
        }
 
        public DbSet<Course> Courses { getset; }
        public DbSet<Department> Departments { getset; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CourseMap());
            modelBuilder.Configurations.Add(new DepartmentMap());
        }
    }

 

There Department.cs and Course.cs are also included.These are the POCO classes i was talking earlier. These two classes are very simple classes and have no dependency from EF. The Department class follows.

public partial class Department
    {
        public Department()
        {
            this.Courses = new List<Course>();
        }
 
        public int DepartmentID { getset; }
        public string Name { getset; }
        public decimal Budget { getset; }
        public System.DateTime StartDate { getset; }
        public Nullable<int> Administrator { getset; }
        public virtual ICollection<Course> Courses { getset; }
    }

You can see the properties that map to the columns of the Department table in the database. The Courses property is a navigation property. A Department entity can related to any number of Courses entities.Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading.

The Course.cs file follows

 public partial class Course
    {
        public int CourseID { getset; }
        public string Title { getset; }
        public int Credits { getset; }
        public int DepartmentID { getset; }
        public virtual Department Department { getset; }
    }

The DepartmentMap.cs file is a configuration file for the Department entity type in the model.It uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

 

public class DepartmentMap : EntityTypeConfiguration<Department>
    {
        public DepartmentMap()
        {
            // Primary Key
            this.HasKey(t => t.DepartmentID);
 
            // Properties
            this.Property(t => t.DepartmentID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
 
            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(50);
 
            // Table & Column Mappings
        this.ToTable("Department");
        this.Property(t => t.DepartmentID).HasColumnName("DepartmentID");
        this.Property(t => t.Name).HasColumnName("Name");
        this.Property(t => t.Budget).HasColumnName("Budget");
        this.Property(t => t.StartDate).HasColumnName("StartDate");
        this.Property(t => t.Administrator).HasColumnName("Administrator");
        }
    }

The CourseMap.cs file is a configuration file for the Course entity type in the model. It uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

 

public class CourseMap : EntityTypeConfiguration<Course>
    {
        public CourseMap()
        {
            // Primary Key
            this.HasKey(t => t.CourseID);
 
            // Properties
            this.Property(t => t.CourseID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
 
            this.Property(t => t.Title)
                .IsRequired()
                .HasMaxLength(100);
 
            // Table & Column Mappings
          this.ToTable("Course");
          this.Property(t => t.CourseID).HasColumnName("CourseID");
          this.Property(t => t.Title).HasColumnName("Title");
          this.Property(t => t.Credits).HasColumnName("Credits");
          this.Property(t => t.DepartmentID).HasColumnName("DepartmentID");
 
            // Relationships
            this.HasRequired(t => t.Department)
                .WithMany(t => t.Courses)
                .HasForeignKey(d => d.DepartmentID);
 
        }
    }

 

8) Finally we need to create the .edmx file. Select the schoolContext.cs file in the Solution Explorer then right-click, select Entity Framework ->View Entity Data Model (Read-only)

Have a look at the picture below.


 

9) Then the entity data model is created.This is read-only model. You cannot work with your model (.edmx) and POCO classes at the same time.This is just for visualisation purposes

Have a look at the picture below

 

if you want to have the XML representation of the .edmx file you can select the View Entity Data Model XML.Select Entity Framework ->View Entity Data Model XML.

If you want to displays the DDL SQL statements that corresponds to the SSDL in the underlying Entity Data Model select Entity Framework ->View Entity Data Model DDL SQL

In my case I see the following T-SQL statements that create my DB structure.


create table [dbo].[Course] (
    [CourseID] [int] not null,
    [Title] [nvarchar](100) not null,
    [Credits] [int] not null,
    [DepartmentID] [int] not null,
    primary key ([CourseID])
);
create table [dbo].[Department] (
    [DepartmentID] [int] not null,
    [Name] [nvarchar](50) not null,
    [Budget] [decimal](18, 2) not null,
    [StartDate] [datetime] not null,
    [Administrator] [int] null,
    primary key ([DepartmentID])
);
alter table [dbo].[Course] add constraint [Course_Department] foreign key 
([DepartmentID]) references [dbo].[Department]([DepartmentID])
 on delete cascade;

Hope it helps!!!

Looking into Entity Framework Code First targeting an existing database

 In this blog post I will try to explain with a hand-on demo how we can use Entity Framework Code first with an existing database. I will create the database and then I will use an ASP.Net MVC 4.0 application to demonstrate how to map Code First EF Workflow to the database.

Before we start I will give again a short introduction to Entity Framework. The stable version of Entity Framework as we speak is EF 5.0.It is available through Nuget and it is an open source project.

The .Net framework provides support for Object Relational Mapping through EF. So EF is a an ORM tool and it is now the main data access technology that microsoft works on. I use it quite extensively in my projects. Through EF we have many things out of the box provided for us. We have the automatic generation of SQL code.It maps relational data to strongly types objects.All the changes made to the objects in the memory are persisted in a transactional way back to the data store. 

You can search in my blog, because I have posted many posts regarding ASP.Net and EF. 


There are different approaches (paradigms) available using the Entity Framework, namely Database First, Code First, Model First. 

You can find in this post an example on how to use the Entity Framework to retrieve data from an SQL Server Database using the "Database/Schema First" approach.

In this approach we make all the changes at the database level and then we update the model with those changes. 

In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework.

This model was firstly introduced in EF version 4.0 and we could start with a blank model and then create a database from that model.When we made changes to the model , we could recreate the database from the new model. 

The Code First approach is the more code-centric than the other two. Basically we write POCO classes and then we persist to a database using something called DBContext.

In this application we will us the Code First approach when building our data-centric application with EF. 

Code First relies on DbContext. We create classes with properties and then these classes interact with the DbContext class.Then we can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests.

DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First).

 

I am running VS Studio 2012 Ultimate edition but you can use Visual Studio Express 2012 for Web. You can install Visual Studio Express 2012 for Web if you download Web Platform Installer.You can download this tool from this link.

1)  I am launching VS 2012 and I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application from the available templates.I will name my application CodeFirstExistingDatabase

2) Normally with Code First we create new classes and then EF knows how tο create the database from those classes. In this application we will do the reverse.

3) Before I create the database I need to download and install Entity Framework Power Tools Beta 3. Go to Tools -> Extensions and updates and search for Entity Framework Power Tools Beta 3 and then install it. Have a look at the picture below. I have already installed it.In you case it will say Install.

 

The good news is that Entity Framework Power Tools will be included in EF 6.0.

4) I have already created a sample database. It is called School. It has two tables with data, Course and Department. There is one to many relationship between Department and Course. A Department has many Course(s). This is the script ( SchoolDB.zip) that will install the database with the data in your SQL Server instance.Make sure you have the database installed.

5) Right-click on your project, then select Entity Framework -> Reverse Engineer Code First.Have a look at the picture below


6) In the next step we will be prompted to connect to the database. Connect to the SQL Server instance and the connect to the DB and hit OK.Have a look at the picture below

 

7) Now the Power Tools of EF have created the necessary classes. Have a look under the Models,Mapping folder to see the generated files.

Have a look at the picture below

 

Open web.config. EF has added a connection string to the database

<add name="schoolContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=school;
         Integrated Security=True;MultipleActiveResultSets=True"
      providerName="System.Data.SqlClient" />

The schoolContext.cs file has been created. There is a class in there schoolContext. It has the same name as the name in the name property of the connection string above (name=schoolContext).The schoolContext class derives from the DbContext. DbContext is a base class in EF and it is responsible for change tracking,persisting data back to the database and in general managing the entity objects during runtime. DbSet properties are also exposed and those properties represent collections of the specified entities in the context.

 public schoolContext()
            : base("Name=schoolContext")

Those two lines of code above tell EF that the connection information for this context should be loaded from web.config.

There Department.cs and Course.cs are also included.These are the POCO classes i was talking earlier. These two classes are very simple classes and have no dependency from EF. The Department class follows.

public partial class Department
    {
        public Department()
        {
            this.Courses = new List<Course>();
        }
 
        public int DepartmentID { getset; }
        public string Name { getset; }
        public decimal Budget { getset; }
        public System.DateTime StartDate { getset; }
        public Nullable<int> Administrator { getset; }
        public virtual ICollection<Course> Courses { getset; }
    }

You can see the properties that map to the columns of the Department table in the database. The Courses property is a navigation property. A Department entity can related to any number of Courses entities.Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading.

The Course.cs file follows

 public partial class Course
    {
        public int CourseID { getset; }
        public string Title { getset; }
        public int Credits { getset; }
        public int DepartmentID { getset; }
        public virtual Department Department { getset; }
    }

The DepartmentMap.cs file is a configuration file for the Department entity type in the model.It uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

 

public class DepartmentMap : EntityTypeConfiguration<Department>
    {
        public DepartmentMap()
        {
            // Primary Key
            this.HasKey(t => t.DepartmentID);
 
            // Properties
            this.Property(t => t.DepartmentID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
 
            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(50);
 
            // Table & Column Mappings
        this.ToTable("Department");
        this.Property(t => t.DepartmentID).HasColumnName("DepartmentID");
        this.Property(t => t.Name).HasColumnName("Name");
        this.Property(t => t.Budget).HasColumnName("Budget");
        this.Property(t => t.StartDate).HasColumnName("StartDate");
        this.Property(t => t.Administrator).HasColumnName("Administrator");
        }
    }

The CourseMap.cs file is a configuration file for the Course entity type in the model. It uses Fluent API to configure the type.It defines the table the entity maps to. It defines-matches the columns of the table with the entity properties. Also defines any relationships and things like Primary key e.t.c. Its contents follow.

 

public class CourseMap : EntityTypeConfiguration<Course>
    {
        public CourseMap()
        {
            // Primary Key
            this.HasKey(t => t.CourseID);
 
            // Properties
            this.Property(t => t.CourseID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
 
            this.Property(t => t.Title)
                .IsRequired()
                .HasMaxLength(100);
 
            // Table & Column Mappings
          this.ToTable("Course");
          this.Property(t => t.CourseID).HasColumnName("CourseID");
          this.Property(t => t.Title).HasColumnName("Title");
          this.Property(t => t.Credits).HasColumnName("Credits");
          this.Property(t => t.DepartmentID).HasColumnName("DepartmentID");
 
            // Relationships
            this.HasRequired(t => t.Department)
                .WithMany(t => t.Courses)
                .HasForeignKey(d => d.DepartmentID);
 
        }
    }

 

8) Now we are ready to query our model and retrieve some data back from the database. We will use the magic of scaffolding to help us out.

We will create a Course controller.Right-click the Controllers folder in Solution Explorer, select Add, and then click Controller. In the Add Controller dialog box, make the following selections and then click Add:


Controller name: CourseController.

Template: MVC controller with read/write actions and views, using Entity Framework

Model class: Course (CodeFirstExistingDatabase.Models)

Data context class: SchoolContext (CodeFirstExistingDatabase.Models)

Views: Razor (CSHTML). (The default.) Then click Add.

Have a look at the picture below

 

The Course controller has been created. Have a look under the Controllers folder.

A part of the Course controller class follows

private schoolContext db = new schoolContext();
 
        //
        // GET: /Course/
 
        public ActionResult Index()
        {
            var courses = db.Courses.Include(c => c.Department);
            return View(courses.ToList());
        }

A class variable has been created that instantiates a database context object.

The Index action method gets a list of Courses along with the related departments using the Include method. This is an example of eager loading. That basically means that when Course entity data is read , related data is retrieved along with it in the first attempt.

I am not going to write anything else on this method.

Under the Views folder a Course folder has been created with the Index.cshtml,Create.cshtml,Delete.cshtml,Edit.cshtml,Details.cshtml views.

Now we are ready to retrieve data from the database through our model. I am going to make a small change to _Layout.cshtml file in the menu id so i can click to see the Courses.

  <ul id="menu">
                 <li>@Html.ActionLink("Home""Index""Home")</li>
                 <li>@Html.ActionLink("About""About""Home")</li>
                 <li>@Html.ActionLink("Contact""Contact""Home")</li>
                 <li>@Html.ActionLink("Courses""Index""Course")</li>
  </ul>

I just added

  <li>@Html.ActionLink("Courses""Index""Course")</li>

9) Build and run your application. Then click Courses from the menu.Title and credits data appear for each Course along with the related Department name.

Have a look at the picture below.

 

Hope it helps!!!

Creating tooltips using JQuery

I have been using JQuery for a couple of years now and it has helped me to solve many problems on the client side of web development.

You can find all my posts about JQuery in this link. In this post I will be providing you with a hands-on example on how to create a stylish tooltip using JQuery.

In this hands-on example I will be using Expression Web 4.0.This application is not a free application. You can use any HTML editor you like.You can use Visual Studio 2012 Express edition. You can download it here. 

We need to download the latest version of JQuery. You can download it here.

We will need some markup first.This is the sample HTML 5 page

Type or (copy paste) the markup in your favorite HTML editor (VS, Expression Web,Notepad++)

 

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Liverpool Legends</title>
    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
     <script type="text/javascript" src="tooltip.js"></script>

       
</head>

  <body>
    <header>
   
   
        <h1>Liverpool Legends</h1>

    </header>
   
    <div id="main">
   
 
     <a class="liverpool" href="http://en.wikipedia.org/wiki/John_Barnes_%28footballer%29" target="_blank" Tooltip="One of the greatest midfielders to wear the Liverpool shirt">John Barnes</a>
<br/>
<a class="liverpool" href="http://en.wikipedia.org/wiki/Kenny_Dalglish" target="_blank" Tooltip="The greatest ever player that has played for Liverpool">Kenny Dalglish</a>
<br/>
<a class="liverpool" href="http://en.wikipedia.org/wiki/Steven_Gerrard" target="_blank" Tooltip="A liverpool legend and the captain of the team">Steven Gerrard</a>
     
    </div>
   
   
    <footer>
   
    <p>All Rights Reserved</p>
 
    </footer>

  
  </body>
 
</html>

I have some links in this simple html page. When I hover over the links I want the the contents of the Tooltip attribute to appear on the right of the links as a tooltip. When I mouse out of the links then the tooltip contents should disappear.

I am including a link to the JQuery library in the head section of the HTML markup.

I will also include the external .css stylesheet file with the various styles for the HTML elements in the head section.

You must create another file first e.g mystyle.css and copy-paste in it the code below

body
{
background-color:#efefef;

}

header

{

font-family:Tahoma;
font-size:1.3em;
color:#505050;
text-align:center;
}

a:link {color:#64000; text-decoration:none;}   

a:hover {color:#FF704D; text-decoration:none;}  


.tooltip {
    display: none;
    font-size: 12pt;
    position: absolute;
    border: 2px solid #000000;
    background-color: #b13c3c;
    padding: 12px 16px;
    color: #fff347;
}
   
    footer
{
background-color:#999;
width:100%;
text-align:center;
font-size:1.1em;
color:#002233;
}
 

Have a look at the class tooltip above.

I have also included a link to the external .js javascript script (tooltip.js) file with the various styles for the HTML elements in the head section.

Type (copy-paste the following) javascript code in the tooltip.js

$(function() {
    $('.liverpool').hover(function(event) {
        var toolTipcontents = $(this).attr('Tooltip');
        $('<p class="tooltip"></p>').text(toolTipcontents)
            .appendTo('#main')
            .css('top', (event.pageY - 40) + 'px')
            .css('left', (event.pageX + 60) + 'px')
            .fadeIn(4000);
    }, function() {
        $('.tooltip').remove();

    }).mousemove(function(event) {
        $('.tooltip')
        .css('top', (event.pageY - 40) + 'px')
        .css('left', (event.pageX + 60) + 'px');
    });
   
     });


Let me explain what I am doing with the code above.

  • First I make sure that DOM has loaded before I do anything else.
  • Then in the hover over event, I store in the variable toolTipcontents the contents of the Tooltip attribute.Have a look here for the attr() function.
  • Then I create a p tag dynamically and assign the contents of the toolTipcontents variable to it.Have a look here for the text() function.
  • Then I simply append this p tag to the main div of the page and then set the position (top,left) that the tooltip will appear.Have a look here for the appendTo() function. Also have a look here for the css() function.
  • Then I use an effect to make the tooltip contents appear with a simple fading. .Have a look here for the fadeIn() function.
  • Then in the hover out event I simply remove the p tag.Have a look here for the remove() function.
  • Finally because I want the tooltip contents to move along as the mouse moves I add some code to the mousemove() event. Have a look here for the mousemove() event.


Make sure you view your page in you browser of preference.

Have a look at the picture below to see what I see when I view this page on the browser and hover over a link.

 

Hope it helps !!!

Looking into the various ways that content can be shared in a DotNetNuke site

In this post I will demonstrate with a hands-on example the various ways content can be shared across many pages in a DotNetNuke site.

I will continue writing posts about DotNetNuke because it is my favourite CMS,based on ASP.Net and I use it a lot. 

I have installed DNN 7.0 in a web server. You can see the default installation and site -http://dnn7.nopservices.com/

Bear in mind that this is the community edition of DotNetNuke

1) I am logging into my site as a host - power user.

2) I am going to add a Text/HTML module to the Home.aspx page.

3) I am navigating to Modules -> Add New Module. From the available modules I choose HTML module.This is the most commonly used module in DNN sites. We can add content, images, flash files into this module.

4) I am adding this module to the ContentPane of the Home page

Have a look at the picture below

 

5) Now, that I have the module in my pane, I must add some content to it.I just click on the Edit Content

Have a look at the picture below

 

6) I add some sample content (inside the HTML editor) on the page and click Save.My content has been added.

Have a look at the picture below

 

7) Now what if I wanted to share the contents of the the Text/HTML module across other pages of the site?

I navigate to the http://dnn7.nopservices.com/AboutUs.aspx page,then Modules -> Add Existing module. Then I select the Home page, the Text/HTML module I added in the Home page (I have titled it DNN) and then I add it in the new page (AboutUs) in the ContentPane

Have a look at the picture below

 

8) The module and its contents are inserted in the AboutUs page. Have a look at the picture below

 

 9) Now if I go back to the Home page and I add some more content.Have a look at the picture below

I have added "The main site where you can download everything is http://www.dotnetnuke.com". If you navigate to the AboutUs page you will see that those changes were reflected to that page as well.

10) But what if I did not want this to happen? I mean what if we wanted to copy a module across one or more pages but didn't want to have the content changes of one module reflected to the others in the other pages.

First I am going to delete the Text/HTML module (titled DNN) from the AboutUs page.

Have a look at the picture below

 

11) Now I am going to add the Text/HTML module (titled DNN) from the Home page to the AboutUs page again.I navigate to the http://dnn7.nopservices.com/AboutUs.aspx page,then Modules -> Add Existing module. Then I select the Home page, the Text/HTML module I added in the Home page (I have titled it DNN) and then I add it in the new page (AboutUs) in the ContentPane.Please note that I have checked the option Make a Copy

Have a look at the picture below

 

The Text/HTML module is added to this page as well. Now if I navigate to the Home page and add another line of content in the Text/HTML module e.g

You can download the latest version of DotNetnuke and very useful manuals.

and then move back to the AboutUs page, we will see that this new change did not reflect on the AboutUs page.

12) Finally I would like to show you another way to share content across multiple pages in a DNN site.

I am adding a new module to the Home page.  I am navigating to Modules -> Add New Module from the control panel. From the available modules I choose HTML module.I add some sample content to this module. You can add anything you like. I have titled this module DNN RoadMap by going to the module Settings.

Have a look at the picture below

 

Then I add the module title and in Advanced Settings, I check the option Display Module on All Pages. By doing that this module will appear in the same position in all pages of the site.

I have the option to add this module only to the pages ( Add to new pages only? ) that will be created in the future (new pages) but I will not do that right now.

Then I hit the Update button. This module will be added to all pages.

Have a look at the picture below.

 

Please note that by using this setting we have the following behavior

  •  If you change the contents of the module titled DNN RoadMap that was added to all pages, those changes will be reflected across the site.
  •  If you delete the module from one page, that does not mean that all modules from all the pages will be deleted. 
  •  If you go to any page that the module DNN RoadMap was added and then go to Settings and then uncheck the option Display Module On All Pages , then this module will disappear from all the pages except the current one.

Hope it helps!!!

Removing DotNetNuke copyright message from a DNN site

I have been using ASP.Net extensively to build web applications based on the .Net Framework. In this blog I have been demonstrating with hands-on examples how to use ASP.Net Web Forms and ASP.Net MVC to implement functionality commonly found on ASP.Net web sites.

I have also used DotNetNuke - DNN (the Open Source Web Application Framework of my choice) to build websites.I am also the co-admin of the greek DotNetNuke community and I decided that I will use this space to write a series of posts regarding DotNetNuke. I have decided to keep those posts short. I will provide tips and tricks and answers to questions I often get when I teach about DotNetNuke in open seminars.

I would like to introduce DotNetNuke to you before I move on.DotNetNuke is an Open Source Web Application Framework that is based on ASP.Net.


It is ideal for creating and deploying projects such as:

  • Commercial Web Sites
  • Corporate Intranets and Extranets
  • Online Publishing Portals
  • Other Web Applications

There are 3 DNN editions.DotNetNuke Professional edition,DotNetNuke Enterprise edition and DotNetNuke Community edition. Have a look at a comparison of the various editions here.

I will be using the community edition in all my posts.

In this short post I will show you how to remove the DotNetNuke copyright message from the View source (View -> Page Source) of your DNN site.

Before I move on I must have a working installation of DNN.

I have installed DNN 7.0 in a web server. You can see the default installation and site - http://dnn7.nopservices.com/

In another post of mine I will demonstrate how to install DotNetNuke 7.0 in your machine or a live web server.

Let's move on with our actual example.

When I view my website - http://dnn7.nopservices.com/ on the browser and right-click on the page (View --> Page Source) I see the following message.

Have a look at the picture below


 

One question I often get is how to remove that copyright message and the keywords (which certainly will be irrelevant with the keywords we want to add for our specific site)

We login as superuser to our DNN site and then choose Host->Host Settings

Have a look at the picture below

 

Then I choose Basic Settings, then Appearance.

There is a setting - Show Copyright Credits? - which is checked. We must uncheck this option and click Update.

Have a look at the picture below

 

When I view my website again and then right-click on the page (View --> Page Source) , I do not see either the DNN copyright message or the keywords which were specific to DNN.

Have a look at the picture below

 

Please note that you can follow these steps for your DNN 6.0 website.

Hope it helps

More Posts Next page »