Category Archives: Coding

Coding topics related to web app

ASNA Visual RPG – Using The List Class with Generic Types

One of my most favorite classes in the .NET Framework has to be the List Class in the System.Collections.Generic namespace. More specifically, the generic list class as List(T) where T represents a generic type. According to Microsoft Developer Network (MSDN), the list class represents a strongly typed list of objects that can be accessed by index. The List class also provides methods to search, sort, and manipulate lists.

Collections Vs. Arrays

In many applications it is desirable to create and manage groups of related objects. The .NET Framework offers two ways to group objects;

  1. Creating arrays of objects
  2. Creating collections of objects

Arrays are most useful for creating and working with a fixed number of strongly-typed objects.

Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change.

If your collection contains elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. A generic collection enforces type safety so that no other data type can be added to it. When you retrieve an element from a generic collection, you do not have to determine its data type or convert it.

A collection is a class, so you must declare a new collection before you can add elements to it. Here is an example where I created a collection of Guitar objects, and used the add method of the List class, to load the collection with guitar objects;

The List class has great sorting capabilities. The List Class contains a Sort method that is easy to use when the collection contains simple value types like strings or integers. However when the collection of objects are complex types, with multiple properties, sorting by the value of specific properties does get a little more complicated. Here is an example;

I created a class called guitar with multiple properties as follows;

Now, lets say I want to sort a collection of guitar objects by price. With the sort method of the List class I can delegate sorting by price to another class, whose sole purpose is to perform the sort function. I can accomplish this by inheriting from another class in the System.Collections namespace called Comparer and overriding its Compare method.
Here is the class I wrote for this purpose;

Anytime I need to sort a collection of guitars by price, I can simply pass an instance of the SortGuitarsByPrice class, as an argument to the List Sort method. Here is a code snippet;

Here is another example for sorting the collection of guitars by builder and model;

To Array

Converting the generic list of objects to a simple array of objects can be very handy in a number of situations. For example, a generic list of objects can be very powerful in a web service application. However, it may be necessary to convert the generic list to an array, in order to support Java and other types of web service consumers. To accomplish this the List class also contains a ToArray() method. Here’s a code snippet;

In my next post I’ll discuss the search capabilities of the List class. I’ll also cover the object-oriented design concept of delegation with an example that utilizes the FindAll() method of the list class.

Code-First Entity Framework’s Fluent API

By Tim Daniels
This is a follow-up to my post on the Code-First Development Workflow. In that post I described how the Code-First workflow automatically generated an object model and a SQL Server database, by implementing the concept of convention over configuration. With this approach, Code-First assumes that the POCO classes defined in the Entities class library, follow the conventions of the schema that Entity Framework uses for a conceptual model. If this is the case, then Entity Framework is able to work out the details of what needs to be done, to form the object model and the relational database. However, if the conventions established in the POCO classes do not produce the desired result, you still have the ability to add configurations to your classes. As we look more closely at this approach, you will see that sometimes the best solution, is a compromise between two opposing techniques and technologies.

When I defined the domain entities for the Action Manager app, I created a one-to-many relationship between the customer object and the project object. In other words, a customer can have one-to-many projects. Here is the code where this is accomplished.

In the customer class, there is a virtual property called Projects, which is defined as a generic list of Project objects. This is known as a navigation property. The project class also has a navigation property of type customer. In this case, the navigation properties establish the convention that a customer can have one to many projects. With this bit of information, Entity Framework created the Customers table and the Projects table in the SQL Server database as illustrated here;

Fluent API Customers table and Projects table

Fluent API Cutomers table and Projects table

As you can see from the code snippet above, I chose not to clutter up the project class with a property for customer ID. However, this caused Entity Framework to create a foreign key relationship between projects and customers that allows the foreign key to be null. Obviously, this was not my intention.

With the code-first fluent API, I can configure the contextual model to generate the foreign key relationship between project and customer ID as not nullable. Here is the code where this is accomplished.

The DbContext class has an overridable method called OnModelCreating. This is where I can tweak the conventions of the entity classes, with specific configurations, to produce the desired result. In this case, the HasRequired method of the modelBuilder class, configures the Customer property of the Project entity, to be required for input. This configuration causes the foreign key relationship between project and customer ID to be defined as not nullable, as illustrated here.

Fluent API Configuration of Customers table and Projects table

Fluent API Configuration of Customers table and Projects table

Here is an outstanding article by Julie Lerman on Code First Relationships Fluent API. Julie covers this subject in more detail with several different examples of configuration through the fluent API.

Managing Database Connections

By Tim Daniels

Before an application can access information from a database, a proper connection to the server hosting the database, and the database itself, must be established. Managing database connections to optimize application performance, and application maintainability, is relatively easy to accomplish on the Microsoft .NET platform. To demonstrate this, I’ve developed a C#.NET class, which utilizes three key components for managing database connections;

Configuration File

First, lets discuss the configuration file. A configuration file in .NET, is simply an XML file with parent/child nodes. Each node can contain a set of both system defined, and programmer defined, key/value pairs. These key/value pairs contain application settings to control specific application and program level functions. The configuration file can be accessed by program code throughout an application. Many of the project templates in Visual Studio will automatically generate a configuration file for the project. However, a configuration file can be manually added to a project simply by right clicking on the project name in the Solution Explorer, taking the add new item menu option, and then selecting Application Configuration File, as illustrated here;

Adding an application config file

Adding an application configuration file to a project in Visual Studio 2012

This will add an XML file called App.config to the Visual Studio project. There is one subtle difference when adding a configuration file to a website project. The configuration file is called Web Configuration File, and adds an XML file called Web.config to the project, as illustrated here;

Adding a web configuration file

Adding a web configuration file to a website project in Visual Studio 2012

The beauty of the configuration file, is that it’s deployed along with the application. Configuration files can be changed as needed. Developers can use configuration files to change settings without recompiling the application. Administrators can use configuration files to set policies that affect how applications run on their computers.

Here is the application configuration file I created for an application I’m currently developing.

As you can see there are several XML nodes dealing with Entity Framework, which is another component I’m using in this application. For this discussion we are only concerned with the “configuration” node and its child node “connectionStrings”.

Now lets look at an example of using the configuration file to manage database connections in an application. Below is a C# class I wrote called “ConnectionsStrings”. Here is how the class is implemented in an application that access a SQL Server database.

Database Connection Management Solution
The objectives for developing a database connection management solution are as follows;

  • Develop a reusable class with flexibility to retrieve a connection string from the App.config file, or the Web.config file, and return the string to the consumer
  • Implementation of the ConfigurationManager class, to take advantage of having the database connection string coded in one place, the App.config file. Thus, eliminating the need to have it hard-coded throughout the application. This improves overall maintainability
  • Implementation of the SqlConnectionStringBuilder class, to supply additional values to the connection string, such as user name and password

Configuration Manager
The ConnectionStrings class below, has a method called BuildConnectionString. You will notice that the method is also overloaded with a version that will accept the following parameters;

  • dataSource
  • userName
  • userPassword

The BuildConnectionString method implements two classes from the System.Configuration name space.

The ConfigurationManager class has a property called ConnectionStrings. This property gets the connection strings section data from the current application’s default configuration file. It returns a connection string settings collection object. This collection object holds the contents of the connection strings section of the configuration file. Refer back to the configuration file example above to see the contents of the connection strings section. Remember how I described the contents of the configuration file as key/value pairs. In this case, the key is name=”DbConnection”. The value associated with this key is connectionString=”Data Source=.\SQLEXPRESS;Initial Catalog=Lexicon.ActionManager.ProjectManagementContext;Integrated Security=True”.

The following line of code retrieves the value associated with “DbConnection” and assigns it to variable called settings which is a type of ConnectionStringSettings.

Don’t forget to add a reference to the System.Configuration name space in your project and put the using System.Configuration statement at the top of the class.

Connection String Builder
Now lets take a look a the SqlConnectionStringBuilder class. This class comes in handy when additional information needs to be added to the connection string in the configuration file. In cases where it may not be practical to store the connection string in a configuration file, it can be used to build the entire connection string from a set of parameters. The SQLConnectionStringBuilder class has numerous properties for configuring all kinds of settings related to database connectivity. In my ConnectionStings class, I overloaded the BuildConnectionString method to accept data source, user name and password as parameters, that supply additional information for the connection string retrieved from the configuration file.

Final Implementation
In order to make the ConnectionStrings class as reusable as possible, I’m hosting it within a separate class library called “Connections”. This class library is referenced by a console application project I developed for unit testing purposes. This is illustrated in the solution explorer of Visual Studio 2012.

Solution Explorer with Connections class library

Solution Explorer with Connections class library

Finally, here is one implementation of the ConnectionStrings class, where it is used to populate the connection string property of a database instance of a database context class.

Visual Studio 2012 and Web API

By Tim Daniels
Visual Studio 2012 recently became available, so I decided to download the Express for Web edition from the Microsoft Products Store. Here is a snapshot of the new look and feel of Visual Studio 2012. See what else is new in Visual Studio 2012.

Visual Studio 2012

Visual Studio 2012 – New look and Feel

Within Visual Studio 2012, I have discovered a new technology called Web API. According to website, ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. The Web API framework appears to be a subset of the MVC 4 design pattern, which is also included in Visual Studio Express 2012. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup for enjoyable, agile development. ASP.NET MVC includes many features that enable fast, Test Driven Development (TDD) for creating sophisticated applications that use the latest web standards.

As you know from my most recent articles, I’ve been focusing on developing web services based on the Microsoft Windows Communication Foundation (WCF). You may also recall that the web service I developed is based on the REST architectural model. Since the Web API technology is also based on REST, I have decided to add this technology to my repertoire. My objectives are the following;

  • Learn Web API from the online tutorials at the ASP.Net website
  • Develop a prototype web service with Visual Studio 2012
  • Deploy the web service to the could using Microsoft Azure
  • Develop a client app for mobile devices like IPad to consume the web service
  • If all of this works as expected, I will develop a new web service for the World of Art Web App based on Web API

Client Consuming From The Data Access Layer

When I first launched the World Of Art web app, I wrote a post entitled  Improving the Design, where I  expressed concerns over the tight coupling between the user interface and the SQL Server database. In today’s post, I will demonstrate how the user interface can consume data without any regard as to what or where the data source is. This decoupling of the user interface from the data source, is made possible, by separating the entity data model classes, data access classes, and the domain entities classes, into distinct architectural layers of the application.

In the first iteration of the Artist Web Form, I used three ASP.Net user interface server controls;

  • DetailsView
  • GridView
  • SqlDataSource

In the latest iteration of the user interface, I added a new web form called ArtistEntityWebForm, which eliminates the SqlDataSource control for querying the World of Art database. With the first iteration of the artist web form, it wasn’t necessary to write any C# code to retrieve data, or bind data to the user interface controls. The ASP.Net engine on the web server, performed all of these operations automatically, based on the XHTML markup in the web form. By eliminating the SqlDataSource control,  it is now necessary to write some C# code, to retrieve data through the data access layer, and bind it to the views controls. Here is the XHTML markup of the artist entity web form;


Here is the C# code in the code behind file;

At the top of the C# file, you can see that it is referencing the ArtWorldOjects class library. The classes in this library represent the objects found in the world of art domain. The C# file also references the WorldOfArtWebApp.DataAccess name space in the data access layer. There are two methods called in the page load event;

  • LoadArtistView()
  • LoadWorkOfArtView()

Both methods create a new instance of the appropriate class in the Data Access Layer. The constructor of each class calls methods to retrieve data through the data entity model and initialize the appropriate collection of world of art objects. I added a get list method to each class in the data access layer to return a simple array of objects. These get list methods are now the data source for the detail views control and the grid view control. All this client object needs to know, is that it can consume an enumerable list of world of art objects, by instantiating the appropriate class in the data access layer and calling the get list method of that class.

Click Here to render the new artist entity page and see the results of all the code on today’s post.

Data Access Layer – Implementing the Abstract Interface

In this post, I will demonstrate how I implemented the abstract interface called IArtWorldCollections. Below are two code snippets illustrating the implementation;

Following is the C# source code of the IArtWorldCollections interface. The interface has the following components;

  • A read only property, called WorksOfArtContext of type object context. The entity data model is an Object Context Class
  • A read only property, called ArtWorldCollection of type generic list. The Generic List Class Represents a strongly typed list of objects that can be accessed by index. It Provides methods to search, sort, and manipulate lists.
  • A read only property, called ExceptionMessage of type string. This property will store the message text, generated by any exceptions, thrown by any operations, performed in the methods of the class implementing the interface.
  • The final component is a method, called GetArtCollectionData, which accepts no parameters and returns no value. The purpose of this method, is to populate objects in the World Of Art Domain, with data from the World of Art entity data model. Then add each object, to the generic list property, called ArtWorldCollection.

