C#/.NET

Writings about C# 4.0 and the .NET Framework.

Microsoft .NET

Subscribing to DWebBrowserEvents2::FileDownload from WinForms WebBrowser control through the Dynamic Language Runtime (DLR).

0

I will come back and add more detail to this blog at a later date, but I was helping on MSDN forums and wrote this neat example for someone. It uses the dynamic language runtime and C# 4.0 to take advantage of some of the events exposed by COM through the ActiveXInstance of the WebBrowser control. It intercepts the file download dialog when it detects you downloading an exe file and cancels the download.

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 System.Diagnostics;
using System.Reflection;

namespace WindowsFormsApplication12 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            webBrowser1.Url = new Uri("http://www.dcomproductions.com/products/faulttrack");
        }

        /// <summary>
        /// Fires before navigation occurs in the given object (on either a window or frameset element).
        /// </summary>
        /// <param name="pDisp">Object that evaluates to the top level or frame WebBrowser object corresponding to the navigation.</param>
        /// <param name="url">String expression that evaluates to the URL to which the browser is navigating.</param>
        /// <param name="Flags">Reserved. Set to zero.</param>
        /// <param name="TargetFrameName">String expression that evaluates to the name of the frame in which the resource will be displayed, or Null if no named frame is targeted for the resource.</param>
        /// <param name="PostData">Data to send to the server if the HTTP POST transaction is being used.</param>
        /// <param name="Headers">Value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code.</param>
        /// <param name="Cancel">Boolean value that the container can set to True to cancel the navigation operation, or to False to allow it to proceed.</param>
        private delegate void BeforeNavigate2(object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel);

        /// <summary>
        /// Fires to indicate that a file download is about to occur. If a file download dialog box can be displayed, this event fires prior to the appearance of the dialog box.
        /// </summary>
        /// <param name="bActiveDocument">A Boolean that specifies whether the file is an Active Document.</param>
        /// <param name="bCancel">A Boolean that specifies whether to continue the download process and display the download dialog box.</param>
        private delegate void FileDownload(bool bActiveDocument, ref bool bCancel);

        protected override void OnLoad(EventArgs e) {
            dynamic d = webBrowser1.ActiveXInstance;
            string uri = string.Empty;

            d.BeforeNavigate2 += new BeforeNavigate2((object pDisp,
                ref dynamic url,
                ref dynamic Flags,
                ref dynamic TargetFrameName,
                ref dynamic PostData,
                ref dynamic Headers,
                ref bool Cancel) => {

                uri = url.ToString();
                Trace.WriteLine(uri);
            });

            d.FileDownload += new FileDownload((bool bActiveDocument, ref bool bCancel) => {
                bool isFile = uri.EndsWith("exe");

                if (isFile) {
                    bCancel = true;
                    Trace.Write("Canceled a file download from the DLR.");
                }
            });
        }
    }
}
Microsoft .NET

Embedding referenced assemblies as an Embedded Resource, and resolving dependencies at runtime.

2

This was inspired by this question on StackOverflow. First off, this is bad design unless you are designing some sort of setup application. But, specifically for those who still wish to proceed, here is how you do it.

Download Example Code
EmbeddedReferenceApplication.zip

In this example, there are two projects. ‘EmbeddedReferenceApplication.exe’ and ‘EmbeddedReference.dll’. Here are the steps.

  1. Add a hard reference to EmbeddedReference.dll from EmbeddedReferenceApplication.exe
  2. Go to the reference Properties, and set Copy Local = False
  3. Right click your project and add the referenced assembly as a link (Add As Link)
  4. Right click the linked assembly in your project, and set its build output to ‘Embedded Resource’
  5. Modify your code with proper manifest name handling/resolution
  6. See the example code or post comments for more help
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using EmbeddedReference;

namespace EmbeddedReferenceApplication {
    class Program {
        static void Main(string[] args) {
            AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve;
            MyMain();
        }

        private static void MyMain() {
            EmbeddedReference.MessageHelper.ShowMessage();
        }

        private static Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
            string manifestResourceName = "EmbeddedReferenceApplication.EmbeddedReference.dll"; // You can also do Assembly.GetExecutingAssembly().GetManifestResourceNames();
            string path = Path.Combine(Application.StartupPath, manifestResourceName.Replace("EmbeddedReferenceApplication.", ""));
            ExtractEmbeddedAssembly(manifestResourceName, path);
            Assembly resolvedAssembly = Assembly.LoadFile(path);
            return resolvedAssembly;
        }

