SharpCrafters Blog

The official blog of SharpCrafters and PostSharp: annoucements, tips & tricks

Advanced
26 April 2012


Just a quick note to say we’ve fixed the PostSharp Toolkits so that you can build them from source code. Previously, some artifacts were hardcoded to our development environment.

Note that the objective of the toolkits is to provide you with ready-made implementations, so we encourage you downloading the NuGet packages instead of building from source code.

In order to build the toolkits, follow these steps:

1. Download the source code from GitHub

Clone the repository git://github.com/sharpcrafters/PostSharp-Toolkits.git or download the source code from https://github.com/sharpcrafters/PostSharp-Toolkits.

2. Install PostSharp

You need PostSharp to build the toolkits, but we don’t use NuGet to retrieve it from the network. This is because the build script needs to be compatible with our development environment. The minimal version number of PostSharp you need is specified in the dependencies section of the file $\Build\NuGet\Logging\PostSharpDiagnosticsToolkit.nuspec.

If you’ve installed PostSharp with the setup program, you can go to the next step. Otherwise, you need to create a file named $\Dependencies\PostSharp\PostSharpDir.Custom.targets, which specifies where PostSharp is installed. Note that this file should not be checked into the source control.

Here is the content of this file for our development environment:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PostSharpDir>c:\src\PostSharp-2.1\Build\bin</PostSharpDir>
  </PropertyGroup>
</Project>

3. Build from Visual Studio or MSBuild

At this point, you will probably want to open the solution PostSharp.Toolkits.sln and build it.

4. Build the NuGet packages

When all binaries are built, you can create the NuGet packages by calling

msbuild Build\NuGet\NuGet.proj

The usual disclaimer

Of course, this blog post has to come with the usual disclaimer that PostSharp Diagnostic Toolkit uses PostSharp SDK, which is officially undocumented and unsupported. That is, we are happy to show you how things work, but we won’t answer questions related to its implementation. The source code of the toolkits itself is largely undocumented and is provided AS IS, and we won’t accept this kind of criticisms.

Happy PostSharping!

-gael

Toolkits
3 April 2012


One of the ideas behind the PostSharp Toolkits was a zero code change requirement, that would allow you to simply install the relevant toolkit from NuGet, rebuild your project and that’s it. To achieve that, we have revived the PostSharp XML configuration. The XML configuration is the unification of the Plug-in and Project models in the project loader. Let’s have a look on how PostSharp Diagnostics Toolkits use this XML configuration.

PSPROJ XML Configuration

After installing the PostSharp Diagnostics Toolkits via NuGet, a file with the .psproj extension will be created, named after the current project. The .psproj files are an XML representation of the PostSharp Project structure – containing the configuration of the application, with resolved properties and references.

Let’s take a look at the default configuration that is produced by the PostSharp Diagnostic Toolkit package:

<?xml version="1.0" encoding="utf-8" ?>
<!-- Default project used when PostSharp is detected according to project references. -->
<Project xmlns="http://schemas.postsharp.org/1.0/configuration" 
ReferenceDirectory="{$ReferenceDirectory}">  
 
<Property Name="LoggingBackend" Value="trace" />
 
<Using File="default"/>
<Using File="..\..\Build\bin\{$Configuration}\PostSharp.Toolkit.Diagnostics.Weaver.dll"/>
<Tasks>
   <XmlMulticast />
</Tasks>

<Data Name="XmlMulticast">
    <LogAttribute
xmlns="clr-namespace:PostSharp.Toolkit.Diagnostics;assembly:PostSharp.Toolkit.Diagnostics" />
    <LogAttribute
xmlns="clr-namespace:PostSharp.Toolkit.Diagnostics;assembly:PostSharp.Toolkit.Diagnostics"
AttributeExclude="true"
AttributeTargetMembers="regex:get_.*|set_.*" /> 
</Data>
</Project>

Let’s look at the properties more closely:

