Home > Articles > Programming > Windows Programming

Practical Code Generation in .NET: Generating a Connection String Manager

  • Print
  • + Share This
Peter Vogel walks you through an end-to-end solution for code generation that concentrates on integrating with Visual Studio and working with the CodeElement objects.
This chapter is from the book

In this chapter:

  • Defining the Problem
  • Setting Up the Add-In
  • Creating the Code Generator
  • Customizing the Template
  • Generating Code
  • Reading Input
  • Notifying the Developer
  • Supporting Customization
  • Tying Generation to Events
  • Generating a Simple Class

In this chapter, I walk through an end-to-end solution for code generation that concentrates on integrating with Visual Studio and working with the CodeElement objects. The code for this solution is kept purposely simple to avoid involving other tools. (For example, I only make minimal use of the code editor object.) The case study in the next chapter includes a wider range of tools, including the CodeDom.

I've also assumed that there will be only one configuration file open at a time—because you can only have one app.config or web.config in a project, that's not an unreasonable assumption. However, because a Visual Studio solution can include multiple projects, it's at least conceivable that a developer could have two or more configuration files open at a time. The case study in the next chapter shows a more sophisticated process for handling events to support scenarios where multiple files that trigger code generation could be open.

This solution does demonstrate how to do the following:

  • Support all project types, including ASP.NET websites, without using the VsWebsite objects (or, at least, only having to use them once)
  • Support customization by the developer
  • Read existing files in the project to get the input specifications
  • Create a page in the Tools | Options dialog to allow the developer to configure code generation
  • Tie code generation to events in Visual Studio

As part of this solution, I include some utilities that you can use in other code-generation solutions. One caveat: To simplify the code in this example, I assume that I'm only generating C# code, although I discuss where the solution would be different when supporting Visual Basic.

Finally, within those self-imposed limitations, I've tried to demonstrate a variety of techniques to show the range of options available to you when generating code. My goal for this chapter is to demonstrate a process for developing an add-in, along with some of my best practices and design patterns I follow.

Defining the Problem

The problem I want to address is relatively simple: handling the connection strings in an application's configuration file. A typical example of the separate section available for holding connection strings in an app.config or web.config file looks like this:

  <add name="Northwind" connectionString="..."
       providerName="System.Data.SqlClient" />

When retrieving the connection string, you access the connection strings as named members of a collection. To retrieve the connection string from the previous example in a non-ASP.NET application, you'd use this code:

string MyConnection = ConfigurationManager.

Here is the syntax for an ASP.NET application:

return System.Web.Configuration.WebConfigurationManager.

This syntax creates problems for developers. The absence of IntelliSense support when specifying the connection string means that you have to switch back to your configuration file in order to find what connection strings you have and what you called them; if you mistype the name of the connection string, you won't find that mistake until that line of code executes (probably when someone who has input into your job appraisal is looking over your shoulder). You don't have to take my word that this syntax is error-prone: Did you catch the misspelling of "Northwnd" in the sample code? It should have been "Northwind" to match the connectionString example—but if you don't spot that problem when reading the code, you won't find it until the code executes.

A Model Solution

ASP.NET provides a better model for handling connection strings in the way that the personalization provider handles properties. As with connection strings, you define personalization properties by entering XML tags into your website's configuration file. A typical example looks like this:

   <add name="LinesPerPage" type="int" defaultValue="0"/>

Unlike connection strings, however, at runtime, you don't access your personalization properties as members of a collection. Instead, you access the properties you defined in the Web.config through properties on the Profile object, like this:

Profile.LinesPerPage = 15;

When entering this code you get full IntelliSense support for all the Profile properties (see Figure 9-1). If you ask for a property that doesn't exist, your problem is found at compile time, not runtime. Overall, personalization delivers a solution that provides better support to developers than is available with connections strings, even though the input to both processes is the same.

Figure 9-1

Figure 9-1 Although personalization properties are defined in an application's configuration file, access to those properties is handled through specific properties on the Profile object.

The personalization solution is made possible through the magic of code generation: By analyzing the entries in the configuration file, Visual Studio and ASP.NET generate a Profile object with all the properties specified in the Web.config file's XML tags. Because the data type for each property is specified in the XML tags, the generated code isn't "general-purpose" code with multiple if statements checking the data type or with all variables declared as type Object—you get the specific code you need for the properties you defined in the configuration file.

A similar solution for connection strings lets the developer write code like this:

string MyConnection = ConnectionManager.Northwind;

In this solution, the ConnectionManager object is a static class that isn't instantiated and has a property for each connection string. This solution gives the developer full IntelliSense support and compile-time checking when accessing a connection string.

The code for my ConnectionManager object looks something like this for Northwind property in a non-ASP.NET project:

public static partial class ConnectionManager
  public static string Northwind
    return ConfigurationManager.

Supporting Customization

The ConnectionManager solution also allows the developer to introduce custom code to support those instances where a full connection string isn't stored in the configuration file. For instance, one of my clients provides data gathering and storage services to their customers. To support scalability (and to help ensure privacy), each customer's data is kept in a separate database. As a result, my client stores a template connection string in the application's configuration file. The template contains replaceable components that support tailoring the connection string for each customer. In my client's application, whenever a connection string is retrieved, code in the application modifies the template and tailors the string to work with a specific customer's database. The ConnectionManager solution supports this kind of modification by allowing the developer to step in and add his or her own code to the process.

  • + Share This
  • 🔖 Save To Your Account