Always Get Better

Archive for the ‘General Programming’ Category

Display Class Objects in CheckedListBox

Sunday, March 28th, 2010

If you want to use anything more complex than a list of strings in a ListBox, you’re in luck because the control accepts all types of objects.

Custom Objects (Blog Posts) Displayed in a CheckListBox

Custom Objects (Blog Posts) Displayed in a CheckListBox

In this case, I want to display a list of posts found in a blog. Blog is a class which contains Posts, an array of Post classes. To start, I created the CheckedListBox in the form designer, and I add the posts to it like this:

clbPages.Items.AddRange(_blog.Posts);

If I do nothing else, the ListBox will call the Post’s ToString() method and will display as:

Post
Post
Post
Post

We have two options for displaying this correctly:

1. Override the ToString() method. I don’t recommend doing this because ToString() is much more appropriately used in a debugging context.

2. Add a string converter: This will automatically convert each post object to a usable string when called by an object like a ListBox. ListBox uses Convert.ToString() – this uses that converter more appropriately. ToString() should only be used as a fallback.

<pre>
// Use System for the Type object
using System;
// Use ComponentModel for the TypeConvert base class
using System.ComponentModel;

namespace SiteAssistant.Blog
{
    /// <summary>
    /// Converts a post into a list-friendly string, for checkbox lists
    /// </summary>
    class PostConverter : TypeConverter
    {
        /// <summary>
        /// Indicates whether the Post can be converted to a destination type
        /// </summary>
        /// <remarks>
        /// We only support conversions to STRING at present
        /// </remarks>
        /// <param name="context"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context,
            Type destinationType)
        {
            if (destinationType == typeof(string))
                return true;
            else
                return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// Converts the post to the destination type. If the destination
        /// type is not supported, the base Conversion is applied.
        /// </summary>
        /// <remarks>
        /// We only support converting posts to strings at present.
        /// </remarks>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture, object value,
            Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                string text = "";
                Post p = value as Post;
                // Ensure that the Post is not null, avoid errors
                if (null != p)
                {
                    text = p.Title;
                }
                return text;
            }
            else
            {
                return base.ConvertTo(context, culture, value, destinationType);
            }
        }
    }
}
</pre>

The code we write in .NET is like the meat inside a sandwich. The framework is the bread that wraps around our logic and keeps our application together. Our new Posts string converter will be called by the application without us needing to override the Convert function.

It doesn’t happen by magic of course. The final change we have to make is to add information about our conversion function to the posts class:

<pre>
    [System.ComponentModel.TypeConverter(typeof(PostConverter))]
    public class Post
    {
        // Rest of the code goes here
    }
</pre>

That’s all there is to it! Now we can pass a list of Posts to the CheckedListBox and manipulate each item directly. In this application, I will be using this technique to provide the Post object to the text editor with a double-click.

iTunes – The Future, or Just a Toy?

Saturday, February 6th, 2010

Following iTunes’ development has been an interesting experience. We’re moving toward a world in which physical packages of music is a thing of a past; in the meantime we’re stuck with a middling service.

My complaint goes something like this:

My wife recorded Grey’s Anatomy; when she was watching her tape the next day, she was surprised to find advertisements telling her the story from her episode was being continued in a crossover Private Practice on a different channel. Oops.

So I went on iTunes and bought her the episode she missed. $3.50 is pretty steep for a 40 minute TV show but that’s the price you pay for the convenience. After enjoying the program, my wife decided she wanted to see the rest of the season – so I bought that for her too.

When you buy a season of TV, iTunes warns you that any previously purchased episode will be downloaded again – essentially you’d be paying for it again. I can handle that – it makes sense that an item would be sold individually and part as a collection.

Two problems (both stemming from me not digging deep enough into the literature, but also totally unreasonable):
1. When I was billed for the season, I was billed individually for every episode, at the full $3.50 rate. So there was no reason to double-bill me for the episode I’d already purchased since the billing wasn’t based on a ‘full season’ – why is the system unable to correlate previous purchases and prevent the double-purchase?

2. I thought I was buying a whole season of the show – in fact I only bought the episodes that had already been released. A “Season Pass” (pay for the season and new episodes download as they become available) is something completely different… it would have been nice to have been informed of the difference.

$42 is a lot of money to pay for 11 episodes of TV. I don’t think I’ll be dropping a lot of money into iTunes when I can pay half that amount for a full season on DVD – not to mention get the benefits of hard copy, physical media.

My verdict: iTunes is an interesting model and was a fun experiment for us, but not at all cost effective. Bandwidth can be expensive, but the cost of distributing digital media is essentially $0. I would have thought TV episodes could be sold for less than $1 and still make a healthy profit for the content creators (no manufacturing costs, no distribution, no retail partners — Apple takes a cut and the rest is pure profit). What can I say, I was the one who got suckered into paying double the price for half the product.

A Simple Makefile for the Go Language

Tuesday, January 19th, 2010

Hey folks, it’s been awhile!

I’ve been playing with Google’s Go language, and will be sharing what I’ve learned over the coming weeks.

First off, which seems like the easier way to compile your source code? This:

6g fib.go
6l fib.6
mv 6.out fib

or this?


make

Personally, I prefer using a Makefile, even for a small project with one source file.

Without further adieu, a simple Makefile for the Go Language:


GC = 6g
LD = 6l
TARG = fib

O_FILES = fib.6

all:
make clean
make $(TARG)

