[WPF] Prevent the user from pasting an image in a RichTextBox

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

WPF’s RichTextBox control is quite powerful, and very handy if you need to accept rich text input. However, one of its features can become an issue: the user can paste an image. Depending on what you intend to do with the text entered by the user, you might not want that.

When I googled for a way to prevent that, the only solutions I found suggested to intercept the Ctrl-V keystroke, and swallow the event if the clipboard contains an image. There are several issues with this approach:

  • it doesn’t prevent the user from pasting using the context menu
  • it won’t work if the command’s shortcut has been changed
  • it doesn’t prevent the user from inserting an image using drag and drop

Since I wasn’t satisfied with this solution, I used the .NET Framework Reference Source website to look for a way to intercept the paste operation itself. I followed the code from the ApplicationCommands.Paste property, and eventually found the DataObject.Pasting attached event. It’s not a place where I had thought to look, but when you think about it, it actually makes sense. This event can be used to intercept a paste or drag and drop operation, and lets the hander do a few things:

  • cancel the operation completely
  • change which data format will be pasted from the clipboard
  • replace the DataObject used in the paste operation

In my case, I just wanted to prevent an image from being pasted or drag and dropped, so I just cancelled the operation when the FormatToApply was "Bitmap", as shown below.

XAML:

<RichTextBox DataObject.Pasting="RichTextBox1_Pasting" ... />

Code-behind:

private void RichTextBox1_Pasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.FormatToApply == "Bitmap")
    {
        e.CancelCommand();
    }
}

Of course, it’s also possible to handle this in a smarter way. For instance, if the DataObject contains several formats, we could create a new DataObject with only the acceptable formats. This way the user is still able to paste something, if not the image.

Posted in WPF. Tags: , , , , . No Comments »

Weak events in C#, take two

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

A few years ago, I blogged about a generic implementation of the weak event pattern in C#. The goal was to mitigate the memory leaks associated with events when you forget to unsubscribe. The implementation was based on the use of weak references to the subscribers, to allow them to be garbage collected.

My initial solution was more a proof of concept than anything else, and had a major performance issue, due to the use of DynamicInvoke every time the event was raised. Over the years, I revisited the weak event problem several times and came up with various solutions, improving a little every time, and I now have an implementation that should be good enough for most use cases. The public API is similar to that of my first solution. Basically, instead of writing an event like this:

public event EventHandler<MyEventArgs> MyEvent;

You write it like this:

private readonly WeakEventSource<MyEventArgs> _myEventSource = new WeakEventSource<MyEventArgs>();
public event EventHandler<MyEventArgs> MyEvent
{
    add { _myEventSource.Subscribe(value); }
    remove { _myEventSource.Unsubscribe(value); }
}

From the subscriber’s point of view, this is no different from a normal event, but the subscriber will be eligible to garbage collection if it’s not referenced anywhere else.

The event publisher can raise the event like this:

_myEventSource.Raise(this, e);

There is a small limitation: the signature of the event has to be EventHandler<TEventArgs> (with any TEventArgs you like, of course). It can’t be something like FooEventHandler, or a custom delegate type. I don’t think this is a major issue, because the vast majority of events in the .NET world follow the recommended pattern void (sender, args), and specific delegate types like FooEventHandler actually have the same signature as EventHandler<FooEventArgs>. I initially tried to make a solution that could work with any delegate signature, but it turned out to be too much of a challenge… for now at least Winking smile.

 

How does it work

This new solution is still based on weak references, but changes the way the target method is called. Rather than using DynamicInvoke, it creates an open-instance delegate for the method when the weak handler is subscribed. What this means is that for an event signature like void EventHandler(object sender, EventArgs e),  it creates a delegate with the signature void OpenEventHandler(object target, object sender, EventArgs e). The extra target parameter represents the instance on which the method is called. To invoke the handler, we just need to get the target from the weak reference, and if it’s still alive,  pass it to the open-instance delegate.

For better performance, this delegate is created only the first time a given handler method is encountered, and is cached for later reuse. This way, if multiple instances of an object subscribe to an event using the same handler method, the delegate is only created the first time, and is reused for subsequent subscribers.

