DCSIMG
October 2007 - Posts - .NET Geek

.NET Geek

"It is upon the Trunk that a gentleman works" - Confucius

October 2007 - Posts

How to Manage Online Resources

Here's a frequent problem I'm giving another shot at. We all browse the web and every now and then, like every day, find something that's worth keeping. I've long ago quit using browser integrated bookmarks. I just hate it.
I haven't gotten around to try any of the online solutions such as del.ico.us and others. But maybe I should.

A while ago I started to write myself emails with a link to the page I wanted to keep. I'm using Outlook 2007 on Vista so I get excellent index support and finding the emails later is a snap.

In order to introduce a little order in my inbox, I created a sub folder of the inbox named Links. I created a few sub folders of the links folder. For now I just got Dev, Tech and Private. After that I set up rules in outlook to move emails that I have sent to these sub folders. To make this work I add a keyword to the subject of the links I'm sending to myself, "_dev:", "_tech:" and "_pri:". (I'm adding these to the end of the subject to not screw up the sorting)

That gives me a little more structure and I can still search the Links folder and it's sub folders.

How do you organize the information overflow? Do you have any good tips?

Share this post :
Posted: Oct 17 2007, 11:03 PM by Kim | with 4 comment(s)
תגים:

The Best Programming Font

A topic that never seem to get old is the choice of your programming font. Every now and then major dev and tech blogs review and revisit font choices for programmers. Two weeks ago Jeff Atwood did a recap of good programming fonts. He did a pretty extensive review in 2004 as well. Scott Hanselman is another top blogger who often shares his opinions on choosing a font for Visual Studio. (There are so many posts on Fonts on Scott's site that there's no point in linking to them. Just go to his blog and search for font.)

The above wasn't just an excuse to link to Jeff's blog (which has massive traffic), but because I believe CodingHorror did a disservice to my favorite programming font.

Before getting to that I believe that the choice of programming font is important. We often spend the majority of our day in Visual Studio reading and writing code. If anything can assist to minimize eye fatigue and head-aches it is worth doing. Especially if it is as simple as changing a font. The hard part is of course picking a font.

In order to pick a font, it is not enough to view a few high def screen shots and select the one you think looks the prettiest. You need to spend a few hours (or a few days) using the font while registering how you feel with regards to eye fatigue and general tiredness.

About a year ago I did extensive experimentation using different fonts. I decided to spend at least a day on any font that didn't immediately make me sea-sick.

I'll make a long story short. After trying out Lucida Console, Consolas, Courier New (the default), Monacco, Proggy Clean and others I came across Envy Code R. This is a font produced by Damien Guard and it is excellent. It even supports Italic comments in Visual Studio.

This font has a caveat though, it looks really good only when using 10 point size. This is where Coding Horror missed on the font review. Jeff decided to compare the fonts using 11 points.

In the end, picking a font is really a very individual choice. What works for me doesn't necessarily work for you.

I don't think that Courier New, the default font for Visual Studio, is as bad as many argues, but there are better options available. It's worth it to try out a few different options though.

I wonder how many just stick to the default?

Blog vs CodeProject, compare and contrast

It's been over a year since I started this blog. And I like it. I like the online presence it gives. I am gaining a few new contacts and friends and in general it's a cool thing. After the last blogger's meeting at the local Microsoft offices I was full of motivation. I have written more posts in the last week than the last 3 months. (Only 6, but anyhow) I signed up with Feedburner and I've been tracking stats. Slowly growing...

Today I decided to check up on the number of page views of my CodeProject articles. I have only written two articles, but they have been viewed by --- 26,000 --- people!
If you are interested in the articles, here they are:

The blog is obviously more personal and expressive and I get to decide on the content without rigid guidelines.

For now I'll continue with the blog and I'm preparing a few posts on important design principles. I guess the best thing is I don't have to make a black or white choice.

But, you can't argue with the numbers and it just makes me wonder were to focus.

Or maybe numbers isn't everything???

A few comments on the IDesign Coding Guideline

I just finished reading through the latest version of Juval Lowy's C# Coding Standard which I picked up through Maor David's blog. Juval does make the point that the standard document emphasizes breadth as opposed to depth, but some things should be explained. I'm not claiming to be anywhere near Juval's level of expertise, but I think it is important to read experts opinions with a critical eye. There's at least one part of the standard that is IMHO either wrong or misleading depending on how you look at it. It could definitely lead to subtle bugs.

