Always Get Better

Posts Tagged ‘programming’

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.

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.

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] )

Looking Out My Back Door 2008

Wednesday, December 31st, 2008

Good-bye 2008, you have been good to me. Over the course of the past 12 months I have learned a great deal about who I am and what I can accomplish, leaving me in fine form to hit the ground running in 2009.

Thank you for taking the time to visit my little piece of cyberspace and commenting on some of what I wrote. The discussions were always respectful and informative; there are a lot of smart people riding the intertubes.

I’d like to take a moment now to stop and reflect on the last 12 months before starting the New Year.

January
I started this blog early in January, and skipped all formalities by jumping into a discussion about difficulties I had been experiencing with Google. I still think that was a good choice – I want to avoid making a big deal about this blog (except for occasional posts like this one, obviously) and starting off with the solution to a problem I had been facing was the perfect way to start splashing in the blogosphere. For the remainder of the month I discussed solutions in ASP.NET and the joys of working from home, both subjects which I had a great deal of experience with being simultaneously a full-time student and a full-time programmer.

February
My studies shifted to bizarre Java tricks and database connection tips in February, yielding one of my more popular articles about correctly using the memory management capabilities in C# to properly control database connections in ASP.NET. I am particularly proud of that article because it represented a step forward for me in the way I am able to communicate my ideas, not to mention it solved some of the more frustrating programming problems I had been having at the time.

March
In March my writing took a bit of an ironic tone, starting with my discovery of Google’s “bad page” warning. My writing suffered as I was unfortunately busy with everything from moving into a new home, to end-of-year college projects, to a massive assignment at work, and launching a second blog. As a result Always Get Better stagnated slightly, however the traffic continued to grow.

April
April saw a return to writing about useful tech tips and obscure programming knowledge. I also wrote the blog’s most popular article to date about methods for closing forms in C#; it still generates confusion and misunderstanding so I may revisit the concept in a more detailed article in the New Year. SQL tricks and platform differences were a big deal as well and will continue to be moving forward since I absolutely love SQL.

May
I realized that perfection was not a destination but rather a road to be followed halfway through the year and as a consequence started to take myself less seriously. My biggest time waster in May was in finding solutions to simple ASP.NET problems so I made more effort to publish those as I went along.

June
June was another bad month for blog posts. I only ended up posting a single token snippet referencing parse optimization in SQL on the final day of the month. Lame.

July
July was an incredibly busy month at work but I managed to post while I went through the pain of switching to Vista

August
The stress of July led me to reminisce about the time I once wasted playing MUDs. August was a month of ASP.NET issues, Internet Explorer oddities, and a positive change in my thinking about the future of this blog.

September
In September I had a paradigm shift in my perception of Flash as a programming platform with the discovery of Flex Builder 3. I have learned so much about this tool since those early days and am eager to share some of the knowledge I gained in a series of upcoming posts.

October
The lights went out on Always Get Better in October. This was a dark month for a number of reasons but I can’t make any excuses for not posting at all. One thing I did realize during this month was the need to back off some of my other projects and focus more energy on my writing online. By this time next year I hope to be earning enough from my blogs that I can afford to spend a greater portion of my time working with them.

November
November was a month of Flex, Adobe woes, a change in providers, Drupal databases, Drupal layout, and Drupal administration. I launched a second blog – this time politically-related – with help from my brother which has taken off at an alarming rate.

December
This month was the real eye-opener for me. With so many feeds and connections opened up to me, I feel as though I am watching the recession unfold in slow motion; but I don’t necessarily feel any more informed. Blogs often feel like the same news regurgitated and wrapped in commentary which is a great way to form opinions on issues but not necessarily a great way to understand the complexities of those issues. In my own work, I hope to teach as much as to give opinion – I leave the real journalism to the journalists and pillars of media like the New York Times. Although they claim to have a leaky boat I think they will weather these rocky waters just fine and be prouder for it.

2009 and Beyond
I am endlessly optimistic about the new year and experiences it will bring. I will do my best to make this blog better and will continue the network-building activities I have started this year. My greatest failure in 2008 was not promoting this site very much – in the New Year I will get the word out. Hopefully the items I write will be of use to someone out there. With any luck they might even pop a note in the comments to let me know I was able to do a decent job.

Thank you for sticking with me through this year, and I look forward to an interesting New Year!

The Net is Recession-Proof; Hire a Blogger

Sunday, November 30th, 2008

An interesting article at the Silicon Alley Insider today – recession winners are designers and SEO experts.  Advertising is tricky for businesses because dollars spent can’t always be tracked to dollars earned.  When it comes to designing a web site I like to go with the analogy of a salesperson.  A web site is like an employee who works 24/7, can serve unlimited numbers of customers, and remembers everything they are told about every product.  Every dollar spent on a corporate web site is returned to the company passively over time – and as the site ages and grows in traffic, its value continues to increase.

Those are interesting elements to keep in mind when making purchasing decisions.  As we head into hard times it is more important than ever for businesses to connect to their customers in real and organic ways – social networking is the tool for the job.

For the best bang-for-the-buck, look for companies to increase efforts at creating and maintaining blogs either through the acquisition of in-house writers or by outsourcing to professional bloggers.  Blogs are search-engine darlings, but their real power lies in the fact that people are not just visiting blogs – they are reading them and participating in discussion.

Any company that has not yet begun to consider the benefit of the blogging medium to increase their brand awareness is going to find themselves left behind like the dinosaurs of the industrial revolution.

C#: Using Suffixes to Declare Data Literals

Thursday, May 1st, 2008

This isn’t new, but handy to have.  In order to tell the compiler which data type we’re using, we use suffix notation as follows:

  • Unsigned integer, U: e.g. 34506U
  • Long integer (signed), L: e.g. 5297532L
  • Unsigned long integer, UL: e.g. 30958UL
  • Float, F: e.g. 13.6F
  • Double, D: e.g. 14.3D
  • Decimal, M: e.g. 19.95M

C#: Finding the Number of Days Between Two DateTime Items

Tuesday, April 29th, 2008

One very common requirement is for the number of days elapsed since a particular Date and Time. In C# this can be accomplished through the use of the TimeSpan class.

The easiest way to create a TimeSpan is like this:

TimeSpan tsMySpan = DateTime.Now.Subtract( dtCompareTime );

// The number of days elapsed can be accessed like this:
// tsMySpan.Days


SEO Powered by Platinum SEO from Techblissonline