Powered by discountASP.NET
referal ID: sdtref
Why recommend discountASP.NET?

Archives
Steve Trefethen Steve's RSS Feed Subscribe or via email
What's this?
Contact me Send mail to the author(s)
About Me
View my LinkedIn profile

Add to Google
Subscribe with Bloglines
MCP Microsoft Certified Professional

Falafel Software
Online or OnSite TestComplete Training
Blogroll
Recent Comments
My Online Tools
Stats
Total Posts: 472
This Year: 77
This Month: 2
This Week: 1
Comments: 1660
Tags
Disclaimer
The posts on this weblog are provided �AS IS� with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer�s view in any way.
My most popular blog posts (Q1 2008)
# Tuesday, April 15, 2008

C# Source Code Formatting Preferences

Posted @ 1:37AM

Categories: .NET | Opinion | Programming

Tags:  |  | 

I just tried checking in some C# code and ran into a merge error so I fired up Araxis Merge and noticed hundreds of unexpected changes all to whitespace! That was a bummer because I just wanted to check in and call it a night but alas, it’ll have to wait a day. Now, I know code formatting can be a religious issue but...

Here are a few examples, the actual code of which is unimportant for the purposes of this discussion:

1 public void foo(string locator) { 2 try { 3 if (selenium.IsElementPresent(locator)) 4 break; 5 } catch (Exception) { 6 } 7 }
and
1 public void foo(string locator) 2 { 3 try 4 { 5 if (selenium.IsElementPresent(locator)) 6 break; 7 } 8 catch (Exception) 9 { } 10 }

I’d call the latter more "mainstream" as the majority of Open Source projects I’ve looks at (including dasBlog, FileHelpers, RssToolkit, SubSonic, CCNET and SubText) all seem to align the braces with a few exceptions like the empty catch block or a single statement block. I haven’t downloaded the .NET sources yet but I’d be interested to know what Microsoft uses.

Chuck Jazdzewski, a well known 'softie publishes a good deal of C# code on his blog formatted using the top style. A few colleagues, John Waters, Falafel's CTO and Adam Andersen have both blogged using the latter style, here and here respectively.

Which do you prefer? Do you consider either more "mainstream" than the other?

[Update: April 15, 2008] Added a list of OS projects I've looked at.
# Wednesday, January 23, 2008

NDepend and static code analysis for .NET

Posted @ 12:25AM

Categories: .NET | Development | Tools

Tags:  |  | 

Recently, I’ve been spending time analyzing code from a project I’m working on using NDepend 2.6. NDepend is described as...

...a static analyzer that simplifies managing complex .NET code bases.

It digs deep into your code providing an incredible level of detail. Should you decide to take a look at NDepend be sure to give yourself several hours to spelunk as there’s tons to dive into. For starters here is a screenshot of what you can expect when you load a project:

NDepend Static Code Analysis Tool

In this image the mouse (not pictured) is hovering over an assembly name in the Dependencies pane, in the center of this image. Simultaneously the assembly region is is highlighted in the Metrics pane, in the top right.

Querying your code

While I’m still very new to this tool and digging away the thing that’s really caught my attention is CQL. Here’s a closer look at the CQL Query pane:

NDepend CQL Queries Pane

CQL stands for Code Query Language and it’s exactly what it sounds like, SQL for code, the heart of NDepend. In fact, you can check out the CQL v1.5 spec. In the above image, the queries you see are provided by default when you load a new project. On the left is a list of query groups which is a one to many with the queries listed on the right. In the image at the top I’ve selected a query titled "Methods too big" which equates to this in CQL:

// <Name>Methods too big (NbLinesOfCode)</Name>
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE NbLinesOfCode > 30 ORDER BY NbLinesOfCode DESC
// METHODS WHERE NbLinesOfCode > 30 are extremely complex and
// should be split in smaller methods
// (except if they are automatically generated by a tool).
// See the definition of the NbLinesOfCode metric here http://www.ndepend.com/Metrics.aspx#NbLinesOfCode

Notice the blue highlights on the Metrics pane, again the one with the gray sphere’s, which represent methods from the query result set. Double clicking any of the sphere’s opens that method in VS.NET, very nice. Btw, NDepend includes copy/paste syntax highlighting of CQL queries, also a nice touch.

NDepend CQL Intellisense

Clearly, CQL is incredibly powerful and the engine that drives the code analysis used in NDepend. I think it’s a very natural approach for .NET developers and if you’ve worked with SQL at all you’ll find picking up CQL straightforward. Although, NDepend does go one step further by providing CQL Intellisense making it easier to get started with the new query language.

While the Intellisense support is nice it would be even better if it listed things like assemblies, namespaces and types (among others) where appropriate rather than just listing "assembly" or "type".

Continuous Integration Support

