Programming

Clarifying Passing Arguments ‘By-Value’ or ‘By-Reference’ in .NET

As a C# developer, I have been approached countless times with the following question…

Do methods in C# receive their arguments by value or by reference?

If you are a C# developer (or really any developer) and have not been approached with this question, you are in the minority.

I felt I have always been able to answer this question correctly, but have not truly understood my reasoning. This lead me to seek clarification on how these languages handle passing arguments to their functions.

After researching different articles/books/blogs that attempt to explain this, I was able to gain a better understanding.

Are method arguments in C# passed by value or by reference?

First, we want to make sure that we give the textbook answer that will get you through most interviews and friendly discussions.

The following explanation was taken from MSDN – Passing Parameters in C#

In C#, arguments can be passed to parameters either by value or by reference…

To clarify, this says that argument CAN be passed by valur or by reference, but it goes on to explain that by default, arguments are passed by value. In order to pass by reference, you must use the ref  keyword.

 What does this actually mean?

Assuming we are strictly talking about the inherent pass by value behavior that C# is defaulted to (no ref keyword like .NET), this means the following:

  • When an object is passed as an argument to a method, the method receives a reference to the object. However the object reference itself is passed by value.
  • Properties of the original object CAN be modified, but the object reference itself CANNOT.

What does this look like in code?

Using the two implementations of ChangeAge(…) given below, we can visualize what passing by value and passing by reference looks like in C#.

 

The first implementation does not include the ref keyword for the Person argument, therefore is defaulted to pass by value.

private static void ChangeAge(Person person,int newAge)
{
    person = new Person();  //We CAN'T do this!
    person.Age = newAge;
}

The second implementation specifies the ref keyword for the Person argument.

private static void ChangeAge(ref Person person,int newAge)
{
    person = new Person(); //We CAN do this!
    person.Age = newAge;
}

If we have a simple console application such as the following:

public static void Main(string[] args)
{
    Person person = new Person();
    person.Age = 5;

    //Attempt to change 'Age' to 10
    ChangeAge(person,10);

    Console.WriteLine(person.Age);

    //Attempt to change 'Age' to 10
    ChangeAge(ref person,10);

    Console.WriteLine(person.Age);

    Console.ReadLine();
}

We end up with the following console output. Note that only the second invocation of ChangeAge(…) modifies the Age property of the Person object.

 

What is the explanation of this behavior?

As we mentioned earlier, in C#, you can pass an argument by value and also by reference.

The first implementation of ChangeAge(…) does not specify the ref keyword, therefore does not pass a value by reference, but by value. The confusion here is because it still seems we are passing a reference to the Person object we have created. What we essentially have is a copy of the reference and not the actual reference to the Person object. This is why the modification fails, because we are attempting to replace the object itself before modifying the value.

If we want to replace the object iself, we must utilize the ref keyword and pass the Person object as an explicit reference.

Hopefully this wil clarify some of the differences of passing arguments by value or reference.

Enforcing Method Parameter Conventions Using Roslyn Diagnostics With C# Part 2: Code Fix Provider

Introduction and Recap

In my last post, Enforcing Method Parameter Conventions Using Roslyn Diagnostics With C# Part 1:Diagnostics , I showed how you can use the .NET Compiler Platform (Roslyn) to enforce conventions in your code base by implementing code diagnostics.

More specifically, we looked at enforcing method parameter conventions for a given user defined type (or interface). If you want additional insight on the sample convention, please refer to the previous post. To recap, our convention has the following properties.

  • Any public service method in the internal service layer must specify a parameter type of IInternalUser.
  • The IInternalUser parameter must be specified first in the method signature.
  • Only implemented members of service interfaces can be public. Everything else must be private.
Along with these properties are several assumptions that are mentioned in the previous article in order to keep this example short and to the point.
The result of the last post left us with a diagnostic that gave us an error or warning if this convention was not followed. An example of this is shown in the screenshot below.

This was a very basic task and provided realistic benefits based on our convention. However, we want to also be able to provide suggested code fixes when this occurs. For this example we want to rearrange the parameters in the method signature to satisfy our convention. This is where the ICodeFixProvider helps.

Using ICodeFixProvider, we can specify instructions for replacing the existing syntax tree with an updated tree which includes our transformed fixes. This is not quite as trivial as implementing our DiagnosticAnalyzer.

The Implementation

We already have implemented our code diagnostic, so we just our code fix. Assuming you have followed the directions correctly in the first article, you should still have your template CodeFixProvider.cs in your project. It should look the same as the following screenshot.

The template code provides a fix that will make declarations all upper case, but we do not care about this.  Our goal is to take the improperly ordered parameter list and replace it with one that satisfies our convention.


Step 1: Implement GetFixesAsync

We need to rewrite the logic for GetFixesAsync to find the method declaration(s) that our implemented diagnostic was created for and return a code action for each that will invoke the fix that we implement. This leaves us with a fairly straight forward implementation for GetFixesAsync  as the logic for transforming the syntax tree will be housed in our own FixIInternalUserOrdinal which we will implement in the next step.

Go ahead and replace the GetFixesAsync with the following implementation.

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
	SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

	SyntaxToken token = root.FindToken(span.Start);

	TextSpan diagnosticSpan = diagnostics.First().Location.SourceSpan;

	// Find the method declaration identified by the diagnostic.
	MethodDeclarationSyntax declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().First();

	// Return a code action that will invoke the fix.
	return new[] { CodeAction.Create("Reorder Parameters", c => FixIInternalUserOrdinal(document, declaration, c)) };
}