Note that technically, the created delegate is not a “real” open-instance delegate such as those created with Delegate.CreateDelegate. Instead it is created using Linq expressions. The reason is that in a real open-instance delegate, the type of the first parameter must be the type that declares the method, rather than object. Since this information isn’t known statically, I have to dynamically introduce a cast.

 

You can find the source code on GitHub: WeakEvent. A NuGet package is available here: ThomasLevesque.WeakEvent.

The repository also include code snippets for Visual Studio and ReSharper, to make it easier to write the boilerplate code for a weak event.

C# Puzzle 2

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

Just another little puzzle based on an issue I had at work…

Consider this piece of code :

Console.WriteLine($"x > y is {x > y}");
Console.WriteLine($"!(x <= y) is {!(x <= y)}");

How would you declare and initialize x and y for the program to produce the following, apparently illogical, output?

x > y is False
!(x <= y) is True
Posted in Puzzles. Tags: , . 2 Comments »

How to retrieve dates as UTC in SQLite

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

SQLite is a nice in-process database engine: it’s very lightweight, doesn’t require any server or configuration, and runs on all platforms. There is even an official ADO.NET provider that’s very well made. However, if you store dates as UTC with this provider, you will probably encounter a serious issue: even though the date is properly stored as UTC (it’s stored in a form similar to ISO8601, with a ‘Z’ to indicate the UTC timezone), when you read it back from the database, you will get a DateTime converted to local time, with Kind = Unspecified. Here’s an example that exhibits the problem (using Dapper in LINQPad):

void Main()
{
    string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db";
    using (var connection = new SQLiteConnection(connectionString))
    {
        connection.Open();
        connection.Execute("create table Foo(Id integer not null primary key, CreationDateUtc datetime not null)");
        
        var foo = new Foo{Id = 42, CreationDateUtc = DateTime.UtcNow};
        foo.Dump("Original object");
        connection.Execute("insert into Foo(Id, CreationDateUtc) values (@Id, @CreationDateUtc)", foo);
        var foo2 = connection.Query<Foo>("select * from Foo where Id = @Id", new{ Id = 42 }).SingleOrDefault();
        foo2.Dump("After reading from DB");
    }
}

class Foo
{
    public int Id { get; set; }
    public DateTime CreationDateUtc { get; set; }
    public DateTimeKind Kind { get { return CreationDateUtc.Kind; } }
}

Here’s the output:

image

As you can see, after reading it from the database, the date is no longer in UTC, and doesn’t even contain an indication that it’s a local date. This can cause all kinds of bugs if your code is comparing dates that are supposed to be UTC.

I initially tried to fix that in my code by manually converting the date, before I realized that the solution was much simpler (although not very well documented): there is a connection string setting to control how dates are handled. You just need to specify DateTimeKind=Utc in your connection string:

string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db;DateTimeKind=Utc";

If you’re using SqliteConnectionStringBuilder to build the connection string, just set the DateTimeKind property to DateTimeKind.Utc.

As you can see, the date kind is now preserved:

image

 

Important caveat: this setting will apply to all dates read from this connection. If you have dates that were not stored as UTC, the provider will assume that they are UTC dates anyway, which will produce incorrect results. So, only do this if you store all dates as UTC.

Exception filters in C# 6: their biggest advantage is not what you think

Very poorPoorAverageGoodExcellent (3 votes) 
Loading...Loading...

Exception filters are one of the major new features of C# 6. They take advantage of a CLR feature that was there from the start, but wasn’t used in C# until now. They allow you to specify a condition on a catch block:

static void Main()
{
    try
    {
        Foo.DoSomethingThatMightFail(null);
    }
    catch (MyException ex) when (ex.Code == 42)
    {
        Console.WriteLine("Error 42 occurred");
    }
}

As you might expect, the catch block will be entered if and only if ex.Code == 42. If the condition is not verified, the exception will bubble up the stack until it’s caught somewhere else or terminates the process.

At first glance, this feature doesn’t seem to bring anything really new. After all, it has always been possible to do this:

static void Main()
{
    try
    {
        Foo.DoSomethingThatMightFail(null);
    }
    catch (MyException ex)
    {
        if (ex.Code == 42)
            Console.WriteLine("Error 42 occurred");
        else
            throw;
    }
}

Since this piece of code is equivalent to the previous one, exception filters are just syntactic sugar, aren’t they? I mean, they are equivalent, right?

WRONG!

Stack unwinding

