Microsoft Cloud Authors: Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie, Elizabeth White

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Customizing the Compilation Process and Tweak the Run Time For Superior Results

I've tried to make it a point to learn different programming languages throughout my career

I've tried to make it a point to learn different programming languages throughout my career. It's not that I'm fluent in multiple languages (for example, I wouldn't call myself an Eiffel expert by any stretch of the imagination), but by learning about a language's features and ideas I've been able to broaden my perspective. This has its benefits when I'm designing or implementing a piece of code, because I've able to add different ideas into the code base that don't exist in the feature set of the language. For example, Eiffel has the idea of design-by-contract, which allows you to define pre- and post-conditions along with class invariants in your code, ensuring that callers set their parameters correctly and guaranteeing that an object will always be in a certain state. I find those ideas beneficial in creating defensive, maintainable code.

However, sometimes it's frustrating when I've used a feature in a language and my current language of choice doesn't have that feature. Java has checked exceptions, which forces you to define which exceptions a method may throw, thereby minimizing the chance that an unhandled exception could occur. .NET has no native concept of a checked exception, so the best you can do is provide documentation that lists the exceptions that a method could throw, or rip into the method implementation itself via ILDasm or Reflector and see if there are any throw statements in the method. Neither approach works in my book. Documentation can be incomplete (I've run into a case where a property threw an exception that was not listed in the SDK) and looking at method implementations can be tedious, especially if you have to look at all of the methods a method calls, and so on.

Extending the Compilation Process
So let's say you're really hooked on a language feature that's not in C#. How would you be able to use it? Well, you can't just add the keyword to the code base. For example, if you added a throws keyword to a C# method, the compiler would bark at you, because it wouldn't understand what "throws" means. You could also search the Internet to see if there's a language that targets the CLR that has the feature you're looking for. This could work (and I keep a list of .NET compilers at www.dotnetlanguages.net), but there are issues with that approach as well. You may not be proficient in that language, or there may not be a .NET compiler for that language, or the place you work may not like it if you introduce another language into their environment. Another idea would be to write a customized compiler for C# that would understand what "throws" meant. That would be problematic because your code would no longer be compliable with the standard C# compiler.

What we need to do is come up with a way to define custom features into a language without affecting the code in such a way that it could not compile with the standard compiler. This can be done using a combination of .NET features and a .NET tool:

  • Compilers via a CodeDomProvider
  • Custom attributes
  • Custom FxCop rules
Figure 1 gives a high-level overview of this extensible compiler. Essentially, the extensible compiler uses a CodeDom compiler to create an assembly in a normal fashion. Then, the extensible compiler uses FxCop to run the assembly against a number of custom rules. These rules look for specific coding constructs or custom attributes to ensure the code follows the extended features that a developer wants to use. Let's take a look at how each of these aspects of the extensible compiler works in more detail.

Plugging Compilers in with the CodeDom Providers
The first part to extensibility is to use a CodeDom provider. Both C# and VB have CodeDomProvider implementations (Microsoft.CSharp.CSharpCodeProvider and Microsoft.VisualBasic.VBCodeProvider, respectively). A CodeDomProvider has methods to compile code (via CreateCompiler) and to generate code from a CodeDom tree (via CreateGenerator). However, the CreateParser methods on both the C# and VB implementations return null references (in the beta 2.0 versions they return a NotImplementedException, but this may change in the future). This is unfortunate, because a compiler gets us from point A to point C. Using a generator gets us from point B to point A. It would be ideal if we could get a parse that would take code files (point A) and generate a CodeDom tree (point B). Then we could change the tree and use an ICodeCompiler reference to generate an assembly.

What we can do, though, is use an ICodeCompiler reference to compile code files for us, and, if that's successful, check the resulting assembly to ensure the code follows our custom features. This limits us from injecting code into the assembly, but at least we have a way to use a standard API in .NET to compile our code and potentially add different providers from other language vendors.