I attempted to comment anything that was not straight forward and will not spend time going over each line of this implementation. If you would are having trouble understanding any of this, I would recommend spending a few minutes reviewing Getting-Started – Syntax Transformation (C#).

It is important to understand that we are grabbing the method declaration from the diagnostic that was provided, and then passing it into our FixIInternalUserOrdinal. 

Step 2: Implement FixIInternalUserOrdinal

Unlike GetFixesAsync which has no logic for transforming the syntax tree, FixIInternalUserOrdinal  is entirely responsible for this transformation and contains the logic for reordering the parameters in our method signature to satisfy our convention.

If you have not done it already, you can delete MakeUppercaseAsync  and add the following code.

 private async Task<Document> FixIInternalUserOrdinal(Document document,MethodDeclarationSyntax methodDeclaration,CancellationToken cancellationToken)
{
	//Document to return;
	Document newDocument = null;

	//Retrieve original paramater list syntax node from method declaration
	ParameterListSyntax originalParameterListSyntax = methodDeclaration.ParameterList;

	//Retrieve original paramater list from paramater list syntax nodes
	IEnumerable <SyntaxNode> parameters = originalParameterListSyntax.ChildNodes();

	//Retrieve only paramaters with identifier name child nodes from original paramater list
	IEnumerable <SyntaxNode> parametersWithIdentifierNames = parameters.Where(p => p.ChildNodes().Any(q => q is IdentifierNameSyntax));

	SyntaxNode internalUserSyntaxNode = null;

	//Iterate over parameter list
	foreach (SyntaxNode syntaxNode in parametersWithIdentifierNames)
	{
		//Grab identifier token text from identifier name
		string identifierTokenText = syntaxNode.ChildNodes().First().GetFirstToken().Text;

		//Set as IInternalUserSyntax if matching
		if (identifierTokenText == "IInternalUser")
			internalUserSyntaxNode = syntaxNode;
	}

	if (internalUserSyntaxNode != null)
	{
		//Create new paramater list
		SeparatedSyntaxList<ParameterSyntax> newParamList = new SeparatedSyntaxList<ParameterSyntax>();

		//Add IInternalUser parameter first
		newParamList = newParamList.Add((ParameterSyntax)internalUserSyntaxNode);

		//Iterate over old list of parameters
		foreach (SyntaxNode parameter in parameters)
		{
			//Add to new list if not IInternalUser Parameter
			if (!parameter.GetText().ToString().Contains("IInternalUser"))
				newParamList =  newParamList.Add((ParameterSyntax)parameter);
		}

		//Replace the parameter list in the method declaration
		ParameterListSyntax newParameterListSyntax = originalParameterListSyntax.WithParameters(newParamList);

		//Replace the old paramater list declaration with the new paramater list declaration
		SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
		SyntaxNode newRoot = oldRoot.ReplaceNode(originalParameterListSyntax, newParameterListSyntax);

		//Returned document with transformed tree
		newDocument =  document.WithSyntaxRoot(newRoot);
	}

	//Return new document
	return newDocument;
}

Again, I am not going to spend time explaining each of these lines of code as I have done my best to explain it through the use of comments.

Instead, I will give a brief summary of the steps I took to reorder the parameters in the method signature. It is important to note that syntax trees are immutable. This means that even if the API exposes methods such as Replace(..) and WithXXX(…), it is actually creating a new object. The summary below uses terminology loosely but you should still keep this in mind.

  1. Grab a reference to the original parameter list node from the method declaration.
  2. Filter the list of parameter nodes to those with which use IdentifierNameSyntax so we can search for any tokens named “IInternalUser”.
  3. Iterate over each parameter in this filtered list until we find one that has a token matching “IInternalUser”.
  4. Create a new parameter list node and add the IInternalUser parameter node as the first item in the parameter node list.
  5. Iterate over the rest of the parameters and add to the new parameter list if not the IInternalUser  parameter node.
  6. Grab old syntax tree root and replace the old parameter list node with the new one that was just created with the correct parameter list.
  7. Return the new document with the transformed syntax tree.

Result!

You should now be able to test and even debug your new diagnostic by hittingControl + F5. This should spawn a new Visual Studio Instance in which you can use our previous project example that should use your diagnostic as an extension.

You should see the following diagnostic feedback.

Now that you have implemented a code fix, you should see a light bulb overlay appear in the left margin.

If you click on this, you should see our code fix Reorder Parameters.

The final result should look like the following in which we no longer see any diagnostic feedback because our convention is now satisfied!

Syntax Tree Visualizer

When you download the Roslyn preview, you can also utilize a useful tool within Visual Studio 2013, The Syntax Tree Visualizer. This proved to be very helpful as I was manipulating the syntax trees using transforms.  As an example, I have provided a before and after screenshot of our test code following the code fix. If you look closely, you will see the highlighted parameter (which represents our IInternalUser parameter) change positions under the method declaration syntax.

The screenshot below shows the syntax tree before the code fix.

Here is the same syntax tree after our code fix has been executed.

We have implemented a diagnostic and code fix to satisfy our convention. In our next article, I will probably try a more complex example.

Feedback Appreciated

I understand that there is several if not dozens of different ways that this example could have been accomplished. If you seem something I could have done more efficiently, or something is done incorrectly, let me know! This is all new to me and I am enjoying getting to know the Roslyn API. I appreciate any feedback that can be given on the subject matter. Additionally, if you have any ideas on conventions that you might have on your development team that you think would be a good example, let me know as well!

 

Enforcing Method Parameter Conventions Using Roslyn Diagnostics With C# Part 1: Diagnostics

Introduction

With all the hype coming off Microsoft’s BUILD 2014 Developer Conference and making The Roslyn Project open source, I wanted to take some time and familiarize myself with some of the concepts that were covered in Future of C# talk given by Mads Torgersen and Dustin Campbell.

Among several other announcements, they gave a demo on how to implement a ‘Diagnostic with Code Fix’.  In the example, they focus on implementing a diagnostic for conditionals used without braces and also provide the one click fix, similar to ReSharper.

When Roslyn was first announced, I did not quite see the benefit or need to implement custom code diagnostics and fixes. Having since then been a part of a larger enterprise team with a large code base and a strict set of standards and conventions, I now see a niche opportunity to experiment with this functionality.

Aside from the documented source code for Roslyn, it is still fairly early and not many examples are available. Additionally, I try to avoid spending too much of my free development time browsing source code (although I probably shouldn’t). Thus, I wanted to find something that I could easily implement and would provide a significant impact across our code base.

In this article, I am not going to show how to configure Roslyn or Visual Studio 2013. If you need help with this, then you can go use the two following links as resources.

The Convention

I wont get into too much detail on the conventions we use and for privacy reasons, I will modify our conventions for this example.

Our code base follows a service-oriented approach. Additionally, we break down our services into business,internal and external services.

For this example, I will assume that we have the following convention on our internal service layer.

  • Any public service method in the internal service layer must specify a parameter of type IInternalUser.
  • The IInternalUser parameter must be specified first in the method signature.
  • Only implemented members of service interfaces can be public. Everything else must be private.
Invalid Implementations:
public bool CheckUserCredentials(){...}
public bool CheckUserCredentials(string username,string password){...}
public bool CheckUserCredentials(string username,string password,IInternalUser internalUser){...}
Valid Implementations:
public bool CheckUserCredentials(IInternalUser internalUser){...}
public bool CheckUserCredentials(IInternalUser internalUser,string username,string password){...}
For this example, we are not going to worry about checking whether the method is an implementation of the service interface.
Pretty straight forward!

 

 The Implementation

For this article, we will only focus on the Diagnostic Analyzer and leave the Code Fix for Part 2.

Assuming that you have properly followed the directions that were provided for setting up Roslyn, you should have a Visual Studio instance loaded with a project containing the following template code files.

  • DiagnositcAnalyzer.cs
  • CodeFixProvider.cs
You may have some other files included, but they are not relevant for this article. We are going to only focus on DiagnosticAnalyzer.cs. If you open DiagnosticAnalyzer.cs, you should see template code such as the following:

It is nice that they provided us with template code, but we are going to move right along.

As mentioned earlier, we want to provide feedback in the form of a warning or error, for any method signature that contains a parameter of type IInternalUser that is not listed as the first parameter. This is of course a very basic example.

Step 1: Implement AnalyzeSymbol

We need to rewrite the logic for analyzing symbols from the templated code to what we want.

Replace the template AnalyzeSymbol  method with the following code:

public void AnalyzeSymbol(ISymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
	var methodSymbol = (IMethodSymbol)symbol;

	//Check if any method parameters are of type IInternalUser
	if (methodSymbol.Parameters.Any(p => p.Type.Name.Contains("IInternalUser")))
	{
		var paramter = methodSymbol.Parameters.First();

		//Check if IInerternalUser type is first parameter and there is more than one expected parameters
		if (!paramter.Type.Name.Contains("IInternalUser") && methodSymbol.Parameters.Count() > 1)
		{
			var diagnostic = Diagnostic.Create(Rule, methodSymbol.Locations[0], methodSymbol.Name);
			addDiagnostic(diagnostic);
		}
	}
}

This code simply checks to see if any method parameters are of type IInternalUser and checks the position if necessary. If it finds a parameter of type IInternalUser and it is not first in the list of parameters, it creates a diagnostic and invokes the addDiagnostic callback.

Step 2: Modify SymbolKindsOfInterest Auto Property Getter

In order to notify of the type of symbol(s) we want to analyze in AnalyzeSymbol , we need to modify the getter for the SymbolKindsOfInterest property to return an ImmutableArray<SymbolKind> representing SymbolKind.Method.  This is very simple and simply requires replacing the SymbolKindsOfInterest property with the following:

public ImmutableArray<SymbolKind> SymbolKindsOfInterest { get { return ImmutableArray.Create(SymbolKind.Method); } }

 

Step 3: Modify DiagnosticAnalyzer Meta Data Constants

The final step is the simplest and is only required to give proper context to the diagnostic you have just created. For this particular example, I simply want the feedback to the user that it is required that the IInternalUser parameter when present must be first in the parameter list. This can be done by changing the Description  and MessageFormat constants to the following:

internal const string Description = "IInternalUser parameter needs to be first in method signature";
internal const string MessageFormat = "IInternalUser parameter needs to be first in method signature";

You can of course provide a format string for the MessageFormat constant, but I see no need for this example.

Result!

You should now be able to test and even debug your new diagnostic by hitting Control + F5. This should spawn a new Visual Studio Instance in which you can create a new project that should use your diagnostic as an extension.

So why would somebody want to enforce conventions or standards on method signatures? You may not have realized it, but most of the common libraries we use also follow some type of pattern or standard for method signatures. This is why you can typically expect parameters to stay the same as you iterate over method overloads.

Some additional examples of why you might enforce method signatures and parameters are shown in the following list:

  • Ensure that one character parameter names are not used.
  • Ensure that parameter names are camel cased (or whatever).
  • Ensure that you are or aren’t using certain parameter types.
  • Utilize conventions for method names and return types (i.e. returns void is prefixed with “Is” or “Check”).
  • Restrict the maximum amount of parameters used in any method signature.

Stay tuned for the next article where we will implement a CodeFixProvider that will automatically rearrange the parameters so that they correctly match our convention!

The Conference Hall Entrance

AWS Re:Invent 2013: The Good, The Bad, and The Ugly

I wanted to give it a few days after I got back from AWS Re:Invent 2013 before I recollected on the different events. Being in Las Vegas for a week straight is a feat in itself. Attending an 8 hour bootcamp and 1 hour sessiosn for the entire week is mentally and physically exhausting. Nonetheless, it was a privelage to be able to attend accompanied by my CTO and CIO.

The Good

I wasn’t quite sure what to expect since I had never attended a conference of this size and magnitude, but I was impressed with the organization of all the events throughout the entire week. All meals, bootcamps and sessions were  very well organized.It never once (aside from the keynote) felt like there was 10,000 poeple attending the same conference.

One of the surprises that caught me off guard was the “office hours” provided by the Solution Architects and AWS Experts throughout the week,. I was not expecting to be able to interact one-on-one with such ease with experts in one of the main respective product domains such as the following:

  • Deployment
  • Management
  • Database
  • Storage
  • Network

It was a good opportunity to be able to pick the brains of some of the more intelligent poeple responsible for some of the most sophisticated products available. Atthough I do not specifically remember the names of any of the experts I spoke with, this was easily one of the biggest benefits of the conference and makes me want to go back next year.

Lastly, the AWS Re:Play party was pretty well done. A Surprise set by Deadmau5 was the icing on the cake. Although, it is hard to go wrong with a laser obstable challenge, a helicopter course, 50+ bars and buffet style tables and a full fledge techno concert with a bunch of programmers. Well played Amazon…well played…

The Bad
Without getting to the complaining yet, there was some parts of the conference that I think should be improved.

Diversity of the breakout sessions was minimal-to-none. At a certain point, my CTO whispered to me in between sessions that he didn’t know if he could attend another session because he was “too databased out”. This was something that came as a surprise to me since he is a self proclaimed enthusiast on new and improved database technologies.

The experience level of the breakout sessions was hard to determine and was often misleading from their title and description. The result of this was poeple often walking out after discovering they were attending a high level overview of topics they were already familiar with. One person in particular this impacted was or CIO who seemed to have the worst luck when picking sessions. Too frequently between sessions he displayed his dissaproval of the bootcamp sessions.

One thing that left me dissapointed after the conference was that I had only heard of solutions of successful migrations of infrastructures to AWS. During his keynote speech, Amazon CTO Werner Vogels claimed that the point of AWS Re:Invent was to “learn”. This made sense at the time.

Unfortunately, after the bootcamps, breakout sessions and keynotes, I had really only learned of the many startups that had storybook tales to tell of their migrations to AWS. What I did not hear much about were the failures of moving to the cloud and AWS. This was quite ironic to me considering a metaphor that was given during one of the keynote presentations involving a car being painted.(You would know if you heard the metaphor). I will try to find the slide once they become available with the quote on it, but to paraphrase, it said “Do not tell me what is working as it does not accomplish anything. Tell me what is not working. That is how things progress.”

The Ugly
Now for the complaining! I will try to keep this short and sweet.

One of the problems that seemed to persist throughout the entire week was technology failure in bootcamps and breakout sessions. Of course it is hard to cater to 10,000 plus poeple, but as a company who is exposing ‘scalable’ services, it seems that this would be a top priority. Too often, our labs and breakout sessions were interrupted by technology problems. For some, this was a problem more than others. Fortunately, AWS was nice enough to keep open the bootcamp labs for weeks following the conference since so many poeple experienced technical issues.

The time schedule of bootcamps and breakout sessions struck the wrong chord with me. Maybe it is just me, but I was not too fond of having an eight hour bootcamp and having only one hour breakout sessions. It seemed like eight hours was way too long for any developer to sit in one spot for, and one hour was not long enough to cover anything important that cant be read later on.

What would I like to see differently for AWS Re:Invent 2014?

  • More diversity in breakout sessions. This would hopefully leave poeple not feeling so exhausted after hearing discussions on the same problems several times throughout the week.
  • More descriptive and organized breakout sessions so everyone has a better idea of what they are getting themselves into.
  • Equal focus on explaining scenarios that were unsuccessful migrating to the cloud and what could be done to avoid those scenarios.
  • More reliable technology and focus on the software that is running the bootcamps and breakout sessions. Come on Amazon!
  • Shorten the length of bootcamps (maybe into two days) and increase breakout sessions enough so that they can get into more details.
AWS Re:Invent was definitely a success and was an excellent opportunity for me. I hope that I get the opportunity to attend again. Looking forward to AWS Re:Invent 2014!
Here are some pictures from the conference!

Observer Pattern using Generics, Reflection and the Command Pattern

Primarily developing for the web, I don’t often find myself running into brain busting problems in which I must look to design patterns. This is fortunate at times, but I would be lying if I said I didn’t miss the cool satisfaction of the end result of a thoroughly thought out and designed solution to a problem using a nice pattern.

The last true time I was faced with a problem like this, I was working with a colleague of mine on a Form Building application for the desktop. Having not much experience, I was forced to learn from my coworkers on the best practices, and this new buzz word “Design Patterns”.

Since then, although I am limited by the stateless scope of the HTTP protocol, and web development in general, I have attempted to keep my design skills sharp. In a recent post, I showed the implementation of a generic ServiceFactory<T> that could be used to dynamically bind services at runtime using ChannelFactory.  Furthermore, I have continued to sharpen my skills by writing a small “MockMarket” (Bad play on words of a StockMarket…I know). This example would uses the Observer Pattern to facilitate command notifications to observing objects. This example “playfully” resembles a stock market and contains the basic operations one might expect from the stock market. Of course, I know nothing about the stock market, and I don’t care to learn anything more then what I already do, so If I happen to have butchered terminology or logic regarding this context, please forgive me.

Here is a Class Diagram of the Stock Market Application. I have never had much patience for UML diagrams, and this was no different, so forgive my laziness.

Stock Martket Class Diagram - Observer Pattern

If it is not apparent from the diagram, we first and foremost have the two primary components needed when implementing the observer patten: StockProvider which implements IObservable (this object is often called the “subject”) interface, and the StockClientX(s) which implement the IObserver interface(These are known as the “observers”). The StockProvider(subject) maintains a list of its dependent StockClients(observers) and is resposible for notifying them of any changes. The condition on which a notification is sent is dependent on how generic you plan on making your design. In the case of this example, we have generalized the notification scheme the StockProvider uses to handle any type of notification. Later, we will go into more detail how this is accomplished.

Lets start with our interfaces, first we have our IObservable interface contains operations for registering, unregistering and notifying observers.

public interface IObservable
{
   void Notify(ICommand command);
   void Register(Observer observer);
   void UnRegister(Observer observer);
}

 

Our IObserver interface which is an empty itnterface, but will server an important role as as as a contract for all observing types.

public interface IObserver{}

Since we are implementing a stock market application, when a notification is sent out following a certain action executed by the stock market, we will want to know additional information when notified. This leads us to the command pattern. We want to encapsulate the notification, or actions when they are sent. If we wanted, we could even include operations on these command objects. Stock Markets perform many functions, or actions that would cause notifications, but we will focus on four:

  1. Raising Stock
  2. Lowering Stock
  3. Buying Stock
  4. Selling Stock
These are the actions of our stock market that will trigger a Notification to be sent to corresponding observers. These observers will want to know information about the notification they receive which is why these are perfect for our command objects. Since we are using a generalized implementation of the observer pattern, we will want to specify a common contract between these command objects using an ICommand interface.
public interface ICommand{}
For our four command objects, we will implement the ICommand interface. Below is the code for our four command object implementations.
public class StockRaisedCommand : ICommand
{
    public string Symbol {get;set;}
    public int OldPrice { get; set; }
    public int NewPrice { get; set; }
}

public class StockLoweredCommand:ICommand
{
    public string Symbol {get;set;}
    public int OldPrice {get;set;}
    public int NewPrice { get; set; }
}

public class NewStockAddedCommand : ICommand
{
    public string Symbol { get; set; }
    public int Price { get; set; }
    public int Amount {get;set;}
}

public class StockSoldCommand : ICommand
{
    public string Symbol { get; set; }
    public int Price { get; set; }
    public int AmountSold { get; set; }
}
Thanks to some help from a colleague Joseph Kelly, I was able to use generic interface types of type IListener to generalize the command behavior for each StockClient. What does this mean? First, let’s take a look at the IListener interface.
public interface IListener
{
    void Handle(T t);
}

Next, we want to implement our StockClientX(observer) classes. These classes all implement the IObserver interface. The Stock Clients represent any entity in the stock market that will be affected or will take action when any of the four command actions we have specified are notified. Our StockClient(observer) classes will implement the IListener interface to be notified by the StrockProvider(observable) class for a specified ICommand type. The StockClient classes must also implement the IObserver interface to specify a contract and to be collected by the StockProvider class.

public class StockClientA:IObserver,IListener<StockRaisedCommand>,IListener<StockLoweredCommand>
{
    public string Name { get; set; }
    public void Handle(StockRaisedCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles Stock: {1} Raised From Price:${2} to New Price:${3}",
                                    Name,command.Symbol,command.OldPrice,command.NewPrice));
    }

    public void Handle(StockLoweredCommand command)
    {
       Console.WriteLine(String.Format("{0} Handles Stock: {1} Lowered From Price:${2} to New Price:${3}",
                                    Name,command.Symbol,command.OldPrice,command.NewPrice));
    }
}

