Turning Off Code Block Highlighting in Visual Studio 2010

1. June 2010

I have been using Visual Studio 2010 for a while now and one of the features that drove me crazy was the block highlighting. I went hunting for a way to turn this off. I found it on a MSDN blog post. I have found I like the feature though just no the default colors. Here is the fix I put in place.

Go to Tools –> Options –> Fonts and Colors:

image

In the Display Items list find Collapsible Region Item:

image

Leave the foreground color the default and change the background to a dark gray. I did it with the custom color selector like so.

image

This makes the regions far more eye candy and less ouch.

image

Enjoy.

Converting NUnit Tests to MSTest for CI builds

15. March 2010

So I found a problem that the project I am working on had a bunch of nUnit tests that needed converted to MSTest and I really didn’t want to do a find replace on all the keywords so I did the following.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixtureTearDown = Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute;
using TestFixtureSetUp = Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute;
using Explicit = Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute;

Then you just paste this into the using of your test file, and remove your nUnit references. Bob’s your uncle converted.

Productivity, Testing , ,

Visual Studio 2010 Install fest

3. March 2010

The Tyson internal user group and the North West Arkansas User Group are throwing a party. Visual Studio 2010 is here and we need to install it. Bring yourself, your laptop (optional) and come game and install with us. We are have pizza and drinks and a good time.

GDH Has Agreed to sponsor the food!!! Go GDH!

sponsor-gdh 

 logoTysonLogo image mslogo_black

VS2010Installfest

Directions:

Here is the Bing Map

Please register at http://vs2010installfest.eventbrite.com/

Look Forward to seeing you there.

campus Map

Community

Resharper ? Optimize your code analysis

3. March 2010

When running Resharper against legacy code I have found that I would like to turn off code analysis for certain files, folders, or code blocks so I went hunting in Resharper options land and found the nugget that I was hunting for.

Open Resharper Options:

image

Then go to Code Inspection Settings ?>

image

If you add a Generated Code Region Resharper will ignore everything in that region. You can name it something subtle like ?Resharper Ignore this please? like so.

image

You also have that advanced button that allows you to add entire files and folders to be skipped.

image

 

Enjoy the increased performance of Resharper with all your legacy code.

Resharper and Using Directive clean up

3. March 2010

I have come across something in the project that I am working on that is weird. Resharper marks a using directive as unused because we use it through reflection. When we do a clean up it is removed. So I went hunting and found that you can tell Resharper to never removed certain namespaces. You can also tell it to add certain namespaces by default.

Open your Resharper Options Menu.

image

Then go to language ?> Namespace Import

image

Just click add on the should not be removed for the ones you don?t want deleted and add on the right for the ones that you want to add by default.

 

Enjoy.

WCF Serialization of Cyclic References

2. March 2010

When serializing object to a client through WCF you often have reference objects that are needing to be serialized. This becomes a problem if the 
reference parent and reference child are both of the same type. This causes
WCF to barf over cyclic references. There are two fixes. If you are using
.NET 3.5 or previous you can do this (Thanks to Chabster):