$(TARG): $(O_FILES)
$(LD) -o $@ $(O_FILES)
@echo "Done. Executable is: $@"

$(O_FILES): %.6: %.go
$(GC) -c $<

clean:
rm -rf *.[$(OS)o] *.a [$(OS)].out _obj $(TARG) *.6

Google Launches Its Own Programming Language

Thursday, November 12th, 2009

Google has taken another step toward world domination with the launch of an experimental new programming languages aptly named “Go”. Go promises to pick up where C and Python left off, providing programmers with a new garbage-collecting low level languages suited to efficient server programming.

I spent the better part of last night looking for a way to get Go‘s tool chain to run under Windows using Cygwin. Unfortunately the tools can’t be created; even if they could, they would produce binary files which would be unusable within Cygwin/Windows due to their low-level nature.

If you are a Windows programmer hoping to give Go a try, your best bet is to download the andLinux distribution – this is a native Linux distribution that runs similar to a virtual machine under Windows. Once you have set it up, go to the Installing Go page for instructions on getting started with the new language.

VISTA: How to fix SQL Server Express Error – CREATE DATABASE permission denied in database ‘master’

Thursday, November 5th, 2009

If you’re using SQL Server Management Studio Express under Windows Vista and see either of these errors:

CREATE DATABASE permission denied in database 'master'

or

The database [Name] is not accessible. (Microsoft.SqlServer.Express.ObjectExplorer)

Here’s the fix:

  1. Close SQL Server Management Studio Express
  2. Open your start menu and locate that program.
  3. Right-click on the Management Studio and choose ‘Run as Administrator’
  4. Fixed!

I swear the simplest solutions can be the hardest to find – hopefully this saves someone (or my forgetful self!) some aggravation.

Speeding up Report Calculations

Saturday, October 10th, 2009
Get Yourself Out of Debt
Creative Commons License photo credit: faungg

When creating reports that are calculation-heavy, it’s tempting to create functions like ‘calculatePercent()’ or ‘calculatedMedian()’ so the correct numbers are available on demand.

Sounds good and convenient, but what happens when you have 100 different calculations to make across 50,000 data records? Each report will take 5 million passes to generate. That could take a long time especially if there are multiple reports being generated.

DRY – Don’t Repeat Yourself

Fortunately, the solution is straightforward. Rather than passing through those 50,000 records 100 times (once for each percentage needed), create an array for your values and calculate ALL of them in one shot. Then, just have calculatePercent() and calculateMedian() call from that array. Sounds simple, and it is as the pseudocode below shows:


for each record:
for each value:
valueList[value].append( record[value] )

The Traditional “Waterfall” Software Development Lifecycle

Sunday, July 12th, 2009

You can still see ghosts of the traditional “waterfall” method of software development in modern agile practices. The traditional model involved long periods of planning followed by development and extended maintenance periods – ideal for long-lived systems (I’m shuddering and thinking of COBOL apps running on mainframes).

With today’s rapidly-evolving platforms and business’ intolerance for risk, developers are called upon to deliver solutions faster on changing hardware and software. The focus has shifted toward quick development cycles and constant integration.

At the basic level, the process is the same: plan, build, deploy.

A full understanding of the traditional “waterfall” software development lifecycle (SDLC) can help any programming communicate more clearly with project managers or clients who are more inclined to understand projects in these terms.

Phase 1: Planning (Logic)

The planning phase of the SDLC involves communicating with the project’s key stakeholders in order to understand the project’s requirements. What are the goals of the project, and what are the expected costs?

At this stage there is no program code involved, nor is there discussion of any particular programming language or framework. The goal is to understand what the new software will do and why; not how.

The planning phase is also the time to assess other possible solutions that could meet the client’s recommendation. This is where most analysts fail – rather than let their project stop at this point, many organizations will endeavour to push their own solution. Try to ignore the dollar signs – if you can meet your clients needs by integrating an existing solution rather than developing something new, you will make them happier because they save money and end up with a product that is completely within their best interests.

Phase 2: Design

The design phase brings us closer to writing code, but we still haven’t opened our IDE yet. At this stage our job is to create the software on paper based upon the requirements we came up with in the previous step.

Many clients feel like they are in over their head when your design starts taking form, but you can’t let them off the hook. You need to take the time to explain your design and make sure the client is fully aware and in agreement with what you are doing. Teach them how to communicate with you; learn the terms they use so you can speak their language.

Phase 3: Implementation

When we start programming, this is the part we envisioned ourselves doing. In reality, this is the part we do the least (assuming we did our job right in phases 1 and 2). We’re talking about getting down and dirt with raw code.

Phase 4: Maintenance

This is the most expensive part of the project – keeping the software running. If you’re lucky you will be gone after phase 3 – if your successor (the maintenance programmer) is lucky you will have done a thorough job of your documentation in all of the previous phases.

Maintenance deserves special thought because it occurs over time, so it gets absorbed as an ongoing cost to the business. It can be hard to justify spending a lot up-front to develop a new system when the existing one “already works, and costs less”. Always weigh the ongoing costs of developing and supporting features for an aging system versus performance gains and optimizations possible with new software.

Sometimes it makes sense to keep existing software in operation; sometimes businesses hold onto decaying systems far too long. There will always be a point where the newer system costs more to operate than the old would have cost for the same stretch of time; however, the total cost of ownership – satisfaction, new features, bug fixes – needs to be considered, not just the cost of implementing the new system.


SEO Powered by Platinum SEO from Techblissonline