Welcome!

Microsoft Cloud Authors: Yeshim Deniz, Janakiram MSV, John Katrick, David H Deans, Andreas Grabner

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
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.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. 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 gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"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...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.