Skip to content

Clarius Consulting
Syndicate content
Clarius Bloggers
Updated: 40 min 58 sec ago

MVP 2010

Fri, 07/02/2010 - 01:48

Today I received the confirmation email. I am a MVP again for Visual C#.

I want to thank my MVP lead Fernando Garcia Loera and the rest of people involved in the evaluation process for the recognition of my community efforts.

 

Thanks Microsoft!!!

Pablo

Categories: Companies

How to install Visual Studio 2010 Search References and Pro Power Tools side by side

Wed, 06/09/2010 - 15:52

The new Visual Studio 2010 Pro Power Tools bring a new Add Reference dialog that completely replaces the classic one when you click the familiar Add Reference command:

image

It seems like a nice dialog that is more aligned with the new Add New dialog and the Extension Manager one. But for this particular case, I believe it's awfully overkill (what's the use of that right sidebar? what's the use for the categories of assemblies split between Framework and Extensions?).

The (also new) Search References extension which I blogged about earlier, gives you the familiar classic dialog enhanced with the must-have Search capability:

image[10]

This dialog has a few key usability features that make it a snap to use (and better than the Pro Power Tools one, I think): it will open up focused on the search textbox, it will remember your last search, and it supports keyboard-only usage extensively (i.e., type "entity", down-arrow to enter the filtered list, shift or control multi-select, press Enter and done!). Also, as you're already used to, double clicking on a reference also directly adds it and dismisses the dialog (in the Pro Power Tools you need to close the dialog explicitly).

 

If you want to continue using this familiar, lightweight and simpler dialog, but still want to install the Pro Power Tools, you can easily disable its "Add Reference" dialog by going to your %LocalAppData%\Microsoft\VisualStudio\10.0\Extensions\Microsoft\Visual Studio 2010 Pro Power Tools folder, and deleting the AddReference.dll and AddReference.pkgdef files.

 

Enjoy!

Categories: Companies

Add References with Search

Wed, 06/09/2010 - 15:08

If you have been using VS2010 for any significant amount of time, you surely came across the awkward, slow and hard to use Add Reference dialog. Despite some (apparent) improvements over the VS2008 behavior, in its current form it's even LESS usable than before. A brief non-exhaustive summary of the typical grief with this dialog is:

  1. Scrolling a list of *hundreds* of entries? (300+ typically)
  2. No partial matching when typing: yes, you can type in the list to get to the desired entry, but the matching is performed in an exact manner, from the beginning of the assembly name. So, to get to the (say) "Microsoft.VisualStudio.Settings" assembly, you actually have to type the first two segments in their entirety before starting to type "Settings".
  3. Lazy loading with no progress indicator: loading is done asynchronously in VS2010, supposedly improving the situation from VS2008 where it would just freeze until it was done. Well, without an indicator, you don't know when loading is done and when it's safe to assume a given assembly isn't there because it is truly not available.
  4. Random order while lazy loading: moreover, while the lazy loading is happening (and you don't know when it's done), entries in the list are added in an almost random order, so any scrolling or typing you do results in constant repositioning of the current selection and changes to the underlying list. This makes it effectively impossible to use the dialog until the lazy loading is completed.
  5. No sorting while lazy loading: related to the previous one, you cannot sort the list at all until the lazy loading is complete, so scrolling is impossible.

 

So we decided to do something about it. I introduce you to the Search References extension:

image[5]

From the Extension Manager in Visual Studio 2010, you can simply search the Online Gallery for "Search Reference" and install it right-away:

image

The dialog loads VERY fast. And because a picture speaks a thousand words, here are more screenshots to get you excited.

Partial matching:

image[10]

Multi-selection:

image[18]

Current project .NET profile aware. Silverlight 4:

 image[23]

Silverlight 3:

image[28]

 

Enjoy, and don't forget to rate it!

Categories: Companies

MEF, IServiceProvider and Testing Visual Studio Extensions

Wed, 06/09/2010 - 00:42

In the latest and greatest version of Visual Studio, MEF plays a critical role, one that makes extending VS much more fun than it ever was.

So typically, you just [Export] something, and then someone [Import]s it and that's it. MEF in all its glory kicks in and gets all your dependencies satisfied.

Cool, you say, so let's now import ITextTemplating and have some T4-based codegen going! Ah, if only it was that easy. Turns out by default, none of the VS built-in services are exposed to MEF, apparently because there wasn't enough time to analyze the lifetime, initialization, dependencies, etc. for each one before launch, which makes perfect sense. You don't want to blindly export everything now just in case. There's also the whole VS package initialization thing which in this version of VS is not so transparently integrated with the MEF publishing side (i.e. a MEF export from a package can get instantiated before its owning package, and in fact, the package can remain unloaded forever and the export will continue to be visible to anyone).

So, you just have to calm down, and re-encounter "good"-old IServiceProvider. Turns out, that's still the "blessed" way to get your dependencies, but now you can get the service provider from MEF instead:

[ImportingConstructor]
public TextTemplate([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)

Note that in typical VS fashion, the actual exported contract (interface) is SVsServiceProvider, which can be converted automatically to an IServiceProvider.

But, if you make your entire class just work off of this service locator (doing GetService here and there), you lose all the "explicit-ness" that comes from having a proper constructor that declares that this class needs, say, an ITextTemplating. This makes it much harder for consumers attempting to reuse the implementation to figure out what this component needs.

Fortunately, MEF does not require your importing constructors to be public, so you can provide the MEF-exclusive constructor as internal, and make the constructor with your explicit dependencies public:

[ImportingConstructor]
private TextTemplate([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
    : this(serviceProvider.GetService<STextTemplating, ITextTemplating>())
{
}

public TextTemplate(ITextTemplating templating)
{
    Guard.NotNull(() => templating, templating);

    this.templating = templating;
}

Your tests will also instantiate this class exclusively from the non-MEF constructor, and pass moqs as needed. (note I'm using a simple generic GetService extension method on IServiceProvider to make code more concise).

 

/kzu

Categories: Companies

A really simple ViewModel base class with strongly-typed INotifyPropertyChanged

Fri, 05/14/2010 - 13:03

I have already written about other alternative ways of implementing INotifyPropertyChanged, as well as augment your view models with a bit of automatic code generation for the same purpose. But for some co-workers, either one seemed a bit too much :o).

So, back on the drawing board, we came up with the following view model authoring experience:

public class MyViewModel : ViewModel, IExplicitInterface
{
    private int value;

    public int Value
    {
        get { return value; }
        set { this.value = value; RaiseChanged(() => this.Value); }
    }

    double IExplicitInterface.DoubleValue
    {
        get { return value; }
        set { this.value = (int)value; RaiseChanged(() => ((IExplicitInterface)this).DoubleValue); }
    }
}

You can see how raising property changed on a property is just a matter of passing an expression like "this.PropertyName" to the base RaiseChanged method. This is 100% refactoring friendly. No magic strings.

Also, we support raising a property changed for an interface that you implemented explicitly, like the second case.

The base class defines the RaiseChanged method as follows:

protected void RaiseChanged<TProperty>(Expression<Func<TProperty>> propertyExpresion)

Note how the TProperty type parameter can be completely omitted from the call to RaiseChanged() from the derived class, letting the compiler figure it out. The expression, being anything matching a Func<T>, could conceivable be an invalid reference to a property the object does not own, so we validate that in the method body by inspecting the expression tree:

protected void RaiseChanged<TProperty>(Expression<Func<TProperty>> propertyExpresion)
{
    var property = propertyExpresion.Body as MemberExpression;
    if (property == null || !(property.Member is PropertyInfo) ||
        !IsPropertyOfThis(property))
    {
        throw new ArgumentException(string.Format(
            CultureInfo.CurrentCulture,
            "Expression must be of the form 'this.PropertyName'. Invalid expression '{0}'.",
            propertyExpresion), "propertyBLOCKED EXPRESSION;
    }

    this.OnPropertyChanged(property.Member.Name);
}

We first ensure the expression references a member and that the member is actually a property. Next, the IsPropertyOfThis method verifies that the target of that property access is actually a reference to "this". This is kinda cool:

private bool IsPropertyOfThis(MemberExpression property)
{
    var constant = RemoveCast(property.Expression) as ConstantExpression;
    return constant != null && constant.Value == this;
}

We just look for a constant expression and compare its value to "this" :). For the explicitly implemented property case, there will be a cast before the reference to "this", so we remove it if necessary to get access to the constant:

private Expression RemoveCast(Expression expression)
{
    if (expression.NodeType == ExpressionType.Convert ||
        expression.NodeType == ExpressionType.ConvertChecked)
        return ((UnaryExpression)expression).Operand;

    return expression;
}

All in all, a fairly simple base class with a tiny bit of strong-typed help for raising notify property changed events for view models.

Next, we'll augment it with knowledge of IDataErrorInfo and System.ComponentModel.DataAnnotations attributes.

Full ViewModel class code available.

 

Enjoy!

Categories: Companies

Crazy Linq: performing System.ComponentModel.DataAnnotations validation in a single statement

Thu, 04/15/2010 - 18:08
public static IEnumerable<ValidationResult> Validate(object component)
{
    return from descriptor in TypeDescriptor.GetProperties(component).Cast<PropertyDescriptor>()
            from validation in descriptor.Attributes.OfType<System.ComponentModel.DataAnnotations.ValidationAttribute>()
            where !validation.IsValid(descriptor.GetValue(component))
            select new ValidationResult(
                validation.ErrorMessage ?? string.Format(CultureInfo.CurrentUICulture, "{0} validation failed.", validation.GetType().Name),
                new[] { descriptor.Name });
}

Enjoy!

Categories: Companies