Project – the XML root node – defines the PostSharp Project configuration.

The property LoggingBackend specifies the logger that should be used by the Diagnostics Toolkit. This value is set during the installation of the toolkit via NuGet. The supported values in the PostSharp Diagnostics Toolkit package are trace (default) and console. Additional packages, PostSharp Diagnostics Toolkit for Log4Net and NLog add log4net and nlog as the supported backends.

The Using directives are a part of the plug-in model, allowing PostSharp to use external services. In this case, there are two entries (additional entries are added by other toolkits), the default, which is a required entry, and a (relative) path to the actual weaver implementation of our toolkit. At build time, PostSharp looks for project configurations in the referenced DLLs.

The Tasks section specifies a key feature of the XML configuration – the XML Multicasting. Like regular aspect multicasting, that is, the ability to apply a single aspect to multiple elements, XML Multicasting allows you to define aspect multicasting declaratively via XML. The XmlMulticast task will look for the data island with the name XmlMulticast, instantiate and apply the aspects that are specified within.

Which brings us to the actual LogAttribute aspect, that is shipped with the toolkits. This is a custom MethodLevelAspect, that is defined in the assembly PostSharp.Toolkit.Diagnostics.dll. The two entries in the XML file above define that the aspect will be applied by default to a) all methods in all types of the current assembly and b) will ignore property getters and setters. These lines are equivalent to applying the aspect on assembly level in code:

[assembly: Log] 
    
[assembly: Log(AttributeExclude="true" AttributeTargetMembers="regex:get_.*|set_.*")]

You can limit the multicasting by using the regular PostSharp filters, such as AttributeTargetTypes.

Logging Options

To control the logging level, severity and granularity of the logging, the Diagnostics toolkits include several options for fine-grained control over the logging output:

OnEntryLevel/OnSuccessLevel/OnExceptionLevel – specifies the logging level (severity) of the Entry/Exit/Exception message (e.g. “Entering: MyType.MyMethod()/Leaving: MyType.MyMethod()”)

Possible values:

  • None – the message will not be logged
  • Debug – the message will be logged at Debug/Trace level (when applicable)
  • Info – the message will be logged at Info level
  • Warning – the message will be logged at Warn level
  • Error – the message will be logged at Error level
  • Fatal – the message will be logged at Fatal level

OnEntryOptions/OnSuccessOptions – sets options for logging parameters and return values.

The options include:

  • None – no parameter information will be included
  • IncludeParameterType – includes the type name of the parameter
  • IncludeParameterName – includes the name of the parameter
  • IncludeParameterValue - Includes parameter value, by calling ToString on the object instance
  • IncludeReturnValue – includes the return value (applicable on OnSuccessOptions only)
  • IncludeThisArgument – includes the value of this argument in an instance method

The default values for the different options are:

Option Name Default Value
OnEntryLevel Debug
OnSuccessLevel Debug
OnExceptionLevel Warning
OnEntryOptions IncludeParameterType, IncludeParameterName, IncludeParameterValue
OnSuccessOptions IncludeParameterType, IncludeReturnValue
OnExceptionOptions None (exception is printed using the OnExceptionLevel severity)

Examples:

Suppose we have a method Reverse in class StringUtils, that takes in a string and returns a reversed string. With the default settings, using NLog as the backend, our call to this method with the word “orange” will be logged like this:

 

...

TRACE Entering: MyApplication.StringUtils.Reverse(System.String input = "orange")
TRACE Leaving: MyApplication.StringUtils.Reverse(System.String) : "egnaro"
...

 

In the Entering line, the method signature contains the type name (System.String), the parameter name (“input”) and its value. The Leaving line contains only the parameter type and the return value.

Let’s look at another example. Suppose you have a class Customer, implementing an Active Record pattern, located in the namespace MyApplication.Data. Suppose we want to log all calls made to methods in this namespace with the Info level, and having the value of the instance (this argument) printed in the log output together with the value of the parameters. Simply add the following line to the .psproj file:

 

