Category Archives: Architecture

Architecture topics related to web app

Customized Configuration File Sections

The Microsoft .NET framework supports application figuration files for Windows applications, and web applications. An application configuration file is an XML document which contains settings specific to an application. The file contains configuration settings that the common language runtime can read. It can also contain settings that the application itself can read.

In this post I’ll show you how to create custom configuration file sections and how to access the configuration settings in an AVR.NET program. In order to demonstrate this concept, I have created an example AVR.NET application dealing with geometric shapes. In the application configuration file, I want to provide settings that an application administrator can manipulate, without modifying or rebuilding the application. For this example the settings will control the order in which geometric shapes will be drawn by the application.

Here is the XML of the App.config file

In this configuration example, everything is contained in the configuration section. Within the configSections element I describe my custom section with a sectionGroup element. On line 4 of the XML file I declare a sectionGroup named “shapeConfiguration” and a section named “shapeOrder”. I also specified that this section consists of name/value pairs by giving the type attribute a value of “System.Configuration.NameValueSectionHandler”. The type attribute is required, and specifies the name of the configuration section handler class, that handles the processing of the configuration settings that are in the section or element that is specified in the name attribute.

Accessing The Configuration File In AVR.NET

Accessing the configuration settings in an AVR.NET class will require two using statements;

The AVR.NET example will use the ConfigurationManager Class and the NameValueCollection class. The ConfigurationManager class will access the settings in the shapeOrder element of the configuration file. The NameValueCollection class will store the settings in memory as a collection of key/value pairs.

Here is the AVR.NET Code

The ConfigurationManager Class has a GetSection method that takes a string argument. Notice how the string is in file path notation for navigation to the shapeOrder element in the configuration file. The GetSection method returns a type of System.Object, so I used the AVR *As keyword to cast the name/value pairs of the shapeOrder element to a NameValueCollection. This type cast is also facilitated by the NameValueSectionHandler class I specified in the configuration file.

Now I can use the name value collection to assign a sorting rank to each instance of shape.

Here is the AVR.NET code

The NameValueCollection class has a Get method that accepts a string argument, which represents a key associated with a value in the collection. The Get method retrieves the value associated with the key. Notice how I used the Type class and the GetType method of each shape to form the key to get from the name value collection. This ensures that I retrieve the correct sort ranking associated with each shape object, no matter what the new instance of the shape class is called.

Each shape object has a RankOrder property which can be set based on the shapeOrder settings in the configuration file.

The GetShapesWithRank function in the above code snippet returns a generic list of shape objects. In my next post I’ll show you how to sort the generic list of shapes based on the RankOrder property of each shape.

Object Oriented Programming Stuff

Each shape class is derived from a shape base class which implements a shape interface. In the code snippet below, you can see that the IShape interface provides an abstraction for all shape entities referenced by the application. The interface defines only the essential elements of a shape;

  • Rank Order – a property that defines the rank of a shape in a hierarchy
  • Draw – a method for drawing a shape

The Shape class implements the IShape interface. You can see that the implementation of the Rank Order property is now concrete. However, the Draw method remains abstract and it is defined as a virtual method by the Modifier keyword with a value of *Overridable.

The concrete implementation of shape is completed in the Square class and the Circle class. They inherit from the Shape base class and override the Draw method with their own unique implementation. The Modifier keyword with a value of *Overrides facilitates the concrete implementation.

The following code sample demonstrates how well AVR.NET supports object oriented programming concepts like abstraction and inheritance. This design makes the AVR.NET code more flexible, reusable and maintainable. This design is much less vulnerable to the impact of ever changing requirements.

Here is the AVR.NET code where the shapes object model is defined

The complete source code of the application developed for this post can be downloaded here.

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.

Visual Studio 2012 and MVC 4

By Tim Daniels
In my previous post, I laid out a set of objectives for pursuing the ASP.net Web API technology, for developing RESTful web servies. I quickly discovered that the Web API technology is actually a subset of the MVC 4 design pattern, which is available as a project template in Visual Studio 2012.

I decided to take a detour of my objectives and explore the MVC 4 design pattern in more detail. I must say, the detour has taken more time than I anticipated, but it has proven to be well worth the extra time. The MVC 4 template in Visual Studio 2012 automatically generates a fully functional website solution. The template contains all of the required components of the Model-View-Controller (MVC) design pattern. The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes:

  • Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
  • View. The view manages the display of information.
  • Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

Here is the structural relationship between the three objects.

Model-View-Controller design pattern

