Monday, October 19, 2015

Explanation of the GetPropertyName Function

I was recently asked how a particular GetPropertyName function my team was using worked. This is what I said:

Usage Example

C#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static void Main(string[] args)
{
    var demoClass = new Demo();
    Console.WriteLine("demoClass.{0}: {1}", 
        Utilities.GetPropertyName(() => demoClass.TestProperty),
        demoClass.TestProperty);
    Console.WriteLine("demoClass.{0}: {1}", 
        Utilities.GetPropertyName(() => demoClass.TestNumber),
        demoClass.TestNumber);
}

VB.NET

1
2
3
4
5
6
7
8
9
Sub Main()
    Dim demoClass As New Demo()
    Console.WriteLine("demoClass.{0}: {1}",
                      GetPropertyName(Function() demoClass.TestProperty),
                      demoClass.TestProperty)
    Console.WriteLine("demoClass.{0}: {1}",
                      GetPropertyName(Function() demoClass.TestNumber),
                      demoClass.TestNumber)
End Sub

Usage Explanation

The first line prints of the method prints the name of the demoClass’s TestProperty property and its value. The second line prints the name of the demoClass’s TestNumber property and its value.

GetPropertyName Function Overview

The GetPropertyName function returns a string.

The GetPropertyName function takes a single input argument which must be a lambda expression. The lambda expression must be a function. The function must contain a single statement that returns the value of one of the object’s properties.

The GetPropertyName function uses built-in .NET framework functionality to get the name of the property that was accessed by the lambda expression and returns that property name as a string.

More information about lambda expressions:

GetPropertyName Code

C#

1
2
3
4
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    return ((MemberExpression)expression.Body).Member.Name;
}
  • The <T> in GetPropertyName<T> is used to genericize the class that is used in the lambda expression.
  • The Expression<Func<T>> in (Expression<Func<T>> expression) indicates the input argument to the GetPropertyName function must be a lambda expression that is a function that uses an object of type “T”. Expression is a special .NET Framework datatype that causes the compiler to create and populate a data structure that contains details about the code inside a lambda expression. More information about this data type can be found at http://msdn.microsoft.com/en-us/library/Bb335710.aspx https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.
  • expression.Body gets the body of the lambda expression.
  • ((MemberExpression)expression.Body) casts the body of the lambda expression to a MemberExpression. A MemberExpression is a datatype that represents a class’ property being accessed. If the lambda expression passed into the GetPropertyName function is not a single line of code that accesses a class property, an InvalidCastException will be thrown at runtime.
  • The Member property of the MemberExpression datatype represents the property being accessed. It is of type MemberInfo.
  • The Name property of the MemberInfo type returns the name of the property as a string.

VB.NET

1
2
3
Public Function GetPropertyName(Of T)(expression As Expression(Of Func(Of T))) As String
    Return DirectCast(expression.Body, MemberExpression).Member.Name
End Function
  • The (Of T) in GetPropertyName(Of T) is used to genericize the class that is used in the lambda expression.
  • The Expression(Of Func(Of T)) in (expression As Expression(Of Func(Of T))) indicates the input argument to the GetPropertyName function must be a lambda expression that is a function that uses an object of type “T”. Expression is a special .NET Framework datatype that causes the compiler to create and populate a data structure that contains details about the code inside a lambda expression. More information about this data type can be found at http://msdn.microsoft.com/en-us/library/Bb335710.aspx https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.
  • expression.Body gets the body of the lambda expression.
  • DirectCast(expression.Body, MemberExpression) casts the body of the lambda expression to a MemberExpression. A MemberExpression is a datatype that represents a class’ property being accessed. If the lambda expression passed into the GetPropertyName function is not a single line of code that accesses a class property, an InvalidCastException will be thrown at runtime.
  • The Member property of the MemberExpression datatype represents the property being accessed. It is of type MemberInfo.
  • The Name property of the MemberInfo type returns the name of the property as a string.

Why are we using GetPropertyName?

So why do we use GetPropertyName instead of just passing in a string constant (see alternate code below)?

C#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static void AlternateVersion()
{
    var demoClass = new Demo();
    Console.WriteLine("demoClass.{0}: {1}",
        "TestProperty",
        demoClass.TestProperty);
    Console.WriteLine("demoClass.{0}: {1}",
        "TestNumber",
        demoClass.TestNumber);
}

VB.NET

1
2
3
4
5
6
7
8
9
Sub AlternateVersion()
    Dim demoClass As New Demo()
    Console.WriteLine("demoClass.{0}: {1}",
                      "TestProperty",
                      demoClass.TestProperty)
    Console.WriteLine("demoClass.{0}: {1}",
                      "TestNumber",
                      demoClass.TestNumber)
End Sub

If the name of a demoClass’s property changes, the developer needs to remember to update the code to use the new name. The string is not tied to the class at all. One alternative would be to add readonly properties to the class that returned the name of the properties (e.g. Demo.TestPropertyName or something like that), but the developer would still need to remember to update that property’s name if its associated property’s name changed.