        private static void ExtractEmbeddedAssembly(string manifestResourceName, string path) {
            Assembly assembly = Assembly.GetExecutingAssembly();
            using (Stream stream = assembly.GetManifestResourceStream(manifestResourceName)) {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                using (FileStream fstream = new FileStream(path, FileMode.Create)) {
                    fstream.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }
}

What this does is subscribes to AssemblyResolve and allows the application domain to resolve your assembly to a custom path – in our case, we resolve to the application directory but we are extracting the assembly first, and returning the resolved assembly. You can use this same code to resolve dependencies and assemblies from custom directories and paths.

A key note is lines 12 and 13. You must not use any code directly in the Main method that would otherwise reference a dependency. What this causes is for your exception to be thrown while Main is compiled, and before it is run. You will never give the application domain a chance to perform dependency resolution. However, a quick fix is to throw it into a helper method called MyMain (call it SubMain or something similar), that would not otherwise reference the dependency until its invoked.

Microsoft .NET

Adding extension method support for .NET 2.0

0

.NET Framework 2.0 does not support extension methods out of the box, because you cannot reference System.Core that was introduced in .NET 3.5. However, by adding a simple attribute class you can use extension methods in .NET 2.0 as well. Here is the snippet.

namespace System.Runtime.CompilerServices {
    /// <summary>
    /// Mimics the .NET 3.5 extension methods attribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    internal sealed class ExtensionAttribute : System.Attribute {
        /// <summary>
        /// Instantiates a new instance of the ExtensionAttribute class
        /// </summary>
        public ExtensionAttribute()
            : base() {
        }
    }
}

Here is an example afterwards using extension methods in one of our applications.

namespace Setup.AppCode {
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Text;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// Extension methods class
    /// </summary>
    public static class ExtensionMethods {

        public static void DisableAllLinks(this LinkLabel control) {
            foreach (LinkLabel.Link link in control.Links) {
                link.Enabled = false;
            }
        }

        public static void EnableAllLinks(this LinkLabel control) {
            foreach (LinkLabel.Link link in control.Links) {
                link.Enabled = true;
            }
        }

    }
}

And don’t forget to import the namespace that contains your extension methods where you will need them so they appear correctly.

Microsoft .NET

N-Tier Architecture Best Practices, Part 2: 3-Tier Architecture with interfaces and a Data Tier

1

N-Tier Architecture Best Practices, Part 1: 2-Tier Architecture with just a Data Tier
N-Tier Architecture Best Practices, Part 2: 3-Tier Architecture with interfaces and a Data Tierthis article
N-Tier Architecture Best Practices, Part 3: DLinq / Linq to SQL
N-Tier Architecture Best Practices, Part 4: Entity Framework
N-Tier Architecture Best Practices, Part 5: Unity Framework

Download the Source Code for this Article
N-Tier Architecture (3-Tier)

In the previous article I covered 2-Tier Architecture with just a presentation layer and a data tier. In this article, I will show you how to expand this into a 3-tier architecture that will allow you to utilize your data tier with flexibility. You will need to download the source code from the previous article for this example, because I will be expanding upon it. You should already be very familiar with the code before proceeding.

Now let’s say you wanted to add a library to the project to handle all the rules of the business. This might be something like making sure that all employees in the company have valid pay rates and salaries. So we add a new Class Library project and call it NTier.BusinessRules along with a class called EmploymentValidation.

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

namespace NTier.BusinessRules {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Validates employees to ensure their profiles meet business rules and standards
    /// </summary>
    public static class EmploymentValidation {
        /// <summary>
        /// Validates the specified pay rate
        /// </summary>
        public static bool ValidatePayrate(float rate) {
            if (rate < 0f) {
                return false;
            }
            return true;
        }
    }
}

Now this is great, because in NTier.Data.DataTier we can validate the employee’s payrate in AddEmployee and UpdateEmployee. So let’s add a reference to NTier.BusinessRules from NTier.Data and add our validation. Note that I will use an elipse ( … ) to represent sections of code we are not changing to help condense this post.

Changes to NTier.Data.DataTier.cs

namespace NTier.Data {
    using System;
    using System.Collections.Generic;
    using System.Data.SqlServerCe;
    using NTier.Data.Objects;
    using NTier.BusinessRules;
    ...
}
public static bool AddEmployee(NTier.Data.Objects.Employee employee) {
    if (!EmploymentValidation.ValidatePayrate(employee.Payrate)) {
        return false;
    }
    ...
}
public static bool UpdateEmployee(NTier.Data.Objects.Employee employee) {
    if (!EmploymentValidation.ValidatePayrate(employee.Payrate)) {
        return false;
    }
    ...
}

Okay, great; if we try to add or update an employee that has a payrate below 0, it will fail and that is what we want. Now this seems great, we just added validation to our project with ease. Now, what if your employee object actually has 50+ properties that need to be validated? Often times you want to keep your object itself simple. This will help you maintain it in the future, so the first thought is to pass the object itself to our validation library. Wait, we can’t!

NTier.Data references NTier.BusinessRules, therefore NTier.BusinessRules can never reference NTier.Data as this would cause a circular dependency. This is where 3-tier architecture using interfaces comes into play. We don’t need to pass the object itself, we can pass a contract that defines that object and stores the valuable information we need to validate. We don’t need anything else, but we need to add another new project called NTier.Common.Interfaces and our IEmployee interface to represent our object.

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

namespace NTier.Common.Interfaces {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Defines the base properties for an Employee
    /// </summary>
    public interface IEmployee {
        int ID { get; }
        string Email { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
        float Payrate { get; set; }
        string Title { get; set; }
    }
}

Now first what we want to do is add a reference to NTier.Common.Interfaces from NTier.Data and derive Employee from IEmployee. Also don’t forget that because NTier.Presentation uses NTier.Data, it must also use NTier.Common.Interfaces, so we add that as a reference as well. Add your references, and make the following change to Employee.cs.

public class Employee : NTier.Common.Interfaces.IEmployee {
    ...
}

Now to resolve the circular dependency we are going to reference NTier.Common.Interfaces from NTier.BusinessRules. Add your reference, then make the following changes to EmploymentValidation.

namespace NTier.BusinessRules {
    ...
    using NTier.Common.Interfaces;

