Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

17 October 2012

How to generate missing Fakes shims

While using the Fakes (Moles) isolation framework, you will notice some mscorlib shims are missing, particularly in the System namespace. For example, System.Fakes.ShimEnvironment does not exist. Although these are missing by default, you can request the compiler to generate shims for specific objects. This post provides steps to request Fakes shim generation for System.Environment and an example of implementation.

This tutorial targets Microsoft Fakes Isolation Framework on Visual Studio 2012 Ultimate or later; but, this process is also compatible with the developmental version, project name "Moles", running on Visual Studio 2008 or 2010. This tutorial assumes you have basic understanding of the MSTest framework.

27 March 2012

Creating a Comprehensive Event Logger

Would you rather try to decipher the meaning of an error in the Windows application event log, or ram a fork into the back of your hand?  I thought so.

The problem with the event logs is they are notoriously uninformative.  It seems that their purpose is to taunt IT personnel, by suggesting some helpful information is available. Yeah, right.  There are entire Web sites dedicated to deciphering event identification numbers mean.  The necessity for such sites is just plain sad.  Apparently, leaving what happened a mystery is a better alternative to including actual WORDS that describe the problem, in human language.

I implore you: do not be that kind of developer!  I always insist on making everything human readable, and easy to understand.  By leveraging the extensible nature of .NET, we can easily log useful and meaningful information to the event log, which will help the user or IT administrator fix the problem, and/or help the developer debug the issue.

Here's how you can use a single method, to alleviate the IT admin's urge to strangle you.

05 July 2011

Assembly Not Available in the Currently Targeted Framework

Oh, dreaded .NET 4.0 target framework issue... how I loathe thee.

Symptoms

When attempting to compile a .NET application, using Visual Studio 2010, the build fails, and the following warnings, or similar warnings, are issued:
The primary reference "System.Configuration.Install", which is a framework assembly, could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0". To resolve this problem, either remove the reference "System.Configuration.Install" or retarget your application to a framework version which contains "System.Configuration.Install". 
The primary reference "System.ServiceProcess", which is a framework assembly, could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0". To resolve this problem, either remove the reference "System.ServiceProcess" or retarget your application to a framework version which contains "System.ServiceProcess".
I found that even though the .NET Client profiles are supposed to be a subset of the full profile, many assemblies, including the two noted above, are not included in the "Add Reference" dialog.  These assemblies properly appear in the Client Profile.  It's as if the list has somehow been modified.  Now, to identify the culprit...

25 May 2011

How to Stub Dependency Event Handlers in Integration Tests

Integration tests help you ensure dependencies behave as expected.  When creating unit tests, developers go to great lengths to eliminate dependencies, but that's not our objective.  The application should already have passed unit tests, before proceeding with integration tests. We want to ensure that integrating the application with its dependencies works as expected.

"Dependencies" includes other modules, APIs, frameworks, hardware, databases, networks, etc.  We want to ensure the application works with these other resources as expected.  This demonstration code implements constructor injection, to simplify testing.  Dependency injection is essential to unit testing, but also proves useful for integration testing.  The injection is important, because we want to isolate a specific dependency and inject a controlled mock object for others.

12 April 2011

Unit Testing with Moles and Pex - Part 1

This post discusses key ways of improving the effectiveness and code coverage on unit tests, using the Visual Studio Test Framework, including the developing Moles and Pex technologies.  Other frameworks and harnesses such as nUnit, Moq, etc. are not discussed in this post.

Moles is Microsoft's code instrumentation, or mock framework, used to isolate environment dependencies.  Moles was created expressly to enable Pex to function.  Moles is discussed in greater detail, after the break.

Pex intelligently examines the logic branches of the code to be tested, and then generates a series of input values that should or should not fail, thereby maximizing test code coverage.

Before we start talking about Moles and Pex, there are some elementary, yet vitally important topics to review about unit testing.  Adhering to these rules play into the effectiveness of Moles and Pex.  I strongly advise reading, before moving on to part 2, but I really can't stop you, can I? (or can I? Muahaha!)

24 March 2011

Active Directory Properties for C#

I compiled the following list of Active Directory properties, while developing a solution. This list is more comprehensive than those I found on the InterWebs.

Please submit suggestions for additions to this list, via the comment block, below!  Code thrives on community feedback. (Code is posted after the jump break...)

29 December 2010

Advanced C# Windows Service Installation

Click this link, to download source code.
Today, I'm going to show you how to efficiently create Windows Services and deployment projects, using C# in Visual Studio 2010.  These techniques illustrate methods of centralizing key information about the services included in the project, to prevent typos and other mistakes attributed to setting similar properties in decentralized locations.

This example is especially useful for projects that contain several services that use common code bases.  For example, I have a service suite that monitors several FTP drop directories on a server.  Each watcher performs different, custom actions; but, 90-95% of the code is common to all services.  For this and other reasons not discussed here, it makes sense to simply package all services in one project.  The more popular alternative is to create a common library, install to GAC, and create individual service solutions.