By using the GetPropertyName function, if a property is renamed, Resharper can automatically rename our GetPropertyName lambda expressions. If we are not using Resharper and we rename a property, we will get a compiler error if we forget to update the property's name wherever it is used.

Monday, September 07, 2015

Linux Support for Arduino Leonardo / Micro USB Game Controllers

A few months ago I posted an article that described how 3 USB game controllers could be added to the Arduino Leonardo and the Arduino Micro. Out of the box, they look like a USB serial port, keyboard, and mouse to the host computer, but with these modifications they can also look like 3 game controllers. This works great on Microsoft Windows (I have tested it on 7, 8.1, and 10), but it does not work on Linux.

If you plug the modified Arduino Leonardo or Arduino Micro into a machine running Linux and do a listing on the input devices, you will see the Arduino mouse, but not the joysticks.

Before Plugging in the Arduino Leonardo or Micro


After Plugging in the Arduino Leonardo








After Plugging in the Arduino Micro








To get this to work on Linux, you need to adjust a setting on the usbhid driver. This can be done by editing the /boot/cmdline.txt file. Add the following string to the end of the line of text in this file (there should only be one line of text in this file):

For the Arduino Leonardo

usbhid.quirks=0x2341:0x8036:0x040

For the Arduino Micro

usbhid.quirks=0x2341:0x8037:0x040

Explanation

0x2341 is the Vendor ID for Arduino
0x8036 is the Product ID for the Leonardo
0x8037 is the Product ID for the Micro
0x040 indicates the Multiple Input “quirk” should be used (i.e. HID_QUIRK_MULTI_INPUT)

Example







After changing the /boot/cmdline.txt file the Linux machine will need to be rebooted. You will need to have root privileges to edit the /boot/cmdline.txt file. Now when the modified Arduino Leonardo or Arduino Micro is plugged in, three new joysticks will appear.

After Applying Setting – Arduino Leonardo













After Applying Setting – Arduino Micro













Wednesday, July 15, 2015

Introduction to Domain-Driven Design

The article “An Introduction to Domain-Driven Design” by David Laribee (https://msdn.microsoft.com/en-us/magazine/dd419654.aspx) provides a great introduction to Domain-Driven Design (DDD). The definitive book for this topic, “Domain-Drive Design: Tackling Complexity in the Heart of Software”, by Eric Evans, can be a bit overwhelming (especially if one has never been exposed to DDD before), but this article is a great starting point for people wanting to learn more about Domain-Driven Design. The author himself describes this article as a “gentle introduction to designing and evolving rich domain models”. The following is a brief summary of the topics covered in this article.

Model-Driven Design

The software we write is just a model of the system or business process we are automating. The model in everyone’s head and the model that gets implemented in software is never exactly the same. The concept of modifying software over time to more closely match the true model is model-driven design.

Ubiquitous Language

Terminology used by experts in any domain to describe concepts in that domain is called the Ubiquitous Language. Class names, variable names, etc. in the software should use terms from this Ubiquitous Language. Both the business experts and the programmers should be using the same language to describe the business.

Bounded Context

Most enterprise systems have course-grained areas of responsibility. In DDD these areas are called Bounded Contexts. A context map is used to diagram the Bounded Contexts and describe how they relate to one another. Each Bounded Context can have its own unique Ubiquitous Language.

Anti-Corruption Layers

An Anti-Corruption Layer is a DDD pattern that is used to prevent non-domain concepts from leaking into a model. A repository or data access layer is an example of an Anti-Corruption Layer. They keep SQL or other persistence details out of your model.

Entities

An Entity is a noun (i.e. a person, place, or thing) that has both an identity and a lifecycle. For example, a person has a name, a car has a VIN, a city has a name, etc. Also, a person has a birthday and eventually a day they died, a car has a manufacture date, etc.

Value Objects

Value Objects are descriptors or properties that do not have an identity, they simply describe something about an entity. Value Objects are also immutable (i.e. they do not change value once they are created). An object representing the value $35.75 USD is an example of a Value Object (i.e. a decimal value 35.75 and an indicator the value is in US dollars).

Aggregate Roots

An Aggregate is a cluster of associated objects (e.g. entities, value objects, etc.) that are treated as a unit. An Aggregate Root is the single, specific entity in the Aggregate that objects outside the scope of the Aggregate are allowed to hold a reference to. Objects inside the Aggregate are allowed to refer to each other, but objects outside of the Aggregate must go through the Aggregate Root to access objects in the Aggregate.

Domain Services

Domain Services are classes use to represent operations or processes that do not have an identity or lifecycle in the domain. They are typically named after verbs or business activities defined in the Ubiquitous Language. A “funds transfer” service that withdraws money from one account and deposits it into another account is an example of a Domain Service.

Repositories

Repositories are used to retrieve and store entities. They prevent database or persistence concepts (e.g. SQL statements, stored procedures, etc.) from getting in the model. They are an example of an Anti-Corruption Layer.

DDD Resources

DDD combines many good object-oriented programming principles, design patterns, software development practices, techniques, and philosophies. The following resources are good places to learn more about DDD: