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. 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.

Modernizing the User Interface with Image Buttons

The content for today’s post was contributed by Jonathan Greenstreet, ASNA Europe Regional Manager UK/Ireland/Netherlands/Scandinavia/South Africa.

As the leader in IBM i Modernization, ASNA offers two products that provide staged modernization of IBM i applications to the Microsoft .NET Framework.

  1. ASNA Wings lets you quickly and effectively give your RPG applications the user experience they deserve, with no disruptive changes to your RPG source code. The Wings UI is an alternative and your original green screen can still be made available for some users if necessary.
  2. ASNA Monarch transforms IBM i programs or applications originally written in ILE RPG or RPG/400®, into a native Microsoft .NET application. For a complete re-platforming, Monarch can even migrate your IBM i database to SQL Server™. The result is a browser-based, .NET version of your RPG application. Once migrated to .NET you can then extend and enhance the application in many ways.

Both products create a state-of-the-art, browser-based, user interface by transforming display file DDS into ASP.NET Web Forms. Microsoft ASP.NET Web Forms are an industry standard, so you can use standard Web techniques to further modernize and improve the user interface.

In this post, Jonathan offers a simple tutorial on how to add image buttons to a DdsSubfile.

A DdsSubfile is an ASNA user interface control that provides an ASP.NET equivalent to the DDS display file subfile. Mark up code for the DdsSubfile control, and a variety of other ASNA controls, is automatically generated when a DDS display file is transformed into an ASP.NET web form through Monarch or Wings. ASNA provides user interface controls, based on DDS display file constructs, to make it easier for RPG programmers to further modernize and improve the transformed user interface.

The ASNA user interface controls are drag and drop widgets that are fully integrated into the Microsoft Visual Studio development environment, as illustrated here;

ASNA user interface controls in the Visual Studio toolbox

ASNA user interface controls in the Visual Studio toolbox


Now Lets get into the details of Jonathan’s tutorial on how to add image buttons to a DdsSubfile.

Objective

To replace the selection field in a DdsSubfile by using images to give the end user the ability to point and click at the option required.

Example of a standard selection option in a subfile

Standard subfile with multiple option selections

Standard subfile with multiple option selections

Example of replacing standard selection option with images

Selection with Images

Selection with Images

How to implement changes

  1. Add jQuery to the project
  2. Create JavaScript file to hold the action to take when clicking on an image
  3. Create JavaScript method for when the images are selected
  4. Add jQuery and JavaScript to the master page
  5. Add image to the DdsSubfile
  6. Hide display file selection option from the screen
  1. jQuery can be added to your project in a number of ways, in this example we will outline the one which enables you to use it without having to connect to the internet
    • Download the lastest release of from jQuery
    • Add the download file to your project
      jQuery file download

      jQuery file download

  2. Create a JavaScript folder to hold the required JavaScript file using Visual Studio add item.
    JavaScript file folder in Visual Studio

    JavaScript file folder in Visual Studio

  3. Add the following JavaScript to the .js (JavaScript) file

  4. Under the body tag of the master page add

    This will allow jQuery and the JavaScript to be visible to all the pages that utilize the master page.
    Note : If you want this functionality to be enabled in the popup windows, please ensure that this is also added to the popup window master page.

  5. Add the images to the DdsSubfile

    Here is breakdown of the attributes inside the input tag above;

    Src : where the required image is held
    Onclick : the JavaScript method to be invoked
    Style : the position where the image is to display in the DdsSubfile and the height and width of the button. (If the height and width are standard throughout all the buttons this could be moved to a CSS file.)
    Title : The text to display if the mouse is hovered over the image.

  6. The original selection option is no longer required to be displayed. This option cannot be removed or set to visible = *False. The way to hide this is in the style option of the control, set “visibility : hidden”

Overloading Methods with ASNA Visual RPG

Today I’ll be discussing another great feature of the ASNA Visual RPG (AVR) for .NET language. This feature is called method overloading and it provides two great benefits to your coding efforts;

  1. Simplifies complex coding requirements
  2. Enhances code performance

In AVR, method overloading simply means that functions in an AVR class can have the same name but with different parameters passed to it. The name of a function, combined with the set of parameters passed to it, form what is called the signature of the method. Here is an example of an overloaded method called GetItem, with three different signatures;

The AVR.NET compiler will compile all three methods to the intermediate language code as expected. One thing to remember, is that when it comes to overloading a method, the value returned by the method is not considered part of the method signature. As you can see in the second overloaded example of GetItem, it returns a different type from the other two overloaded methods.