But before we get there I want to make a few other points. For starters, the coding standard is very good. I do question whether someone who doesn't understand the underlying reasoning behind some of the practices will be able to follow them correctly, but it's one of the better coding standards I've seen.

Credit: The texts following the # signs are taken from the guideline. (You did read the license didn't you???)

I disagree with or at least question the following practices:

Section 2 Coding Practices

#4: A method should not have more than 200 lines.
I don't ever want to see a method with 200 lines!

#10b: Use method level comments only as tool tips for other developers.
I don't think this is practical on many projects. Most of the projects I have been working on have been in development for significant periods while the system is still evolving. It often doesn't make sense to produce external documentation on a code base that is still in development, which might be for a very long time. So as a developer I expect to understand most assumptions and intent to be obvious from the source code itself. Following this guideline might depend on the team structure though.

#28: Always use a curly brace scope in an "if" statement, even if it conditions a single statement.
I would create an exemption from this rule for argument guard statements. these are almost always single line ifs. Adding scope braces here only introduce noise in my opinion.
eg.

private void MyMethod(string paramName, object MyObject)

{

    if (string.IsNullOrEmpty(paramName))

        throw new ArgumentNullException("paramName");

    if (MyObject == null)

        throw new ArgumentNullException("MyObject");

 

    // More code here ...

}

#29: Avoid using the ternary conditional operator.
I don't see any problem using the ternary operator for conditions that are clearly read using that operator.

#60: Use application logging and tracing.
This is not a code standard.

Enough nitpicking...

