Chris Eargle

Life Student of the Kodefu Arts

Exposing a Generic List

by chris 30. September 2008 13: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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

c#, design, interfaces

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (0) | Post RSSRSS comment feed

Expression Blend 2 SP1 Preview Released

by chris 26. September 2008 08: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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

expression blend, download

Bleeding Edge

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (0) | Post RSSRSS comment feed

Set Operations in MSBuild

by chris 24. September 2008 14: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)

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

msbuild

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (1) | Post RSSRSS comment feed

Exists in MSBuild 3.5

by chris 23. September 2008 12: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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

msbuild, bug

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (0) | Post RSSRSS comment feed

Environment Variables and MSBuild

by chris 20. September 2008 06: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.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

msbuild, environment variables

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (0) | Post RSSRSS comment feed

Dev InTENsity

by chris 16. September 2008 13: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

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

code camp

Path Notes

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (3) | Post RSSRSS comment feed

Generics Don't Make Me Sad

by chris 15. September 2008 13: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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

generics, list<t>, conversion

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (1) | Post RSSRSS comment feed

ASP.NET MVC Framework Presentation

by chris 10. September 2008 08: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.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

mvc

CEDG

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (0) | Post RSSRSS comment feed

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen

About the author

Chris Eargle Chris Eargle
Enterprise .NET developer in Columbia, SC.

E-mail me Send mail

Pages

  • Presentations

Twitter Updates

    Recent comments

    • Kicking Off 2009 In Style (1)
      Justin James wrote: Congrats to both, particularly the C# MVP! I took … [More]
    • MDC Atlanta (6)
      SEO Dubai wrote: I forgot to congratulate you..:) [More]
    • MDC Atlanta (6)
      SEO Dubai wrote: wish you are happy in your new place.. [More]
    • WCF 3.5 Security Guidelines (9)
      Busby SEO Test wrote: nice work man [More]
    • Project Astoria September 2007 CTP Released (1)
      Busby SEO Test Pinay wrote: good luck to the project, i hope it gonna finish q… [More]
    • Load Balancing Header Issue (5)
      Busby SEO Test wrote: Me too [More]
    • WCF 3.5 Security Guidelines (9)
      Busby SEO Test wrote: nice work man [More]
    • WCF 3.5 Security Guidelines (9)
      Busby seo test wrote: Security indeed is very important in web developme… [More]
    • The Path Is Not a Legal Form (5)
      Busby SEO Test wrote: thanks for the information [More]
    • The Path Is Not a Legal Form (5)
      Busby SEO Test wrote: Thanks for share you analize on this post. [More]

    Archive

    • 2009
      • January (1)
    • 2008
      • December (5)
      • November (4)
      • October (7)
      • September (8)
      • August (5)
      • July (1)
      • June (1)
      • April (4)
      • March (1)
      • February (4)
      • January (5)
    • 2007
      • December (5)
      • November (1)
      • October (6)
      • September (3)
      • August (1)
      • June (1)

    Tags

    • activex
    • addin
    • ado.net data services
    • ajax
    • architecture
    • asp.net
    • astoria
    • azure
    • beta
    • bug
    • c#
    • champs
    • code camp
    • com
    • community
    • communitycredit
    • consolas
    • continuous integration
    • conversion
    • ctp
    • database
    • deployment
    • design
    • design principles
    • download
    • ebook
    • entity
    • entlib
    • environment variables
    • expression blend
    • fail
    • font
    • framework
    • gadget
    • generics
    • grid
    • guidelines
    • icon
    • ineta
    • interfaces
    • jacksonville
    • lamdba
    • linq
    • linqtosql
    • list
    • live mesh
    • macro
    • mdc
    • mobile
    • msbuild
    • msdn
    • msi
    • mvc
    • mvp
    • powertoy
    • preview
    • properties
    • ray ozzie
    • refactoring
    • regasm
    • russ fustino
    • security
    • serialization
    • silverlight
    • snippet
    • source code
    • sql server
    • sql2008
    • sqlmetal
    • srss
    • starter kit
    • stream
    • string
    • tfs2008
    • trial
    • usability
    • ux
    • vb.net
    • vbscript
    • vista
    • visual studio
    • vs2008
    • wcf
    • web
    • winforms
    • wpf
    • xml

    Categories

    • RSS feed for Bleeding EdgeBleeding Edge (5)
    • RSS feed for Build NinjaBuild Ninja (2)
    • RSS feed for CEDGCEDG (2)
    • RSS feed for GeneralGeneral (1)
    • RSS feed for KodefuKodefu (21)
    • RSS feed for Path NotesPath Notes (10)
    • RSS feed for PresentationPresentation (5)
    • RSS feed for TechniquesTechniques (2)
    • RSS feed for TrainingTraining (5)
    • RSS feed for WeaponsWeapons (4)
    • RSS feed for ZenZen (5)

    Archive

    Blogroll

    • RSS feed for Structure Too BigStructure Too Big
      • Should you buy an exten...
      • WorldMaps Update
      • MSDN Roadshow -- coming...
    • RSS feed for Chris CraftChris Craft
      • Alpha Blending and the...
      • How to Resize Images Pa...
      • Raleigh Code Camp Fall...
    Download OPML file OPML

    Disclaimer

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

    © Copyright 2009

    Sign in