Bookmark and Share

Exposing a Generic List

by KodefuGuru 30. September 2008 18:35

You're writing a Customer class, and the Customer class contains a collection of Account objects. Because you want to add and remove accounts with ease, you implement this collection as a List<T>.

    public class Customer
    {
        
private List<Account> accounts = new List<Account>();

        
public List<Account> Accounts
        {
            
get { return accounts; }
        }
    }

Life is good. Your tests iterate through the accounts, add new accounts, and remove accounts. However, when you run FxCop, it complains that you shouldn't expose generic lists.

Do not expose List<T> in object models. Use Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V> instead. List<T> is meant to be used from implementation, not in object model API. List<T> is optimized for performance at the cost of long term versioning. For example, if you return List<T> to the client code, you will not ever be able to receive notifications when client code modifies the collection.

FxCop is correct in its assessment as it becomes more difficult to later add underlying functionality. But I feel that it leaves out an important point. You shouldn't expose too much about your implementation, and this relays to the world that Customer uses a List<T>. Consumers of the Employee class don't care that you've implemented List<T>, they only care about the interface. Expose the public property as the interface the consumer should be using. In this example, our consumers want to utilize the interface IList<T>. Refactoring this is pretty easy: modify the property to be IList<Account>.

    public class Customer
    {
        
private List<Account> accounts = new List<Account>();

        
public IList<Account> Accounts
        {
            
get { return accounts; }
        }
    }

In other cases, the consumers may only want to iterate the collection without making modifications. In that situation, expose the list as IEnumerable<T>. The point is to take into account the interface that consumers want to utilize, then hide your implementation.

You shouldn't do it this way if the collection needs to be serialized. In that case, stick with one of the concrete classes such as Collection<T> like FxCop suggested.

Bookmark and Share

Expression Blend 2 SP1 Preview Released

by KodefuGuru 26. September 2008 13:43

The Expression Blend team announced the released of of Service Pack 1 for Expression Blend 2 today. Here are the details for this release.

This Service Pack provides you with all of the functionality you had with our earlier Expression Blend 2.5 June 2008 Preview. Besides allowing you to create new projects for WPF, Silverlight 1, and Silverlight 2 RC, we are also exposing new platform functionality like Font Embedding / Subsetting for Silverlight 2 projects.

You can download the service pack here.

Bookmark and Share

Set Operations in MSBuild

by KodefuGuru 24. September 2008 19:13

There are scenarios where the situation calls for performing set operations on item collections. You may want to join them together, subtract one from another, or perform an inner join. I originally came up with the idea to demonstrate these from this forum question. These examples work in both MSBuild 2.0 and MSBuild 3.5. A 3.5 only version is included with the attachment to this article.

Set Up

Create an empty msbuild file. Add a default target that you will use to perform the set operations and display messages to show your results.

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <
ItemGroup>
        <
SetA Include="alpha;beta;gamma;delta"/>
        <
SetB Include="alpha;gamma;epsilon"/>
    </
ItemGroup>

    <
Target Name="Build">
    </
Target>        
</
Project>
Union All

Perhaps the easiest set operation is the Union All. This operation combines one collection with another, including duplicates. We only have to use the CreateItem including both sets. Add the following code inside your target to see this in action.

<CreateItem Include="@(SetA);@(SetB)" >
    <
Output TaskParameter="Include" ItemName="UnionAllSet"/>
</
CreateItem>

<
Message Text="Union All: @(UnionAllSet)"/>
Minus

The Minus operation works similar to the Union All operation. However, instead of including both sets, you include one set and exclude the other.

        <CreateItem Include="@(SetA)" Exclude="@(SetB)" >
            <
Output TaskParameter="Include" ItemName="MinusSet"/>
        </
CreateItem>

        <
Message Text="Minus: @(MinusSet)"/>
Intersect

Intersect only takes items that are in both collections. It starts to get tricky with this operation and in fact was the catalyst for this article. I attempted to perform this one using conditions, but nothing seemed to work. I finally realized I would have to perform multiple operations to get the desired intersection: take the first set and exclude the minus set.

<CreateItem Include="@(SetA)" Exclude="@(MinusSet)" >
    <
Output TaskParameter="Include" ItemName="IntersectSet"/>
</
CreateItem>

<
Message Text="Intersect: @(IntersectSet)"/>
Union

The Union operation pulls elements from both item collections. This is very similar to Union All except that it does not include duplicates. To accomplish this, take the UnionAllSet and exclude IntersectSet. Since this removes the original and duplicate items, add IntersectSet back to the results.

<CreateItem Include="@(UnionAllSet)" Exclude="@(IntersectSet)" >
    <
Output TaskParameter="Include" ItemName="UnionSet"/>
</
CreateItem>
<
CreateItem Include="@(IntersectSet)" >
    <
Output TaskParameter="Include" ItemName="UnionSet"/>
</
CreateItem>

<
Message Text="Union: @(UnionSet)"/>
Conclusion

These are basic examples of doing set operations in MSBuild. Combined with batching and transforms, there isn't much standing in the way of defining your item collections how you wish.

Be sure to download the samples below. It includes an MSBuild 3.5 version using the new, cleaner ItemGroup syntax.

MSBuildSetOperations.zip (1.12 kb)

Bookmark and Share

Exists in MSBuild 3.5

by KodefuGuru 23. September 2008 17:12

Gael Fraiteur reported differing behavior with the Exists condition in MSBuild 3.5, which has been verified to be a bug by Microsoft.

Here is the setup. Have one file import a file from a different folder. Have that imported file import another relative to that file's path. Add a condition to check if the file exists to the Import task.

File 1 (foo.proj):

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <
Import Project="..\Bar\bar.targets" />
    <
Target Name="Build">
        <
Message Text="$(FooBar)"/>
    </
Target>
</
Project>

File 2 (bar.targets):

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <
Import Project="message.targets" Condition="Exists('message.targets')"/>
</
Project>

File 3 (message.targets):

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <
PropertyGroup>
        <
FooBar>Hello World!</FooBar>
    </
PropertyGroup>
</
Project>

If you run C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\msbuild.exe foo.proj, "Hello World" will be displayed. If you run C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe foo.proj, the text will be empty and nothing will display.

You can use absolute paths to get around this relative pathing issue in Exists. However, in the case of imports, I recommend removing the condition. In most cases your build should fail if the script failed to import a file.

Tags: ,

Kodefu

Bookmark and Share

Environment Variables and MSBuild

by KodefuGuru 20. September 2008 11:26

Everything worked fine the last time I gave my MSBuild presentation. There were no changes to my files, so imagine my surprise when I load things up to practice today only to be met by failures. 

"C:\Demos\Introducing MSBuild\AccountManager\example01.proj" (default target) (1) -> "C:\Demos\Introducing MSBuild\AccountManager\AccountManager.sln" (default target) (2) -> (ValidateSolutionConfiguration target) ->  C:\Demos\Introducing MSBuild\AccountManager\AccountManager.sln.cache(81,5): error MSB4126: The specified solution configuration "Debug|MCD" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration.

The problem indicated by this error message is that the solution configuration is Debug|MCD. More specifically, this means that the platform equals MCD. I looked through all the solution files to find this mysterious MCD platform. I found nothing anywhere. Then I set the property through the msbuild commandline, and everything worked perfectly. The perplexing thing was that I set it to default in the project file if it was empty.

That was the key. It wasn't empty by the time the project file got ahold of it.

Environment variables are passed into MSBuild as properties. Keep this in mind if you're trying to figure out while your builds fail from certain machines due to errors being thrown from invalid property values. In fact, my problem came about because I purchased a new laptop from Gateway. I'm not sure what software they installed that set the environment variable, but it has the potential to wreak havoc on your build process if transitioning to a new build server.

Bookmark and Share

Dev InTENsity

by KodefuGuru 16. September 2008 18:45

I will be presenting at New England Code Camp 10: Dev InTENsity! this weekend. Chris Bowen has posted the schedule on his blog.

Here are my presentations:

Sunday, September 21st 9:00am, Room MPR B (moved to MPR A), New Features in C# 3.0
Sunday, September 21st 12:30PM, Room MPR B, Introducing MSBuild

Bookmark and Share

Generics Don't Make Me Sad

by KodefuGuru 15. September 2008 18:15

I came across an interesting blog post today entitled, "C# generics make me sad..." by Matt Sheppard.

Matt has an issue with generic Lists, in that you can't easily convert from one to another even if one constraint is inherited from the other constraint.

List<String> sl = new List<String>();
List<Object> ol = new List<Object>();
ol = sl;

This will throw the error "Cannot implicitly convert type ‘System.Collections.Generic.List<string>’ to ‘System.Collections.Generic.List<object>’ ."

Matt then tries to cast sl to List<Object>. This fails too, as List<String> and List<Object> are two different classes. String may inherit from Object, but List<String> does not inherit from List<Object>.

One responder provided a link that goes into detail of why this doesn't work. However, the point of this post is to provide a simple solution to Matt's main gripe that "it would be nice to have a clean way to perform an explicit conversion rather than having to manually loop through..."

List<T> does have a method called ConvertAll, although you have to pass in a delegate. It makes for messy looking code, but it is the correct way to solve this problem.

ol = sl.ConvertAll<Object>(new Converter<String, Object>(delegate(String s)
{
      return s;
}));

There is another way to do this with other methods on List<T>. The methods aren't necessarily meant to convert one list to another but result in less mess.

ol.AddRange(sl.ToArray());

I would let either block pass a code review barring other cirumstances.

Bookmark and Share

ASP.NET MVC Framework Presentation

by KodefuGuru 10. September 2008 13:34

The Columbia Enterprise Developers Guild will be meeting today at Midlands Tech NE Campus Auditorium at 6:00 pm. Brian Hitney will be presenting on the ASP.NET MVC Framework. 

Meeting Summary
When:  September 10th, 2008 @ 6:00 PM
Where:  Midlands Tech NE Campus Auditorium
Who:  Brian Hitney
What: MVC Framework
Technical Sponsor: TEKsystems
Agenda
6:00  Pizza and Networking
6:30  Announcements
6:45  Sponsors
7:00  Presentation
8:30  Closing and SWAG Handouts

Topic – Model View Controller Framework

The ASP.NET MVC framework enables you to easily implement the model-view-controller (MVC) pattern for web applications. This pattern lets you separate applications into loosely coupled, pluggable components for application design, processing logic, and display. By separating these concerns, web applications can be easily tested, components plugged and swapped, and the code is just more maintainable. MVC applications also lend themselves to very clean URIs that can be accessed in a RESTful manner.
Presenter – Brian Hitney

Brian Hitney is a Developer Evangelist with Microsoft Corporation, covering North and South Carolina. He frequently delivers presentations and works with local community groups and customers on emerging technologies, .NET, and developer tools. Prior to his Developer Evangelist role, Brian worked as a software engineer on a Windows Vista team in Redmond, and before he joined Microsoft he helped build large scale e-commerce applications for various companies across the United States. Brian is based out of Greensboro, NC.

 

Tags:

CEDG

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
C# MVP, INETA Community Champion


MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er

I have joined Anti-IF Campaign


World Map

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010