If you’ve followed my blog you know I’ve written quite a bit about CruiseControl.NET which NDepend integrates nicely with. Included is a command line tool which will generate your NDepend output for integration with your build results. Here is a short screencast available with more details so I’ll leave it at that.

Conclusion

I’ve already spent numerous hours exploring my code and playing with CQL and I still just scratching the surface. I’ve also managed to find and fix a number of issues and improve and optimize my code. The NDepend website has lots of screencasts on how to accomplish various tasks using NDepend and be sure to read Patrick’s blog for lots more information on NDepend.

What do you use for static code analysis?

In the interest of full disclosure, I was provided a copy of NDepend v2.6.3 for review with no strings attached for which I’d like to thank NDepend’s developer Patrick Smacchia for the license and providing such a great tool to the .NET community!

 
ActiveFocus.netActiveFocus
UNITING TEAMS FOR PEAK PERFORMANCE
Web base Project Management Software
Click here for pricing as well as hosting options
View the roadmap
Ad by Falafel Software
# Sunday, December 09, 2007

Using CruiseControl.NET to manage EDI Invoice processing

Posted @ 11:07PM

Categories: .NET | Development | Open Source

Tags:  |  | 

A few months ago I started working in an area I previously knew little about, EDI. EDI stands for Electronic Data Interchange and it defines standards for how businesses communicate with one another electronically. The basic flow of information for what I’m working on looks like this:

  EDIDiagram
The document numbers above correspond to the following:

  • EDI 850 = Purchase Order (PO)
  • EDI 810 = Invoice
  • EDI 997 = Functional Acknowledgement

My client represents the seller’s side of this diagram and I’m specifically working on the lower half of this picture, the invoicing portion, as there is existing software which handles PO’s. As indicated in light red there is a trading partner involved which brokers various services between buyers and sellers including providing EDI services. The EDI "documents" are cryptic delimited text files exchanged via numerous transport mechanisms though FTP is used in this case.

The Flow

Basically, there is a system which polls the trading partner, again via FTP, looking for new purchase orders. When one is found the file is downloaded, validated, processed and an acknowledged (EDI 997) is transmitted back to the trading partner. Eventually, the order works it’s way through the system and an invoice is generated at which point, an EDI 810 is generated and transmitted to the trading partner, validated and again acknowledged with an EDI 997, a mirror image of the EDI 850 processing. For brevities sake I’m glossing over parts of this process but you get the gist of what’s going on.

When I first was assigned to start working on EDI invoicing I had a lot of things to learn including EDI, the current processes involved in invoicing and the software that handled purchase orders among others. I quickly learned via not so subtle hints that the existing software which handles PO’s wasn’t considered maintainable and is badly in need of replacement.

Using CruiseControl.NET

Once I got my feet grounded I realized this system closely resembled a continuous integration process and started investigating using CruiseControl.NET as the primary engine to drive invoice handling. I already knew CruiseControl.NET brought a number of interesting features to the table including:

  • Open Source
  • Polling architecture for trigging task execution
  • Open plug-in architecture for things like source control providers and task execution
  • Easily configured using XML (ccnet.config)
  • A customizable web based portal for monitoring projects
  • Email publishing for notifications
  • Logging

Basically, you can envision CruiseControl.NET as the two blue circular arrows in the middle of the above diagram. In a future, post talk more about the specific implementations of ISourceControl and ITask that I’ve written to manage this EDI process.

# Thursday, November 01, 2007

Processing CSV files in C# using Open Source FileHelpers Library

Posted @ 1:39AM

Categories: .NET | howto | Open Source | Programming

Tags:  |  |  | 

Scott Hanselman recently posted about parsing CSV files from PowerShell and while I found it interesting I didn’t find the solution to be intuitive though perhaps that’s just me. I’ve recently purchased PowerShell in Action by Bruce Payette and I like the idea of PowerShell though I find myself bailing back to a plain old Command Prompt quite frequently. Anyway, a few days ago I blogged about using the Open Source FileHelpers library for parsing fixed and delimited length files. I thought it might be fun to tackle Scotts problem and see just how difficult it would be to duplicate his solution in C#. Here is what he was parsing (at least a snippet of it anyway):

"File","Hits","Bandwidth"
"/hanselminutes_0026_lo.wma","78173","163625808"
"/hanselminutes_0076_robert_pickering.wma","24626","-1789110063"
"/hanselminutes_0077.wma","17204","1959963618"
"/hanselminutes_0076_robert_pickering.mp3","15796","-55874279"
"/hanselminutes_0078.wma","14832","-1241370004"
"/hanselminutes_0075.mp3","13685","-1840937989"
"/hanselminutes_0075.wma","12129","1276597408"
"/hanselminutes_0078.mp3","11058","-1186433073"

With FileHelpers the first thing to do is define a class that maps the data in your file which for Scott’s data would look something like this:

    [DelimitedRecord(",")]

    class Show

    {

        public string Filename;

        [FieldConverter(typeof(IntConverter))]

        public Int32 downloads;

        [FieldConverter(typeof(IntConverter))]

        public Int32 bandwidth;

    }

Notice the class attribute indicates the separator used. Also notice the member attributes that provide string conversion for the integer values read from the file. Since the integers, unfortunately, have quotes the stock FileHelpers converter won’t work though that’s easily solved by writing a new IntConverted like this:

    public class IntConverter : ConverterBase

    {

        public override object StringToField(string from)

        {

            if (from != "" || from != "\"\"")

                return Convert.ToInt32(from.Substring(1, from.Length - 2));

            else

                return string.Empty;

        }

    }

For parsing the file we use FileHelpers DelimitedFileEngine like this:

     DelimitedFileEngine e = new DelimitedFileEngine(typeof(Show));

     e.Options.IgnoreFirstLines = 1;

     object[] shows = e.ReadFile("c:\\shows.txt");

This creates an instance of the engine passing our Show class type with an option to ignore the first line of the file (the one with column headings). Calling ReadFile parses it into and array of Show objects populated with the data. Next, we’ll change the filename to the episode number using Scott’s regex and sort the data both using anonymous delegates:

    Regex regex = new Regex("\\d{2}(?=[_.])");

    Array.ForEach((Show[])shows, delegate(Show one)

        { one.Filename = regex.Match(one.Filename).ToString(); }

    );

    Array.Sort((Show[])shows, delegate(Show one, Show two)

        { return one.Filename.CompareTo(two.Filename); }

    );

Finally, we sum the downloads and print the data. Note this for loop modifies the array using the first instance of an episode to aggregate the total downloads, perhaps not optimal but gets the job done:

    Show sh = (Show)shows[0];

    for (int i = 1; i < shows.Length; i++)

    {

        if (((Show)shows[i]).Filename.CompareTo(sh.Filename) == 0)

            sh.downloads += ((Show)shows[i]).downloads;

        else

        {

            Console.WriteLine("{0,-4} {1,-6}", sh.Filename, sh.downloads);

            sh = ((Show)shows[i]);

        }

    }

    Console.WriteLine("{0,-4} {1,-6}", sh.Filename, sh.downloads);


So, what’s the point? Well, at the end of Scott’s post he wrote:

It took less time than it would take to write a C# program and it’s easily modified ad-hoc.

Armed with FileHelpers this took no time at all, the bulk of the code is spent working with the data not importing into a usable form. Another point is, IMO the C# code is considerably easier to read. I’m finding that getting my head around PowerShell commands to be a bit awkward. For me PowerShell is tantilizingly powerful but I feel requires a different enough mind set to perhaps thwart rapid adoption. I can empathize with all those people who have "been meaning to try..." Of course, I suppose if we all had the chance to sit down with Lee Holmes things might be different.
# Tuesday, October 30, 2007

Microsoft's interesting "embrace" of Windows Open Source

Posted @ 12:54AM

Categories: .NET | dasBlog | Open Source

Tags:  |  | 

If you follow Microsoft’s web development world you might have noticed an interesting trend dating back to January of this year. You see, back in January they hired RubyCLR guru John Lam. In July they hired top tier (.NET) blogger and lead developer of the dasBlog open source blog engine Scott Hanselmen. More recently they’ve hired Phil Haack, lead developer for SubText another .NET blog engine and now they’ve hired Rob Conery the developer of SubSonic.

It’s possible and perhaps the hiring trend extends further back than January although these four hires alone seem fairly significant in the realm of .NET based OS software. It makes me wonder if perhaps Jeff Atwood is next? He just finished writing An ASP.NET 2.0 Anthology with none other than Phil Haack (and a few others) and already has a deal with Microsoft where they’ll match his OS donations. Of course, ScottGu is a big blogger and he personally reached out to Rob Conery so it wouldn’t surprise me if Scott and his crew have "gone shopping" for people who are influential .NET bloggers as well as OS developers. In fact, Rob talked about the significance of keeping his blog as well as his SubSonic work alive and I’m sure similar conversations occurred with ScottH and Phil.

To top it all off, check out this email from last May that Clemens Vasters (the original dasBlog developer) sent to the dasBlog developer’s mailing list. Here is a quote from that message.

"The purpose of this work is, as indicated, to use the engine as a testbed for a lot of new technologies we’re bringing online in RTM or Beta form over the course of the next several months. The current intent is to have all dasBlog-based bloggers from our division here at Microsoft and also the one or the other official "team blog" run on that testbed."

I’ve been using dasBlog for about a year now and I really like it so all this attention will be interesting to watch. I wonder what it means for SubText?