Now lets implement this interface in an actual C# class. Following is the C# source code, for a class I added to the data access layer. The class is called ArtWorldCollectionArtist, and as you can see, it implements the IArtWorldCollection interface, replacing the generic type T, with an object of type Artist, from the World of Art Domain. We replaced the generic object type of T, with the object type of Artist, because the purpose of this implementation is to generate a list of Artist objects, populated with data through the entity data model.

The three properties of the IArtWorldCollection interface are implemented with the following protected members of the class;

  • m_context, of type WorldOfArtContext, from the object context class of the WorldOfArt entity data model
  • m_artistList, of type Generic List, object type of Artist replaces the generic T type
  • m_exceptionMessage, of type string

The constructor method of the ArtWorldCollectionArtist class, initializes the protected members based on their object types. The constructor method also calls the GetArtCollectionData() method. In this method I use the Language-Integrated Query(LINQ) syntax available in C#, to perform a query against the World Of Art data model. We will cover LINQ in more detail in a future post. I employ a ForEach loop, to load the results of the query into the Artist List Collection. Notice how the query is not against a SQL Server databse table, instead the query is against the Artist property of the object context, in the World of Art Data Model. Therefore, I can create a new instance of the Artist object from each Artist in the result set of the query. I can populate the properties of the Artist object, with data from the properties of the Artist class in the data model.

Finally, with the implementation of the IArtWorldCollection interface, we have achieved the separation of concerns we’ve been striving for. Notice how the ArtWorldCollectionArtist class has no concern for the source of the artist data. There is no code for opening and closing a connection to the database server. No need for hard coded SQL commands like “SELECT FirstName, LastName, BirthDay, City, Country, TypeOfArtist FROM aspnet_Artist” which can be severely impacted by changes to the database tables. The coding task is simplified by the entity data model, because now I’m coding against classes and properties, instead of hard coding table and column names. The hard tasks, of connecting to the database and accessing the tables of the database, have been abstracted into the entity data model. Even if the source of data changes from a Microsoft SQL Server database, to an ORACLE database, or even a data service, the ArtWorldCollectionArtist class would not be impacted by any of these changes.

One last comment on implementing a generic interface for data access, through the entity data model. The payoff for using this approach will continue to increase, as we further implement the interface, to access data and populate other elements in the World of Art domain; such as the works of art created by the artist. More on this in my next post.

Separation of Concerns – Data Access Layer

Now that the World of Art database has been abstracted, as an entity data model, we can focus on adding the data access layer to our architecture. This layer will act as an interface to the entity data model. The data access layer will create distance and independence from the data source, for the user interface layer, the business logic layer and the services layer.

The first thing I want to do in the data access layer, is create an abstract interface. The following code snippet illustrates this. As you can see, this is a generic interface. I’m using the System.Collections.Generic class, to declare this as a public interface called IArtWorldCollection, which implements a generic object type signified by “T”. The single purpose of this interface, is to create a generic list or collection of objects, from the World of Art Domain. We will reveal the details on how this is done, when we actually implement this Interface.

The Data Model Layer

As discussed in the last post, we are going to apply a layered architectural structure, to the World of Art web app. The first layer we are going to develop, will be called the Data Model Layer. The purpose of this layer is to achieve a separation of concerns. To create distance and independence, between code supporting the application’s user interface, and code supporting access to the data source.

We will begin by adding an object model to the application. This object model is based on the World Of Art Relational Database, developed in a prior iteration. See Generating Data Model Based on Relational Database, for step by step instructions on generating the data model. As mentioned in previous posts, our data model layer is based on the Microsoft ADO.NET Entity Framework.

Now that the data model is generated, I’m going to display another illustration of the World of Art database diagram, which the data model is bases on. This diagram is more detailed, and shows the properties of each column of the two tables, currently in the database. Also, remember the “one-to-many” relationship between an artist and their works of art. An artist can create one or more works of art. This relationship is illustrated by the key and infinity symbols in the diagram. Please keep this diagram in mind, when we examine the data model diagram, based on this database.

Database Diagram for Data Model

World of Art Database Diagram

