Newest Posts

Using ISynchronizeInvoke to update your UI safely from another Thread.

Microsoft .NET

If you are still using .NET threads to do multi-threading in your applications (compared to the Task Parallel Library or something else), then it is often a mistake of developers on how they update their UI thread. First off, stay the heck away from CheckForIllegalCrossThreadCalls. If you want your application to have unpredictable behavior, throw intermittant exceptions, and have loads of problems then go right ahead. If you want to do things right, read on.

In the early days of .NET, it was common to implement the Invoke pattern which is actually more work than needed. Most if not all WinForms controls for example implement an interface called ISynchronizeInvoke. You can use this to easily update your controls safely from another thread, in a single line of code. Here is the implementation:

namespace YourApplication {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;

    /// <summary>
    /// Helper class that allows synchronized invoking to be performed in a single line of code.
    /// </summary>
    internal static class SynchronizedInvoke {
        /// <summary>
        /// Invokes the specified action on the thread that the specified sync object was created on.
        /// </summary>
        public static void Invoke(ISynchronizeInvoke sync, Action action) {
            if (!sync.InvokeRequired) {
                action();
            }
            else {
                object[] args = new object[] { };
                sync.Invoke(action, args);
            }
        }
    }
}

This is just a helper class I usually include in all my WinForms projects as SynchronizedInvoke.cs. But the call is very simple. Let’s say you have a thread that runs a method called “ThreadWork” and you want to set the value of a progress bar you’ve named ‘uxProgressBar’ to 100 at the end of the method.

private void ThreadWork() {
    // Do some work on a thread
    SynchronizeInvoke.Invoke(uxProgressBar, () => uxProgressBar.Value = 100);
}

The key is the first parameter, also called the ‘sync’, is the object you want to invoke on, and the second is just an anonymous method (you can also specify an actual Action). There’s really nothing more to it, but you should also give a read to the article I wrote on using the Task Parallel Library titled ‘Writing thread-safe event handlers with the Task Parallel Library in .NET 4.0‘ which in my opinion is a better way to perform threaded operations and UI updates.

Writing thread-safe event handlers with the Task Parallel Library in .NET 4.0

Microsoft .NET

Download Example Code
TasksWithThreadSafeEvents.zip

In this article we will be using the following technologies:

  • .NET 4.0
  • Windows Forms (WinForms)
  • Task Parallel Library (TPL, part of .NET 4.0)

In a nutshell, I am talking about writing thread-safe events for WinForms. I’ve not ventured into the world of WPF quite yet, so this article may or may not apply to WPF.

Now, with that said, you may be familiar with the concept of BeginInvoke, EndInvoke, and Invoke to access WinForms controls safely from other threads. The amount of code to do that can be quite cumbersome, and to me it looks like speghetti. Another way to do it was by using ISynchronizeInvoke which you could wrap into a helper class, and do invoking in a single line of code. These methods all work great.

There are quite a few articles that explain how to do thread-safe and synchronized events with the Task Parallel Library, but they often are long and complicated. The other problem with the majority of these articles out there all assume one, single, horrific thing: You will always be writing your parallel code inside the form and have access to your controls other other referencable objects. Furthermore, they all seem to implement some sort of helper class that comes as an extra. In this article, my aim is a bit more specific. Take the System.Net.WebClient class for example. It exposes an event called DownloadProgressChanged. You know what is great about this? It’s thread-safe, and it doesn’t have a clue about your form or controls. That’s what this article is about. I am going to show you how to write a class with completely thread-safe events using the TPL and just a few lines of code.

The code:

//-----------------------------------------------------------------------------
// <copyright file="Counter.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace TasksWithThreadSafeEvents.Objects {
    using System;
    using System.Threading.Tasks;
    using System.Threading;

    internal class Counter {
        // CLR generated constructor

        #region Events

        /// <summary>
        /// Occurs when the counter has counted
        /// </summary>
        public event EventHandler CountChanged;
        private void OnCountChanged() {
            if (CountChanged != null) {
                CountChanged(this, new EventArgs());
            }
        }

        /// <summary>
        /// Occurs when the counter has completed counting
        /// </summary>
        public event EventHandler CountCompleted;
        private void OnCountCompleted(Task task) {
            if (CountCompleted != null) {
                CountCompleted(this, new EventArgs());
            }
        }

        #endregion

        #region Properties

        private int m_Maximum = 100;
        /// <summary>
        /// Sets the maximum value the counter will count to 
        /// </summary>
        public int Maximum {
            get {
                return m_Maximum;
            }
            set {
                m_Maximum = value;
            }
        }

        #endregion

        #region Methods

        private void Count() {
            for (int i = 0; i < Maximum; i++) {
                Thread.Sleep(50);
            }
        }

        /// <summary>
        /// Runs the counter by starting from 0 and incrementing by one, until the counter reaches its maximum
        /// </summary>
        public void Run() {
            Task.Factory.StartNew(Count).ContinueWith(OnCountCompleted);
        }

        #endregion
    }
}

I shouldn’t have to explain the code, but I will say that the main difference you will see in this event model is that OnCountCompleted defines an argument of type Task. This is because we must specify a Action<Task> when calling ContinueWith when we run our task. We don’t care about the Task object in the event handler, we just want to notify the event that it was completed, and with this approach having to pass an Action<Task> is just a small side-effect.

Often in development you want to write components like this (not specifically a counter), but essentially a class (or wrapper) that does all the work you need to, and is thread-safe at the same time. The reason we do this is we don’t want to have to make it thread-safe everywhere we use it in UI. If I have a class that does not provide thread-safe events, that means I have to write all this thread-safe code in each UI that I use it in. The class we just went over is extremely simple, so let’s wire-up the progress.

First, we need to add a TaskScheduler field to the class.

#region Fields

private TaskScheduler m_TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

#endregion

This should be pretty self-explanatory, but in a nutshell we define this at class-scope, and it creates the object on the same thread that the class is created on (of course). So essentially, when you create the Counter class somewhere in your WinForm, the TaskScheduler is created on the same thread as the form: your UI thread.

Next, we need to actually report progress in our Count() method that actually does the counting. The cool thing about the Task Parallel Library is we can do this in a single line of code.

private void Count() {
    for (int i = 0; i &lt; Maximum; i++) {         
        Thread.Sleep(50);         
            Task.Factory.StartNew(() =&gt; OnCountChanged(),
            CancellationToken.None,
            TaskCreationOptions.None,
            m_TaskScheduler)
        .Wait();
    }
}

We are simply starting a new task using the existing TaskFactory, and hooking it up to our method that invokes the event handler. We don’t need to specifiy anything special for arguments, but we need to make sure we pass in our TaskScheduler. This is important, because the task scheduler will invoke the task on the thread the task scheduler is on: the UI thread.

The second important thing is that we are calling the Wait method. The reason we are doing this is because we want to give whatever hooks up to the event time to execute their logic. For example, a progress bar to update and paint.

That’s all there is too it.. let’s use the code in a simple WinForms app with a progress bar and a button.