public class StockClientB:IObserver,IListener<StockLoweredCommand>
                                                    ,IListener<NewStockAddedCommand>
                                                    ,IListener<StockRaisedCommand>
{
    public string Name { get; set; }
    public void Handle(StockLoweredCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles Stock: {1} Lowered From Price:${2} to New Price:${3}",
                                    Name,command.Symbol,command.OldPrice,command.NewPrice));
    }

    public void Handle(NewStockAddedCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles {1} Shares of {2} Stock Added at Price:${3}",
                                    Name,command.Amount,command.Symbol,command.Price));
    }

    public void Handle(StockRaisedCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles Stock: {1} Raised From Price:${2} to New Price:${3}",
                                   Name,command.Symbol,command.OldPrice,command.NewPrice));
    }
}

public class StockClientC : IObserver,IListener<StockRaisedCommand>,
                                                       IListener<NewStockAddedCommand>,
                                                       IListener<StockSoldCommand>
{
    public string Name { get; set; }
    public void Handle(StockRaisedCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles Stock: {1} Raised From Price:${2} to New Price:${3}",
                                             Name,command.Symbol,command.OldPrice,command.NewPrice));
    }

    public void Handle(NewStockAddedCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles {1} Shares of {2} Stock Added at Price:${3}",
                                             Name,command.Amount,command.Symbol,command.Price));
    }

    public void Handle(StockSoldCommand command)
    {
        Console.WriteLine(String.Format("{0} Handles {1} Shares of {2} Stock Sold at Price:${3}",
                                    Name,command.AmountSold,command.Symbol,command.Price));
    }
}