There is actually a subtle but important difference: exception filters don’t unwind the stack. OK, but what does that mean?

When you enter a catch block, the stack is unwound: this means that the stack frames for the method calls “deeper” than the current method are dropped. This implies that all information about current execution state in those stack frames is lost, making it harder to identify the root cause of the exception.

Let’s assume that DoSomethingThatMightFail throws a MyException with the code 123, and the debugger is configured to break only on uncaught exceptions.

  • In the code that doesn’t use exception filters, the catch block is always entered (based on the type of the exception), and the stack is immediately unwound. Since the exception doesn’t satisfy the condition, it is rethrown. So the debugger will break on the throw; in the catch block; no information on the execution state of the DoSomethingThatMightFail method will be available. In other words, we won’t know what was going on in the method that threw the exception.
  • In the code with exception filters, on the other hand, the filter won’t match, so the catch block won’t be entered at all, and the stack won’t be unwound. The debugger will break in the DoSomethingThatMightFail method, making it easy to see what was going on when the exception was thrown.

Of course, when you’re debugging directly in Visual Studio, you can configure the debugger to break as soon as an exception is thrown, whether it’s caught or not. But you don’t always have that luxury; for instance, if you’re debugging an application in production, you often have just a crash dump to work with, so the fact that the stack wasn’t unwound becomes very useful, since it lets you see what was going on in the method that threw the exception.

Stack vs. stack trace

You may have noticed that I talked about the stack, not the stack trace. Even though it’s common to refer to “the stack” when we mean “the stack trace”, they’re not the same thing. The call stack is a piece of memory allocated to the thread, that contains information for each method call: return address, arguments, and local variables. The stack trace is just a string that contains the names of the methods currently on the call stack (and the location in those methods, if debug symbols are available). The Exception.StackTrace property contains the stack trace as it was when the exception was thrown, and is not affected when the stack is unwound; if you rethrow the same exception with throw;, it is left untouched. It is only overwritten if you rethrow the exception with throw ex;. The stack itself, on the other hand, is unwound when a catch block is entered, as discussed above.

Side effects

It’s interesting to note that an exception filter can contain any expression that returns a bool (well, almost… you can’t use await, for instance). It can be an inline condition, a property, a method call, etc. Technically, there’s nothing to prevent you from causing side effects in the exception filter. In most cases, I would strongly advise against doing that, as it can cause very confusing behavior; it can become really hard to understand the order in which things are executed. However, there is a common scenario that could benefit from side effects in exception filters: logging. You could easily create a method that logs the exception and returns false so that the catch block is not entered. This would allow logging exceptions on the fly without actually catching them, hence without unwinding the stack:

try
{
    DoSomethingThatMightFail(s);
}
catch (Exception ex) when (Log(ex, "An error occurred"))
{
    // this catch block will never be reached
}

...

static bool Log(Exception ex, string message, params object[] args)
{
    Debug.Print(message, args);
    return false;
}

Conclusion

As you can see, exception filters are not just syntactic sugar. Contrary to most C# 6 features, they’re not really a “coding” feature (in that they don’t make the code significantly clearer), but rather a “debugging” feature. Correctly understood and used, they can make it much easier to diagnose problems in your code.

Create an auto-mocking container with Unity and FakeItEasy

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

Unit testing can be tedious sometimes, especially when testing classes that have complex dependencies. Fortunately, some tools make it somewhat easier. I’ve been using FakeItEasy a lot recently; it’s a very easy to use mocking framework for .NET. It has a very lean and simple API based on generics and lambda expressions, and is a real pleasure to work with. It came as a breath of fresh air compared to the old RhinoMocks I had been using before.

But as nice as FakeItEasy is, the process of registering all the fake dependencies for the class you are testing is still a bit tedious. Wouldn’t it be nice if the IoC container could automatically create the fakes on demand ? So this code:

var container = new UnityContainer();

// Setup dependencies
var fooProvider = A.Fake<IFooProvider>();
container.RegisterInstance(fooProvider);
var barService = A.Fake<IBarService>();
container.RegisterInstance(barService);
var bazManager = A.Fake<IBazManager>();
container.RegisterInstance(bazManager);

var sut = container.Resolve<SystemUnderTest>();

Could be reduced to this:

var container = new UnityContainer();