The MVC 4 template in Visual Studio 2012 effectively addresses the architectural concerns covered in this blog throughout the development life cycle of the World Of Art Web App;

  • Separation of concerns between database access, user interface and business logic
  • Incorporates the Entity Framework in a code first process, where the developer can code plain old classes to define the domain in the model, and then generate the database through the entity framework
  • The controller object automatically adheres to best practices when handling http request and response actions

The MVC 4 template automates and streamlines much of the development life cycle, by not only generating code, but also providing a well structured scaffolding approach, which causes architectural and design concerns to fade to the background, allowing the developer to focusing more attention on satisfying the functional requirements of the application.

The ASP.Net Web site has an entire section devoted to the MVC 4 template. There is a complete set of tutorials to help you become familiar with all the components and features of MVC 4. I will continue following the MVC 4 tutorial all the way through deployment of sample movie application. After completing the tutorials, I plan to develop an MVC 4 version of the World of Art Web app, and report on how this template improves application design and development inefficiencies.

Evolution of the User Interface

By Tim Daniels
At this time I have demonstrated three iterations of the Artist web page in The World of Art Web App. The first iteration, simply called the Artist page, was designed with the ASP.Net Web Form model. In this example, I developed the user interface with three ASP.Net server side controls;

The ASP.Net Web Form model depends on the ASP.Net Engine, in the web server, to generate the actual HTML rendered by the client. The input to the ASP.Net engine is the XHTML elements and attributes defined in the .aspx web form file. This model supports a very rapid development process. However, it is a poor architectural design for a distributed web app, because the user interface and database access are tightly coupled. This tight coupling of architectural elements, makes long term maintenance and further development of the app more complicated, because the impact of change has a broad affect across the application. Here is the XHTML source code of the first iteration of the Artist page;

In the second iteration of the Artist page, which I called Art Entities, I eliminated the SqlDataSource web server control, and created a separation of concerns between the user interface and data access. This is where I introduced the concept of a layered architectural design, with the development of the Data Access Layer, and the Data Model Layer. In the Data Model Layer, I developed an Entity Relationship Model with the ADO.Net Entity Framework, which created a line of clear separation, and decoupling, between data access functions and the SQL Server database.

In this phase of development, the user interface evolved into an external layer of the overall web app design. However, the user interface is still based on server side ASP.Net web server controls. I simply exploited the data binding methods, built into these controls, to create an API to the data access layer. Here is the XHTML and C# source code used to render the Art Entities page of the World of Art Web App;

The ASP.Net Web server controls, used in the first two iterations of the user interface, is a suitable design solution for an enterprise level application, which is running internally to the enterprise. The number of users is limited to the employee and associates base, the application is supported by the internal IT infrastructure of the enterprise as an intranet appliation. The view state and post back model, supported by these web server controls, performs very well in this environment. However, if the application is to be distributed over a wide range of clients, and accessible from the world wide web, a much leaner and flexible architectural model is required. This is a requirement for the World of Art Web App. Therefore, in this latest iteration of the app, I added a web service layer to the architecture, based on the Microsoft Windows Communication Foundation (WCF). Accessing the service layer of the World of Art Web app, was a driving factor behind the design of the third iteration of the user interface.

Accessing the service layer, reverses the flow of content between the client and the server. In the previous versions, where server side controls were used, content was pushed from the server to the client. However, acquiring content from the service layer, requires the client to pull content from the server through an HTTP request.

The third iteration of the artists page, which I called Art Entities from Service, is a very minimal and efficient design, utilizing an HTTP GET Request to retrieve artist data from the web service, and JavaScript to render the artist result set in HTML. I also employed a CSS 3 cascading style sheet to complete the look and feel of the page.

Here is the XHTML source code of the ASP.net web form and the JavaScript source code used in the third iteration of the user interface;

Here is the cascading style sheet. You will notice some of the new CSS 3 attributes like “border-radius”, which is used to form the rounded corners of the artist grid in the Entities From Service page.

The AJAX Client and Cross-Domain GET Requests

By Tim Daniels
In developing the client to consume the World of Art Web Service, I decided to stick with the ASP.Net Web Form (.aspx). This allowed me to take advantage of the master page concept already implemented in the World of Art Web App. Following is the markup source code of the .ASPX page. As you can see it has some very basic ingredients;

  • Page declaration with a reference to the web site master page
  • HTML Heading Tag
  • A script tag pointing to a JavaScript source code file called GetArtists.js