Our StockClientX classes can implement this interface in order to specify which types of commands they wish to be notified for. In our StockProvider class, the Notify() method accepts an argument of type ICommand. In a more realistic setting, it would be preferable to make the parameter types of this method to be  of type T, so that we are not restricted on the types of objects that we notify on, and that we listen for. Taking a more generic approach would allow us to refactor the signature of this method to be Notify(T t) in which any object can be used for notification. In turn, this would allow our clients to not be restricted on the types that they are listening for.

The most important class in our stock market, is the StockObserver class. This class implements the IObservable interface and is the responsible for registering and unregistering our observing StockClient classes, and notifying respective clients listening for a given command object. The Notify() method, uses reflection to find all observing objects for a given type of command object. These observing objects can then be notified and passed the respective command object.
public class StockProvider:IObservable
{
    private List _observers = new List();
    public void Notify(ICommand command)
    {
        var targetType = typeof (IListener<>).MakeGenericType(command.GetType());
        if(_observers.Any(p=>targetType.IsAssignableFrom(p.GetType())))
        {
            IEnumerable observers = _observers.Where(p => targetType.IsAssignableFrom(p.GetType()));
            foreach (var o in observers)
            {
                 Type t = command.GetType();
                 MethodInfo method = o.GetType().GetMethods().SingleOrDefault(p =>p.GetParameters().Any(q => q.ParameterType == command.GetType()));
                 method.Invoke(o, new object[] { command });
            }
       }
    }