The guideline I have an issue with is the following: (Page 8 #13)
#13: Avoid using "const" on read-only variables. For that use the "readonly " directive.
Throughout the coding standard Juval is deliberately choosing his wording between never, avoid, strive etc. For that reason a naive reader could very well interpret this bullet as "try not to". Juval is of course right in this guideline, but for reasons that should be understood by the developer. In this case I think it's an error to leave the explanation out.
I'll try to illustrate with an example.

Lets say you have the following code in a class library:

public class ServiceClass

{

    public const int MyConst = 12;

    public readonly int MyReadOnlyVar = 10;

}

And you have the following code in another assembly calling the code above.

ServiceClass service = new ServiceClass();

int someValue = ServiceClass.MyConst;

someValue = service.MyReadOnlyVar;

You deploy both the class library and the assembly calling it. After deployment, a change is being made to the class library. you change the values of MyConst to 15 and MyReadOnlyVar to 15. You now release the class library and life is good. Is it?

What's the values of someValue in the two statements below after the second release of the class library? (Spoiler at the end of the post)

int someValue = ServiceClass.MyConst;

someValue = service.MyReadOnlyVar;

Maybe the guideline should be:
Don't use language features you don't really understand. Maybe my main issues is that this isn't a guideline at all, but a workaround to keep a programmer out of trouble. Well, if you don't know the language you'll get into trouble.

 

 

 

 

 

Initially, when the compiler sees the line
int someValue = ServiceClass.MyConst; it replaces ServiceClass.MyConst with 12. At runtime the class library is not called for the value since it is a constant. As a result of this, the code calling into the class library is not aware that the value of ServiceClass.MyConst has changed. It will continue to use the old value 12 while the new value of MyConst is 15.

 

 

Share this post : digg it! dotnetkicks it! reddit!

New blog post series - Sexy or Solid?

A few posts ago I mentioned that I want to come up with a theme for a series of blog posts.

Here are my thoughts and It's important for me to hear what you think.

New technologies are sexy, cool and fun to play with. Despite that, I don't want this blog to be another what's-cool-right-now blog or what's hot off the MS production line. There are many really good blogs out there and I don't think I have anything substantial to contribute in that area.

I feel much stronger writing about design principles and code. I'm thinking of starting a series that will be a mix of important refactorings, design principles and design patterns.

I am a little torn between doing regular text posts or short screencasts/videos. Certain topics are explained just as well with text, but refactorings and code design could be better communicated using video and voice. The drawback of doing video is that it is much more time consuming.

So my questions to you are:

  1. Would you be interested in a more design centric series of posts?
  2. What do you prefer, more code or more concepts? eg. more code samples or more explanations. (lets say I have to prioritize one over the other)
  3. Do you prefer video or textual posts?

Visual Studio productivity tips

For some time I have been subscribing to Sara Ford's blog where she shares useful tips for Visual Studio users.

One of the tips she shared was using Ctrl+K, Ctrl+C (That is a Ctrl+K followed by a Ctrl+C) to comment out the current selection. Ctrl+K, Ctrl+U will do the reverse and remove the comment. Cool I thought, but not very useful to me since CodeRush lets you comment and uncomment using the ' in VB or the / in C#. But then I was in for a surprise. I do a lot of Xml configuration file editing. Adding and removing comments in Xml is slightly more work than in VB or C#. I was happily surprised when I realized that the Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U works for Xml as well. Anything that minimizes the time I have to deal with angle brackets is worth it.

Here's a list of some other nice tips from Sara's blog:

  1. Optimize Visual Studio for multiple monitors
  2. Show shortcut keys in toolbar tooltips
  3. Using the clipboard ring
  4. Cut single line/Delete single line
  5. Collapse and Expand code

Base64 encode large files - very large files

You have just been assigned the task of writing the code to transfer base64 encoded files over the network. No big deal right. Just that the requirement didn't specify the size of the files. So full of ignorance you write the following code. (Ok, not you, but I did)

   Private Function FileToBase64(ByVal filePathName As String) As String
      Dim contents As Byte() = My.Computer.FileSystem.ReadAllBytes(filePathName)
      Return System.Convert.ToBase64String(contents)
   End Function


Everything looks ok and you're getting ready to put the system under some stress testing before releasing the little baby. There's only one little problem. During testing you realize that the call to System.Convert.ToBase64String(contents) crashes your system with an OutOfMemory exception. WTF???

After two cups of coffee you come back to the computer and after some profiling you realize that the .NET LOH (Large Object Heap) is getting exhausted and so are you.

Enough story telling - let's see how we can deal with the problem of serializing a file of arbitrary size. (just limited by disk space)

Since the attempt above obviously crashes because I just tried to read a 1 GB file into memory let's look at an alternative.

The first decision is that we're going to serialize the file to disk and not to memory. Second we're going to do it in C# since VB.NET obviously isn't up to the task. Just kidding...

When we're done we want to be able to call the following method.

      Dim encoder As New Base64Encoder
      encoder.Encode(inputFileName, outputFileName)

After this call the outputFileName should be a base64 encoded version of the input file.

Step 1:
Create a new class

public class Base64Encoder

Step 2:
Since there's no reason to restrict our encoding method to work only on files, we'll create a more general method

/// <summary>
/// Base64 encode data from the source stream and write
/// the encoded data to the target stream.
/// The client is responsible for closing the streams.
/// </summary>
/// <param name="source">stream containing raw data</param>
/// <param name="target">stream that will receive the base64 encoded data</param>
public void Encode(Stream source, Stream target)
{
    if (source == null)
        throw new ArgumentNullException("source");
    if (target == null)
        throw new ArgumentNullException("target");

    byte[] buffer = new byte[BufferSize];
    XmlWriterSettings settings = InitXmlWriterSettings();
    using (XmlWriter writer = XmlWriter.Create(target, settings))
    {
        writer.WriteStartElement(XmlTagImage);
        using (BinaryReader binaryReader = new BinaryReader(source))
        {
            int bytesRead = 0;
            do
            {
                bytesRead = binaryReader.Read(buffer, 0, BufferSize);
                writer.WriteBase64(buffer, 0, bytesRead);
            } while (BufferSize <= bytesRead);
        }
        writer.WriteEndElement();
        writer.Flush();
    }
}

What this method does is reading from the source stream and writing a base64 version into the target stream. This is the method that actually solves the problem. Instead of loading the whole file into memory, the files gets read chunk by chunk. The base64 encoding is done by WriteBase64() method of the XmlWriter.
Note: In order to keep things simple I stuffed a little too much stuff in the Encode method. You probably want to refactor some of that out.

Step 3:
This does put the burden of creating the streams on the client, so we'll overload this call with the following method.

/// <summary>
/// Base64 encode data from the source file and write
/// the encoded data to the target file.
/// </summary>
/// <param name="source">file containing raw data</param>
/// <param name="target">file that will receive the base64 encoded data</param>
public void Encode(string sourceFile, string targetFile)
{
    if (string.IsNullOrEmpty(sourceFile))
        throw new ArgumentNullException("sourceFile");
    if (string.IsNullOrEmpty(targetFile))
        throw new ArgumentNullException("targetFile");

    FileStream source = null;
    FileStream target = null;
    try
    {
        source = new FileStream(sourceFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
        target = new FileStream(targetFile, FileMode.CreateNew);
        Encode(source, target);
    }
    finally
    {
        if (source != null)
            source.Close();
        if (target != null)
            target.Close();
    }
}
One caveat with this solution is that the XmlWriter will not agree to write none conforming Xml. So we'll end up with a file that looks something like this:
<data>LotsOfBase64EncodedData</data>
The <data> tag is the result of writer.WriteStartElement(XmlTagImage); above.

The InitXmlWriterSettings() looks like this:
private static XmlWriterSettings InitXmlWriterSettings()
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;
    settings.OmitXmlDeclaration = true;
    settings.CloseOutput = true;
    return settings;
}

For now the client will have to  ignore those parts, but we should be able to wrap the XmlWriter or alternatively return a stream reader that will skip those parts. For now it does the job and we can happily transfer files of any size.

Share this post :
Posted: Oct 09 2007, 01:07 AM by Kim | with 12 comment(s) |
תגים:,

Summary of 6 months of reading

The last 6 months I've been in a kind of reading frenzy. The goal has been to improve OOD skills and extend the knowledge of Design Patterns.

The first task was to determine which books to read. I wanted to re-read a few books that I have read previously and I was looking for a few new books as well. After a few refinements the list was as following:

New books:

Title Author My Rating (Ok,Good,Excellent)and Comments
Agile Principles, Patterns and Practices in C# Robert C. Martin Excellent
Test Driven Programming by Example Kent Beck Good
Head First Design Patterns Eric Freeman Excellent (I actually finished the book because I liked the style, but it was too basic)
Object Oriented Analysis and Design with Applications Grady Booch Good, but a little dry.
Framework Design Guidelines Brad Abrams+ Excellent
Object Oriented Design Heuristics Riel OK
Composite UI Application Block David Platt Not worth reading unless you are a totally newbie to CAB and SCSF.

Re-read the following books:

Title Author My Rating (Ok,Good,Excellent)
and Comments
Refactoring Martin Fowler Excellent
Design Patterns Explained Shalloway Ok - Skim read.
Pragmatic Programmer Andrew Hunt Excellent - Skim read.
Code Complete 2nd Edition Steve McConnel Excellent - Skim read.
Design Patterns (GOF) GOF Good - Read patterns I don't know or don't often use.

Though outside the scope of the study goal stated above, I also want to read the following books again. They have been gaining significant amounts of dust since last read.

  • Peopleware - DeMarco
  • Mythical Man Month (Anniversary Edition) - Yourdon

I'm pretty much a book worm. I love to read books and I love to have books. Lots of them. Only the software shelf at home has a total of 114 software related books. (I just counted for this post) That's after tossing out a bunch of books on ATL, C and old versions of SQL Server. It was tough, but even Petzold has left the Shelf. No, don't worry I would never actually throw them out. They just had to leave the shelf.

My reading process
I always take notes as I read. I'm happy to underline and sketch in my books. Most of the notes I don't take are not actually taken when I read. Here's how it goes. I read a chapter underlining and marking up what I think is important. After I'm done with a chapter I take a few minutes and write down the most important headlines that I remember from that chapter. These notes are done in a separate reading notebook and are most often a few keywords or very short sentences. I then go back to the beginning of that chapter and take another 2-3 minutes running through the chapter and see if I missed anything. If I did, I jot down whatever I missed in the notebook. At this point I spend 5-10 minutes (Less if it's really trivial) digesting what I just read before starting the next chapter. At certain intervals, usually when I finish a book, I'll review the comments. I found that these reviews tremendously enhances the amount of information I remember.
I get bored easily. It's a fact and I have stopped trying to fight it. I'm not forcing myself to continue to read a certain book when I get bored and I find most of them are boring at times. Instead I read two or three books simultaneously.

Book selection
As stated above, the first task was to decide which books to read. The main problem here isn't to decide which books are good or not, but which books are good for you. Here's a few characteristics that I use.

  1. The objective quality of the content. If it's not good, I don't want to waste time reading the book.
  2. The Author. I tend to go back to authors I know write books I like.
  3. Writing style of the author. Many times I find books that are hard to comprehend because the author's style doesn't fit what I catch easily. This is hard to know before you actually start reading the book.
  4. Relevance of topics included in the book. Too many times otherwise excellent books are littered with topics not relevant to the target audience of the book. I get the feeling that most of the time this is because the author/publisher couldn't/wouldn't target a more specific audience. The end result is a book that is often longer than it should be and less concise.
  5. Amazon rating. Yes I use that. I have fallen victim of false reviews a few times, but I use the following heuristic to assess the reviews. The number of reviews should be above 10 and there should be a substantial number of votes for the reviews. (I know, substantial is a little vague) But if a book has 25 written reviews and 200 votes where more than 90% of the votes are for the given reviews I tend to trust it. It has served me pretty well.

Conclusion
As I stated above, it's not enough that a book is good, it must be good for you. For this reason it's hard to provide a general guide for what books I would recommend you should read. But I'll try to categorize by level of experience and give it a shot.

No matter what your level of knowledge and experience you have, Code Complete and Pragmatic Programmer are required reading.

If you are new to programming, you should look for reading recommendations elsewhere. IMHO, you will only gain substantially from the above books if you have some programming background. Otherwise they are just overwhelming.

If you're only getting your feet wet with OOD and Design patterns I would suggest the following books in the prescribed order.

  1. Head First Design Patterns. An excellent book on OOD and Design patterns. The samples are in Java, but that didn't interfere with the reading experience at all. (I don't do much Java)
  2. Agile Principles, Patterns and Practices in C#. Also an excellent read.
  3. Refactoring.
  4. Take enough time (That would be measured in months) to practice what you just read and come back and review the recommended reading list. :-)