The next diagram illustrates the data model, which is based on the World of Art database. I used the Entity Data Model Wizard in Visual Studio 2010, to generate the data model. The data model has two classes, based on the two tables in the World of Art database. The Artist table and the Works of Art table, have been abstracted into two separate classes. The columns of the tables are now represented by the properties of each class. Also, notice how the one-to-many relationship between an artist and their works of art is maintained.

Data Model based on World of Art Database

Data Model based on World of Art database

The Entity Data Model Wizard in Visual Studio 2010, not only generates the entity data model diagram illustrated above, it also generates an entire C# code file, which the diagram is based on. The following image is a class diagram I generated in Visual Studio 2010. It’s based on the WorldOfArt.Designer.cs file which was generated by the Entity Data Model Wizard. As you can see, the wizard actually generated three classes. The one in the middle is the WorldOfArtContext class, it inherits the System.Data.Objects.ObjectContext class. The other two classes are based on the two tables in the World of Art database, and inherit the System.Data.Objects.DataClasses.EntityObject class. Like any typical C# class, they have private members and public properties, along with a wide range of partial methods and event handlers, for updating the tables.

WorldOfArt.Designer.cs Data Model Class Diagram

Class Diagram Based on World of Art Data Model

Finally, lets take a look at the World Of Art solution in Visual Studio, with the newly added Data Model layer. The highlighted folder, in the illustration below, represents the Data Model Layer in the World of Art project solution. The folder contains two files;

  • The WorldOfArt.edmx file, is the data model diagram. It can be viewed and modified, in the Entity Data Model Designer, in Visual Studio.
  • The WorldOfArtDesigner.cs file, is the C# source code of the Entity Data Model.
Data Model Layer in Solution Explorer

Data Model Layer in the World of Art Project Solution

In my next post, I’ll discuss the benefits derived from building a Data Model Architectural Layer, and an Entity Data Model.

Source Code Management

Before moving forward with the next iteration of development, I realized there was some administrative work which needed to be taken care of first. I need to bring source code management  technology into the project. With an agile approach to development, it doesn’t take long for a lot of source code and documentation to start piling up. In particular, it’s the number of source code files, which can proliferate and cause confusion. In my opinion, some form of source code management and version control, is absolutely necessary in every software project, regardless of scale, or how many people are working on the project.

There are several aspects to source code management, which should be considered, when selecting tools and technologies for this area of project management. Here are a few things to consider;

  • Version control, at the source code file level, and application level
  • A safe and secure repository for files and documents
  • Controlled access to the repository
  • Ability to check out, and check in files, in the repository
  • Historical log of who made changes, and the nature of the changes
  • Should be easy to use,so as not to distract from core development activities

There are several source code management/repository tools which are readily available. The most popular are;

All three are open source projects, which can be downloaded free of any license fees.

Along with a source code repository and version control system, you also need to find a safe and secure place to host the repository. For this purpose, I chose Google Code. This is a free and secure, project hosting service from Google. Along with hosting the source code repository, Google code provides a number of tools, for documenting and managing projects. Google Code provides easy and convenient access, to the source code of The World of Art project. For review purposes, I plan to provide the readers of this blog, direct access to the source code repository. Google Code supports Subversion, Git and Mercurial.

Finally, I prefer having the luxury, of a transparent integration, between my version control system and my development environment. For this reason, I’ve selected VisualSVN. VisualSVN is a professional grade, Subversion integration plug-in, for Visual Studio. It also supports repository hosting by Google Code. By default, selecting VisualSVN, means I’m also going with Subversion, for source code management.

The following image illustrates the solution explorer, just after the initial commitment of the World of Art project to Subversion, hosted at Google Code. Notice the little green icon next to most elements in the solution. This is a visual indication that the source code file is under version control. The illustration also shows the message log provided by VisualSVN.

VisualSVN integrated in Visual Studio 2010

Artist Content Added to The World of Art Web App

The artist page has been added to The World of Art web app. This iteration of development was performed to satisfy the requirements in my previous post. The Artist Page was developed using an ASP.NET WebForm conponent, in Visual Studio 2010. The ASP.NET Web Form model, along with all of the user interface controls integrated into the model, provides a stable platform for rapid appliation development.

Anyone developing on the ASP.NET platform, should join the Microsoft community. This is a community of developers, who are contributing enormous amounts of knowledge, along with tutorials, based on development. At you will also find an entire section devoted to Web Forms

Take a few minutes and see all of the technical details on how the artist content was added to the website.