//-----------------------------------------------------------------------------
// <copyright file="ShellForm.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace TasksWithThreadSafeEvents.Forms {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using TasksWithThreadSafeEvents.Objects;

    public partial class ShellForm : Form {
        /// <summary>
        /// Instantiates a new instance of the TasksWithThreadSafeEvents.Forms.ShellForm class
        /// </summary>
        public ShellForm() {
            InitializeComponent();
        }

        private void OnButtonClick(object sender, EventArgs e) {
            Counter counter = new Counter();
            counter.CountChanged += OnCountChanged;
            counter.CountCompleted += OnCountCompleted;
            counter.Maximum = uxProgressBar.Maximum;
            uxProgressBar.Value = 0;
            counter.Run();
        }

        private void OnCountChanged(object sender, EventArgs e) {
            uxProgressBar.Value++;
        }

        private void OnCountCompleted(object sender, EventArgs e) {
            MessageBox.Show("The counter has reached its maximum", "Counter", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

The code looks clean, and it was very little work to implement. You could of course modify the code to actually report a value for progress if you wanted by creating your own class deriving from EventArgs, and passing the for-loop indexer to the event args of the event. I hope this helps those out there looking to write simple, thread-safe classes using the Task Parallel Library.

Download Example Code
TasksWithThreadSafeEvents.zip

Limitations of Entity Framework support with MySQL 6.4.3 Connector/Net

Microsoft .NET

I started learning the Entity Framework so I can add support for MySQL side-by-side MSSQL in FaultTrack Professional (issue tracking software I am developing), and I started to run into quite a few limitations with MySQL.

#1    DDL Generation (SSDLToMySQL.tt (VS))
The MySQL DDL Generation Template has some shortcomings. The most obvious that I ran into was max-length string fields. I had a field named ‘StackTrace’ that in MSSQL is nvarchar(MAX). Now in MySQL, the equivelent should simply be varchar(65535), but if you try to run a script to create a field you will get an error. This means that when you generate your DDL script that you have to go back and manually change it. This is because MySQL will actually expect you to use text instead of varchar(65535), and will throw an error.

#2 Guid (UNIQUEIDENTIFIER) Support
UUID() was introduced in later versions of MySQL, and moreso than that you MySQL now treats CHAR(36), BINARY(16) as guid type. The problem with this is when you start using this in your entity lambda expressions, you start to get errors thrown. Take this code example:

///<summary>
/// Returns the end result permission for the specified account and the associated Team Project. This resolves all inherited and override permissions
/// </summary>
public AccountPermissions GetTeamProjectPermission(System.Guid accountID, int collectionID, int projectID) {
    using (FaultTrackObjectContext context = new FaultTrackObjectContext(Settings.EntityConnectionString)) {
        Account account = context.Accounts.Single(a => a.ID == accountID);
        if (account.Role == AccountRoles.Administrator.ToString()) {
            return AccountPermissions.Grant;
        }
        else if (account.Role == AccountRoles.ProjectManager.ToString()) {
            return GetTeamProjectProjectManagerPermission(context, account, collectionID, projectID);
        }
        else if (account.Role == AccountRoles.Developer.ToString()) {
            return GetTeamProjectDeveloperPermission(context, account, collectionID, projectID);
        }
    }
    return AccountPermissions.Revoke;
}

Specifically notice the lambda expression a => a.ID == accountID. This line actually will throw a InvalidOperationException, “The sequence contains no elements”. I know I had exactly one matching element in the database, so I did a little debugging:

Sure enough, what I found was by expanding the results view, that I did indeed have exactly one matching element. So what the heck? The lambda expression is failing; a => a.ID == accountID resolves to false and no matching elements are found. This is because of the way that MySQL stores the Guid. Even though your DDL looks good, your SSDL mappings look great, and your code looks even better, under-the-hood the provider implementation for Guid handling is not properly done. I’ve not looked at it myself, but some other devs I have spoken with have talked about how the connector uses ConvertTo and the conversion fails. Whatever the case may be under-the-hood in the connector, it simply does not work.

What I ended up doing, which was a benefit to my software anyway, was swapping all the primary keys from Guid types to integer types. The bottom line is, Entity has a lot of shortcomings, and it works best with primitive types. Actually, the issue with primitive types deserves its own explanation.

#3 Primitive Types
I want you to take a look at this code.

private bool PermissionConflicts() {
    bool conflicts = false;
    /* required for entity queries */ int accountID = (uxAccounts.SelectedItem as Account).ID;
    /* required for entity queries */ int permission = (int)(AccountRoles)uxPermission.SelectedItem;
    /* required for entity queries */ int grantPermission = (int)AccountPermissions.Grant;
    /* required for entity queries */ int readPermission = (int)AccountPermissions.Read;
    /* required for entity queries */ int revokePermission = (int)AccountPermissions.Revoke;
    switch (m_PermissionType) {
        case PermissionType.TeamCollection:
            if (Context.TeamCollectionPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == grantPermission
                && predicate.TeamCollectionID == m_TeamCollection.ID)) {
                    if (permission == revokePermission || permission == readPermission) {
                        conflicts = true;
                    }
            }
            if (Context.TeamCollectionPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == readPermission
                && predicate.TeamCollectionID == m_TeamCollection.ID)) {
                if (permission == grantPermission || permission == revokePermission) {
                    conflicts = true;
                }
            }
            if (Context.TeamCollectionPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == revokePermission
                && predicate.TeamCollectionID == m_TeamCollection.ID)) {
                    if (permission == grantPermission || permission == readPermission) {
                    conflicts = true;
                }
            }
            break;
        case PermissionType.TeamProject:
            if (Context.TeamProjectPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == grantPermission
                && predicate.TeamProjectID == m_TeamProject.ID)) {
                    if (permission == revokePermission || permission == readPermission) {
                        conflicts = true;
                    }
            }
            if (Context.TeamProjectPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == readPermission
                && predicate.TeamProjectID == m_TeamProject.ID)) {
                if (permission == grantPermission || permission == revokePermission) {
                    conflicts = true;
                }
            }
            if (Context.TeamProjectPermissions.Any(predicate => predicate.AccountID == accountID
                && permission == revokePermission
                && predicate.TeamProjectID == m_TeamProject.ID)) {
                    if (permission == grantPermission || permission == readPermission) {
                    conflicts = true;
                }
            }
            break;
    }
    return conflicts;
}

Specifically, this:

predicate =>
       predicate.AccountID == accountID
    && permission == grantPermission
    && predicate.TeamCollectionID == m_TeamCollection.ID

In this lambda expression, we are operating on primitive types. This is fine, but when you are dealing with non-primitive types, the provider (not just MySQL’s provider), cannot properly convert the non-primitive types into primitive types, and the conversion fails, thus throwing an exception.

Prior to moving to Entity when the software was built on DLinq (Linq to SQL), the lamda was easily expressible:

predicate =>
    predicate.Account == uxAccounts.SelectedItem as Account
    && (AccountPermissions)predicate.Permission == AccountPermissions.Grant
    && predicate.TeamCollectionID == m_TeamCollection.ID

Unfortunately you cannot do that with Entity (hopefully I can use the term ‘yet’). I may write more on the Entity Framework; I am still learning it and it has a lot of potential. Most everything seems to have some workaround, but these were some of the annoyances I ran into that made me think twice about adding support for MySQL. Not everyone has access to an MSSQL Engine and MySQL is the other popular choice among others, so it really is a must.

The myth of misusage of the var keyword since C# 3.0

Microsoft .NET

C# 3.0 introduced a new keyword, var. The var keyword allows you to utilize type inference at compile time which is a really cool feature. Here’s an extremely basic example.

var message = "Hello World";

This should be self-explanatory: The compiler will resolve the local variable ‘message’ to be of type ‘string’, which is inferred by the value in the assignment statement. This is pretty cool, but it was never meant to change the C# specification or rid of using strongly typed names. The optimal usage of the var keyword is when you are dealing with Anonymous Types, and Generics. It was actually introduced along with the release of Linq in C# 3.0 which deals with these two language features quite often.

There are other scenarios where var is useful though, take this statement:

List<KeyValuePair<AccountRoles[], ToolStripMenuItem>> m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

That is a pretty knarly declaration and assignment statement, and this is a scenario where the var keyword would actually be recommended to improve readability to:

var m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

This also benefits the language outside the scope of the compiler. You can easily see that the first sample causes the syntax highlighter on this page to have to scroll – so for programming books, reference material, and blogs like this var has its use outside the realm of actual C# programs.

Bad: When the type is not obvious.

var doc = Factory.GetDocument(); // What is doc?

Good: When the type is obvious.

var text = new StringBuilder(); // We easily can see it is inferred to StringBuilder