Method overloading gives us the ability to provide multiple, unique implementations of the method, while at the same reducing the complexity of the code required to satisfy application requirements. Without the ability to overload the GetItem method, there could only be one implementation of the method. This single implementation would be much more complex, because it would have to perform tests, to determine what kind of argument was passed into each parameter and then branch to the appropriate code, based on the results of each test. All of this testing and branching degrades the runtime performance and efficiency of the method.

Method overloading also provides consumers of the GetItem method with the kind of flexibility and ease-of-use they have come to expect, when interfacing with other .NET classes and methods. The public interface of the ItemDbContext class illustrated above, will expose three methods for retrieving an item object, either with its associated order object or without the order. The consumer of these methods simply has to code the appropriate arguments when invoking the GetItem method and the compiler and common language runtime, will take care of calling the appropriate method. The consumer does not have to be concerned with how these methods are implemented. Their only concern is to satisfy the requirements of the public class interface.

When writing code in Visual Studio that will invoke the GetItem method, the IntelliSense feature of Visual Studio will automatically present each signature of GetItem to the programmer for them to choose from, as illustrated here.

Overloaded Method GetItem Signature 1

Overloaded Method GetItem Signature 1


Overloaded Method GetItem Signature 2

Overloaded Method GetItem Signature 2


Overloaded Method GetItem Signature 3

Overloaded Method GetItem Signature 3


Please feel free to share your thoughts on this post by clicking the leave reply above, or post your comments on Twitter #ASNAVisualRPG.

Below is the complete code for the ItemDbContext class used in the example above. The example application developed for this post, and all of the source code can be downloaded at the following link;

Method Overload Example

The sample database files, which are included with the example application download, can be imported into a local DataGate database on your PC.

Controlling Browser Session Timeout

The content for today’s post was contributed by Jonathan Greenstreet, ASNA Europe Regional Manager UK/Ireland/Netherlands/Scandinavia/South Africa.

ASNA offers products and technologies that will transform the green screen user interface, of RPG based applications running on the IBM i server, into a browser based graphical user interface. One of the challenges of modernizing and migrating the user interface is to make the migration as seamless as possible for the legacy end user community. ASNA has been resolving these challenges for many years with a combination of innovative products, technologies and professional services.

In today’s post Jonathan offers a very simple and effective way of controlling browser session timeout duration, so that the modernized user interface behaves in a way that legacy application users are familiar and comfortable with.

How to stop the browser from timing out with iFrame or jQuery

Summary
To enable the browser not to time out when it is inactive and to enable the server to close down the session soon after the browser has been closed.

Reason for requirements
The default session timeout for Internet Information Server (IIS) is 20 minutes. Although this is normally fine for a typical web application it is not the expected behavior that a traditional 5250 user expects.

A 5250 user expects the application to be available while the browser is open and for the connection to be freed up as soon as the web browser is closed.

Although it is possible in some browsers using JavaScript to detect when they close down, it is not a reliable way to ensure the closing of a session in a timely manner.

Alternative approaches and problems they can cause
The session timeout time can be increased or decreased, by adjusting the time (in minutes) for the sessionState in the web.config file of the project.

The problem with having a long timeout set is that, if the browser is closed while in the application and no notification is sent to IIS about this, the session will remain open for the duration of its set timeout. This can cause problems if database connections are left open and file locks are retained, it will also not allow other resources to be released until the session ends.

The problem with having a short timeout set is that the user has to continually interact with the application to keep their session active and prevent it from timing out. This is the opposite of what a user coming from a 5250 environment expects.

Solutions
Both the following solutions allow you to set the sessionState timeout to its lowest value of 1 minute and allow the application without user interaction to notify IIS that the session should still remain open.

The limitation with both of these solutions is that the session may remain active for a least a minute after the browser has been closed.

Solution 1: iFrame
Create a new aspx page in the project for the browser to communicate with. The page does not need to have code placed in a separate file.

The page can be extremely simple. In the example below I have created a page “Reconnect.aspx” in the root of the directory.

The language could also be C# or VB.

Ensures that the page is never cashed and a new one is delivered every time

Allows the page to be refreshed at required intervals. We have set this to 55 seconds so that it is less than the 60 seconds at which the session timeout is set.

Returns the path relative to the current page. This is very important if you want to use a cookie less environment.