    public void Register(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void Unregister(IObserver observer)
    {
        _observers.Add(observer);
    }
}
Lastly. we want to define a simple service that can represent an actual stock market entity with operations corresponding to our command object types.
public interface IStockMarketService
{
    void Open();
    void RaiseStock(int oldPric,int newPrice,string symbol);
    void LowerStock(int oldPrice,int newPrice,string symbol);
    void SellStock(int price,int amountSold,string symbol);
    void BuyStock(int price,int amount,string symbol);
    void Close();
}

public class StockMarketService:IStockMarketService
{
    private IObservable _provider;
    public StockMarketService(IObservable provider)
    {
        /*Initialize Observable StockProvider*/
        _provider = provider;
    }

    public void RaiseStock(int oldPrice, int newPrice, string symbol)
    {
        StockRaisedCommand command = new StockRaisedCommand();
        command.OldPrice = oldPrice;
        command.NewPrice = newPrice;
        command.Symbol = symbol;
        Notify(command);
    }

    public void LowerStock(int oldPrice, int newPrice, string symbol)
    {
        StockLoweredCommand command = new StockLoweredCommand();
        command.OldPrice = oldPrice;
        command.NewPrice = newPrice;
        command.Symbol = symbol;
        Notify(command);
    }

    public void SellStock(int price, int amountSold, string symbol)
    {
        StockSoldCommand command = new StockSoldCommand();
        command.Price = price;
        command.AmountSold = amountSold;
        command.Symbol = symbol;
        Notify(command);
    }

