Mostrar mensagens com a etiqueta C#. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta C#. Mostrar todas as mensagens

8.04.2011

Redistributing user controls

Ever needed a recipe to build a user control library to use across several web applications? Here's one!
First of all, we should realise that this isn't something you can get out-of-the-box and as such, there are several half-solutions out there, and as far as I know there isn't a perfect one. The one I'm presenting here suits best for what I'm trying to achieve, and it doesn't mean it is the best for other people's situation.

My main motivation, other than user control reusability was to create a project structure that allowed me to migrate a webapplication developed in VB.NET to C#. This has to be done over a long-period and I don't want to keep adding code in VB.NET any time a new feature is needed. Hence I decided to build user controls in C# that I could use in VB.NET pages, thus avoiding any code-behind code in VB.NET.

There is however a big problem with creating user controls outside web applications: We're not supposed to do it! When you build a page (aspx) or a user control (ascx) in a regular web application, the compiler creates an assembly where each of this files produces a class that inherits from our "code-behind" class. This class is where some of the magic happens. When we create a user control outside the web application where the user control is being used the afore-mentioned classes don't exist. So how do we cope with this? We'll create a base class for all our user controls and we inject some magic in it as well! This base class will be responsible for:
  - manually loading the ascx file and parse it to dynamically create the elements/controls present in the ascx.
  - "binding" these elements/controls to the members that represent them in the code-behind class (this members are usually present in the designer file)
Here's the code to such a base class:


And here's the rest of my recipe:

1- Create new asp.net web application project. This makes sure we can create new user controls directly through the "new item" dialog, which would not be possible if we were to create a regular class library project.
  1.1- Clear all the files that visual studio placed inside the new project (leave only the AssemblyInfo.cs)

