AngularJS – CRUD Data Grid I

The goal of this post is to write a single page application (SPA) to display a list of items inside a grid. This grid shall not only display a list of items but also allows all the CRUD operations: Create a new item and Read, Update and Delete for the contained items.

Additional requirements:

  • Show a notification when a server request success or fail.
  • Editing an item: Start editing with a double click and commit the edition with “Enter”.
  • Everything shall be executed without refreshing the web page
  • The complete list of items should only be requested one when the page is loaded.

UPDATE:

Results

Code is available on github: https://github.com/softwarejc/angularjs-crudgrid. Feel free to play with it, find errors and write improvements. You can see a live demo here: AngularJS CRUD Grid III demo.

This is a screenshot of the AngularJS Crud Grid that we are going to implement:

AngularJS Crud Grid

Implementation

Let’s get our hands dirty, we will cover the following points:

  1. Domain: Entity Framework + Domain Services
  2. Server side: WebAPI + ViewModels
  3. Client side: AngularJS + Bootstrap + Toastr
  4. What’s next?

Continue reading

ASP MVC – Template Overview

When a new MVC Web Application is created in Visual Studio a lot of files are added to the solution. The goal of this post is to provide a small overview of all these files, this overview should make easier to understand the MVC solution structure.

The files described here are the files created by default when you add a web project using the MVC template.

Create a a Web project:

New Web Project

Use the MVC Template:

MVC Template

This is the generated project:

MVC Template Project

ASP MVC Template Overview

Let’s start enumerating some created folders:

  • Content: CSS files with view styles. (Bootstrap)
  • Fonts: Some fonts required by the CSS files.
  • Scripts: JavaScript files. (JQuery)
  • Controllers: C# files with the code that is going to be run at the server side.

Now the rest of files and folders with some more details:

Views

This folder contains *.cshtml files. The Razor engine generates the views of our web application out of these files. Typically we will have a view or a group of views for each controller. This folder also contains a Web.config don’t confuse this one with the Web.config at the root of the solution. Razor engine is configured here.

Continue reading

Entity Framework – Lazy Loading

I want to analyse in this post how Entity Framework really interact with the database. i.e. The queries that are really executed.

In previous post I created a database using Code First. These are two of my entities:

A food representation:

public class Food
{
    /// <summary>
    /// Gets or sets the food identifier.
    /// </summary>
    [Key]
    // NOTE: As the name is className + id, this property is not needed
    public int Id { getset; }
 
    /// <summary>
    /// Gets or sets the food name.
    /// </summary>
    [MaxLength(200)]
    [Index(IsUnique = true)]
    public string Name { getset; }
 
    /// <summary>
    /// Gets or sets the recipes needing this Food
    /// </summary>
    // NOTE: EF needs the virtual attribute to enable Lazy loading 
    public virtual List<Recipe> RecpiesNeedingThisFood { getset; }
 
    /// <summary>
    /// Returns a <see cref="System.String" /> that represents this instance.
    /// </summary>
    public override string ToString()
    {
        return string.Format("{0} ({1})"this.Name, this.Id);
    }
}

An entry on my fridge representation: a food and an expire date of this food.

public class FridgeEntry
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FridgeEntry"/> class.
    /// </summary>
    public FridgeEntry()
    {
        ExpireDate = DateTime.MaxValue;
    }
 
    public int Id { getset; }
 
    [Required]
    // NOTE virtual is needed for lazy loading
    public virtual Food Food { getset; }
 
    /// <summary>
    /// Gets or sets the expire date.
    /// </summary>
    public DateTime ExpireDate { getset; }
 
 
    /// <summary>
    /// Returns a <see cref="System.String" /> that represents this instance.
    /// </summary>
    public override string ToString()
    {
        return string.Format("FoodId ({0}) - expire date: {1}"this.Id, this.ExpireDate);
    }
}

How to debug the queries and connections between EF and my database?

A new feature of EF6 is the possibility to log everything that Entity Framework is doing.

