Welcome!

Microsoft Cloud Authors: Stackify Blog, Liz McMillan, David H Deans, Automic Blog, Pat Romanski

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
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal ...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
The buzz continues for cloud, data analytics and the Internet of Things (IoT) and their collective impact across all industries. But a new conversation is emerging - how do companies use industry disruption and technology enablers to lead in markets undergoing change, uncertainty and ambiguity? Organizations of all sizes need to evolve and transform, often under massive pressure, as industry lines blur and merge and traditional business models are assaulted and turned upside down. In this new da...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, 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 strategy.
SYS-CON Events announced today that Grape Up 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. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at Dell EMC, introduced a methodology for capturing, enriching and sharing data (and analytics) across the organization...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...