namespace MetroServer.Infrastructure
{
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method)]
    public class CyclicReferencesAwareAttribute : Attribute, IContractBehavior,                                                  IOperationBehavior
    {
        private readonly bool _on;

        public CyclicReferencesAwareAttribute(bool on)
        {
            _on = on;
        }

        public bool On
        {
            get { return (_on); }
        }

        #region IOperationBehavior Members

        void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
        {
            CyclicReferencesAwareContractBehavior.ReplaceDataContractSerializerOperationBehavior(operationDescription, On);
        }

        void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
        {
            CyclicReferencesAwareContractBehavior.ReplaceDataContractSerializerOperationBehavior(operationDescription, On);
        }

        void IOperationBehavior.Validate(OperationDescription operationDescription)
        {
        }

        #endregion

        #region IContractBehavior Members

        void IContractBehavior.AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        void IContractBehavior.ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            CyclicReferencesAwareContractBehavior.ReplaceDataContractSerializerOperationBehaviors(contractDescription, On);
        }

        void IContractBehavior.ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)
        {
            CyclicReferencesAwareContractBehavior.ReplaceDataContractSerializerOperationBehaviors(contractDescription, On);
        }

        void IContractBehavior.Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }

        #endregion
    }

    public class CyclicReferencesAwareContractBehavior : IContractBehavior
    {
        private const Int32 maxItemsInObjectGraph = 0xFFFF;
        private const bool ignoreExtensionDataObject = false;

        private bool _on;

        public CyclicReferencesAwareContractBehavior(bool on)
        {
            _on = on;
        }

        #region IContractBehavior Members

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            ReplaceDataContractSerializerOperationBehaviors(contractDescription, _on);
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            ReplaceDataContractSerializerOperationBehaviors(contractDescription, _on);
        }

        internal static void ReplaceDataContractSerializerOperationBehaviors(ContractDescription contractDescription, bool on)
        {
            foreach (var operation in contractDescription.Operations)
            {
                ReplaceDataContractSerializerOperationBehavior(operation, on);
            }
        }

        internal static void ReplaceDataContractSerializerOperationBehavior(OperationDescription operation, bool on)
        {
            if (operation.Behaviors.Remove(typeof(DataContractSerializerOperationBehavior)) || operation.Behaviors.Remove(typeof(ApplyCyclicDataContractSerializerOperationBehavior)))
            {
                operation.Behaviors.Add(new ApplyCyclicDataContractSerializerOperationBehavior(operation, maxItemsInObjectGraph, ignoreExtensionDataObject, on));
            }
        }

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }

        #endregion
    }

    internal class ApplyCyclicDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
    {
        private readonly Int32 _maxItemsInObjectGraph;
        private readonly bool _ignoreExtensionDataObject;
        private readonly bool _preserveObjectReferences;

        public ApplyCyclicDataContractSerializerOperationBehavior(OperationDescription operationDescription, Int32 maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences)
            : base(operationDescription)
        {
            _maxItemsInObjectGraph = maxItemsInObjectGraph;
            _ignoreExtensionDataObject = ignoreExtensionDataObject;
            _preserveObjectReferences = preserveObjectReferences;
        }

        public override XmlObjectSerializer CreateSerializer(Type type, String name, String ns, IList<Type> knownTypes)
        {
            return (new DataContractSerializer(type, name, ns, knownTypes, _maxItemsInObjectGraph, _ignoreExtensionDataObject, _preserveObjectReferences, null /*dataContractSurrogate*/));
        }

        public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
        {
            return (new DataContractSerializer(type, name, ns, knownTypes, _maxItemsInObjectGraph, _ignoreExtensionDataObject, _preserveObjectReferences, null /*dataContractSurrogate*/));
        }

    }

Usage:

[OperationContract]
[CyclicReferenceAware(true)]
Object MyMethod(int number); 

Or if you use .NET 3.5 SP1 you can do this:

[DataContract(IsReference = true)]
public class MyClass
  {
        [DataMember]
        public string MyProperty{ get; set;}
  }

I think you will agree .NET 3.5 SP1 is better.

LINQ, Lambda and the Learning Curve

3. January 2010

Been away for a while working on a 107,000 hour project. It isn?t done, but I am making time to blog and do my technical mentorship, because I have come to realize that there will always be high priority projects. You have to take the time to train and mentor during those projects because of that. Now on to the show.

I know that LINQ has received a massive welcome from the community and I have to say that it is a deserved on. On the whole it is a great addition to the language. I however don?t like one part of it. Verbose LINQ. I realize that it is more SQL like and that it is perceived to  shorten the learning curve, but I disagree. Lambdas are where the true power of LINQ sit and using verbose to me seems to focus you to learn LINQ one way so that you can re-learn it another.

I am going to focus on the Lambda side of LINQ simply out of preference. Keep an eye out here for the verbose VS. lambda death match, but that is a post for another time.

Lambda statements are actually fairly simple once you break them up.

SomeList.Where(c=>c.Id == someInt);

The above is the lambda conversion of this code block

foreach (Item item in SomeList)
{
    If(item.Id == soemInt)
        SomeOtherList.Add(item);
}

Lets break down the lambda so that this is a bit more clear.

c =>

