Brendan Enrick

Daily Software Development

My First CodeMash

As a late adopter of CodeMash I can say that version 2.0.1.0 was a great event. There were hundreds of developers there ready to learn and try new things. The intelligent, interesting people sparked many worthwhile conversations. If you’re in the area around Sandusky, Ohio, I highly recommend that you attend the next CodeMash.

Not Your Everyday Conference

I was very pleased with how things were handled with CodeMash. It didn’t feel like the standard “sit in your seat while someone talks at you for an hour”. I really think that involving people is the best way to spread knowledge. One of my favorite quotes touches on this perfectly.

Tell me and I forget. Teach me and I remember. Involve me and I learn.

I can’t say what it was like at every session at CodeMash, but the sessions I attended tried to include the audience when possible.

Software Craftsmanship Workshop

CodeMash has a precompiler the day before the event. The precompiler is a day with two time slots of four hours each. Steve Smith and I ran a workshop during that timeslot. Our Software Craftsmanship workshop went very well. We started by introducing everyone to the concept of Software Craftsmanship. At the end of the day I like to boil this down to people caring about writing good, clean software.

So how does one get better at writing good, clean software? Practice.

  • Write something small and write it well.
  • Try new approaches to a known problem to see if you can improve upon it.
  • Follow along with a known good solution and understand how someone else solves things.
  • Take some bad code and refactor it again and again.

In case you haven’t guessed the goal of our workshop was to give people some practice as well as show them how they can practice on their own in the future.

We started with the Bowling Game Kata from Uncle Bob Martin.  First we went through the slides discussing at each step what he was doing and why he was doing it. This is a great exercise because it lets you see what Uncle Bob does when he hits a wall and needs to back up. At one point in the Kata he realizes that the path he is going down is not correct. This shows you how to identify this situation and then how to resolve it.

After this quick introduction we had everyone dive in with their favorite language attempting to calculate the score of a bowling game.

We continued on with some other exercises including: discussion of followed by implementation of a Supermarket Pricing system and we ended with a bit of fun with FizzBuzz.

I hope those who attended enjoyed the experience, and I welcome everyone to come by our Hudson Software Craftsmanship meetings which meet on the third Wednesday of the month in Hudson , Ohio.

Coding Dojo

This year CodeMash also had a Coding Dojo dedicated to these exercises. Instructions were provided explaining the requirements of the exercises. Some are katas like the bowling game and others exercises to challenge you with creating a good, clean solution to a relatively simple problem.

We recommended people work in pairs with someone they didn’t know, but we had a few people working solo.

Sara Ford stopped by the coding dojo and it seems had a beef with my overuse of the word “kata”. If you’re interested, Steve Smith wrote an interesting response discussing coding katas. The bowling game is a kata to be followed along with and matched exactly. The more closely and exactly that one can match how UncleBob does the kata the better. Some of the other challenges presented there I probably should have titled as “exercises”. Next year, I’ll make sure to have more time to prepare the coding dojo. I hope to see you there.

CodeMash 2010 is this week

logo-codemash I will be attending a great regional event this week. The event is called CodeMash and it is located in Sandusky, Ohio. As the CodeMash site describes it.

CodeMash is a unique event that will educate developers on current practices, methodologies, and technology trends in a variety of platforms and development languages such as Java, .Net, Ruby, Python and PHP.

I hope everyone attending has a safe trip there and has a good time. I look forward to seeing you there. You’ll find me at the Precompiler Software Craftsmanship workshop as well as at the Coding Dojo, which will be open Thursday and Friday in the Banyan room.

I look forward to seeing you all there. If you don’t make it out this year, there is always next year. Have a great week everyone!

My 2010 ASP.NET MVP Award

Today I received an email that has started this year off very well. Microsoft has honored me by re-awarding me with an MVP award in the area of ASP.NET this year. Thank you Microsoft.

MVPLogo

Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP/ASP.NET technical communities during the past year.

I intend to continue working towards a better community. I hope everyone else is as well.

HAPPY NEW YEAR!

Silverlight Web Analytics: First Look

Anyone who has ever run a web site or a blog has probably taken a look at analytics packages to see who is visiting. I’ve recently been working on a very exciting project with Telerik, developing an application to provide this valuable information to bloggers and content creators.

To get things started we decided to tackle some of the basics first by asking these few questions:

  • “How many people are visiting my site?”
  • “Which locations drive the most traffic to my site?”
  • “What is my most popular content?”
  • “Who are the people visiting my site?”

From these simple questions we were able to start the application and get the cool demo set up that we were showing at the Telerik booth during PDC 2009.

The application is based around answering these four fundamental questions which are used to present the information to the users.

VisitorDashboard

Site Visit Information

RegionsDashboard