    public void BuyStock(int price, int amount, string symbol)
    {
        NewStockAddedCommand command = new NewStockAddedCommand();
        command.Price = price;
        command.Amount = amount;
        command.Symbol = symbol;
    }

    private void Notify(ICommand command)
    {
       _provider.Notify(command);
    }

    public void Open()
    {
         Console.WriteLine("DING! DING! DING! - The Stock Market Is Open");
    }

    public void Close()
    {
         Console.WriteLine("DING! DING! DING! - The Stock Market Is Closed");
    }
}
And thats it! We now have a scalable, loosely coupled solution for observing and notifying objects. If a client initially is unable to handle a certain command, but later aquires these capabilitis, they can simply implement the IListener interface to receive notification for that command type. This also works the other way around. If a class is initially able to handle notifications for a certain command type, but later is unable to, they can simply remove the IListener declaration for that command type.
In our client, we can mock a simple example of using this StockMarket service that will look like the following:
public static void Main(string[] args)
{
    /*Create Our StockClient Observer Objects*/
    IObserver stockClientA = new StockClientA(){Name = "Stock Client A"};
    IObserver stockClientB = new StockClientB(){Name = "Stock Client B"};
    IObserver stockClientC = new StockClientC(){Name = "Stock Client C"};

    /*Initialize Our Observable StockPRovider*/
    StockProvider provider = new StockProvider();
    provider.Register(stockClientA);
    provider.Register(stockClientB);
    provider.Register(stockClientC);

    /*Initialize StockMarket Service*/
    IStockMarketService stockMarket = new StockMarketService(provider);

    /*Open The Stock Market*/
    stockMarket.Open();

    /*Mock Stack Value Increase*/
    stockMarket.RaiseStock(5,10,"ABC");
    stockMarket.RaiseStock(3,10,"DEF");

    /*Mock Selling High Valued Stock*/
    stockMarket.SellStock(10,10,"ABC");
    stockMarket.SellStock(10,5,"DEF");

    /*Mock Stock Value Decrease*/
    stockMarket.LowerStock(10,4,"ABC");
    stockMarket.LowerStock(10,4,"DEF");

    /*Mock Buying Low Valued Stock*/
    stockMarket.BuyStock(5,10,"ABC");
    stockMarket.BuyStock(4,10,"DEF");

    /*Close The Stock Market*/
    stockMarket.Close();
    Console.ReadLine();
}

The output from this is shown in the following screenshot.

Design Patterns 2.0 Part 1

Recently, I have been taking an interest in the ways Reflection, Generics and additional language features can be used to help improve commonly used design patterns. I am far from an expert in design patterns, and so I like to see what can be done using additional C# language features.

I want to spend a couple posts on some often used, but simple patterns. I figured none is better to start than the Factory/Abstract Factory pattern. I was recently shown by a colleague “the light” regarding using generics and reflection to shorten the amount of code used when implementing design patterns, and figured I would post a short example.

In this sample, I am going to implement a CommandFactory that will handle the creation of command objects signaled by an arbitrary user action. For brevity, we will not actually be doing any concrete implementation inside the different command classes, but will simply be writing out to the console. Additionally, this example will use contract by interface to “isolate” the different command types. This can also be done using inheritance with a base command class.

First, we want to define our interface, which will serve as a contract to our CommandFactory. The ICommand interface will simple have a ExecuteCommand().

public interface ICommand
{
    void ExecuteCommand();
}

Next, we want to create each of our concrete command classes. Each concrete command implementation must implement the ICommand interface. This will make sense later.

public class EnterCommand:ICommand
{
    public void ExecuteCommand()
    {
        Console.WriteLine("Enter Command Executed");
    }
}

public class InsertCommand:ICommand
{
    public void ExecuteCommand()
    {
        Console.WriteLine("Insert Command Executed");
    }
}

public class DeleteCommand:ICommand
{
    public void ExecuteCommand()
    {
        Console.WriteLine("Delete Command Executed");
    }
}
In a real-world application, each concrete implementation would house the code for doing whatever specific operation was desired for that command object. In this case, we only need to know which command object was executed, so we will just write to the console.
Finally, and most important, we have our CommandFactory which contains the logic for instantiating our command objects intelligently. Of course we could use several different ways of doing this such as if/else statements or one big switch statement, but this causes a maintainability nightmare. If additional types are added, we would need to update these statements every time. Instead, we can write our factory one time to use generics and reflection. If done correctly, when a new type is added, the CommandFactory need not know of it, as it is smart enough to create the type. Lets see how this is done.
public class CommandFactory
{
    public static ICommand Create<T>()
    {
        /*Get all Types from Assembly that are assignable To ICommand*/
        IEnumerable assignableTypes = typeof(T).Assembly.GetTypes().Where(p => typeof(ICommand).IsAssignableFrom(p));/*Retrieve Specified Type T from assignable types*/
        Type commandType = assignableTypes.Single(p => p.Name.Equals(typeof(T).Name));

        /*Create instance using specific command type*/
        ICommand command = Activator.CreateInstance(commandType) as ICommand;

        return command;
    }
}

This implementation of CommandFactory is using reflection to search the assembly for all types that are assignable to the ICommand interface. Since Create<T>() is a generic method, we can use the type specifier to compare against the assignable types in the assembly. Once we have found our type, we can just use the Activator to create a default instance of it. If additional parameters or configuration is needed, this can be handled as well. Lets see a  simple example of what this looks like in action.

/*Represents a user action linked to a 'Enter Command'*/
ICommand enterCommand = CommandFactory.Create<EnterCommand>();
enterCommand.ExecuteCommand();

/*Represents a user action linked to a 'Insert Command*/
ICommand insertCommand = CommandFactory.Create<InsertCommand>();
insertCommand.ExecuteCommand();

/*Represents a user action linked to a 'Delete Command*/
ICommand deleteCommand = CommandFactory.Create<DeleteCommand>();
deleteCommand.ExecuteCommand();

There we have it. Our CommandFactory is generic and scalable enough to handle any additions of new ICommand objects as long as they follow the ICommand contract for the  ExecuteCommand() operation.

Generic ServiceFactory Using StructureMap and WCF

Recently taking on a project for a “light weight” CMS system, I looked to the guidance of a colleague Joe Kelly in order to pick his brain on best practices for a completely service oriented system using .NET MVC 3 with StructureMap IoC and WCF. Joe convinced me that separating the contracts and interfaces into a separate referenced assemblies is the only true way of implementing a true loosely coupled service oriented system. This is done so that the contracts do not create dependencies and that services endpoints can be simply swapped out without causing any significant problems.

Having used StructureMap for my IoC container in the past, I was used to registering local service classed with my container that wrapped my WCF services not knowing that this really defeated the purpose of using IoC, and was in fact creating additional dependencies. Joe pointed out that since I am referencing a separate referenced assembly for my contracts and interfaces, I could use WCF ChannelFactory to register my services through proxies with my IoC container. This seemed foreign to me, and sounded like a lot of extra work, but it turns out I was very wrong. I decided to implement a generic ServiceFactory<T> class to handle my proxy creation when registering my services.

This article assumes that you have knowledge of IoC and WCF, and that you have correctly setup your project for using IoC.

Let’s assume that in my web.config, we have the following three WCF services:

  1. AuthenticationService
  2. AccountService
  3. SecurityService
In our web.config, we have the following:
<client>
    <endpoint address="http://localhost/AuthenticationService.svc"
                   binding="basicHttpBinding" bindingConfiguration="AuthenticationServiceEndPoint"
                   contract="WCFService.Authentication.IAuthenticationService" name="AuthenticationServiceEndPoint" />
    <endpoint address="http://localhost/AccountService.svc"
                   binding="basicHttpBinding" bindingConfiguration="AccountServiceEndPoint"
                   contract="WCFService.Account.IAccountService" name="AccountServiceEndPoint" />
    <endpoint address="http://localhost/SecurityService.svc"
                   binding="basicHttpBinding" bindingConfiguration="SecurityServiceEndPoint"
                   contract="WCFService.Security.ISecurityService" name="SecurityServiceEndPoint" />
</client>
<bindings>
    <basicHttpBinding>
        <binding name="AuthenticationServiceEndPoint" closeTimeout="00:01:00"
                     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                     allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                     maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                     messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                     useDefaultWebProxy="true">
                     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                     <security mode="None">
                         <transport clientCredentialType="None" proxyCredentialType="None" realm="">
                             <extendedProtectionPolicy policyEnforcement="Never" />
                         </transport>
                         <message clientCredentialType="UserName" algorithmSuite="Default" />
                     </security>
        </binding>
        <binding name="AccountServiceEndPoint" closeTimeout="00:01:00"
                     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                     allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                     maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                     messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                     useDefaultWebProxy="true">
                     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                     <security mode="None">
                          <transport clientCredentialType="None" proxyCredentialType="None" realm="">
                             <extendedProtectionPolicy policyEnforcement="Never" />
                          </transport>
                          <message clientCredentialType="UserName" algorithmSuite="Default" />
                     </security>
        </binding>
        <binding name="SecurityServiceEndPoint" closeTimeout="00:01:00"
                 openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                 allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                 maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                 messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                 useDefaultWebProxy="true">
                 <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                  <security mode="None">
                      <transport clientCredentialType="None" proxyCredentialType="None" realm="">
                          <extendedProtectionPolicy policyEnforcement="Never" />
                      </transport>
                     <message clientCredentialType="UserName" algorithmSuite="Default" />
                  </security>
        </binding>
    </basicHttpBinding>
</bindings>
Our ServiceFactory<T> class will be responsible for using this information to create proxies to the class. We can use C# reflection to determine which type of Binding we want to pass into  ChannelFactory<T>.
Here is the ServiceFactory<T> class:
public static class ServiceFactory
{
    private static readonly ClientSection _clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;public static T Create<T>()
    {
        T context = default(T);
        foreach(ChannelEndpointElement endpoint in _clientSection.Endpoints)
        {
           if(endpoint.Contract == typeof(T).FullName)
           {
               IEnumerable<Type> assignables = typeof (Binding).Assembly.GetTypes().Where(p => typeof(Binding).IsAssignableFrom(p));
               Type bindingType = assignables.Single(p => p.Name.ToLower().Equals(endpoint.Name));
               context = ChannelFactory<T>.CreateChannel((Binding)Activator.CreateInstance(bindingType,false),new EndpointAddress(endpoint.Address));
           }
        }
        return context;
    }
}
In our Global.asax, we can now register our services contracts directly through our ServiceFactory.Create<T>() method.
protected void Application_Start()
{
    ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);Configure();}protected void Configure()
    {
        ObjectFactory.Configure(x =>
        {
            x.For<IAuthenticationService>().Use(ServiceFactory.Create<IAuthenticationService>());
            x.For<IAccountService>().Use(ServiceFactory.Create<IAccountService>());
            x.For<ISecurityService>().Use(ServiceFactory.Create<ISecurityService());
        });
}

Make sure that you have referenced your central assembly that contains your interfaces and contracts.

Using a ServiceFactorywill ensure that if we were to change anything within the services used outside of their contracts, we will only need to change the endpoint address in the web.config without affecting anything else in our application.

Don’t Distract New Programmers with “The Easy Way Out”

Recently, I came across a blog post by James Hague regarding avoiding teaching Object Oriented Programming techniques to people with little to no programming experience who are looking to learn. The article is called “Don’t Distract New Programmers with OOP” and this article contains my arguments against James’ advice to new programmers on avoiding OOP.