Here is the XHTML mark up code of the .aspx web form;

The heart of the client application is the JavaScript in the GetArtists.js file. There are two primary functions;

  • getArtistsAjax() – Requests artist data from the World Of Art Web Service
  • updateArtists() – Dynamically generates the user interface

Here is the JavaScript source code of the client.

Lets first examine the getArtistsAjax() function. There are many different ways to perform an HTTP GET request. After trying a number of different combinations, I found this implementation to be a straightforward and flexible solution. The getArtistsAjax() function uses the JQuery.ajax() method, to perform the asynchronous HTTP(Ajax) request for artist data from the ArtService. The jQuery.ajax() method can be configured with a multitude of settings and parameters. However, for the simple HTTP GET request required by this application, I found it necessary to only pass five arguments to the jQuery.ajax() method, which are coded as key/value pairs;

  • type: “GET” – The type of request to make (“POST” or “GET”)
  • url: ‘http://lexicon-software-apps.com/ArtService.svc/GetArtists’ – A string containing the URL to which the request is sent.
  • dataType: “jsonp” – Loads in a JSON block using JSONP. Adds an extra “?callback=?” to the end of your URL to specify the callback. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.
  • success: function() – A function to be called if the request succeeds.
  • error: function() – A function to be called if the request fails.

The most interesting setting is the dataType set to “jsonP”. This gives the client flexibility to perform a “GET” request from a domain other than the one that served the original page request. The following illustrates an example of this. I setup an alternate domain at Winhost called Lexicon-Software-Learning.com. I published the World of Art Web Service at Lexicon-Software-Learning.com. I then changed the url setting to point to the learning domain. Here is the result;

Cross Domain Get Request

The artists entity web page is served from Lexicon-Software-Apps.com domain and the get artists data request is served from Lexicon-Software-Learning.com.

The other primary JavaScript function in GetArtists.js is the updateArtists() function. It receives the JSON formatted data result set from the HTTP GET request. The JSON data is basically an array of artist objects. This function simply iterates through the array of artist objects, and adds them as elements to the web pages’ Document Object Model (DOM) object. I also applied some new CSS 3 style sheet elements, to finish off the look and feel, of the list of artists page.

I will cover the user interface in more detail in my next post. We will also look at the evolution of the user interface in the World of Art Web App, from the first iteration which was server side generated, to this latest iteration which is client side generated.

Here is the CSS 3 Cascading Style Sheet

Implementation of the Web Service Interface

In my last post, we discussed the interface of the WCF application and how it forms a mutually binding contract, between the client and the service. The client must make their request in a format the service is expecting, and the service must fulfill the request in the format specified in the contract. This is all defined in the operation contract of the IArtService interface.

  • The request must be an XMLHttpRequest using the “GET” verb
  • The “GET” request must specifically request access to the ArtService.svc and the GetArtists method
  • The service must respond to the request with data serialized into the Json format

Here is a simple JavaScript function which would satisfy the contractual requirements for a request;

Once again, here is the IArtService interface where the mutually binding contract between the service and clients is defined;

As you can see, the interface also uses the System.Runtime.Serialization and System.ServiceModel.web name spaces to fulfill the request.

Now, lets examine the implementation of the IArtService interface. Here is the source code of the ArtService class which implements the IArtService interface;

As I stated in an earlier post, the purpose of the Art Service Class is not to expose the business logic of the World of Art web app. Instead, the purpose of the Art Service, is to simply expose specific data elements from the World of Art domain, which can be served upon request, to various software clients. In order to retrieve data from the world of art domain, the ArtService class references two name spaces from the WorldOfArtWebApp;

  • ArtWorldObjects
  • WorldOfArtWebApp.DataAccess

With these references, the GetArtist() method can reuse components of the WorldOfArtWebApp from the Data Access Layer and the Data Model defined in the Entity Framework.

The GetArtist() method is bound by the Operation Contract, defined in the IArtService interface, to return a list of artist objects. This requirement is satisfied by simply creating a new instance of the ArtWorldCollectionArtist Class, and accessing the collection of artist objects in the ArtWorldCollection property. The collection of artist objects is retrieved from the WorldOfArtContext, generated from the Entity Framework. The WCF web service will serialize each of this artist objects into JSON format as specified in the operation contract.

In my next post, I will discuss how to specify which properties of the Artist object are exposed to the web service. Also, here is the source code for the ArtWorldCollectionArtist class, invoked by the GetArtist() method.

Web Service Operational Parameters