In all the application pages or, better yet, in the master pages add the following iFrame

Finally to ensure the session is set to timeout after 1 minute set the timeout for the sessionState to 1 minute

Solution 2: jQuery
Ensure that your pages or master pages that are required not to time out have the jQuery .js available to them.

Create a new page. In the example below I have created a page “Reconnect.aspx” in the root of the directory.

Add the following JavaScript to the required pages of master pages;

Finally to ensure the session is set to timeout after 1 minute set the timeout for the sessionState to 1 minute

Overriding Properties with ASNA Visual RPG (AVR)

In this post I’ll demonstrate how to override properties in an AVR Class.

The example application developed for this post, and all of the source code can be downloaded at the following link;

Property Override Example

The sample database files, which are included with the example application download, can be imported into a local DataGate database on your PC.

Lets start off by describing a business domain object model defined by the following classes.

  • Order – represents an order header with a collection of one-to-many line items
  • Item – represents a line item of an order

These are the same classes I used in my previous post on navigation properties in AVR.

Here are code snippets from these two classes;

Order Class

Item Class

In the business application I want to have two versions of the Item object.

  • Version One – The Order property of the Item is populated with the actual Order that the item belongs to. In this case the Item is a stand alone object.
  • Version Two – The item object is part of a collection of items that will populate the Items property of an Order. In this case it would be redundant to populate the Order property of each Item. I want the Order property of the Items to have an instance of the Order object with unpopulated properties

I solved this problem using the class inheritance and class member override capabilities in AVR. There are three features of the Item class that support class inheritance and class member overrides;

  1. The class declaration includes the Modifier keyword with a value of *Extensible as follows;
    BegClass Item Access(*Public) Modifier(*Extensible). This means the Item class can be inherited by sub-classes.
  2. The Order property is defined with the Modifier keyword with a value of *Overridable as follows;
    BegProp Order Type(Order) Access(*Public) Modifier(*Overridable). This means the Order property can be implemented in a completely different way by child-classes that are derived from the Item parent-class.
  3. The _order field that the Order property is based on is declared with the Access keyword with a value of *Protected a follows;
    DclFld _order Type(Order) Access(*protected). This means the _order field is only accessible by members of the Item class and any classes derived from the Item class.

Now I can create a sub-class of Item that overrides the Order property with a completely different implementation of the setter method. Here is the source code for a class that I called ItemOrder;

There are three elements of the ItemOrder class that support class inheritance and overriding class members;

  1. The class declaration includes the Extends keyword with a value of Item as follows;
    BegClass ItemOrder Access(*Public) Extends(Item). This means ItemOrder is derived from the parent class Item.
  2. The Order property is defined with the Modifier keyword with a value of *Overrides as follows;
    BegProp Order Type(Order) Access(*Public) Modifier(*Overrides). This means that when an instance of an Item object is based on the ItemOrder class, the implementation of the Order property will be overridden by ItemOrder class.
  3. All members of the Item base class, declared with the Access keyword value of *Protected, are accessible to the ItemOrder class. Remember the field _order was declared as protected in the Item base class.

In AVR, getter methods are coded inside the BegGet and EndGet keywords. Setter methods are coded inside the BegSet and EndSet keywords. Even though they are framed by some funny looking keywords, getter and setter methods work like any other method in AVR. In the Order property of the ItemOrder class, the setter method has a custom implementation for setting the value of the protected _order field. There are two lines of code in the setter method as follows;

The first line creates a new instance of the OrderDbContext class, which controls all data access to the Order Header file. The second line of code assigns a value to the _order field by invoking the GetOrder method of OrderDbContext. The GetOrder method expects one argument to be passed to it, the order number, which is the key to the Order Header file. The GetOrder method returns a fully populated Order object which is assigned to _order.

With AVR’s class inheritance and class member override capabilities, I now have two ways of implementing the Item object in the business domain object model.

  1. Stand-alone Item – an instance of the ItemOrder class
    In this implementation an order object, with a valid order number, is assigned to the Order property of the ItemOrder class. This invokes the setter method of the Order property of ItemOrder, which will assign an Order object populated from the database.
  2. An Items that is part of a collection of items – an instance of the Item class
    In this implementation an instance of the Order object is assigned to the Order property of the Item class. This invokes the setter method of the Order property of Item, which will assign an Order Object not populated from the database.

Navigation Properties in ASNA Visual RPG (AVR)

ASNA Visual RPG (AVR) is a .NET program language developed by ASNA. In this post I will cover the topic of navigation properties in an AVR class. In order to demonstrate navigation properties, I created a business domain object model consisting of two plain old runtime class objects POCO Classes. The first class represents an order header and the second class represents an order line item.

Here are come code snippets from both classes;

The Order Class

The Item Class

Please notice the Items (plural) property of the Order class. The Items property is a type of generic list consisting of Item objects. This forms a one-to-many relationship between an order and line items in the order. In this structure the Items property is also a navigation property. A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end.

Notice also that the Item class has a navigation property of Order (singular). An Item can exist in only one order. The remote end point of an item is a single order, a multiplicity of one. The remote end point of an order is one-to-many items, a multiplicity of many.

Remember, the definition of a navigation property states that it is optional. For example, when an Order object is populated with data, it is usually desirable to also populate the Items property of the order, with a list of all the line Items associated with that order. On the other hand, when an Item is populated with data, it is not always desirable to populate the Order property of the Item, especially when the Item is part of a collection of Items in that Order. The multiplicity between Orders and Items would be repeated over and over again in the collection of order items. This would be very inefficient. However, when creating a single instance of an Item object, that is not part of a collection of items, it is desirable to populate the order property of the Item object. ASNA Visual RPG for .NET provides the flexibility needed to resolve a scenario like this, with an optional navigation property.

Here is an AVR function I called “PopulateItemEntity” that populates all of the properties of the Item class except the Order property. By not assigning a value to the Item.Order property, the setter method of the Order property is not invoked, leaving the property with a null value.

In case you are wondering why the Order property of the Item class has a modifier of *Overridable, don’t worry, I will cover that in my next post.

Code-First Migrations

Continuing my series on Code first development and workflow, in this blog post I’m covering Code First Migrations. Code First Migration facilitates database changes, implemented and completely driven by changes to the properties of the POCO classes, which define the domain specific object model. Code First Migrations fully support the convention over configuration, and agile application development processes. When practicing a code first development strategy, you immediately dive into an iterative and evolutionary approach to development. With the agile approach, the form and functions of the domain model are continuously evolving over the entire course of the software development life-cycle. You need a simple, fast and smooth mechanism, that will automatically apply object model changes to the database, over many iterations of development.

Visual Studio 2013 automatically generates a Migrations folder in the project, to store a time stamped history of all code first migrations generated for the project. Here is an illustration of the Migrations folder in my current project.

Code First Migrations Folder in the Solution Explorer

Code First Migrations Folder in the Solution Explorer

Here is an example of the code generated in a Code First Migration class.

You can customize the code generated by the migrations engine.

To learn more about Code First Migrations see this walkthrough.

Independent and Dependent Foreign Key Properties

As the form and functions of my domain model evolved, I decided that the performance of the navigation properties of the models could be improved by adding the foreign key property directly into the model, and annotating the navigation properties with the foreign key attribute. This not only improved data access performance, it also streamlined much of the user interface development, when I generated controllers and views directly from the models in the MVC 4 and MVC 5 templates.

Here is a link to stackoverflow that has a very good discussion on Independent Associations Versus Foreign Key Associations

Code-First and ASP.NET MVC 4

With this post I’m continuing my series of articles on Code-First development and workflow. In previous articles I developed a complete domain model for a project management application. This model includes POCO classes, that define each of the entities in the project management domain, along with a database context model defined in Entity Framework. Now I’m ready to build a web application based on this domain model, utilizing the Model View Controller (MVC) design pattern.

At first I decided to build the website using the ASP.NET Web Forms Application template in Visual studio 2012. I figured, since I already developed the domain model, and had Entity Framework generating the object model, I could simply hand craft the controller and view components and add them to the website in separate folders or class libraries. After all, the domain model consists of only nine entities;

  • Customer
  • Industry
  • Person
  • Project
  • Rate
  • Task
  • Timesheet
  • Timesheet Entry
  • Title

However, it didn’t take long to realize, that developing and unit testing all of the classes and methods, required to support the controllers and views for each entity, would be an overwhelming task for one person. Consider this, each entity requires one controller class. Each controller class requires eight action methods to support the Create, Read, Update, Delete (CRUD) operations, which are necessary to maintain each entity of the domain. Each CRUD operation must be supported by a separate view in the user interface. Here is the minimal inventory of components required to support the MVC design pattern with a model consisting of 9 entities;

  • 9 Controller Classes
  • 72 Action Methods
  • 45 View Classes
  • 126 Total components

The minimal number of components required to support an MVC design pattern over a domain model with 9 entities is 126. I estimate this amounts to over 3,000 lines of code. This is an overwhelming coding task for one person. However, MVC is a standardized, repeatable pattern. I decided to take some time to look into automating this development effort.

ASP.NET MVC 4

I changed my strategy, and restarted development of the project management website, using the ASP.NET MVC 4 Web Application template in Visual Studio 2012. I’m not going to get into all of the details of how to build the website using the MVC 4 website template. Instead, I will describe how I incorporated the project management domain model, which I had previously developed, into the MVC 4 website template. However, if you are new to ASP.NET MVC 4, here is an excellent step-by-step tutorial on building an ASP.NET MVC 4 web application called Intro to ASP.NET MVC 4.

Integration Of The Project Management Domain Model Into ASP.NET MVC 4

The ASP.NET MVC 4 Web Application template, generates a fully functional web application based on the MVC design pattern. The website project generated by the template provides a folder called Models. I simply added a C# file to the Models folder and named it ProjectManagementModels.cs. I also declared a name space of Lexicon.ActionManager.Models in the C# file. Then I copied all the source code, of the project management domain model POCO classes, into this one C# file. The result is illustrated below. Notice how the solution explorer in Visual Studio 2012 makes navigation of this rather large source code file very easy.

Project Management Models in Visual Studio 2012

Figure 1. Project Management Models in Visual Studio 2012

I also copied the database context class into this same C# file, as illustrated here.

Database context class to generate object model with Entity Framework

Figure 2. Database context class to generate object model with Entity Framework

Here is the entire source code file ProjectManagementModels.cs.

Adding Controllers And Views For The Project Management Domain Model Into ASP.NET MVC 4

Integrating the project management domain model into ASP.NET MVC 4 was easy enough. Adding the necessary controller and view components was even easier. To add a controller class, simply right-click on the Controllers folder in the Solution Explorer of Visual Studio. This will present a context menu. Hover the mouse pointer over the add menu option to display the sub-context menu, and then click on the controller option. This will display the Add Controller dialogue box, as illustrated in Figure 3.

In the Add Controller dialogue box, first give the new controller class a name. To follow the configuration over convention style of developing, which is supported in ASP.NET MVC 4, the controller name should be the same as the model entity it controls, with a suffix of Controller. In this case, I’m generating a controller class for the project domain entity of the model. Therefore, I simply named the new controller class “ProjectController”.

The Add Controller dialogue box offers numerous Scaffolding options – see Figure 3. This gives the developer total control over the amount of automation and scaffolding generated by ASP.NET MVC 4. The Scaffolding Options are presented in three drop down list boxes;

  • Template – a list of scaffolding template options
  • Model Class – a list of all the entity classes defined in the model
  • Data Context Class – a list of all classes in the model, including the Entity Framework database context class, which defines the object model
  • For Template, I want the highest level of automation and generated scaffolding in my project, so I selected the “MVC controller with read/write actions and views, using Entity Framework”.
  • For Model Class, I selected the “Project” class option from the model
  • For Data Context Class, I selected the “ProjectManagementContext” class option from the model

Finally, after selecting the three scaffolding options, simply click the add button and the ProjectController class is automatically generated, with the eight action methods implementing the CRUD operations to maintain Project objects. The ProjectController class is automatically added to the Controllers folder. The five view classes, which provide the user interface support for the CRUD operations, are also automatically generated and added to the Views folder in the solution explorer. Everything was automatically generated according to specifications I selected in the Add Controller dialogue box.

The results of the generated scaffolding are impressive. The ProjectController class has eight action methods and 128 lines of code. Five views were automatically generated with 553 lines of code. All of this code is fully functional right out of the box.

Adding the project controller to the ASP.NET MVC 4 project

Figure 3. Adding the project controller to the ASP.NET MVC 4 project

Here is the generated code of the ProjectController class;

Conclusions

The development approach I outline in this article probably isn’t for everyone. Some may argue that a certain level of control and flexibility, in structuring an application, is sacrificed with this approach. However, small shops and one person operations, can definitely benefit from the efficiency gained by the automatically generated application scaffolding. There is also a significant improvement in quality, and testing efficiency, gained from tapping into the know how, and capabilities, of a much large community of developers, who are continuously making contributions to the ASP.NET MVC model.

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.