If you have basic knowledge of OOD and Design Patterns I would suggest the following. I would actually skim the GOF book and then do #1 and #2 and then study the GOF book.

  1. Agile Principles, Patterns and Practices in C#.
  2. Refactoring
  3. Design Patterns (GOF)

If you're experienced in OOD and Design Patterns and you have read the books above, you know yourself that reading only gets you that far. Reading more general books probably won't take you to the next level. Find the best developer available to you and spend as much time developing with that person as possible.

Can you recommend any books for me?

Share this post : digg it! dotnetkicks it! reddit!

Schools of Thought - Martial Arts vs Software Development Styles

Uncle Bob of Object Mentor has written a post on the problems of diverse styles of development in software projects.
On the selection of style he writes:

"The problem is, we know that no one style, vision, philosophy, or method is “right”. This knowledge makes us timid. We tolerate other people’s styles and attitudes rather than insisting on a single style and vision for the project. We feel that we have no right to insist on one particular way of doing things, and so we adopt a politically correct viewpoint regarding software."

While I agree on most of the objective points in the post, I have to say that when it comes to Martial Arts - I think Uncle Bob is a little off mark. He compares programming styles to the choice of a martial art such as Tae-Kwon-Do, Karate etc.

"There are many different schools of martial arts. Karate, Tai Kwon Do, Jiu Jitsu, Judo, etc. Which is right? Of course the question is absurd. Right and wrong are not adjectives that apply to individual martial arts. And yet, each martial art attracts dedicated adherents. The intensity of their devotion to their art is almost religious."
...
"Students of Karate have no rational reason to prefer it to Tai Kwon Do."

When the "5 things you didn't know about me" blog posts where flooding the blogoshpere I never responded. But since Martial Arts is a dear subject to me I thought I'll let the word out - I'm a Tae-Kwon-do Black Belt and spent several years actively competing in tournaments. (Ah, those were the days...)

In a choice of Martial Arts it depends on what your goal is. It's not merely an arbitrary choice of style. If you want to get to the Olympics you need to choose one of the styles that participates in the Olympics. If strength is your strongest trait then you wouldn't choose a Martial Art that requires mostly speed and flexibility. If self defense is what you are looking for then you'll pick a Martial Art that excels in that area. If you're just looking for a hobby the I guess the choice might be arbitrary.

IMHO, if you want to drag Martial Arts into the analogy, it's more related to the choice of language and area of development (eg. realtime, MIS, etc.) than style of development. But even then I would object, since the choice of language, platform etc. should be a choice of what's a proper choice for the given project and where you have the potential to excel.