Regional Information

FavoritesDashboard

Most Trafficked Portions

ReferralsDashboard

Referring Locations

I had a great opportunity to speak with Todd Anglin about the project at PDC last month. My discussion of the Silverlight Web Analytics Application is available for viewing on Telerik TV. This demo of the application is a great way to see what we’re working on and give you an idea of what is coming soon.

Subscribe to my RSS feed and come back to read more as I will be posting about the architecture and some of the design decisions we made about the application.

A Quick Answer About Reference Types

Reference types were created to make dealing with pointers a little bit easier. They hide away the details of the pointers, so that the programmer need not think about them. In many ways I think they’re awesome, because they really achieve that goal. The problem is that by abstracting away the details of the pointers they’re sometimes difficult to work with, because they can be a little bit confusing.

I received a comment about this topic on one of my ASP Alliance articles explaining value types and reference types in C#.

First of all the article is excellent.
But why the following program produces output as:: abc:xyz
it should produce xyz:xyz.
I am confused...Plz help
The Code:
string myName = "abc";
string authorName = null;
authorName = myName;
authorName = "xyz";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();
The Actual Output:
abc:xyz
The Expected Output:
xyz:xyz
as it's areference type only one copy is shared between references.

How about if we take this step by step looking at the variables and their values, and I’ll be able to explain why the behavior is as you’ve found. First here is the code we’ll be looking at.

string myName = "Brendan";
string authorName = null;
authorName = myName;
authorName = "Enrick";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();

We are expecting it to print out “Brendan:Enrick”.

Red is for the variables and orange is for referenced values for those variables.

ReferenceTypes1

Notice that when we set a variable equal to a literal string value we get a new location in memory, but when we set it equal to another variable all we are doing is copying the pointer to that memory location. However, when we then set that variable equal to a new literal value it doesn’t replace the old one for both since they each had a pointer. It just creates a new location in memory with that value and assigns a pointer to that variable.

The type of behavior that the writer of this code was trying to achieve could be handled by pointers very easily, but reference types take away control of pointers. Loss of freedom for the sake of safety one might say. Now that I’ve said that everyone will switch back to using c++ to get their pointers back.

Thank you for asking the questions saurabh. I hope this thoroughly answers your question. If you have any more, please feel free to ask them as well.

Expression Blend Issue with Abstract Base Classes

Earlier, I wrote a post about using inheritance with Silverlight UserControls. The post shows really quickly how one can have their UserControl inherit from another class. One tip I’ll mention is that the base class can be abstract, but not if you plan on using Expression Blend. Generally if you have a class which shouldn’t ever be instantiate, you should make it abstract.

The issue is one that I discovered, much to my annoyance, the hard way. As it turns out Expression Blend is currently unable to give a preview of a UserControl that is inheriting from an abstract base class. When you open one of these in Blend you’ll get the Red Box of Death and in it is a message stating, “Exception: Cannot create an instance of “MyClass”.

Not exactly very helpful, but it does at least point you to the fact that there is something wrong with your base class. If you run into this make sure you know that you cannot use a base class. I believe that Blend requires a default constructor, and an abstract class has no constructors.

Solution 1

If you have control of the abstract class, you probably just want to make it a concrete class and hope no one is dumb enough to use it as a concrete class. This is actually a good place for a comment so you have a reminder of why the class is not abstract. Otherwise you might make it abstract again. The comment will also tip someone off that they can make it abstract if Blend ever supports this.

Solution 2

If you don’t have control of the abstract class, perhaps because it is in a class library you’re referencing, you will want to place a concrete class between your class and the abstract. This new class will be the one you specify in your XAML and is thus used by Expression Blend. This one adds an extra layer which really adds nothing and could cause confusion, so I would lean towards the other solution.

Silverlight UserControl Inheritance

One way in which we object-oriented developers try to achieve code reuse is by using inheritance. This allows us to have shared functionality in one place. Awesome we all know how to do this and it’s easy right? Try it in Silverlight for your UserControls. It is a little bit more challenging.

The problem we have is that we’re working with partial classes and these classes are trying to make things difficult for us. One of them is the noticeably declared one in the code behind file. The other one is created from the XAML file. The XAML file declares the base class it is inheriting from. In this instance it is the UserControl class.

Here are the steps required to use a different base class for your UserControls in Silverlight.

1. Create a class inheriting from UserControl and add your desired extras to the class.

2. Create a normal UserControl class and change the base class in the XAML file. You will need to declare an xml namespace for the namespace your base class is in, and use that namespace when declaring the base class.

<UI:MyBaseClass x:Class="MyProject.UI.UserControls.ConcreteImplementation"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:UI="clr-namespace:MyProject.UI" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
 
    </Grid>