    ...
    public static class EmploymentValidation {
        ...

        /// <summary>
        /// Validates the specified employee
        /// </summary>
        public static bool ValidateEmployee(IEmployee employee) {
            if (string.IsNullOrEmpty(employee.FirstName))
                return false;
            if (string.IsNullOrEmpty(employee.LastName))
                return false;
            if (string.IsNullOrEmpty(employee.Title))
                return false;
            if (string.IsNullOrEmpty(employee.Email))
                return false;
            if (!ValidatePayrate(employee.Payrate))
                return false;
            return true;
        }
    }
}

Now notice that I left in the ValidatePayrate() method. This is because often times you are already using this in various portions of your software, and removing or changing this would be a breaking change that could break the software. So we’ll leave that in. But now you can see that we can pass in an interface of IEmployee and validate everything we need. But first, we need to go back and update our AddEmployee() and UpdateEmployee() methods in our data tier.

public static bool AddEmployee(NTier.Data.Objects.Employee employee) {
    if (!EmploymentValidation.ValidateEmployee(employee)) {
        return false;
    }
    ...
}
public static bool UpdateEmployee(NTier.Data.Objects.Employee employee) {
    if (!EmploymentValidation.ValidateEmployee(employee)) {
        return false;
    }
    ...
}

And, we’re done. We can pass around our IEmployee interface because it is shared among all the core libraries, where before we could not have passed around Employee due to circular dependencies. This is what 3-tier architecture with interfaces provides, flexibility and loose coupling between your libraries. Technically it is still pretty tightly coupled, but much more better than a 2-tier architecture.

Microsoft .NET

N-Tier Architecture Best Practices, Part 1: 2-Tier Architecture with just a Data

2

Before I start off on my lengthy post, this article is what sparked my interest. With that linked for you, this will be split into a 5 part blog series each part covering a specific type of n-tier architecture. If there is not a link to the article it has not been published yet.

N-Tier Architecture Best Practices, Part 1: 2-Tier Architecture with just a Data Tierthis article
N-Tier Architecture Best Practices, Part 2: 3-Tier Architecture with interfaces and a Data Tier
N-Tier Architecture Best Practices, Part 3: DLinq / Linq to SQL
N-Tier Architecture Best Practices, Part 4: Entity Framework
N-Tier Architecture Best Practices, Part 5: Unity Framework

Download the Source Code for this Article
N-Tier Architecture (2-Tier)

In most projects you will have to communicate with other objects or a data tier (database engine, file system, or other data source), and passing your objects around can make for some complicated scenarios. One common rut that many developers find themselves in is circular-dependencies.

What is N-Tier Architecture?
N-Tier Archiecture is a term that refers to the number of assemblies, modules, or services that make up a system that allows its different parts to communicate with one another. An example would be a simple system that has some business objects and a database. You may have a module that handles the communication with the data tier, and also stores your business objects, and then maybe a second module that actually handles the processing of the objects such as input and change. This would be a 2-Tier architecture. A 3-Tier architecture would be something like having a module that stores interfaces that defines your business objects, another module that actually implements the business objects, and then a third module that again handles the input and change. N-Tier architecture can get vastly complex, especially in software applications like video games. Imagine a game engine where you have modules that must communicate with one another for handling rendering, player locations, particle effects, game data, network information. You can easily get into a complex system.

What I will cover