<LogAttribute
    xmlns="clr-namespace:PostSharp.Toolkit.Diagnostics;assembly:PostSharp.Toolkit.Diagnostics"
    AttributeTargetTypes="MyApplication.Data.*"
    OnEntryLevel="Info"
    OnSuccessLevel="Info"
    OnEntryOptions="IncludeThisArgument | IncludeParameterValue" />

You can find additional configuration examples in the test projects of the PostSharp Diagnostics Toolkit source code.

Additional notes

In the toolkits we’re done away with manually specifying the ordering using AttributePriority – the value is now generating automatically during compilation, so be aware that ordering of the XML elements matters.

As always, we’d like to get your feedback on our Support Forums for PostSharp Toolkits! If you have suggestions, issues, or any other feedback, please let us know about it!

We hope that you’ll enjoy using the PostSharp Toolkits as much as we enjoy building them!

Happy PostSharping!

-Igal

Webinars
26 March 2012


Last Thursday, our PostSharp MVP Yan Cui joined us for an awesome webinar about how to use AOP to get near-realtime performance information from their servers running in the Amazon Cloud, using AWS CloudWatch.

The video and slides from the live webinar are now online for your viewing pleasure:

And here are the slides:

In the second part of the webinar I give a sneak peek at the PostSharp Diagnostic Toolkit. Download and install it today via NuGet, or get the source code on Github.

Happy PostSharping!

-Igal

20 March 2012