// This will cause the container to provide fakes for all dependencies
container.AddNewExtension<AutoFakeExtension>();

var sut = container.Resolve<SystemUnderTest>();

Well, it’s actually pretty easy to do with Unity. Unity is usually not considered the “cool kid” in the small world of IoC containers, but it’s well supported, easy to use, and extensible. I came up with the following extension to enable the above scenario:

public class AutoFakeExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Strategies.AddNew<AutoFakeBuilderStrategy>(UnityBuildStage.PreCreation);
    }
    
    private class AutoFakeBuilderStrategy : BuilderStrategy
    {
        private static readonly MethodInfo _fakeGenericDefinition;
    
        static AutoFakeBuilderStrategy()
        {
            _fakeGenericDefinition = typeof(A).GetMethod("Fake", Type.EmptyTypes);
        }
        
        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.Existing == null)
            {
                var type = context.BuildKey.Type;
                if (type.IsInterface || type.IsAbstract)
                {
                    var fakeMethod = _fakeGenericDefinition.MakeGenericMethod(type);
                    var fake = fakeMethod.Invoke(null, new object[0]);
                    context.PersistentPolicies.Set<ILifetimePolicy>(new ContainerControlledLifetimeManager(), context.BuildKey);
                    context.Existing = fake;
                    context.BuildComplete = true;
                }
            }
            base.PreBuildUp(context);
        }
    }
}

A few comments on this code:

  • The logic is a bit crude (it generates fakes only for interfaces and abstract classes), but can easily be adjusted if necessary.
  • The ugly reflection hack is due to the fact that FakeItEasy doesn’t have an non-generic overload of A.Fake that accepts a Type as a parameter. Well, nobody’s perfect…
  • The lifetime is set to “container controlled”, because if you need to configure method calls, you will need to access the same instance that is injected into the system under test:
var fooProvider = container.Resolve<IFooProvider>();
A.CallTo(() => fooProvider.GetFoo(42)).Returns(new Foo { Id = 42, Name = “test” });

Note that if you register a dependency explicitly, it will take precedence and no fake will be created. So you can use this extension and still be able to manually specify a dependency:

var container = new UnityContainer();
container.AddNewExtension<AutoFakeExtension>();
container.RegisterType<IFooProvider, TestFooProvider>();
var sut = container.Resolve<SystemUnderTest>();

Of course, this extension could easily be modified to use a different mocking framework. I guess the same principle could be applied to other IoC containers as well, as long as they have suitable extension points.

What about AutoFixture?

Before you ask: yes, I know about AutoFixture. It’s a pretty good library, and I actually tried to use it as well, with some success. The resulting code is very similar to the examples above. The main reason why I didn’t keep using it is that AutoFixture is not really an IoC container (though it does some of the things an IoC container does), and I prefer to use the same IoC mechanism in my unit tests and in the actual application. Also, I’m not very comfortable with the way it handles properties when creating an instance of the SUT. By default, it sets all public writable properties to dummy instances of their type; this is fine if those properties are used for dependency injection, but IMO it doesn’t make sense for other properties. I know I can suppress this behavior for specific properties, but I have to do it manually on a case by case basis; it doesn’t take IoC container specific attributes like [Dependency] into account. So eventually I found it easier to use my custom Unity extension.

Async and cancellation support for wait handles

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

The .NET framework comes with a number of low-level synchronization primitives. The most commonly used are collectively known as “wait handles”, and inherit the WaitHandle class: Semaphore, Mutex, AutoResetEvent and ManualResetEvent. These classes have been there since at least .NET 2.0 (1.1 for some of them), but they haven’t evolved much since they were introduced, which means they don’t support common features that were introduced later. In particular, they don’t provide support for waiting asynchronously, nor do they support cancelling the wait. Fortunately, it’s actually quite easy to add these features via extension methods.

Cancellation

Let’s start with the easiest one: cancellation. There are cases where it would be useful to pass a CancellationToken to WaitHandle.WaitOne, but none of the overloads supports it. Note that some more recent variants of the synchronization primitives, such as SemaphoreSlim and ManualResetEventSlim, do support cancellation; however, they’re not necessarily suitable for all use cases, because they’re designed for when the wait times are expected to be very short.