  • 2-Tier with just a data tier
  • 3-Tier with common interfaces, and a data tier
  • Briefly explain DLinq (Linq to Sql)
  • Briefly explain Entity Framework (Linq to Entities)
  • Briefly explain Unity Framework (Data Injection Framework)

Technologies we will be using for this article

  • C# 4.0
  • .NET 3.5
  • SQL Server CE

2-Tier architecture with a Data Tier Project Structure (image to the left)
We are going to create a solution with two projects. The first, ‘NTier.Data’ will act as the Data Tier. Thie purpose of this is to act as the dependency for all other aspects of the software. It will store the database objects, as well as the class that handles communication between the objects and the database. The second will be ‘NTier.Presentation’, which acts as the executable that is actually used by the client as the UI, and in our case is a very simple Console Application.

The database
The database is just a SqlCe database with an Employees table. Our employee object will match the database schema perfectly in terms of its properties (ie. FirstName, LastName, Email, etc).

The code
There are only three class files, here is the code of all three.

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

namespace NTier.Data.Objects {
    using System;

    /// <summary>
    /// Represents a Employee in the data tier
    /// </summary>
    public class Employee {
        /// <summary>
        /// Gets the Employee's ID
        /// </summary>
        public int ID {
            get;
            internal set;
        }

        /// <summary>
        /// Gets or sets the Employee's email address
        /// </summary>
        public string Email {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the Employee's first name
        /// </summary>
        public string FirstName {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the Employee's last name
        /// </summary>
        public string LastName {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the Employee's payrate
        /// </summary>
        public float Payrate {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the Employee's title
        /// </summary>
        public string Title {
            get;
            set;
        }

        /// <summary>
        /// Overrides base.ToString()
        /// </summary>
        public override string ToString() {
            return string.Format("{0} {1}, {2}", FirstName, LastName, Title);
        }
    }
}
//-----------------------------------------------------------------------------
// <copyright file="DataTier.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace NTier.Data {
    using System;
    using System.Collections.Generic;
    using System.Data.SqlServerCe;
    using NTier.Data.Objects;

    /// <summary>
    /// Interactive class between business logic and the data tier
    /// </summary>
    public static class DataTier {

        private static string m_ConnectionString = @"Data Source=.\Northwind.sdf";
        /// <summary>
        /// Gets the connection string for SQL Server CE
        /// </summary>
        public static string ConnectionString {
            get {
                return m_ConnectionString;
            }
        }

        /// <summary>
        /// Adds the specified employee to the data tier
        /// </summary>
        public static bool AddEmployee(NTier.Data.Objects.Employee employee) {
            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            using (SqlCeCommand command = new SqlCeCommand(Properties.Resources.InsertCommandText, connection)) {
                command.Parameters.AddWithValue("@Email", employee.Email);
                command.Parameters.AddWithValue("@FirstName", employee.FirstName);
                command.Parameters.AddWithValue("@LastName", employee.LastName);
                command.Parameters.AddWithValue("@Payrate", employee.Payrate);
                command.Parameters.AddWithValue("@Title", employee.Title);
                try {
                    connection.Open();
                    return command.ExecuteNonQuery() == 1;
                }
                catch (System.Data.SqlServerCe.SqlCeException) {
                    return false;
                }
            }
        }

        /// <summary>
        /// Returns a collection of all the employee's in the data tier
        /// </summary>
        public static IEnumerable<NTier.Data.Objects.Employee> GetEmployees() {
            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            using (SqlCeCommand command = new SqlCeCommand(Properties.Resources.SelectCommandText, connection)) {
                try {
                    connection.Open();
                }
                catch (System.Data.SqlServerCe.SqlCeException) {
                    yield break;
                }
                using (SqlCeDataReader reader = command.ExecuteReader()) {
                    while (reader.Read()) {
                        Employee employee = new Employee();
                        employee.ID = (int)reader["ID"];
                        employee.Email = (string)reader["Email"];
                        employee.FirstName = (string)reader["FirstName"];
                        employee.LastName = (string)reader["LastName"];
                        employee.Payrate = (float)(double)reader["Payrate"];
                        employee.Title = (string)reader["Title"];
                        yield return employee;
                    }
                }
            }
        }

        /// <summary>
        /// Removes the specified employee from the data tier
        /// </summary>
        public static bool RemoveEmployee(NTier.Data.Objects.Employee employee) {
            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            using (SqlCeCommand command = new SqlCeCommand(Properties.Resources.DeleteCommandText, connection)) {
                command.Parameters.AddWithValue("@ID", employee.ID);
                try {
                    connection.Open();
                    return command.ExecuteNonQuery() == 1;
                }
                catch (System.Data.SqlServerCe.SqlCeException) {
                    return false;
                }
            }
        }

        /// <summary>
        /// Updates the specified employee's information in the data tier
        /// </summary>
        public static bool UpdateEmployee(NTier.Data.Objects.Employee employee) {
            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            using (SqlCeCommand command = new SqlCeCommand(Properties.Resources.UpdateCommandText, connection)) {
                command.Parameters.AddWithValue("@Email", employee.Email);
                command.Parameters.AddWithValue("@FirstName", employee.FirstName);
                command.Parameters.AddWithValue("@LastName", employee.LastName);
                command.Parameters.AddWithValue("@Payrate", employee.Payrate);
                command.Parameters.AddWithValue("@Title", employee.Title);
                command.Parameters.AddWithValue("@ID", employee.ID);
                try {
                    connection.Open();
                    return command.ExecuteNonQuery() == 1;
                }
                catch (System.Data.SqlServerCe.SqlCeException) {
                    return false;
                }
            }
        }
    }
}
//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace NTier.Presentation {
    using System;
    using NTier.Data.Objects;
    using NTier.Data;
    using System.Collections.Generic;

    internal static class Program {
        /// <summary>
        /// Entry Point
        /// </summary>
        public static void Main() {
            Employee employee = new Employee();
            employee.Email = "danderson@dcomproductions.com";
            employee.FirstName = "David";
            employee.LastName = "Anderson";
            employee.Payrate = 35F;
            employee.Title = "President";
            DataTier.AddEmployee(employee);
            foreach (Employee item in DataTier.GetEmployees()) {
                Console.WriteLine(item.ToString());
                Console.ReadKey(true);
            }
            Console.Write("Press any key to exit...");
            Console.ReadKey(true);
        }
    }
}

Something to note is lines 33, 54, 81, 98 of Employee.cs. I saved the query texts in the project’s resource file to keep the code tidy.

Now you can write Program.cs to act however you want, and play with the code. In my example all I am doing is adding an employee to the table with my name, then enumerating the employees and listing them to the console window. Since each time you run my example it adds an employee with the same information and never removes it, you will have x(f) employees where f is the number of times the application has been launched, in the database with the same information.

What advantage does 2-Tier architecture serve?
Alright, in this 2-tier architecture, the advantage is its simple. That’s all there is to it. For each data tier object (ie. something that would need to be committed into a data source), you can simply create the object with its properties, and write the methods in your data tier class to do the work. The simplicity of being able to just pass your object is what makes it desireable. Also note that you do not have any complex dependencies between assemblies, thus you never have to worry about a circular dependency, and its extremely easy to note where everything is at in your project.

In large projects, your Objects folder would get rather large with data tier objects. Which is fine. The disadvantage of a 2-tier architecture is generally as your application becomes exceedingly complex, the simple structure of the project no longer becomes viable because its just not that flexible. Further down the road if you wanted to refactor your objects out of the data tier assembly into a 3-tier architecture, your data tier breaks because you can no longer pass the reference of the object. Thus bringing us into the next part of the blog series, 3-tier architecture.

When to use 2-Tier Architecture
When your requirements are simple and you have a minimal number of assemblies that must reference your business objects. More so, it is actually easier to explain when not to use 2-tier architecture. I’ve compiled a short list of the most common scenarios you should not use 2-tier architecture for.

  • An assembly needs to reference your business objects, but not have access to the data tier
  • You want to extend your business object with additional functionality, but not expose those new features to the data tier

Those are actually the only two reasons that come to mind immediately. If you have some other reasons you can think of that are good, throw a comment down and I will add it to the list. At any rate, the point is that 2-tier is easy to implement, and pretty easy to manage with little effort. The huge downside is once it becomes large, it will be hard to refactor later on. The next blog in the series will be on 3-tier architecture which I will hope to start writing by Monday.

Microsoft .NET

Using ISynchronizeInvoke to update your UI safely from another Thread.

0

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:

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

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.

Microsoft .NET

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

2

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

Microsoft .NET

Limitations of Entity Framework support with MySQL 6.4.3 Connector/Net

1

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.

Microsoft .NET

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

12

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.

Microsoft .NET

Dangers of the public access modifier.

0

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.

Go to Top