Using Ninject for dependency injection

Possibly save 4 hours of your time: If you follow best practice, you may already know about dependency injection. It has many benefits but I won’t talk about it here. You can wikipedia it. I often build ASP.NET MVC and WebAPI applications and in the controller you may create different helper or service class to get your model. Instead of new ‘ing a class, you can create your controller constructor to take in those helper or service class as parameters. Then you can access it directly to retrieve your model. A big benefit is the ability to write unit tests for your controller layer only and mock the helper or service class.

In the example below the controller gets injected an instance of yourService at runtime by Ninject. There are different scopes. By default, it is in Transient scope and it means a new instance is always created. You can read more on different type of scopes here.

Example of api controller:


namespace YourProject.Web.Controllers
{
 [RoutePrefix("api")]
 public class SomeNameController : ApiController
 {
 private readonly IYourService yourService;
 public SomeNameController(IYourService yourService)
 {
 this.yourService = yourService;
 }

 [Route("getproduct/{productId}")]
 [HttpGet]
 public SomeViewModel Get(string productId)
 {
 try
 {
 var model = new SomeViewModel();
 model.Values = yourService.GetValues();
 return model;
 }
 catch (Exception ex)
 {

throw new HttpException(500, ex.Message);
 }
 }
 }

}

I will now talk about how to set up Ninject. Open your web solution. I installed the following from Visual Studio >> Tools >> NuGet Package Manager >> Manage NuGet Packages for solution:

  • Ninject (3.3.3)
  • Ninject.MVC5 (3.3.0)
  • Ninject.Web.Common (3.3.0)
  • Ninject.Web.WebApi (3.3.0)
  • WebActivatorEx (2.2.0)

 

Second, you need to add this static class for NinjectWebCommon.cs.


using System;
using Ninject;
using Ninject.Web.WebApi;
using Ninject.Web.Common;
using System.Web.Http;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourProjectName.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourProjectName.Web.App_Start.NinjectWebCommon), "Stop")]

namespace YourProjectName.Web.App_Start
{
 public static class NinjectWebCommon
 {
 private static readonly Bootstrapper bootstrapper = new Bootstrapper();

/// <summary>
/// Starts the application
/// </summary>
 public static void Start()
 {
 bootstrapper.Initialize(CreateKernel);
 }

/// <summary>
/// Stops the application.
/// </summary>
 public static void Stop()
 {
 bootstrapper.ShutDown();
 }

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
 private static IKernel CreateKernel()
 {
 var kernel = new StandardKernel();
 try
 {
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);

RegisterServices(kernel);

// Install our Ninject-based IDependencyResolver into the Web API config
 GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

return kernel;
 }
 catch
 {
 kernel.Dispose();
 throw;
 }
 }

 /// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
 private static void RegisterServices(IKernel kernel)
 {
kernel.Bind<IYourService>().To<YourService>();
 }
 }
}

When running the app I got the following error. This means your Ninject is not setup properly.

Error: 

An error occurred when trying to create a controller of type YourTypeName. Make sure that the controller has a parameterless public constructor.

Type ‘YourTypeName’ does not have a default constructor

Mastering Ninject for Dependency Injection

Advertisements

System.InvalidOperationException : Unable to determine composite primary key ordering for type Name. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys

Possibly save 1 hour of your time: You may encounter this error if you have multiple keys but didn’t define the column order.


[Table("your_table_name")]
public partial class YourEntityName
{
[Key]
[Column(Order = 1)]
public int Year { get; set; }

[Key]
[Column(Order = 2)]
[StringLength(3)]
public string CountryCode { get; set; }

public double Value { get; set; }
}

 

Setup Entity Framework v6.x

Possibly save 4 hours of your time: This is a brief introduction of setting your project to use Entity Framework v6.

  • Install Entity Framework
  • Create DbContext derived class
  • Create Entity model
  • Add connectionString to configuration
  • Write functional test

Install Entity Framework

In Visual Studio, make sure your project solution is open. Now go to Tools >> NuGet Package Manager >> Manage NuGet Packages for solution…

Select Browse >> then search for EntityFramework. The latest version is v6.2.0 at this time of writing for .NET Framework 4.5.2.

Then check the checkbox for the projects in your solution you want to install. Then click Install.

Once installed, you should see the following references:

  • EntityFramework
  • EntityFramework.SqlServer
  • System.ComponentModel.DataAnnotations

Create DbContext derived class

Next, you need to create a class that inherits from System.Data.Entity.DbContext.

Then create a constructor with the name of the connection string used in the configuration later.

Next you will need to create a property which is a System.Data.Entity.DbSet<entity model> that represents your database table. DbSet is like a collection of the entity models.


public class SomeNameContext : DbContext
 {
  public SomeNameContext() : base("name=SomeNameContext")
  {
  }

  public virtual DbSet<YourEntityName> YourEntitiesName { get; set; }
 }

Create Entity model

You will then create the partial class for the entity model. The model will need a Table attribute with the name of the table as argument.

When you create the properties, you can specify other property attributes such as:

  • Key – represents primary key
  • Column(Order = 1) – must specify column order if multiple keys exist
  • StringLength(30) – limit to 30 characters

[Table("your_db_table_name")]
 public partial class YourEntityName
 {
  [Key]
  [Column(Order = 1)]
  public int Year { get; set; }

  [Key]
  [Column(Order = 2)]
  [StringLength(3)]
  public string CountryCode { get; set; }

  public double Value { get; set; }
 }

Add connectionString to configuration

In the project web or application configuration (web.config or app.config) file add the connectionStrings section if it is not already there and add an element for your connection string.

<connectionStrings>
<add name="SomeNameContext" connectionString="data source=localhost;initial catalog=YourDatabaseName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<connectionStrings/>

Write functional test

Using NUnit.Framework, we can test with the following:


[TestFixture]
public class AlbertaExportValueTests
{
[Test]
public void Test()
{
using (var context = new ExportToolContext())
{
var albertaExports = context.AlbertaExportValues.ToList();
Assert.That(albertaExports.Count, Is.EqualTo(260702));
}
}
}

Reference:

https://msdn.microsoft.com/en-us/data/jj591583

Programming Entity Framework: Code First: Creating and Configuring Data Models from Your Classes

Understanding Umbraco concepts and tutorials

Possibly save 1 hour of your time: After installation of Umbraco, you may now want to implement your own web pages. After you run the app, you can type in /umbraco on the url to go to backoffice (administrator area).

You will need to understand the concept of:

  • Document Type (Structure of content)
  • Template and output Document Type properties
  • Content Node (Content Page)

Other related concepts:

  • CSS and JavaScript
  • Master Page
  • Property Editor

Document Type (Structure of content)

You may need to create a Document Type under Settings. This allows you to define the structure of the content.

create document type.png

You also need to got to Permissions and check Allow as root. This will allow you to select this document type when creating the content node later.

Reference: https://our.umbraco.org/documentation/tutorials/creating-basic-site/document-types

Template and output Document Type properties

The template is automatically generated if you create the document type with template. The template contains Razor code. It creates a .cshtml file under folder Views in the project. The template is basically the view.

create template

Reference: https://our.umbraco.org/documentation/tutorials/creating-basic-site/Creating-Your-First-Template-and-Content-Node

If you want to display something here, you will need to code this or use the feature in the backoffice. It does not automatically create the view elements. For example I know in the document type there is an element named MichaelTopContent. Then in the template, I just add the binding using Razor syntax. i.e. @Model.Content.MichaelTopContent

Reference: https://our.umbraco.org/documentation/tutorials/creating-basic-site/Outputting-the-Document-Type-Properties

Content Node (Content Page)

You can create your own page under Content section. If you want to create a page under Home using the document type create earlier. You need to add permissions for the new document type under the Home document type. Go to Settings >> Document Types >> Home and then Permissions on the upper corner. Under Allowed child node types >> Add child, then select your document type.

Now you will click on Home and create an item under Home by selecting the new document type.

create content node with custom document type.png

CSS and Javascript

There are two project folders where you can put your css and js files namely css and scripts folder. You then can reference those files in your template. i.e.

<link rel="stylesheet" href="css/style.css">

http://scripts/libs/modernizr-2.0.6.min.js

Reference: https://our.umbraco.org/documentation/tutorials/creating-basic-site/CSS-And-Javascript

Master Page

This is same concept as in ASP.NET master pages.

Reference: https://our.umbraco.org/documentation/tutorials/creating-basic-site/Creating-Master-Template-Part-1

Property Editor

You can create your own custom property editor.

Reference: https://our.umbraco.org/documentation/Tutorials/Creating-a-Property-Editor/

Umbraco Users Guide

Install Umbraco Content Management System (CMS)

Possibly save 1 hour of your time: I am trying to use Umbraco CMS, an open source content management system.

I download and install WebMatrix3.

Then I download the latest package for Umbraco and unzip.

Next I right click on folder and choose open as a website with Microsoft WebMatrix

open with webmatrix.png

Then you click Run in the WebMatrix.

run.png

It will bring you to back office (admin area) for Umbraco. You can also install Umbraco Forms by going to the left menu items and click on Forms and then install button. After you install, you still need to buy a license to use it.

back office forms

Umbraco User’s Guide

Install Apache Cordova Update 10

Possibly save 1 hour of your time: I am about to start on a new project that requires website and native mobile application development. After researching between Xamarin and Apache Cordova, I have decided to leverage using html/javascript/css skills with Apache Cordova to build the mobile apps. Of course, you can leverage C# with Xamarin. However I feel that we can leverage javascript for front end development and probably C# for back end API calls.

I am using the following reference if you want to follow:

https://docs.microsoft.com/en-us/visualstudio/cross-platform/tools-for-cordova/first-steps/build-your-first-app

If you haven’t use Apache Cordova before, you will have to install it.

  • Open Visual Studio (mine is Professional 2015)
  • File -> New Project
  • Installed -> Templates -> Javascript or Typescript (I chose Typescript)
  • Then you will see a template for Install Apache Cordova Update 10
  • Double click on it to start the installation
  • Note that it will take 14 GB. The picture below does not show all the required installations, but it does install quite a bit of stuff.
  • Note that it also takes over an hour for me. Prior to install, it will ask you to close all Visual Studio instances.

install Apache Cordova Update 10

After installation, I got the following messages:

after apache cordova installation

This is part of a series of blogs I will be writing as I experience in this journey learning to use Apache Cordova.

  1. Part 1 – Install Apache Cordova Update 10

Apache Cordova in Action

Truncate local SQL Server database log file to save disk space

Possibly save 1 hour of your time: I notice my machine disk space is running low. So where can I save some space? Database log is usually a big one.

First, download a free program call WindirStat. This program will tell you in a very nice visual way of where most of your space are taken up.

So I found out from my machine there are two database log files in which both took up over 50 GB.

Solution: I backup the database first. Then I ran the following command on the specific database in SQL Server Management Studio 2012.

select * from sys.database_files --find the name of the log file

ALTER DATABASE your_database_name SET RECOVERY SIMPLE
DBCC SHRINKFILE('name_of_log', 0, TRUNCATEONLY)
ALTER DATABASE your_database_name SET RECOVERY FULL

Murach’s SQL Server 2016 for Developers