I want to start off by pointing out that I am not a Object Oriented “Fanboy”. I believe that different programming paradigms each have equal importance in their respective problem domains. Functional languages will always be especially useful in mathematics(although I absolutely love it as a DSL in Object Oriented Languages). Logical languages will likely always be used for AI programming and so on. Similarly, Object Oriented Languages will be (or at least should be) the primary paradigm used for applications that use modular business logic.

At its lowest level, programming concepts are language and paradigm independent(for the most part). A conditional statement is a conditional statement no matter what language you write it in, even if they are implemented completely different. In the same way, a loop is a loop and  the focus should be on its purpose and not its specific implementation. The same goes for function/method calls and most often variables. These are all concepts that at the core level of programming and serve a similar if not exact same purpose. It is important these these basic concepts are learned and understood before moving any further. I think that James Hague and most other programmers would all agree on this.

In Hague’s blog article, he starts off by stating the following

Python is good for a wide range of simple and interesting problems that would be too much effort in C. (Seriously, a basic spellchecker can be implemented in a few lines of Python.)

Although I agree that a writing a spellchecker in Python would be trivial compared to C, I disagree with everything else in Hague’s statement.

First, in an article focusing on pointing out the best concepts for teaching programming to new programmers, you state that it “would be too much effort in C.” If effort needed during implementation were the only factor to determine paradigms and languages used, then we would all be in a lot of trouble. Is it not important enough to tell the people you are teaching that the little bit of extra effort of writing in C could result in significant performance differences from that of Python?  Sure, you don’t need performance in a spellchecker, but claiming it would be “too much effort” is not what you should be teaching your students(whoever they may be). Instead, we should be encouraging to use the right tools for the job, regardless of the amount of effort required.

Additionally, when learning programming techniques, is it really such a bad thing to put more effort into something in order to practice these underlying concepts that have been mentioned? Outside of a learning environment, I can understand choosing the option with less effort. Though, while learning, your problem solving threshold needs to be pushed and your way of thinking needs to be remolded in order for you to start to see the big picture. If you simply skip to the “easy way out” (in this case choosing Python over C), than you are overlooking the importance of truly understanding programming at its core level.

Mathematics is an excellent example of this. If taking the “easy way out” was a good way of teaching us the tools needed in mathematics than we wouldn’t bother with basic arithmetic, and we would move straight to using calculators.  We wouldn’t need to learn algebra because we have computers and advanced calculators that can solve any algebra equation known to man. Instead, we begin our study of mathematics by building a foundation of arithmetic. Once we have a sufficient grasp of arithmetic, we can move onto algebra, and so on. This way, we don’t (completely) end up with engineers who don’t know how to add two numbers.

To bring my argument back from its tangent, I use one more excerpt from James blog article:

The shift from procedural to OO brings with it a shift from thinking about problems and solutions to thinking about architecture. That’s easy to see just by comparing a procedural Python program with an object-oriented one. The latter is almost always longer, full of extra interface and indentation and annotations. The temptation is to start moving trivial bits of code into classes and adding all these little methods and anticipating methods that aren’t needed yet but might be someday.

 

This is just a “low blow” coming from somebody who is bitter in accepting the shift from procedural to object oriented, and in that case probably service oriented. It would only be appropriate to point out that the increased benefits of “moving trivial bits of code into classes. and adding all these little methods…” such as maintainability, scalability and testability. Additionally,this “temptation” you speak of is a direct result of your intuition working at its best. The reason you want to move the functionality of a person into its own Person class is because it is intuitive and you can relate to it.  The reason why we build these “crazy class hierarchies” is because that is how they are actually represented as objects. This is why we see the shift from procedural to OOP, because people can understand and relate to the software that they are building.

Am I saying that Object Oriented is the only way to program? No. Am I implying that procedural is a dead paradigm? No. Am I saying that choosing Python over C is always a bad idea? Absolutely Not!

If you are teaching somebody programming, teach them the right way and don’t take the easy way out. If that requires teaching them Object Oriented techniques to explain the functionality of an automobile, then so be it. If that requires you to teach them functional programming in Scheme, then so be it. Although I hope it doesn’t, if it required that you teach them FORTRAN, then so be it.

 

The Annoying HTTP 500.19 Error In IIS 7.5 – URL ReWrite Module

Recently, being given more tasks involving minor administration of sites in IIS, I have ran into several issues that I have had to jump through hoops for in order to get my sites to work.

I just ran into quite an annoying problem that took me some searching to overcome. I want to make sure if anybody else runs into this problem, they do not waste as much time as I do searching for a solution.

My position requires me to look over some already existing sites and often create new ones in the blink of an eye in IIS. In this case, I was asked to create a new instance of a site from one of our development servers to one of our production servers. This seemed simple enough. All I would need to do as I have done many other time is copy over the application, and configure its directory and binding in IIS. Of course, we were encrypting certain values in the Web.config files, but that’s beside the point. Additionally, our web.config file contained several URL Rewrites, which will turn out to be very important.

After initializing the site, and configuring it I received an IIS 500.19 Internal Server Error similar to the following when browsing to the site.

HTTP Error 500.19 Internal Server Error – “The requested page cannot be accessed because the related configuration data for the page is invalid”

Detailed Error information:
Module: IIS Web Core
Notification: Begin Request
Handler: Not yet determined
Error Code: 0x8007000d
Requested URL: http://www.website.com/MyWebSite
Physical path: c:\inetpub\wwwroot\MyWebSite
Login Method: Not yet determined
Login User: Not yet determined
Config Error
Config File: \\?
\C:\inetpub\wwwroot\MyWebSite\web.config

Config Source:
-1:
0:

After searching Google and several blogs, including the following I was unable to come up with any solution. Although, if you are not using ReWrites in your web.config, I would recommend taking a look at any of the following sites.

None of the proposed fixes said anything about rewrites until I had come across
this post regarding a missing rewrite module for IIS. It turns out that all along, the development server had the necessary ReWrite module installed, but the Production server did not. To install the ReWrite module, I went to Using the URL ReWrite Module and installed the correct module on the production server. That solved all my problems.

Following this fix, I cant help but feel that IIS should work on providing a better environment for diagnosing a problem such as this. It would seem fitting that in this event, I was informed that I was missing a required module.