Today I will continue the discussion of the service contract, as defined by the interface generated from the WCF application template. Once again, here is the source code of the interface;

The operational parameters of the service contract are defined as a method. In this application, the method is called GetArtists() and it returns a list of artist objects from the world of art domain, as defined in the ArtWorldObjects name space. Therefore, a reference to the ArtWorldObjects class library is necessary, as indicated by the using statement.

The GetArtists() method is enhanced with the Operation Contract Attribute, which indicates that a method defines an operation that is part of a service contract in a application. The operation contract attribute is also defined in the System.ServiceModel name space.

The GetArtists() method is also enhanced with the WebGetAttribute Class, which indicates that a service operation is logically a retrieval operation and that it can be called by the REST programming model. The WebGetAttribute Calss is defined in the System.ServiceModel.Web name space. The constructor method of the WebGetAttribute class will accept a variety of arguments, as named parameters, which populate the properties of the class and configure the operational contract between the service and client software. This first iteration of the web service is very simple and retrieves a very small data set, so I’m only passing the Response Format argument for now.

The Response Format parameter will set the ResponseFormat property of the WebGetAttribute class. This property determines the format of responses sent from a service operation. The two possible values are Xml and Json.

As you can see, the World of Art Service will return a response in the Json format. JSON stands for JavaScript Object Notation. JSON is syntax for storing and exchanging text information. The web service is now contractually obligated, to respond to requests with text. More specifically, text that is formatted in a way that JavaScript, running on the client, can parse and evaluate as objects. In this application the objects are abstract representations of artists. The clients will receive an array of artist objects. Click on this link, Get Artists to send a request to the World of Art Service, and see the JSON text returned by the service. This link, Artist will take you to the actual website that consumes this JSON data.

In my next post, I will discuss the implementation of the IArtService interface.

Web Service based on WCF and REST

Then next phase in the evolution of the World of Art Web App is the development of a web service, based on the Windows Communication Foundation (WCF), and the Representational State Transfer (REST) architectural model. SO lets get started.

Visual Studio 2010 and the .Net Framework 4.0 make development of web services a very straight forward process. As you would expect, Visual Studio has a WCF Service Application template already installed.

Visual Studio provides a WCF application template already installed

Visual Studio provides a WCF application template already installed

I decided to make the World of Art web service a separate project from the World of Art web app. The primary reason for doing this, is that later in the project, I want to demonstrate cross-domain access to web services, and keeping the service in a separate project will make deployment to multiple domains easier. Here is the solution explorer displaying all of components generated from the WCF application template.

WCF Project in Visual Studio 2010

WCF Project in Visual Studio 2010

The WCF application template generates three very important files for defining and developing the functionality of the web service;

  • Interface defining the contract and operations of the service
  • Web Configuration file
  • Service file

Here is the source code in these three files;

The service file, which I named ArtService.svc

The web configuration file

The Interface

The interface, which I named IArtService, defines both the service contract and the operational parameters of the service contract. The implementation of the interface, will facilitate the fulfillment of contractual requirements, between the client and the web service. The interface is enhanced with the service contract attribute, which indicates that an interface or a class defines a service contract in a application. This attribute is defined in the System.ServiceModel name space of the .NET Framework 4. This name space contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications.

In my next post I will cover the operational parameters of the service contract.

Return of the Jedi Blogger with HTML5 and Web Services

It has been a very busy summer and three months have slipped away since my last post. Since then, I’ve been working on other projects and doing some summer time traveling, which included visits to Los Angeles and Las Vegas. I have also been doing some very interesting work with HTML5 and web services. Well, with summer time activities winding down, it’s time to get back to work on the World of Art Web App project. In coming posts, I will be enhancing the server side of the web app, with a new web service, based on Microsoft’s Windows Communication Foundation (WCF). I will also enhance the client, with a new artist page based on the new web standard, HTML5.

My next post will cover the WCF web service. The purpose of the web service, is to listen for requests from various software clients, and respond to the requests with information from the World of Art Web app. The architectural objective in the design of the web service, is not to expose the business logic of the web app to world wide web. Instead, the design objective is to only expose specific data elements and implement a scheme, that enables client applications to access this data, and manipulate it using their own business logic. With these design objectives in mind, I have decided to use the Representational State Transfer (REST) architectural model.

The web service will reuse all of the Entity Framework and the data access layer components already developed. As previously stated, these components will not be exposed by the web service. However, the web service will use the output of these components to satisfy a basic contract for information, as requested by a client application.

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.