2- Creating user controls in your new project
  2.1 - Add a new "Web User Control" item to your project
  2.2 - Design your control as you always do
  2.3 - Open the designer files and copy the declaration of controls you'll want to access later on to the code-behind class. (You can also keep the designer files as partial classes to your code-behind class, but there's not much point in it as visual studio won't be able to update it later on)
  2.4 - Delete the designer files (unless you've decided to keep it as a partial class)
  2.5 - The control header (in the ascx file) should be cleaned to keep only the Language attribute, thus leaving only the following header:

  2.6 - Change the ascx file build action from "Content" to "Embedded Resource"
  2.7 - Change the control base class from "UserControl" to our own "BaseUserControl"

3- Using the user controls in your web application
  3.1 - Reference the new project in our old web application
  3.2 - Change the web.config to avoid registering the control in every page you'll use it:


Alternatively you could register the control in in the pages you want to use it by adding the following line:


And we're done! Here's a list of the issues found with this solution (so far):
- Couldn't get the control skins to work with my user controls
- Local and Global Resources are currently in the web application (instead of being properly encapsulated in the user controls that uses them), as asp.net loads them from the page, not the user control. There are at least two workarounds for this. We could create a resource provider and resolve the resources manually or we could use resources like we do in a regular winforms application, instead of using the local/global resources asp.net approach.

That's all folks!

2.16.2011

Test INotifyPropertyChanged Pattern implementations

Today, I'll cover a well known topic: different implementations of the INotifyPropertyChanged interface (henceforth referred to as INPC). Its most common use is when you're implementing the MVVM pattern. This interface makes sure that your viewmodel properties update the binded interface components when you change the property value. So, with so many WPF and silverlight applications out there, it's a well known interface and you probably also know that it's regular implementation is somewhat boring and extensively verbose! That's why there are so many different alternatives out there. I decided to collect a few and test them for performance.
The main motivation was to validate the suspected performance penalty of implementations based on expression trees. So I'm pitting this kind of implementation against the most common and basic implementation, two AOP (see http://en.wikipedia.org/wiki/Aspect-oriented_programming) implementations (one using IL weaving and another using a dynamic proxy) and the usage of dependency properties. Dependency properties may seem a little out of place, but they are one of the common alternatives to using the INotifyPropertyChanged.

The main reasons to research for different INPC implementations (the aforementioned boringness and verbosity) should obviously be taken into account. Most developers don't like that they can't use the simpler syntax of automatic properties if the want to use INPC.
It's not my objective to discuss the advantages and disadvantages of each, as you can find easily find several articles that delve deep into that subject. However, there are a few points we should keep in mind when choosing the kind of implementation to use. 
A perfectly good example are the disadvantages of using dependency properties: the need of inheriting from DependencyObject and the fact that these properties can't be changed from non-UI dispatcher threads. These may be two show-stoppers depending on your situation. The first also applies to the usage of expression trees. If your viewmodels are depending on some kind of ViewModelBase class then, that's not much of a fuss, but if you wish to achieve some kind of Naked MVVM implementation (see http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx) than you can't rely on a base class. Anyway, if you can avoid it, there's no need to burn your base class (see http://www.artima.com/intv/dotnet.html). 

On the other hand, most AOP approaches only make sense if you're using an IOC container to resolve your viewmodels. This is due to the fact that you can't instantiate your viewmodel class directly, you'll need to call a method that creates a proxy (where the INPC is injected) for your viewmodel. One of the AOP approaches (the one using PostSharp) we're using here avoids this by injecting the INPC in your class in a post-build action through IL weaving (see http://www.sharpcrafters.com/aop.net/msil-injection).

The Test

The test is pretty simple. Each of the implementations resides in a separate class which has the integer property (conveniently named "Property") we'll be using in the test. This property will be assigned 200.000 times in a cycle and we'll be controlling the time it takes for this cycle to complete. We'll also make sure that the PropertyChanged event is handled by an event handler that does absolutely nothing (we just want to measure the event handler invocation time, not the time the event handler takes to execute, so we're making it as simple as possible).

Example source for a specific test:


I've shown the example of the PostSharp implementation because the AOP test implementations require you to add the event handler through reflection, as the event doesn't exist at compile time. That's the only difference from the non-AOP implementations. Notice that you won't need to do this in real-life applications because you won't be registering explicitly the PropertyChanged event, that's the job of the framework's binding mechanism.
Also note that in the Castle Dynamic Proxy implementation, the instantiation of the test class would be replaced by a call to create the proxy (which, as stated above, would not be visible if we were using an IOC container to resolve the class)
Example:


Test Results


Implementations
Here's the code to the implementations used in the test, which by the way, I'm not claiming ownership for, I've just gathered and altered them slightly where needed.
Common INPC implementation (which I'm calling the "Plain old" way)



Expression Trees implementation

Dependency Properties implementation

PostSharp AOP implementation

Castle Dynamic Proxy AOP implementation



Conclusions
After this, I think it's safe to conclude that the Expression trees implementation implies a severe performance penalty and although it's far simpler than the "Plain old" way of doing it, it still loses in simplicity when compared to the AOP implementations. That said, I should say that I've always been a fan of PostSharp and I currently consider it to be the best way of implementing INPC, although it is a payed tool.

1.19.2011

Stack Walking

Have you ever needed to determine who's calling your methods or merely needed to inspect the call stack?

There's a fairly simple way of doing it by using the StackTrace class. I'll show you an usage example.
First, let's start by creating a small class that creates a stack of 3 method calls just so that we have some to call stack to look into.
This should do it:



Now, let's call Method1 and hook up an event handler that will gather the stack trace and print some information about each stack frame.


You should pay special attention to the boolean parameter of the StackTrace constructor. It defines if file information should be gathered (the file, line and column of the method being called). As we'll see below, gathering this information incurs in a performance penalty! Also, these values will likely be absent from a release build, as it is built without debug symbols.

You may be wondering about the performance of such a feature. I've made some testing and got back the values below. Note that these tests are merely indicative. My laptop had dozens of applications running that could interfere with the processor availability. Anyway, each value from the results below is the best out of three attempts and the average values for a single execution are consistent. Also, for the testing purposes, the Console.WriteLine instructions were removed.
These tests were made using a Debug version of the application.
The graph above shows the time it takes to run several executions of the ShowStackTrace method. The same tests were made with and without gathering file information. As you can see, there is a substantial difference.
The graph below shows the average time of a single execution.
As you can see, a single run, without file information takes in average 0.05 milliseconds! On a debug build! That seems pretty darn fast. It might be interesting to point out that this is the same way that exceptions gather their stack trace.

I wonder how this times stack up against the times achieved in a stack walk using the dbghelp.dll library. Maybe on a future blog post...

12.10.2010

.NET Encryption - Part 3

Now, for the third and last part of this series (first and second parts can be found here and here) about encryption. I've promised before that I would supply example source code for previously mentioned encryption operations. That's what this post is all about. The source below shows how to perform each of these operations with a handful of source code lines. The only thing covered here that I haven't mentioned before is how to derive algorithm keys (which are arrays of bytes) from a string, typically a password or a pass-phrase. That's covered in the first few lines and you should pay special attention to it, because it is something you'll need plenty of times.


Hope you've enjoyed this cryptography sessions.

3.11.2010

WPF Treeview bound to an xml file monitored for changes

Here's a code snippet of a WPF treeview binding to a xml file, which gets reloaded everytime the xml file is physically changed.

The sample xml file I'm using (located at "C:\data.xml"):


The XAML code:


And finally the C# code-behind code for the same window that monitors the xml file changes and updates the binding accordingly:

3.09.2010

Integrating MEF with a K-means algorithm implementation

When we're interested about a new framework and we want to try it out we usually start by creating a small and simple demo application. Afterwards we start thinking in real-life situations where we could use it. Here, I'll describe my first real-life use of MEF.
I have a small application with a custom implementation of the K-means clustering algorithm. Common implementations of this algorithm attempt to find clusters of points. The cluster points are related by the distance between themselves. In my custom implementation, the points are persons and the "distance" is in fact computed by evaluating a series of constraints. 
Each of these constraints is a distinct class, implementing an IConstraint interface. 
Until know I had the following initialization code for constraints:

Then I had the following code to evaluate the constraints:

Note: In here the "distance" between persons is what I call "concordance rate". The bigger the concordance rate, the "closer" the member is to the cluster.
A few days ago, I had to create a new constraint and when I saw that initialization code and "TODO" comment I decided it was time to change it. After careful thought, I decided MEF was the correct choice. With MEF, I managed to replace this tedious initialization code while reducing the coupling between the concrete constraints and the constraint evaluator.
I've just opened all the Constraint classes and added the attribute [Export(typeof(IConstraint))] like this:

Then I've instructed the ConstraintList property to import all the IConstraints. This is done by marking the property with the attribute [ImportMany(typeof(IConstraint))]. Like this:

Last but not least, I had to instruct the class to compose the constraint list. Like this:

Note that I'm using the using an AssemblyCatalog with the executing assembly on purpose, because I want to load the constraints from the current assembly. If I were to move all the Constraints to another assembly (eg: a separate "Contracts" or "Constraints" assembly) this code would be different.
There you go, just a simple refactoring that allowed me to reduce coupling and remove a TODO comment from my code! And I got to use MEF in a real scenario.

3.01.2010

Lazy Loading

Today, I'll discuss one simple class that comes bundled with .NET 4.0. It's one of those small features that don't get much attention, but that truly come in handy. In this case, I'm talking about System.Lazy<T>. It's a simple class that provides support for lazy loading, so we no longer need to do those small pieces of code we've been doing throughout the years, whenever we had to deal with resources whose creation revealed to be expensive.

It's a simple class with a simple purpose, therefore it has a very simple usage, which I'll show in the small snippet below.


The code above will produce the following output:
Before bird creation
Creating Bird
I am a Duck
Before eagle creation
Creating Eagle
I am a Eagle



Notice that the Bird class is only instantiated when "bird.Value" and "eagle.Value" are accessed.
In the example above, I've shown:
- the usage of Lazy<T> in a way that instantiation will be done through a call to the default constructor
- the usage of Lazy<T> with a delegate responsible for the creation itself. This delegate will of course only be called at instantiation time (when the Lazy<T> Value property is accessed)

There are also other Lazy<T> constructors that provide further options regarding thread safety, which I will not discuss here.

2.17.2010

Quick and Dirty Logging

Ever felt the need to quickly implement logging in your application but you don't want to loose time learning/remembering how to use a true logging framework or creating your own utility logging class?
There are some developers who tend to bring their own utility classes in their backpack just in case they stumble upon one of these situations. Most of us however, don't keep track of the utility classes we've written throughout the years or tend to loose that code. So last time it happened to me, I've written this "Quick and Dirty Logging" class using a TraceListener.



Usage examples:



Implementation Details 
Note that I've decided to break the debugger whenever I stumble with an error or warning as long as the assembly is compiled in debug mode. I made this decision because at the time I wanted to be able to fix the errors using the "Edit and Continue" visual studio feature thus shortening the debug-stop-rebuild-restart cycle and saving some time. This code is not supposed to be a production code, but that won't be a problem as long as you make sure you don't deploy debug assemblies anywhere other than a developer machine.

Also as we're using the System.Diagnostics.Trace features, make sure you have tracing enabled in your project (the TRACE compilation symbol needs to be defined), which is the default for visual studio C# projects.

Remember that there are logging frameworks far more customizable and faster than this small logging class. This isn't supposed to replace any other logging mechanism, it's just a quick solution empowered by its simplicity.

Conclusion
Next time I feel the urge to create a quick logging mechanism I'll try to remember this post and gather this code. But then again, when that happens, I'm pretty much sure Murphy's Law will make sure I won't get internet access. Probably the proxy will die on me while I'm opening the browser!