This statement is declaring that the item in the list we are looking at is going to be held in the local variable named ?c?. This is no different than naming the variable in a for each loop ?c?. You can name your lambda variables more intuitively and I would encourage you to do so. Something like this.

SomeList.Where(menuItem => MenuItem.Id == someInt);

Once the object is declared you have the ability to use all of the members of that object. That is how we are able to use the ?Id? property to check something for a Boolean property. Selecting based on some Boolean expression is the most common use for Lambdas but not the only one.

List<SubMenu> submenus = SomeList.Select(menuItem => new SubMenu() 
                                                   {
                                                         ParentMenuId = menuItem.Id 
                                                   });

In this example we have created a submenu item from all the menu items in the list. We did this through the power of LINQ to let use change the output type of the selection at will. This is very usefull when you are creating items from other items. The code block that would represent is:

List<SubMenu> SubMenus = new List<SubMenu>();

foreach(MenuItem item in SomeList)
{
    SubMenu subMenu = new SubMenu();
    subMenu.ParentMenuId = item.Id;
    SomeOtherList.Add(subMenu);
}

To me this power is amazing. I have the ability to replace entire loops with a single line. The hit to readability is a concern but lambdas lend themselves to so many applications, and are key to LINQ so it should be part of the core toolset of a developer. If you use some sense and name your lambda variables intuitively you should get a lot of great millage out of LINQ without losing your readability.

C#, C# Helpful Functions, .NET

Comments versus Well written code

16. September 2009

So the conversation started today about a guy leaving our team and needing to knowledge transfer his part of the code base to the other team members. The lead programmer on the project told him to stop working on new development and start commenting his code so that the people coming in after him would understand what he had been doing.

Personally the first thing I do when opening a code base that I am not familiar with is to press CTRL-M, CTRL-O and start looking around. ( CTRL-M, CTRL-O is the default visual studio short cut for minimize all outlining. You get to see method declarations, and that is about it.) This will collapse blocks of comments so that they are not intrusive. I never re-expand them. The idea that you need comments for understanding code to me is a big red flag for bad code. I feel well named variables are much more intuitive to learning a new code base than using comments.

I have never sat down to learn an entire code base at one sitting. I am normally working on a small part or a bug fix and need to find something that is very specific. To that end a well named class/method/property is much more helpful with you use the ?Edit->Find? code parser than having to sort through and search all the comments for the set of information that you need.

Also, I am sure that almost everyone has opened a piece of code that had a form1, or class1 class right? Those names that MS graces us with are not supposed to stay named that. Here is the way you avoid this.

Step 1: Go to add class

Step 2: DON?T CLICK OK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Step 3: Look down at the bottom of the dialog and type in something intuitive.

image

Step 4: Go drink something with an umbrella and retire to the happy place of understandable class name land.

To prove my point.

   1:  //This is a class that handles 
   2:  //calculating tax for sales in 
   3:  //several states
   4:  public class class1
   5:  {
   6:          //Calc sales total for a couple states
   7:          //AR - tax 9.5%
   8:          //NM - tax 5.5%
   9:          //TX - tax 8.5%    
  10:          public decimal calc(decimal a, string n)
  11:         {
  12:               //The quick red fox jumped over the lazy brown dog.
  13:               //The quick red fox jumped over the lazy brown dog.
  14:               //The quick red fox jumped over the lazy brown dog.
  15:               //The quick red fox jumped over the lazy brown dog.
  16:               switch(n)
  17:               {
  18:                     case "AR":
  19:                            {
  20:                                  return  a * 1.095;
  21:                             }
  22:                             break;
  23:                      case "TX":
  24:                              {
  25:                                  return a * 1.0875;
  26:                              }
  27:                              break;
  28:                      case "NM":
  29:                             {
  30:                                  return a * 1.055;
  31:                              }
  32:                              break;
  33:                }    
  34:         }
  35:  }

versus my way

   1:  public class MultiStateSalesTaxCalculator
   2:  {
   3:          public decimal ARKANSAS_STATE_SALES_TAX = 0.095;
   4:          public decimal TEXAS_STATE_SALES_TAX = 0.095;
   5:          public decimal NEW_MEXICO_STATE_SALES_TAX = 0.095;
   6:   
   7:          public decimal CalculateSalesTotalWithTaxByState(decimal SubTotal, string stateAbreveation)
   8:         {
   9:               switch(stateAbreveation)
  10:               {
  11:                     case "AR":
  12:                            {
  13:                                  return  SubTotal + ( SubTotal * ARKANSAS_STATE_SALES_TAX)  ;
  14:                             }
  15:                             break;
  16:                      case "TX":
  17:                             {
  18:                                  return SubTotal + ( SubTotal * TEXAS_STATE_SALES_TAX);
  19:                              }
  20:                              break;
  21:                      case "NM":
  22:                             {
  23:                                  return SubTotal + ( SubTotal * NEW_MEXICO_STATE_SALES_TAX);
  24:                              }
  25:                              break;
  26:                }    
  27:         }
  28:  }

C# Functions that might help pt. 1

14. September 2009

When talking to a friend of mine we had the idea to do a blog series over C# functions that might help people if they don?t know about them. This will be categorized so you can keep up on it, and it will be once a week on Mondays. First I was going to start with ?continue?. Nest ifs inside a loop cause major performance issues in most applications but there are a few ways to avoid this. The MSDN definition of continue is ?The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.? . Here is the code snippet that we are going to clean up. ?Caution the following code is not suitable for young viewers or those that are faint of heart.?

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter != null)
                {
                    parameter.MethodName = "Something";
                    if (parameter.children != null)
                    {
                        foreach (var child in parameter.children)
                        {
                            if (child.MethodName == null)
                            {
                                child.MethodName = "Something";
                            }
                        }
                    }
                }
            }

I know right? We can clean this up by inverting the first if to a continue statement.

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                    if (parameter.children != null)
                    {
                        foreach (var child in parameter.children)
                        {
                            if (child.MethodName == null)
                            {
                                child.MethodName = "Something";
                            }
                        }
                     }
            }
We can still clean this up by inverting the children check to a continue statement.
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                if (parameter.children == null) continue;
                foreach (var child in parameter.children)
                {
                    if (child.MethodName == null)
                    {
                        child.MethodName = "Something";
                    }
                }
            }

We can also do this to the if inside the second for each loop.

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                if (parameter.children == null) continue;
                foreach (var child in parameter.children)
                {
                    if (child.MethodName != null) continue;
                    child.MethodName = "Something";
                }
            }

This is a much cleaner section of code but is not great. It still has a nested for each loop. which makes my insides scream, but we will attack that sort of nesting next week.

.NET, Productivity, C# Helpful Functions

Generics ? What you should know?

11. September 2009

I have had some interesting conversations over the last week or so about generics. It was brought up out of a MCTS study group and then in the internal DNUG that I lead. so let me break it down.

Without Generics -

I have to setup collections of objects manual and for each type that I want to use. To add, sort, filter, or aggregate this collection takes a lot of code and time. Some things like ArrayList return objects which means all that casting or reflection over head to get into the objects I need.

With Generics -

I have to setup a collection and give it the input types. It handles sorting, filtering, adding, and aggregates through the use of generic Action<T>, Func<T>, or Predicate<T>. I can write sorts and filters and make them generic so that I don?t have to copy/paste change type.

Generics are not the end all and be all but they help a great deal when you are trying not to repeat yourself. I have found that when using generics that the compiler actually spits out the methods with the implemented types in them, which means that generics while great are syntactic sugar, and I have a sweet tooth.

With Linq being based on the use of IEnumerable<T> and the new parallel extensions to .NET 4.0 being able to spread the workload of Action<T> and Task<T> across multiple processors I would tell everyone. Start learning generics. It is easy to use once you wrap your head around it. Like if I wanted to add two numbers of different types I could write this:

public float Add(int one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(decimal one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(int one, int two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(double one, double two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(int one, double two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(double one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

or I could write this:

public float Add<T, T2>(T one, T2 two)
{
      return float.Parse(one.ToString()) + float.Parse(two.ToString());
}

Which would you prefer?

 

Enjoy, and remember.

Code Like you have to support it.