The bottom line is that I wanted to simplify management and deployment.  To simplify service registration, I created a "ServiceInfo" class attribute into which all service information is entered, instead of mucking about in several ProjectInstaller files.  View the full article, to get source code and a complete walk-through.

UPDATE 13 MAR 2012: I updated the code sections, to use formatted HTML, instead of using JavaScript code coloring.  The code was formatted a bit, for fit, and to make the LINQ more efficient.  Therefore, the code in the download won't be exactly the same, but it works.

16 December 2010

How To Create a C# Windows Service Application

Today, I wrote a Windows service application.  Because part of my day job is teaching C# and .NET, I was inspired to write a "how to" document.  The Walkthrough: Creating a Windows Service Application in the Component Designer article found on MSDN is quite helpful, if you know your way around C# and .NET.  Anyone who doesn't understand C# and .NET enough to make short work of the document arguably has no business writing a service; but, we all have to learn sometime.

UPDATED 29 MAY 2012 - Revised several areas for clarity and simplification, and updated formatting.

09 September 2010

Optional Argument Overload Bear Traps

C# programmers, beware the optional argument overload trap!  If you don't already know about Optional Arguments and Named Arguments, read through my post, Introduction to Optional Arguments and Named Arguments.

Unfortunately, one of my clients is not a C++ programmer, and encountered this issue, when updating a common library.  Realizing this issue may severely impact large applications (i.e. enterprise, B2B, etc.), I thought it best to discuss it openly.  Using optional arguments may be setting yourself a trap that will be difficult to escape, in the future.

Introduction to Optional Arguments and Named Arguments

This is an introduction to Optional Arguments in C# 4.  C# programmers, beware the optional argument overload trap!  If you already know about Optional Arguments and Named Arguments, you may want to check out my post, Optional Argument Overload Bear Traps.

25 August 2010

Efficient Use of Nullable Types

I saw a brief post about nullable types, today, and realized (not by fault of the post itself, rather through my own experiences) that a surprising number of .NET developers either don't know they exist, don't use them correctly, or don't use them efficiently.  Furthermore, nullable types were a topic of the C# class I just finished conducting.

20 August 2010

Extensions: Watch Your Step

I had one of those moments where I wonder if I'm really an expert-level C# programmer, and thought I'd share my embarrassing moment, to help other programmers who are new to extensions, are having the same problem, or for a good laugh.

I created the following C# extension, to safely handle conversion of an object that may contain DBNull to a string; because System.Object.ToString() throws an exception when the object is DBNull.

28 July 2010

User Control Design Time Detection

Today, I created a wizard application in WPF/C#.  Each "page" of the wizard is a user control.  Each user control is largely autonomous, each having a pointer to a singleton instance DataManager class that persists data between the controls and parent window.  When a control is made visible, it checks the values of the DataManager class, to ensure the requisite values are available, etc.

The "page" controls are not instantiated on-demand, for reasons I will not discuss here.  When viewing the main window in the WPF designer, all of the user controls that perform data verification in their IsVisibleChanged event handler cause the WPF designer rendering to fail, although I did get several MessageBoxes containing the various validation error messages.  (At least I know those work well!)

The solution is to wrap all validation logic in an IF statement that checks to see if the control is being rendered in a designer.  It we are indeed in design time, the validation logic is stepped over.

private void UserControl_IsVisibleChanged(
    object sender, 
    DependencyPropertyChangedEventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this)
        || this.Visibility != Visibility.Visible)
        return;

    // Validation logic here...
}

22 June 2010

Threading and Static Generic.Dictionary Issues

I ran into this issue, recently, and was inspired by uber-tester Tess Ferrandez*, to blog it, myself.

Generally, one remembers to lock() or Monitor.TryEnter() their resources, in a multi-threaded situation.  Collections are often needed by multiple threads, and can be made static, to make them generally accessible to all threads.  Furthermore, collections support concurrent readers, making them ideal for multi-thread access.

So, what happens if another thread writes to the static dictionary, while reading?  Well, it isn't a disaster, nor a deadlock, but it sure gets slow!  The problem is the reader(s) contend with the writer, as the dictionary keys are being updated.  If several threads are attempting to traverse the keys, performance suffers greatly, and you'll eventually receive an InvalidOperationException.

In the threading section of the Dictionary<T> MSDN documentation, we find:
"Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
A Dictionary<TKey, TValue> can support multiple readers concurrently... blah blah blah"
Many programmers (unfortunately, myself included) stop reading at that point, and return to coding with a smile, because they discovered a thread safe, concurrent read collection.  If we keep on reading, we find the answer to the problem:
A Dictionary<TKey, TValue> can support multiple readers concurrently, ...as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
Simply locking the resource prevents the whole issue.  It is well worth the time to insert Monitor.TryEnter statements throughout the code, rather than suffer intermittent performance issues.

*Check out the Tess Ferrandez's blog post, High CPU in .NET app using a static Generic.Dictionary.  Her post is directly related to this one, and provides debug details.