Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

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)

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.

IoT & Smart Cities Stories
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...