The truth is, you can come up with more good examples of when to use var, then when not to use it. Another example would be refactoring. Say you have the following.

List<Order> orders = Factory.GetOrders();

Later down the road if the return type of Factory.GetOrders() were to change, you would have to go refactor every declaration that uses that method. However with var, you would not have had to done this if you used var in the first place.

var is pretty controversial, but the general consensus from the experts is its not as bad as everyone thinks.

Dangers of the public access modifier.

Microsoft .NET

Did you know that the public access modifer in C# is essentially the equivalent to extern in C++? According to the C# 4.0 language specification, it is.

People need to be careful with the public keyword. public in C# is not equivalent to public in C++! In C++, it means “internal to my compilation unit.” In C#, it means what extern meant in C++ (i.e., everybody can call it). This is a huge difference!

This was best said by Krzysztof Cwalina, quoted in the revised Fourth Edition of The C# Programming Language. It actually makes more sense to me know when I browse the .NET Framework source code as to why I see Microsoft using internal access modifiers quite a bit more often. If you are rusty and don’t quite remember the access modifiers they are:

public
Access not limited.

protected
Access limited to this class or classes derived from this class.

internal
Access limited to this program.

protected internal
Access limited to this program or classes derived from this class.

private
Access limited to this class.

But remember, as Christian Nagel said it best, that internal is rather best described as being “access limited to this assembly”, because a program can be defined as a collection of executables and assemblies, and a class marked as internal cannot be accessed by an assembly referencing it.

Why abstraction can be detrimental.

Microsoft .NET

The other day someone asked a question about the relation between the Socket class, and the UdpClient class. Specifically, what is the relation? While the answer is simple because UdpClient is merely wrapper around a UDP initialized socket, this also lead me to thinking more about abstraction.

So what is abstraction?
Take the following code sample.

XDocument xdoc = XDocument.Load(ConfigurationFilePath);
string boolstr = xdoc
    .Element("ApplicationConfiguration")
        .Element("Settings")
            .Element("AutoLogin")
            .Attribute("Enabled")
            .Value;
return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);

Imagine if you had to write that every time you wanted to retrieve a value in a configurationfile. That’s a lot of replicated code. In it’s simplist form, a C# Property is a form of abstraction – it hides the underlying implementation. Functions can also be considered abstraction. So, in essence we could do the following.

/// <summary>
/// Gets or sets a System.Boolean value indicating whether automatic login is enabled
/// </summary>
public static bool AutoLoginEnabled {
    get {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        string boolstr = xdoc
            .Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value;
        return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);
    }
    set {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        xdoc.Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value = value ? Boolean.TrueString : Boolean.FalseString;
        xdoc.Save(ConfigurationFilePath);
    }
}

So what happened here? We took a segment of code and wrapped in a C# Property, hiding the underlying implementation. This is called abstraction. So now we can easily just call SomeClass.AutoLoginEnabled = true, and the Property takes care of the dirty work underneath. Now this is obviously a very basic concept of abstraction. Generally, real-world abstraction in program code means asbtracting base classes, services, and other really complex things, but the idea here to understand the basic concept of abstraction.

How this relates to UdpClient and Socket
I always thought the Socket class was easy enough, but I often find that quite a few people prefer to use UdpClient or TcpClient, because they feel that it is easier to work with. This may be the case, but even the Socket class is a layer of abstraction as it is a wrapper around the Berkeley socket interface.

C# makes abstraction easy to do. It’s plain and simple. The reason this is dangerous though, is because often times developers create so many layers of abstraction, that it is often hard for either Jr. Developers or new people to the code to learn what is going on. I often find that many beginners in programming can understand the fundamentals of the code they are using. So in this case a beginner programmer may learn the UdpClient class inside-and-out, but in the end, they may not have a single clue about how that class is actually implemented, what goes on underneath, and how network programming is actually done.

In short, absraction is a good thing – when you also take the time to learn and understand the underlying implementations. However, you can definitely see how this can act negatively on a developer’s understanding of program code.