</UI:MyBaseClass>

3. Change the inheritance in the code behind (.cs or .vb) file so that it is using the new base class. [Optional – Because of the way partials work you don’t need to declare this one as inheriting from the base class, but it does make things more obvious for someone using the code.]

Enjoy using your base class in Silverlight.

Working with Interfaces - Practical Uses

Expanding on an article I wrote a couple of years ago where I explained interfaces in C#, I’d like to explain why people should use interfaces. I received an email from a reader of my ASP Alliance article. He understands how interfaces work, but he’s trying to see why so many people are raving wildly about their greatness. His questioning of them is great, because it really is not obvious why interfaces are useful. Anyone who says otherwise is just trying to brag.

A couple of years ago, you wrote an article for ASP Alliance called "Understanding Interfaces." Once again, I saw how the code works, once again, I failed to see how it will benefit me.

Here's where everything breaks down for me: You create an interface with just method, property and event signatures. Then you inherit them in a class, recreate these same signatures and write the code to implement these methods and properties.

So I’ll start by mentioning that nearly all patterns, practices, principles, etc. in software development are based on code reuse. One of the most important reasons for code reuse is change. Developers are always responding to and creating changes. We must mitigate the risks of change, identify where changes will occur, and we must make changes.

Right about now you might be thinking, “but interfaces don’t reuse code. They just force you to implement new code. Using inheritance would be the way to achieve code reuse.” You ate technically correct. You understand how interfaces work, but you’re not seeing why we use interfaces. Interfaces themselves do not give us code reuse at all, however, they enable us to achieve code reuse.

Remember that I said that we must identify where changes will occur. Making this identification allows us to isolate changes thus mitigating the risks of changes and allowing us to make changes. Isolating the places that change also allow us the reuse the code which does not change, so by keeping some parts separate we can reuse others. The interfaces are for the places we can’t reuse the code.

Interfaces are “places of change”. Each implementation of the interface is a variation on how that required piece of the puzzle could have been implemented. This is contrary to how you’ll see a lot of interfaces used. It is sometimes difficult to see this as the behavior of interfaces, because people overuse interfaces.

As I see it, I could have saved a whole lot of time by not creating the interface in the first place! I mean, it's not doing any work. I still have to create the signatures in the class. Why on Earth do people praise these things and call them the answer to multiple inheritence? They don't do anything!

It is mostly true that interfaces don’t do anything. As far as being executable code is concerned an interface is basically just a worthless extra step, so why would we use them? Declaring an interface is like saying, “there is more than one way that this behavior could be implemented, but interactions with this behavior should be done this way only.” Having that common “interface” allows us to use any of these implementations interchangeably.

When to Use Interfaces

Some people would recommend that interfaces should be used everywhere. I’ve heard people say that no variable should be declared with a concrete type if it can be avoided. That may be a valid point, but if you’re just learning how interfaces can be useful that is a bad approach. If you don’t see value in interfaces, you will certainly not see the value of them when people use them everywhere. This washes them out and obfuscates their purpose.

Interfaces are used for logic which will have multiple or changing implementations. This means that we should use them in places where we will out of necessity have duplicate logic. Using the interface is what allows us to do this. Take a look at this code for composing a letter.

public string ComposeLetter(string recipientName, 
string messageBody, bool isFormal)
{
string messageText = string.Empty;
if (isFormal)
{
messageText += GetFormalGreeting(recipientName);
}
else
{
messageText += GetCasualGreeting(recipientName);
}

messageText += messageBody;

if (isFormal)
{
messageText += GetFormalSignature();
}
else
{
messageText += GetCasualSignature();
}

return messageText;
}

Notice how we have these flow control operators dictating how the code will execute. What will happen if we need to have a third option for greetings and signatures for family members? We might add another else-if or we might use a switch. Either way this code gets larger and changed every time.

However, if we identify the aspects of the code that are changing we can isolate them and mitigate the risks of changing the code by keeping separate the logic which has multiple implementations. Notice we have already used one form of encapsulation by keeping each of those pieces of logic in separate methods. The logic we haven’t encapsulated is the flow control.

We can create an interface for it. The best name I’ve got for now is IFormalityGenerator, which is not a great name, but it will do for now. I’ll create that interface with two methods: GetGreeting and GetSignature. Very simple interface. Now we can rewrite our method to look like this.

public string ComposeLetter(string recipientName, string messageBody, 
IFormalityGenerator formalityGenerator)
{
string messageText = string.Empty;

messageText += formalityGenerator.GetGreeting(recipientName);

messageText += GetMessageBody();

messageText += formalityGenerator.GetSignature();

return messageText;
}

