If only I were

Building Great Software

Posts Tagged ‘C#

Func<T> based Generic List Initializers

with 7 comments

A couple of weeks ago I was writing some code to initialize List<T> but my technique was very verbose and it seemed to be a distraction from what I was trying to do. Plus it seemed that every one else was writing about getting their func on.

So I looked back at some code that Nick Parker had written:

   1: public class Builder
   2: {
   3:     public static TType Create<TType>(Action<TType> actionOnTType) where TType : new()
   4:     {
   5:         var item = new TType();
   6:         actionOnTType(item);
   7:         return item;
   8:     }
   9: }

And tweaked it to initialize a list:

   1: public class Builder
   2: {
   3:     public static List<TType> CreateList<TType>(long size, Func<TType> initExpression)
   4:     {
   5:         var items = new List<TType>();
   6:         for (long i = 0; i < size; i++)
   7:         {
   8:             TType item = initExpression();
   9:             items.Add(item);
  10:         }
  11:
  12:         return items;
  13:     }
  14: }

Now I can initialize a list like this:

   1: List<Door> doors = Builder.CreateList(100, () => new Door {IsOpen = false});

Just for the record the Func initialization above could handle much more complex scenarios if needed. My usage is very simple.

Another variation on this is to create an extension method that does the same initialization like this:

   1: public static void Init<TType>(this IList<TType> values, int size, Func<TType> initExpression)
   2: {
   3:     for (int i = 0; i < size; i++)
   4:     {
   5:         TType item = initExpression();
   6:         values.Add(item);
   7:     }
   8: }

And here is how you would use the extension method version:

   1: var doors = new List<Door>();
   2: doors.Init(10, () => new Door());

Thanks to Nick Parker for some suggestions as I was working on this.

Something I would like to figure out is how to do this based on IEnumerable instead of IList. If you have ideas regarding implementing this on IEnumerable please add them as comments.

Also, if you want to see where I was using this, pull down the subversion source here: http://subversion.assembla.com/svn/solon-tools/trunk/Puzzles

kick it on DotNetKicks.com

Written by Chris Sutton

December 6, 2008 at 1:19 pm

Posted in Learning, Technology

Tagged with , ,

Twin Cities Code Camp MVC Session

with one comment

Thanks to everyone who attended my ASP.Net MVC session. I hope you enjoyed it and I hope you get the opportunity to try out what the MVC framework has to offer. The slides have a lot more information than what I was able to get through in my talk. The project is still very young, but has so much potential.

Please leave comments here and let me know what you thought of the session. I’m trying to constantly improve it to make it the right fit.

More ASP.Net MVC Slides.

Written by Chris Sutton

April 8, 2008 at 11:41 am

Twin Cities Code Camp IV

with 3 comments

Yesterday, I was in the Cities at the fourth Twin Cities Code Camp.  It really was a fantastic experience, likely the the best one yet (I presented at the first two code camps as well). From the presentations I attended I would say that the quality of the presentations was very high. They easily would rival what you get at a paid conference. I also met a bunch of people I had never seen in person which is really cool.

Some of the Iowa crowd that went up was Javier Lozano, Bryan Sampica and Greg Wilson. There were several other attendees from Bryan’s company as well. The Iowa presenters and attendees have grown significantly since the first one where I was the sole Iowan as far as I know.

Some interesting people I met/saw were D’Arcy Lussier, Neil Iverson (Inetium), Brandy Favilla (New Horizons), Robert Boedigheimer, Chris Williams (Magenic), Aaron Erickson (Magenic), Kent Tegels (DevelopMentor), Jeff Ferguson, Chris Johnson, Saviz Artang, John Thurow, Kirstin (Magenic), Nicole and Kristen (New Horizons) and Justin Chase.

My favorite session was Neil Iverson’s PowerShell for Developers.  It was a fast paced live demo that kept incrementally building.  Rarely have I been so engaged in a session. D’Arcy’s MVC vs ASP.Net talk was also really interesting.  We only had about 6 people in the session, so we went around the room and said where we were coming from in our ASP.Net development experience. Then D’Arcy showed us how he typically structures his webforms applications, and we peppered him with questions.  I learned a lot from the session.

My talk was the second of the day in the large seminar room so we actually had about 50 people in the session.  One thing that was cool was that D’Arcy Lussier did an intro talk right before mine, so I got to build off of what he did in the session before. Mine seemed to go pretty well. There were a lot of questions and interest in what MVC brings to web development in the Microsoft space.

Jason Bock did a great job again bringing this all together.  It’s a lot of work coordinating an event like this.

If you liked what you got at the Twin Cities Code Camp you’ll definitely want to check out the Iowa Code Camp.  We’ll be a little bit smaller, but have some top notch presenters, a great facility and will have great prizes as well.  The registration is right on the home page and is as simple as it gets.

Written by Chris Sutton

April 6, 2008 at 9:27 pm

TechEd 2008 – Developers

leave a comment »

This year for the first time TechEd is spanning two weeks. The first week is for developers and the second week is for the “other” people – the IT Pro crowd :)

I’ll be working at TechEd as a Technical Learning Guide(TLG) in the Hands on Labs area and may do an Instructor Led Lab. It’ll take 32 hours of the week, but I’m hoping to catch some of the other sessions as well.

The word on the street is that all of the TLG’s will be wearing sexy black shirts, so it should be pretty easy to find us. 

The conference is in Orlando the first week of June. It might be worth checking it out if you have a week to spare and want to get some insight on the latest technologies from Microsoft.

Written by Chris Sutton

March 31, 2008 at 9:34 pm

Posted in Technology

Tagged with , , , ,

PowerShell Hex to Char

with 4 comments

Rob Conery posted a poem in hex on Friday and since I’m playing with PowerShell quite a bit, I decided to convert it back to readable English with some PowerShell.

First, I copied and pasted the hex characters into a text file and saved it as message.txt.

Next, I needed to load the file into a PowerShell variable so I could manipulate it. I’m issued the command in the same directory where message.txt is located.

$m = gc message.txt

Explanation: PowerShell variables are always prefixed with a $ symbol so in this case $m is going to hold the contents of message.txt.  gc is an alias to the Get-Content cmdlet which literally get the contents of a file.

Next, we build up the actual statement to convert the hex values to decimal and then decimal values to a characters.

$m.Split() | % {[Convert]::ToInt32($_,16)} | %{[Convert]::ToChar($_)}

.Net Type Explanation: $m is a string type at this point. You can verify it by issuing this statement – $m.GetType().FullName – and you will get System.String back. PowerShell is built on top of the .Net type system so you have access to all of the same objects and members as you do in C# or VB.Net.  $m.Split() is going to give back an array of strings.

Pipeline Explanation: You can’t go very far in PowerShell without encountering the pipeline. The statement above you read from left to right, and you use the | symbol to separate the statement into three distinct sections. The first section makes an array of strings from the original data.  The second section converts each hex value to an integer and the third section changes the decimal value to a readable character.  Each section of the pipeline gets processed and then the results of the current section get passed to the section to its right so it can do a new set of operations.

% Explanation: The % symbol is an alias to the ForEach-Object cmdlet. It is also aliased as foreach. % is usually going to be paired with a block {} that will be repeated for each item in a list/collection/array.

$_ Explanation: $_ is a variable reference to the current item in the foreach operation.

[Convert] Explanation: Square brackets around a word like [Convert] say that you are invoking a preexisting .Net type called Convert. If you were writing a C# or VB.Net app you could easily call Convert.ToInt32(“32″) and it would convert the string representation to an integer type.  So here, [Convert].ToInt32($_, 16) is an overload of the ToInt32 function that takes a string representation of a hex value and converts it to an integer.

:: Explanation: The :: operator lets you invoke a method or property on a .Net Type, hence we have [Convert]::ToInt32($_,16)

You have to read this poem vertically at this point, but you can do the work to fix that. I’m almost sure there are probably some ways to simplify this expression as well, so feel free to post comments on improvements you would make. This has become a much longer post than I originally intended, but before I sign off here is what the fully qualified expression would look like:

$m.Split() | ForEach-Object {[Convert]::ToInt32($_,16)} | ForEach-Object {[Convert]::ToChar($_)}

Written by Chris Sutton

March 30, 2008 at 2:36 pm

Posted in Technology

Tagged with , , , ,

ReSharper 4 EAP – 764

leave a comment »

I just downloaded and installed nightly build 764 of ReSharper 4. I usually don’t go this bleeding edge, but I’m feeling a little dangerous.

Most people I’ve read say that these builds are pretty stable by now. I’ll post with an update by the end of the week.

Written by Chris Sutton

March 29, 2008 at 7:44 pm

A well-used string extension method

leave a comment »

James-Newton King posted an interesting extension method called FormatWith() that you can call from any string literal or variable.

There are two useful aspects to this function.  1) You can format a string inline instead of wrapping your string with String.Format():

string Name = “Chris”;

“My name is {0}”.FormatWith(Name);

In my opinion, the less you have to nest items – String.Format(“…{0}”) – the easier it will be to read. Chaining items together could be abused, but over all it is simpler for the reader and writer.

2) It allows for named placeholders like this:

Person aPerson = new Person();

aPerson.FirstName = “Chris”;

aPerson.LastName = “Sutton”;

“My full name is {FirstName} {LastName}”.FormatWith(aPerson);

Check out James’ post to see his implementation, its surprisingly simple.

Much of what C# 3.0 brought us was simplified syntax and the potential for code that is easier to read and write (more fluent). This use of extension methods is more natural and expressive and will certainly make my coding cleaner.

Written by Chris Sutton

March 28, 2008 at 8:58 am

Posted in Technology

Tagged with , , ,

Cedar Rapids 2008 Launch Event

leave a comment »

This Monday, March 17th, is our CRIneta.org Visual Studio/SQL Server 2008 Launch Event.  If you want to learn about the new products and you want to have a great time and win from a huge pool of excellent prizes, then go to CRIneta.org and RSVP to be a part of this event.

Tim Barcz, Greg Sohl, Arian Kulp and I are presenting sessions on Visual Studio enhancements, Linq, IIS 7, C# 3, the new .Net Framework features and the new SQL data types.

We have room for 50 people and 38 are RSVP’d already, so don’t wait too long. We are doing the Launch at the Marriott on Collins road in Cedar Rapids. Check the website for more details.

Written by Chris Sutton

March 13, 2008 at 9:18 pm

Iowa Code Camp – Spring 2008

leave a comment »

We are planning our first ever Iowa Code Camp.  It’s going to happen at the University of Iowa’s Conference Center in Iowa City on Saturday May 3rd.

The details are coming together nicely and we already have about 1/2 of our speakers in place.

Our current sponsors are:

  • University of Iowa
  • Microsoft
  • And several others are in the works

We are currently looking for more sponsors to provide some good food, drinks and prizes.

If you are interested in helping in any way, leave me a comment and I’ll make sure to pass your information on to the right person.

Javier has already posted the Code Camp on bostondotnet.org

A New Year in Iowa

with 2 comments

2008 is here and it’s freezing (about 4° F, without wind chill) cold. I pulled out my snowshoes today and hiked for about 40 minutes into a strong headwind. It was a good hike, but I had to duck into a culvert a couple of times to keep my face from freezing. I hope to be outside much more this year (biking, canoeing, hiking, fishing and snowshoeing).

On the tech front I’m going to blog more consistently. Iowa doesn’t currently have many prolific tech bloggers, so I think its time we banded together. Here are a few of the Iowan techies I know: Tim Barcz, Javier Lozano, Arian Kulp, Nick Parker, Tim Gifford and Bryan Sampica.

We are planning the first ever Iowa Code Camp possibly on Saturday March 1st.  There will be more to come on this. If you are interested at all in helping out, please contact me and I’ll get you plugged in. The website is certainly not ready, but I’ll be working on it as I have time.

CRIneta.org held even in attendance and stabilized a bit this year. I’ll likely be president again this year; I’d like to keep the stability and grow the group in 2008. We’ll bring in two Ineta speakers and might get to bring a third national speaker if things work out with one of our sponsors. We’ve also had an excellent experience with our local speakers and want to keep them presenting (Javier, Arian, Nick, Mike Jackson, Eric Johnson and Bryan).

Happy new year.

Written by Chris Sutton

January 1, 2008 at 9:53 pm

Follow

Get every new post delivered to your Inbox.