A CancellationToken exposes a WaitHandle, which is signaled when cancellation is requested. We can take advantage of this to implement a cancellable wait on a wait handle:

    public static bool WaitOne(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
    {
        int n = WaitHandle.WaitAny(new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout);
        switch (n)
        {
            case WaitHandle.WaitTimeout:
                return false;
            case 0:
                return true;
            default:
                cancellationToken.ThrowIfCancellationRequested();
                return false; // never reached
        }
    }

We use WaitHandle.WaitAny to wait for either the original wait handle or the cancellation token’s wait handle to be signaled. WaitAny returns the index of the first wait handle that was signaled, or WaitHandle.WaitTimeout if a timeout occurred before any of the wait handles was signaled. So we can have 3 possible outcomes:

  • a timeout occurred: we return false (like the standard WaitOne method);
  • the original wait handle is signaled first: we return true (like the standard WaitOne method);
  • the cancellation token’s wait handle is signaled first: we throw an OperationCancelledException.

    For completeness, let’s add some overloads for common use cases:

        public static bool WaitOne(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOne(Timeout.Infinite, cancellationToken);
        }
    

    And that’s it, we now have a cancellable WaitOne method!

    Asynchronous wait

    Now, what about asynchronous wait? That’s a bit harder. What we want here is a WaitOneAsync method that returns a Task<bool> (and since we’re at it, we might as well include cancellation support). The typical approach to create a Task wrapper for a non-task-based asynchronous operation is to use a TaskCompletionSource<T>, so that’s what we’ll do. When the wait handle is signaled, we’ll set the task’s result to true; if a timeout occurs, we’ll set it to false; and if the cancellation token is signaled, we’ll mark the task as cancelled.

    I struggled a bit to find a way to execute a delegate when a wait handle is signaled, but I eventually found the ThreadPool.RegisterWaitForSingleObject method, which exists for this exact purpose. I’m not sure why it’s in the ThreadPool class; I think it would have made more sense to put it in the WaitHandle class, but I assume there’s a good reason.

    So here’s what we’ll do:

  • create a TaskCompletionSource<bool>;
  • register a delegate to set the result to true when the wait handle is signaled, or false if a timeout occurs, using ThreadPool.RegisterWaitForSingleObject;
  • register a delegate to mark the task as cancelled when the cancellation token is signaled, using CancellationToken.Register;
  • unregister both delegates after the task completes

    Here’s the implementation:

        public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
        {
            RegisteredWaitHandle registeredHandle = null;
            CancellationTokenRegistration tokenRegistration = default(CancellationTokenRegistration);
            try
            {
                var tcs = new TaskCompletionSource<bool>();
                registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                    handle,
                    (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
                    tcs,
                    millisecondsTimeout,
                    true);
                tokenRegistration = cancellationToken.Register(
                    state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
                    tcs);
                return await tcs.Task;
            }
            finally
            {
                if (registeredHandle != null)
                    registeredHandle.Unregister(null);
                tokenRegistration.Dispose();
            }
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);
        }
    

    Note that the lambda expressions could have used the tcs variable directly; this would make the code more readable, but it would cause a closure to be created, so as a small performance optimization, tcs is passed as the state parameter.

    We can now use the WaitOneAsync method like this:

    var mre = new ManualResetEvent(false);
    …
    if (await mre.WaitOneAsync(2000, cancellationToken))
    {
        …
    }
    

    Important note: this method will not work for a Mutex, because it relies on RegisterWaitForSingleObject, which is documented to work only on wait handles other than Mutex.

    Conclusion

    We saw that with just a few extension methods, we made the standard synchronization primitives much more usable in typical modern code involving asynchrony and cancellation. However, I can hardly finish this post without mentioning Stephen Cleary’s AsyncEx library; it’s a rich toolbox which offers async-friendly versions of most standard primitives, some of which will let you achieve the same result as the code above. I encourage you to have a look at it, there’s plenty of good stuff in it.

  • Posted in Code sample. Tags: , , . 4 Comments »

    Leveraging ReSharper annotations

    Very poorPoorAverageGoodExcellent (No Ratings Yet) 
    Loading...Loading...

    I don’t think it’s really necessary to present ReSharper (often abbreviated R#), but in case you don’t know about it, it’s a tool made by JetBrains that performs real-time analysis of your C# or VB.NET code to warn you about possible bugs, bad practices, convention violations, etc. It also provides many useful refactorings and code generators. I’ve been using it for a few years now, and it has tremendously improved both my productivity and my coding style.

    Among other things, R# warns you about incorrect usage of .NET Framework methods. For instance, if you’re calling Path.GetFullPath with a path that might be null, it gives you a warning:

    image

    How does R# know that Path.GetFullName doesn’t accept a null argument? And how does it know that Console.ReadLine can return null? I guess it could have been hard-coded, but it wouldn’t be a very elegant approach, and wouldn’t allow easy extensibility… Instead, ReSharper uses external annotations. These are XML files that are shipped with R# and contain a lot of metadata about .NET framework classes and methods. This data is then used by the analyzer to detect possible issues with your code.

    OK, but what about third-party libraries? Obviously, JetBrains can’t create annotations for those, there are too many. Well, the good news is that you can write your own external annotations for libraries that you use, or for your own code. However, for your own code, there is a much more convenient alternative: you can apply the annotations directly in your code as attributes. There are two ways to get those attributes:

    • Reference the assembly where they are defined (JetBrains.Annotations.dll in the R# installation directory). This is fine if you don’t mind having a reference to something that has nothing to do with your application. That’s probably not a good idea for libraries.
    • Declare the attributes in your own code. You don’t actually have to write them yourself, because R# has an option to copy their implementation to the clipboard, as shown below. You just paste it to a code file in your project.

    image

    Now that you have the attributes, how do you use them? I’ll show a few examples for the most common annotations.

    NotNull

    This annotation indicates that the element on which it is applied cannot, or must not be null.

    If you apply it to a method or property, it means that the method or property will never return null:

            [NotNull]
            public string GetString()
            {
                return "Hello world!";
            }
    

    When a method has this attribute, if you test if the return value is null (or not null), R# will warn you that the condition is always false (or true):

    image

     

    If you apply it to a method parameter, it means that null is not a valid argument value:

            public string Repeat([NotNull] string s)
            {
                if (s == null) throw new ArgumentNullException("s");
                return s + s;
            }
    

    If R# determines that the value passed for s can be null, it warns you about it, as shown in the first example.

    This annotation can be added automatically using ReSharper’s quick-fix menu. The “Not null” option will just add the annotation; the “Check parameter for null” option will add a check and the annotation:

    image

    image

     

    CanBeNull

    This is the opposite of NotNull. Applied to a method or property, it means that the method or property can return a null value. Applied to a method parameter, it means that the argument value is allowed to be null.

    Pure

    This one is very useful. Applied to a method, it means that the method is pure. A pure method has no observable side effect, so if you don’t use the return value of the method, the call is useless, so it’s probably a mistake. Typical example with String.Replace:

    image

     

    StringFormatMethod

    This annotation indicates that a method works like the String.Format method, i.e. it takes a composite format string followed by arguments that will replace the placeholders in the format string:

            [StringFormatMethod("format")]
            public static void Log(string format, params object[] args)
            {
                ...
            }
    

    It lets R# warn you if the placeholders and arguments don’t match:

    image

    UsedImplicitly

    This one tells ReSharper that a code element is used, even though R# cannot statically detect it. It has the effect of suppressing the “(…) is never used” warning. It’s useful, for instance, when a type or member is used only via reflection.

    NoEnumeration

    This annotation is applied to an IEnumerable parameter, and means that the method will not enumerate the sequence. R# warns you when you enumerate an IEnumerable multiple times, so using this attribute prevents false positives for this warning:

            public static IEnumerable<T> EmptyIfNull<T>([NoEnumeration] this IEnumerable<T> source)
            {
                return source ?? Enumerable.Empty<T>();
            }
    

     

    InstantHandle

    This one is applied to a delegate parameter, and means that the delegate will be executed during the execution of the method. It prevents the “Access to modified closure” warning that occurs when a lambda captures a variable that is later modified.

    ContractAnnotation

    This annotation is a powerful way to describe how the output of a method depends on its inputs. It lets R# predict how the method will behave. For instance, this method will return null if its argument is null, an not null otherwise:

            [ContractAnnotation("null => null; notnull => notnull")]
            public object Transform(object data)
            {
                ...
            }
    

    Thanks to the annotation, ReSharper will know that if the argument was not null, the result will not be null either.

    This method doesn’t return normally (it throws an exception) if its argument is null:

            [ContractAnnotation("value:null => halt")]
            public static void CheckArgumentNull<T>(
                [NoEnumeration] this T value,
                [InvokerParameterName] string paramName)
                where T : class
            {
                if (value == null)
                    throw new ArgumentNullException(paramName);
            }
    

    This lets R# know that if you pass a null to this method, the code following the call will never be reached; if it is reached, the value can be assumed to be not null.

    LocalizationRequired

    This annotation means that a property or method parameter should be localized; if you pass a hard-coded string, R# will warn you and suggest to extract it to a resource file.

    image11

    Conclusion

    Now, you might be wondering, “why should I go through the trouble of adding all those annotations to my code?”. The reason is simple: it helps ReSharper help you! By giving it more information about your code, you allow R# to give you better advice and produce less false positives. Also, if you’re a library author, it makes your library more comfortable to use for ReSharper users. I use R# annotations extensively in my Linq.Extras library, so it’s a good place to find more examples.

    Note that I only described a small part of the available annotations. There are many more, mostly related to ASP.NET-specific scenarios. You can see them all in the annotations file generated by ReSharper, or in the documentation (which isn’t quite complete, but is still useful).

    C# Puzzle 1

    Very poorPoorAverageGoodExcellent (6 votes) 
    Loading...Loading...

    I love to solve C# puzzles; I think it’s a great way to gain a deep understanding of the language. And besides, it’s fun!

    I just came up with this one:

    static void Test(out int x, out int y)
    {
        x = 42;
        y = 123;
        Console.WriteLine (x == y);
    }
    

    What do you think this code prints? Can you be sure? Post your answer in the comments!

    I’ll try to post more puzzles in the future if I can come up with others.

    Posted in Puzzles. Tags: , . 12 Comments »

    Customizing string interpolation in C# 6

    Very poorPoorAverageGoodExcellent (3 votes) 
    Loading...Loading...

    One of the major new features in C# 6 is string interpolation, which allows you to write things like this:

    string text = $"{p.Name} was born on {p.DateOfBirth:D}";
    

    A lesser known aspect of this feature is that an interpolated string can be treated either as a String, or as an IFormattable, depending on the context. When it is converted to an IFormattable, it constructs a FormattableString object that implements the interface and exposes:

    • the format string with the placeholders (“holes”) replaced by numbers (compatible with String.Format)
    • the values for the placeholders

    The ToString() method of this object just calls String.Format(format, values). But there is also an overload that accepts an IFormatProvider, and this is where things get interesting, because it makes it possible to customize how the values are formatted. It might not be immediately obvious why this is useful, so let me give you a few examples…

    Specifying the culture

    During the design of the string interpolation feature, there was a lot of debate on whether to use the current culture or the invariant culture to format the values; there were good arguments on both sides, but eventually it was decided to use the current culture, for consistency with String.Format and similar APIs that use composite formatting. Using the current culture makes sense when you’re using string interpolation to build strings to be displayed in the user interface; but there are also scenarios where you want to build strings that will be consumed by an API or protocol (URLs, SQL queries…), and in those cases you usually want to use the invariant culture.

    C# 6 provides an easy way to do that, by taking advantage of the conversion to IFormattable. You just need to create a method like this:

    static string Invariant(FormattableString formattable)
    {
        return formattable.ToString(CultureInfo.InvariantCulture);
    }
    

    And you can then use it as follows:

    string text = Invariant($"{p.Name} was born on {p.DateOfBirth:D}");
    

    The values in the interpolated strings will now be formatted with the invariant culture, rather than the default culture.

    Building URLs

    Here’s a more advanced example. String interpolation is a convenient way to build URLs, but if you include arbitrary strings in a URL, you need to be careful to URL-encode them. A custom string interpolator can do that for you; you just need to create a custom IFormatProvider that will take care of encoding the values. The implementation was not obvious at first, but after some trial and error I came up with this:

    class UrlFormatProvider : IFormatProvider
    {
        private readonly UrlFormatter _formatter = new UrlFormatter();
    
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return _formatter;
            return null;
        }
    
        class UrlFormatter : ICustomFormatter
        {
            public string Format(string format, object arg, IFormatProvider formatProvider)
            {
                if (arg == null)
                    return string.Empty;
                if (format == "r")
                    return arg.ToString();
                return Uri.EscapeDataString(arg.ToString());
            }
        }
    }
    

    You can use the formatter like this:

    static string Url(FormattableString formattable)
    {
        return formattable.ToString(new UrlFormatProvider());
    }
    
    ...
    
    string url = Url($"http://foobar/item/{id}/{name}");
    

    It will correctly encode the values of id and name so that the resulting URL only contains valid characters.

    Aside: Did you notice the if (format == "r")? It’s a custom format specifier to indicate that the value should not be encoded (“r” stands for “raw”). To use it you just include it in the format string like this: {id:r}. This will prevent the encoding of id.

    Building SQL queries

    You can do something similar for SQL queries. Of course, it’s a known bad practice to embed values directly in the query, for security and performance reasons (you should use parameterized queries instead); but for “quick and dirty” developments it can still be useful. And anyway, it’s a good illustration for the feature. When embedding values in a SQL queries, you should:

    • enclose strings in single quotes, and escape single quotes inside the strings by doubling them
    • format dates according to what the DBMS expects (typically MM/dd/yyyy)
    • format numbers using the invariant culture
    • replace null values with the NULL literal

    (there are probably other things to take care of, but these are the most obvious).

    We can use the same approach as for URLs and create a SqlFormatProvider:

    class SqlFormatProvider : IFormatProvider
    {
        private readonly SqlFormatter _formatter = new SqlFormatter();
    
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return _formatter;
            return null;
        }
    
        class SqlFormatter : ICustomFormatter
        {
            public string Format(string format, object arg, IFormatProvider formatProvider)
            {
                if (arg == null)
                    return "NULL";
                if (arg is string)
                    return "'" + ((string)arg).Replace("'", "''") + "'";
                if (arg is DateTime)
                    return "'" + ((DateTime)arg).ToString("MM/dd/yyyy") + "'";
                if (arg is IFormattable)
                    return ((IFormattable)arg).ToString(format, CultureInfo.InvariantCulture);
                return arg.ToString();
            }
        }
    }
    

    You can then use the formatter like this:

    static string Sql(FormattableString formattable)
    {
        return formattable.ToString(new SqlFormatProvider());
    }
    
    ...
    
    string sql = Sql($"insert into items(id, name, creationDate) values({id}, {name}, {DateTime.Now})");
    

    This will take care of properly formatting the values to produce a valid SQL query.

    Using string interpolation when targeting older versions of .NET

    As is often the case for language features that leverage .NET framework types, you can use this feature with older versions of the framework that don’t have the FormattableString class; you just have to create the class yourself in the appropriate namespace. Actually, there are two classes to implement: FormattableString and FormattableStringFactory. Jon Skeet was apparently in a hurry to try this, and he has already provided an example with the code for these classes:

    using System;
    
    namespace System.Runtime.CompilerServices
    {
        public class FormattableStringFactory
        {
            public static FormattableString Create(string messageFormat, params object[] args)
            {
                return new FormattableString(messageFormat, args);
            }
    
            public static FormattableString Create(string messageFormat, DateTime bad, params object[] args)
            {
                var realArgs = new object[args.Length + 1];
                realArgs[0] = "Please don't use DateTime";
                Array.Copy(args, 0, realArgs, 1, args.Length);
                return new FormattableString(messageFormat, realArgs);
            }
        }
    }
    
    namespace System
    {
        public class FormattableString
        {
            private readonly string messageFormat;
            private readonly object[] args;
    
            public FormattableString(string messageFormat, object[] args)
            {
                this.messageFormat = messageFormat;
                this.args = args;
            }
            public override string ToString()
            {
                return string.Format(messageFormat, args);
            }
        }
    }
    

    This is the same approach that made it possible to use Linq when targeting .NET 2 (LinqBridge) or caller info attributes when targeting .NET 4 or earlier. Of course, it still requires the C# 6 compiler to work…

    Conclusion

    The conversion of interpolated strings to IFormattable had been mentioned previously, but it wasn’t implemented until recently; the just released CTP 6 of Visual Studio 2015 ships with a new version of the compiler that includes this feature, so you can now go ahead and use it. This feature makes string interpolation very flexible, and I’m sure people will come up with many other use cases that I didn’t think of.

    You can find the code for the examples above on GitHub.

    css.php