Implementing Real-Time Language Translation Using .NET Control Adapters
The Case for Control Adapters
A fundamental tenet of programming is that you separate behavior that’s subject to a high degree of change from behavior that won’t change much over time. Sometimes this is easier said than done, particularly if you’re working with web applications. If you have full access to the code base, making changes shouldn’t be difficult. But what if the code base is unavailable, or you’re working with code that’s embedded in live web pages? No matter how well-segmented the application, if you can’t write lines of code, implementing changes can be nearly impossible, particularly if you’re dealing with changes that involve enhancements to presentation as well as business logic.
Fortunately, control adapters, new to .NET 2.0, allow you to enhance server controls on an existing web page without having to rewrite code that’s part of the page’s original code base. A control adapter is a class that you create that adapts another server control to a given need (see Figure 1). The simplest way to alter the adapted server control’s output is by providing override code to the control adapter’s Render(HTMLTextWriter writer) method, as I’ll demonstrate later on in this article.
Figure 1 Control adapters enable you to alter a control’s behavior without having to modify the original code base.
Control adapters live in assemblies that are independent of the assembly in which the adapted control resides. Once the control adapter is written, there’s no more code to write to get it to modify the behavior of the adapted control. You apply your control adapter to the server control being adapted, by making a declarative entry in your application’s .browser file.
You can configure a control adapter to work with all browsers or with particular browsers. For example, you can write a control adapter that tells a text box to render in an Arial font face if the consuming browser is Internet Explorer, and Times Roman if the browser is Firefox. Granted, the "font by browser" example is a bit trivial—not really worth the labor of learning a new technology. But there’s more to be gained than just changing a font. Once you get the hang of using control adapters, the implications are significant.
To demonstrate the power of the technology, I’ll show you the basics of making a simple control adapter. Then I’ll elaborate on those concepts and create a control adapter that will take a .NET server control written to display output in English, and translate it to display output in any one of a variety of languages. We’ll do this all in runtime, without any use of the .NET localization framework. The final outcome of our labor is shown in Figures 2–5.
Figure 2 Original code.
Figure 3 Code in French, created by using a control adapter.
Figure 4 The same code, displayed in German.
Figure 5 Finally, a Chinese version.