Using Attributes to Define Features
A second part to adding custom features is liberal usage of custom attributes. An attribute is a piece of data that gets injected into an assembly during compilation. If you've ever made a class serializable or worked with Web services, chances are good that you've used attributes. What's nice about attributes is that you can create custom attributes to create your own features. Listing 1 shows the definition of ThrowsAttribute and its usage on a method. As you can guess, ThrowsAttribute is used in the extensible compiler framework to implement checked exceptions. The great thing about attributes is another developer could compile code that uses that custom attribute with no problems.

However, just defining a custom attribute doesn't complete the architecture. Custom attributes are only effective at run time. There are some attributes in .NET that will affect the compilation process (CLSCompliantAttribute is one that comes to mind), but there's no way you can hook into the compilation process to see if attributes exists on key members of an assembly and use their existence (or lack thereof) to halt compilation. That's where the third piece of the puzzle comes into play: FxCop custom rules.

FxCop to the Rescue
FxCop is a tool that is used to check your assemblies to see if they're violating any rules. These predefined rules fall into categories such as security, design, and globalization, just to name a few. If you've ever run FxCop on your assemblies, you may be very surprised (and somewhat frustrated) at the number of rule violations that occur. However, I've always found FxCop to be an indispensable tool to use in a build process. It helps prevent bad code from living in the code base by creating reports that you can read to see just what's going on when developers are checking in new code.

The reason why I bring FxCop into the mix is that it has the ability to read the entire contents of an assembly. The Reflection API is vast, but it can't read the opcodes from a method (although this changes in 2.0). To add custom language features, this is a necessity, and that's exactly what FxCop has. It allows you to define your own custom rules, even if your rule requires you to discover every opcode, try-catch-finally block, and local definition in a method. In the case of the ThrowsAttributes, it's essential to have intimate detail about the exception blocks because we need to keep track of which exceptions were thrown at which points in a method, and to keep track of those exceptions that have the potential to leak out of the method.

The extensible compiler uses an FxCop project file that lists those rules that should be checked after normal compilation is complete. A project file is just an XML file, and it's not too hard to hand-edit to change the list of rules it should run. The code drop for the extensible compiler has a project file that's pretty slim - I encourage you to use it if you want to add other rules since it's already tweaked to ignore the vast array of built-in rules that FxCop provides.

As you can imagine, the hardest part of this process is writing the custom rules. A CodeDomProvider gives us the compiler out of the box, and creating custom attributes is relatively straightforward. The key is creating rules that will implement custom features. FxCop has a great SDK to find out all sorts of things that are going on within a method, but there's no documentation for this SDK. If you look at the source code for the extensible compiler, though, you'll see four examples of custom rules that you can use to understand how these custom rules can be written. I've also provided a reference to articles that demonstrate the power of FxCop's SDK. Feel free to download the code and play with it, and let me know if you have any questions. Enjoy!


More Stories By Jason Bock

Jason Bock is a senior consultant for Magenic Technologies (www.magenic.com). He has worked on a number of business applications using a diverse set of substrates and languages such as C#, .NET, and Java. He has written numerous articles on software development issues and has presented at a number of conferences and user groups. Jason holds a Master's degree in Electrical Engineering from Marquette University. Visit his Web site at www.jasonbock.net.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
.NET News Desk 12/04/05 12:04:31 AM EST

Customizing the Compilation Process and Tweak the Run Time For Superior Results. I've tried to make it a point to learn different programming languages throughout my career. It's not that I'm fluent in multiple languages (for example, I wouldn't call myself an Eiffel expert by any stretch of the imagination), but by learning about a language's features and ideas I've been able to broaden my perspective. This has its benefits when I'm designing or implementing a piece of code, because I've able to add different ideas into the code base that don't exist in the feature set of the language.

IoT & Smart Cities Stories
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER gives detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPOalso offers sp...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...