Welcome!

Microsoft Cloud Authors: Yeshim Deniz, Janakiram MSV, Andreas Grabner, Stackify Blog, Liz McMillan

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.

Conclusion
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!

References

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.

@ThingsExpo Stories
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...