The context.Database has a Log property which is type Action<string> if this action is not null EF will call it always he connect to the database.

Define a logger, to analyse the Lazy loading a simple method writing in console the messages is enough:

private static void ConsoleLogger(string msg)
{
    msg = msg.Trim();
 
    if (!string.IsNullOrEmpty(msg))
    {
        Console.ForegroundColor = ConsoleColor.DarkGray;
        Console.WriteLine(DateTime.Now.TimeOfDay.ToString("g"));
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine(msg);
 
        Console.ResetColor();
    }
}

Now we just have to define this  logger as the logger of the context.Database.

EF Lazy loading testing

We have already a way to see the connections between EF and the database, now let’s analyse it:

Continue reading

Entity Framework – Local and Azure connection

In previous posts I used EF using the local database and using the Azure SQL Server. This is the configuration I use now to connect to my local database in Debug mode and to my Windows Azure database in Release Mode.

App.config

  <connectionStrings>
    <!--Azure MyFood database-->
    <add 
        name="MyFoodAzure"
        providerName="System.Data.SqlClient"
        connectionString="Data Source=i608rt1tak.database.windows.net;Initial Catalog=MyFood;Integrated Security=False;User ID=ravened;Password=pass¿;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False" />
    
    <!--Local MyFood database-->
    <add 
        name="MyFoodLocal"
        providerName="System.Data.SqlClient"
        connectionString="Server=(localdb)\v11.0;Integrated Security=true;Database=MyFood;"/>
  </connectionStrings>

DbContext

    public class FoodContext : DbContext
    {
 
        // NOTE: Call base constructor to specify the connection string name
#if !DEBUG
        // In Release mode it will look for the Cloud connection string
        public FoodContext() : base("name=MyFoodAzure") { }
#else
        // In Release mode it will look for the Cloud connection string
        public FoodContext() : base("name=MyFoodLocal") { }
#endif
 
        public DbSet<Food> Foods { getset; }
        public DbSet<Recipe> Recipes { getset; }
        public DbSet<FridgeEntry> Fridge { getset; }
 
    }

Azure SQL Server – Entity Framework Connection

By default when Entity framework is added to a project, a file “App.config” is created if it doesn’t exists yet.
( “Web.config” in web applications).
A default connection factory that will connect to a local database is added in this file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
 
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
  </startup>
 
  <!-- By default, when no connection string is specified use the local database.-->
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
 
</configuration>
  

This factory will be used when no connection string for the specified context is found. But let clarity how EF try to find the connection string to use…

Which connection string will EF use?

To connect to the database we use a context that extend DbContext.

By default if we don’t call a DbContext base constructor, E.F. will look for a connection string name using the name of our defined context.

namespace CodeFirstAzureTest.Data
{
    public class FoodContext : DbContext
    {
        public DbSet<Food> Foods { getset; }
        public DbSet<Recipe> Recipes { getset; }
        public DbSet<FridgeEntry> Fridge { getset; }
 
    }
}

It is possible to specify the name of the connection string or the complete connection string calling the base constructor:

using System.Data.Entity;
using CodeFirstAzureTest.Data.Entities;
 
namespace CodeFirstAzureTest.Data
{
    public class FoodContext : DbContext
    {
        // NOTE: Call base constructor to specify the connection string name
        public FoodContext() : base("name=MyFood") { }
 
        public DbSet<Food> Foods { getset; }
        public DbSet<Recipe> Recipes { getset; }
        public DbSet<FridgeEntry> Fridge { getset; }
 
    }
}

When no connection string is defined, if a defaultConnectionFactory is defined, EF will use it to create a connection string using the name of the connection string he needs.

e.g. If we don’t specify the connection string name in our context and EF cannot find any connection string the factory will create one using exactly this name. This is why by default the database created locally had this name in my previous post.

Connect EF to Windows Azure

To connect to a Windows Azure we need to do the following steps:

Continue reading