We now just make the decision sooner and only once which implementation we are using. If this is a formal letter we will use the FormalFormalityGenerator. If it is casual we will use the CasualFormalityGenerator. Down the road when we create one for family members we can just go and create an implementation for the FamilyFormalityGenerator. We’ve made it so we create new code each time instead of going and changing the existing code in this method.

The power of an interface is in its ability to encapsulate the volatile aspects of a program and isolate that which can be reused more easily.

Users Don't Read Your Text

A few days ago Jeff Atwood wrote a great post about users. This is my post adding to his.

I also develop applications, and user interfaces is a common topic of discussion. The interface of an application is one of the most important aspects of it. What a lot of people seem not to realize and Jeff nicely highlights is that users don’t read anything. Trust me. I use a lot of applications, and I avoid reading anything that is more than six or seven letters long.

If I have to read something to use an application you’re probably going to lose me. I am not here to learn your application I am here to use your application. Jeff shows this image as what a user sees on Stack Overflow when writing a question.

su-ask-what-the-user-sees

I think he is a little bit off here. Why? Oh I don’t know, because he includes the preview. I might look at the preview, but only if I am concerned about how something is formatted. If I don’t think I did anything complicated I don’t bother checking the preview. I figure I should be able to use this page while only really reading this section.

su-ask-what-the-user-really-sees

When I need to reference something I will find it on the page. However, the 90% case is going to be this. I’ll make a decision if I need to look elsewhere, and I’ll be annoyed when I have to.

I use Stack Overflow and I think the interface is great Jeff. You support standard keyboard shortcuts, so I can learn what they do and how to format them by only observing the editor and occasionally the preview section. When I need a list I know to use the buttons at the top. Anything that is a standard convention I will follow. You give me a toolbar of choices and keyboard shortcuts and I’m set.

I think it is most important to follow common practice if you want things right. I am not sure why people have such trouble with Stack Overflow’s editor.

Working with the Default Layout of Silverlight RadCharts

The default layout for a RadChart works for most situations. It has a ChartArea, a ChartLegend, and a ChartTitle. These are easy to work with, and if you want you can break from the norm and create your own custom Silverlight Rad Chart layout. If you’re sticking with the default you almost certainly have some settings and properties to which you will want to make adjustments. In order to do that you might define these in the XAML.

<UserControl x:Class="MyApplication.UI.Charts.SuperSweetChart"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:telerikChart="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Charting" 
    xmlns:chart="clr-namespace:Telerik.Windows.Controls.Charting;assembly=Telerik.Windows.Controls.Charting" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <telerikChart:RadChart x:Name="Chart1" 
                               Loaded="Chart1_Loaded">
            <telerikChart:RadChart.DefaultView>
                <chart:ChartDefaultView>
                    <chart:ChartDefaultView.ChartArea>
                        <chart:ChartArea LegendName="CustomLegend" NoDataString="">
                            <chart:ChartArea.DataSeries>
                                <chart:DataSeries x:Name="DataSeries1" >
                                    <chart:DataSeries.Definition>
                                        <chart:PieSeriesDefinition 
                                            LabelOffset="0.6d" 
                                            ShowItemToolTips="True" 
                                            ItemToolTipFormat = "#XCAT" 
                                            DefaultLabelFormat = "#%{p0}" />
                                    </chart:DataSeries.Definition>
                                    <chart:DataPoint YValue="35" />
                                    <chart:DataPoint YValue="15" />
                                    <chart:DataPoint YValue="55" />
                                </chart:DataSeries>
                            </chart:ChartArea.DataSeries>
                        </chart:ChartArea>
                    </chart:ChartDefaultView.ChartArea>
                    
                    <chart:ChartDefaultView.ChartLegend>
                        <chart:ChartLegend x:Name="CustomLegend" 
                                           UseAutoGeneratedItems="True" />
                    </chart:ChartDefaultView.ChartLegend>
                    
                    <chart:ChartDefaultView.ChartTitle>
                        <chart:ChartTitle>
                            <TextBlock Text="Traffic Sources"/>
                        </chart:ChartTitle>
                    </chart:ChartDefaultView.ChartTitle>
                    
                </chart:ChartDefaultView>
            </telerikChart:RadChart.DefaultView>
        </telerikChart:RadChart>
    </Grid>

Notice the three parts are the ChartArea, the ChartLegend, and the ChartTitle. Use the properties of these to make your adjustments. If you don’t want to change these in the XAML then don’t include them. If you’re going to work from the code behind it doesn’t hurt to have these here, but it can be useful.

You can access these in the code behind by either declaring their x:Name property or by referencing them from the RadChart’s x:Name like this. Chart1.DefaultView.ChartArea.

Plus keeping things in here keeps designers happy, and we design-challenged people really appreciate happy designers willing to assist us.