It’s not often that a bug fixes deserves a blog post, but today it happened :-(

64-bit programs (*.exe) processed by PostSharp 2.1.0.0-2.1.6.9 are unable to allocate more than 2GB of memory because of a invalid flag in the NT Header (IMAGE_FILE_32BIT_MACHINE instead of IMAGE_FILE_LARGE_ADDRESS_AWARE). Yes, just one bit.

This issue is especially nasty because generally invisible during testing. It’s only in production that a process attempts to use more memory. The program would them have terminated with an OutOfMemoryException.

Big thanks to Augustunbear Zhang for diagnosing this issue.

The issue is fixed at revision 2.1.6.10.

We recommend customers who have PostSharp-enhanced 64-bit programs (*.exe) in production to rebuild their project and redeploy them.

We sincerely apologize for the inconvenience this issue is causing. For any question or assistance, do not hesitate to contact me personally.

Happy PostSharping!

-gael

Annoucements
16 March 2012


With all the good reasons mentioned by Ayende, we decided to officially switch PostSharp 2.1 to a continuous deployment process. We are abandoning the distinction between “milestone releases” and “hotfixes”. Since today, you will know always download the latest revision from the principal download page, as well as on NuGet.

Ayende’s article came at a time when we were frustrated with our release cycle. Although we released dozens of hotfixes, the front-page download was still the initial 2.1 RTM release because we constantly deferred the SP1. Clearly, the majority of people were not downloading the best-quality release, and were therefore hitting bugs that have already been solved for a long time. Not the best user experience!

Technically, the difference is quite small. PostSharp’s build and test processes have always been automated. It takes about 50 minutes to build and test all components. Uploading to our download manager is very easy too – copy the build output to a network share and execute a script that synchronizes with Amazon S3. Therefore, the time-to-market of a bug fix has always been very short – a couple of hours, typically. The fact that deployment is now integrated with the build script does not really change this fact.

Thus, the most significant difference is that we will actually publish hotfixes as front-page downloads.

Unlike “hotfixes”, “milestone releases” got additional manual testing on virtual machines, where the later got only automated testing. Installation tests are still not automated, so there’s a slight chance to get a regression in a front-page release. We bet that these defects will be infrequent and quickly detected by the community.

Bottom line: we bet that the overall quality will be higher by switching to continuous development.

Happy PostSharping, now with a fresh version!

-gael

Toolkits
7 March 2012


We have just released an update for the PostSharp Diagnostics Toolkit – Log4Net and System.Diagnostics.Trace now join NLog and System.Console as the supported logging frameworks.

What does this mean for you? It means that you can now add logging to your application without any code changes – just by downloading a NuGet package:

  • For System.Diagnostics.Trace support:

  • For Log4Net support

  • For NLog support

We have changed the NuGet package name a bit to make it more readable, and made the version number match that of the PostSharp build the package depends upon.

As I mentioned in the previous blog post, the NuGet package creates a .psproj file in the project’s directory named after the project. This is an XML file, which contains the configuration that is processed by PostSharp during compilation. I will go into much greater detail about the XML configuration in the next blog post.

As always, the source code for the PostSharp Toolkits is available on Github. Your feedback is very appreciated – please tell us your suggestions and issues on our Support Forums for PostSharp Toolkits.

Happy PostSharping!

-Igal

Webinars
28 February 2012


Last week we were honored to have our friends at IdeaBlade join us for a very special webinar, dealing with real world AOP usage. Ward Bell, V.P. of Technology at IdeaBlade, did an excellent job of demonstrating how Aspect-Oriented Programming and PostSharp helps creating clutter-free data access, using their flagship product, DevForce.

DevForce uses PostSharp to infuse “Code First” entity model classes - entities like Customer and Order – with rich behaviors that go way beyond property change notification. You write entities with simple getters and setters; after PostSharp, they support property validation, entity navigation, lazy loading, dirty tracking, and UI data binding.

Here is the recorded webinar and the slides for your viewing pleasure! You can download the source code for the demo application and the slides from the IdeaBlade Documentation site.

Q&A

During the webinar you have asked us great questions, and, as promised, here are the answers to all of them:

Q: Does DevForce integrate with PostSharp?

A: Yes, DevForce Code First is built with PostSharp, so you don’t need a PostSharp to use it!

Q: Does any entity with a FirstName property get that clown verifier, or just Employee?

A: Just the Employee. As you can see, the type of the entity is passed into the custom verifier:

Q: Is it possible to step through the injected behaviors?

A: Yes, if you have the requisite symbol files (pdb files) loaded. It is rare to want to step through either the PostSharp or DevForce code itself, though. You’re usually debugging your own code, such as the “NoClownsVerifier”.

Q: Can you show some of the code in IdeaBlade.Aop?

A: Here is the definition for the two aspects provided by DevForce:

As you can see, it uses PostSharp’s abilities to introduce, or inject, behaviors at compile-time to the target classes, so it implements things like INotifyPropertyChanged for you in your entities automatically!

Please note that the specific behaviors we have injected may or may not be enabled when the entity is detached. For example, entity navigation properties require the EntityManager to locate the related entities in cache or query them from the database if necessary. Validation triggered by property setting requires an attached validation engine (our VerifierEngine) which is made available to the entity instance via its attached EntityManager. Accordingly, DevForce only enables these behaviors when the entity is attached. The capability has been injected, the code has been woven into the class, but the feature is turned off for detached entities.

Q: If you add your own properties to POCO class do you need to somehow tell PostSharp not to interfere with it?

A: The [Unmapped] attribute tells DevForce (and Entity Framework) that this property is NOT mapped to a column in the database and is not persisted. DevForce won’t activate the injected behaviors for such properties either (although we are considering an attribute that would tell DevForce to enable some of the behaviors for non-persistent properties in a future release).

Q: Can you provide you own base class for navigation property collections?

A: You can take over the behavior of any property, including navigation properties, via DevForce “property interceptors”, another feature that PostSharp weaves into your entity properties. Interceptors can be specified in the entity, in the base class, or in a separate property interceptor provider that DevForce will discover (we never require a base class in Code First).

Q: How do you mark a property to not have a specific aspect apply to it?

A: If this is a PostSharp question, the answer is “it’s up to how you implement your aspects.”

The DevForce aspects are applied at the class level but you can opt out at the property level with the [Unmapped] attribute. We only have two aspects (one for entities, one for complex objects) so I think what you’re asking is about opting out of one or more of the interfaces. DevForce lets you inject your own custom behavior into our interface implementations so you can do coarse grain or fine grained alterations of our implementations.

Q: How were the Employee.cs, Customer.cs and other table classes created?

A: I could have written them entirely by hand.  I found that boring so I used what we call our “Code Second” technique. I pointed the EF Designer at the database and asked it to generate code with our “Code First” T4 code generator. Then I threw away the EDMX and went to town, cleaning out anything I didn’t like in the generated entity classes. What you see is what I decided to keep.

Q: How do you convert an existing “Database First” to the code-first model?

A: You might try the Code Second technique that I described above.

Q: How is the raising change notification done on the FullName property in the Employee class?

A: I used DevForce property interception feature which is also woven into the properties via AOP. I added the following code at the bottom of the Employee class:

DevForce recognizes this as an Employee property interceptor for FirstName and LastName. The implementation raises PropertyChanged when either of those properties has finished setting its value.

We are considering the possibility of automating discovery of FullName’s dependence upon FirstName and LastName but that capability is not in this release.

Final words

We hope that you enjoyed this very special webinar! If you have any more questions about how to use PostSharp, please visit our Support Forums to have them answered. For more information about DevForce and IdeaBlade, please visit their website.

We thank Ward Bell and IdeaBlade for the wonderful presentation and the Q&A! See you all next time!

Until then,

Happy PostSharping!

-Igal

Webinars
22 February 2012


Join us on Thursday, February 23 at 9:00 AM PST | 12:00 PM EST | 5:00 PM GMT for the next PostSharp Live Webinar when our guest will be Ward Bell.

Ward is V. P. of Technology at IdeaBlade and, with over 25 years of application development experience, he champions the company's customer-focused product direction.

Due to the popular demand of last week's live webinar, we've asked Ward to join us again to show how IdeaBlade's DevForce product uses PostSharp to infuse “Code First” entity model classes - entities like Customer and Order – with rich behaviors that go way beyond property change notification.

During the webinar you will learn:

  • How IdeaBlade uses PostSharp to achieve important product goals
  • Which alternatives to PostSharp the company considered, and rejected
  • What initially worried IdeaBlade about using AOP and PostSharp
  • Where IdeaBlade is planning to go next with PostSharp

If you've ever wondered what difference AOP and PostSharp can make in real products, and want to gain insight into how it can help with your own project, be sure to watch Thursday's webinar.

Happy PostSharping!

-Britt

Toolkits, Annoucements
21 February 2012


Since its inception, PostSharp had always allowed making Aspect-Oriented Programming in .NET easy, allowing developers to produce cleaner code, encapsulating infrastructure code behind reusable modules.

We are pleased to announce today that we are making this even easier – with PostSharp Toolkits!

What are PostSharp Toolkits?

PostSharp Toolkits are a collection of ready-made solutions for adding common infrastructure code, such as logging, exception handling and performance monitoring to your application with no changes to your source code! Powered by PostSharp, the most complete AOP solution for .NET, the PostSharp Toolkits build upon the raw power of Aspect-Oriented Programming to seamlessly apply those solutions throughout your application.

Sounds interesting, how does it work?

We have great examples on how to add things like logging, tracing, and exception handling to your code. We’ve built upon this knowledge, and added things like XML-configuration, so no changes in the source code are required! Simply grab the toolkit from NuGet, and you’re all set!

What toolkits currently exist?

With the first release, we’re introducing the PostSharp Diagnostics Toolkit – an instrumentation toolkit that adds diagnostics features, such as logging, exception handling, performance counters and feature tracking to your application. The PostSharp Diagnostics Toolkit includes pluggable support for the leading logging frameworks, such as NLog. Support for additional frameworks is coming soon!

Note: As this is a work in progress, the PostSharp Diagnostics Toolkit currently only has logging support, with a very limited feature set. In the following releases, we will introduce additional configuration options, support for popular frameworks and other cool stuff!

The source code for the PostSharp Toolkits is available on GitHub, and we’re going to introduce new features based on your feedback in short release cycles.

Getting started

Here is how to add logging to your application without changing a single line of code:

Starting with a simple project:

  • Step 1: Add the PostSharp Diagnostics Toolkit from NuGet to the assembly you wish to instrument. It downloads PostSharp automatically as a dependency (please note that you need PostSharp 2.1 SP1 or higher for the PostSharp Toolkits).

  • Step 2: Rebuild your application

When you now run your application, this is what is printed in the output:

How did this happen?

The NuGet installation creates a .psproj file named after the current project in the source tree. This is an XML file, containing the configuration, which is processed by PostSharp during compilation.

The details about the XML configuration will be posted on GitHub. For now, just note that in the <Data> section there is a definition of LogAttribute. This is equivalent of placing the LogAttribute (part of the toolkit) on an assembly level in the source code, via:

[assembly: LogAttribute]

By default, it will be applied to all methods of the application. You can use the Filtering Properties to limit the multicasting. Please refer to the Online Documentation for details.

If we take a look at the compiled assembly in our favorite decompiler, we can see that the output lines were added directly in the method bodies, and no reference to PostSharp.dll is required!

What about writing the output to a file?

Glad you asked! The PostSharp Diagnostics Toolkit for NLog is exactly the solution for writing the output to NLog. Install it from NuGet, it will download all the required dependencies automatically. You will then need to configure NLog (either manually, or by downloading a NuGet package NLog.Configuration, which contains a sample configuration file for NLog). Then simply rebuild your application, and NLog will be automatically added to it!

Few notes:

The PostSharp Toolkits project is built using the PostSharp SDK. The PostSharp SDK is completely unsupported and undocumented, for the reasons detailed in this blog post. While the source code is available on GitHub, any questions pertaining to the PostSharp SDK will go unanswered.

The PostSharp Toolkits is an ongoing project, we are aiming at short (2-week) release cycles, bringing you more features based on your feedback!

Questions? Suggestions? Bugs?

Please visit our dedicated PostSharp Toolkits Support Forum to let us know what you think!

Happy PostSharping!

-Igal

Annoucements
13 February 2012


I’m happy we finally refreshed our front-page download and released PostSharp 2.1 SP 1, featuring 48 bug fixes and user stories.

All fixes were already available under the “download” section, so it’s not that anyone had to wait so long to get a solution.

This service packs solves virtually all defects that have been reported to us, most notably:

  • compatibility with Code Analysis (FxCop) – the infamous file locking issue
  • compatibility with Code Contracts (issues with debugging symbols)
  • compatibility with Silverlight 5
  • issues in PostSharp HQ when upgrading PostSharp

This makes this release a very stable one. For a list of all fixes, see the release notes.

The SP 1 contains the following new enhancements:

  • View source code enhanced by PostSharp from Visual Studio using your favorite decompiler.
  • Example code migrated to Visual Studio 2010 and cleaned up, licensing under BSD 2.0.
  • Refresh (actually, revival) of the XML project system:
    • Unification of plug-in configuration (psplugin) and project configuration (psproj).
    • Support for services that do not refer to PostSharp.Sdk.dll.
    • Support for data islands inside XML project files.
  • Adding aspects (actually, MulticastAttribute) to an XML project file – so without changing anything to source code.

The last few enhancements can appear a little cryptic to you, but they open the way to a new line of features we’ll blob about from next weeks: PostSharp Toolkits. They will make it easier to use the power of PostSharp without the difficulty of learning aspect-oriented programming.

Happy PostSharping!

-gael

Filter by APML