Recently in Programming Category

Recently I was building a simple web application form where one of select boxes was driven by the value of a different box. The original code for this seemed pretty straightforward, but while the code worked perfectly in Firefox and Chrome, it was producing amazingly strange behaviour in Internet Explorer. Namely, when I’d rebuild the select box, IE would not position the text correctly inside of it, the dropdown wouldn’t appear reliably, and when it would, it wouldn’t necessarily show the correct text for the selections. In one case it was actually displaying four selections, when there were in fact only two. You could use the keyboard to select the values correctly, but this was still absolutely unacceptable behaviour.

I’ll do a write up on the behaviour later this week, but I decided to jump the gun and present the solution I developed first, since I don’t have good simple examples just yet. I ended up trying several ways of creating the options before appending them to the select element, but eventually, I had to completely recycle the selectbox in order to make it behave correctly. I’ve had other pages that didn’t misbehave in quite this way, so I’m trying to figure out the minimum case to recreate the problem before I send it to Microsoft.

Luckily, JavaScript makes it pretty easy to branch code based on browser in a way that doesn’t require doing the browser check all the time. Below is a generic version of the function to do the replacement, which includes calling a ‘change’ event handler, which unfortunately can’t be anonymous (at least in YUI3) since ‘change’ events can’t be simulated. Actually, having to rebind the changeeventhandler every time you change the contents of the select box is the only possible ‘challenge’ in the problem.

The non-IE version is a couple of hundred bytes lighter, and should be faster (though for most use cases, the difference is likely negligible). I’m not sure yet what the increased garbage collection load of this will do to IE, but in my case, that’s not likely to be a problem.

Introducing gallery-slideshow for YUI3

| No Comments | No TrackBacks

Recently, at work, we had a desire to update an instance of a flash-based slideshow widget on our commencement website. This widget did absolutely nothing special, but the real problem we had was that, we didn’t actually have a license for Flash, and the way the slideshow had been built, we needed to be able to build the SWF file from scratch in order to update the order. Since our users rarely come to us with anything that isn’t some sort of emergency, we had to take the flash files to another department to make our quick change and compile a new SWF.

Of course, I knew there was no reason to continue to use unconfigurable Flash for this, but YUI didn’t have a slideshow widget. So, I decided to start writing one. Due to the excellent widget framework, I had a quick-and-dirty example written in a mere couple of hours. Of course, that was not something I was really going to release, though I did push it up to my github.

It was about a week before I was able to return to the project, but I have now submitted a very basic, but functional widget to the Y! CDN.

The javascript to run the above slideshow is simple, for the user:

The CSS that it requires is straightforward, and is part of the widget’s assets:

The widget will automatically take care of placing the images in the upper-left hand corner of the widget’s content box, as well as cycling through all the images using the transition sent in via the animation configuration option.

The core of slideshow is mostly done at this point. I plan to add support for the an image to transition in, instead of only having the top image transition out. Most functionality will likely be added via the plugin framework. And I have several plugins planned.

  • Titles - Adds the widget header which will be populated with the ‘title’ value from the images array.
  • Descriptions - Like Titles, but in the footers. I’m thinking this will take either a string or a function to generate the content of the footer div.
  • Image Centering - This will center all the images in the content box, allowing the slideshow to consist of images of different sizes.
  • Image Navigation - Buttons (probably images with click events, but you get the idea) which will allow the user to force transition between images.

The plugin framework is great because it allows you to customize a widget with exactly the kind of features you need. There are a lot of other kinds of plugins that would be appropriate, and I’m certainly open to feature requests, or pull requests would be better!

Software Testing Club Magazine

| No Comments | No TrackBacks

The Software Testing Club, an organization I had never heard of before Ara Pulido who works for Canonical on the QA Team, mentioned it on her blog, recently released the first issue of the own Community Magazine. Having downloaded and read it over the last few days, I was pretty pleased with the content, and will likely continue to read, especially since my testing chops could use some improvement as I’m expected to be a developer and tester in my current position.

And I would argue that even developers not in dedicated test roles should read this magazine, since it provides good feedback, especially on bug reporting and the mechanisms (and importance) of testing. Unfortunately, the Magazine doesn’t seem to have made any efforts to sort of bridge that gap between developers and testers. To be fair, it was written by people focusing on test, and developers have often been harsh toward testers, so I’m not necessarily blaming them for the making fun of developers that’s done. I merely found it interesting how prevalent media around this conflict are.

The only real complaint I have with the magazine is that it does have some editing issue. Sentences getting cut off at page breaks, obvious typos, etc. I hope that the STC can improve their processes and put out a more polished community magazine in the future. Still, for a first effort it’s a good read, and it has plenty of information I’m still mulling over.

Bazaar Version Control Thoughts

| No Comments | No TrackBacks

It’s been a while since I’ve posted on this topic, but I’ve been giving a lot of thought to open source distributed version control systems (DVCS) again. In my opinion, this space has essentially become a three-horse race, between bazaar, git, and mercurial. At this time, I can’t even guess which is used more between git and bazaar. Git powering projects like the Linux kernel, gnome, not to forget everything on github. Bazaar, however, is the VCS of choice for Launchpad, which hosts a ton of code too. Mercurial, isn’t a bad system, but from my perspective, it’s not different enough from git to bother, while I definitely see the niche that bazaar fills. Obviously, my opinion on Mercurial is not the only one, but I’ve talked about git before, though I might want to revisit the subject.

Today however, is about Bazaar. Mostly, I find Bazaar fills a really interesting niche that I hadn’t realized before. Developers had long been talking about the need for version control, and systems like Subversion have often been viewed as simple introductions into these concepts, since they’re pretty straightforward to use. However, Bazaar is fantastic, because in many ways it takes the simplicity (and familiarity) of a system like subversion, but applies distributed concepts that will benefit all developers.

I’ve a firm believer in DVCS, particularly with the ease of branching, merging, local commits, easy sharing… Bazaar works as a great tool. Personally, it hasn’t replaced git as my preferred VCS system, but I’ve been using it a fair amount lately on Launchpad (and it’s Launchpad integration is flat amazing), and I’ve come to appreciate the niche that it follows. Basically, if something like git, which I can see why a person would find fairly alien, is unpalatable for some reason, I think bazaar bridges the gap in an intersting fashion, and can bring people into the distributed mindset with a minimum amount of pain.

My feelings toward bazaar are mixed. It’s a really capable system, it works really well, and it hides away it’s complexity in a way that would be really non-intimidating to new users. But, it’s so simple, that certain things don’t work in a way I like. I don’t like that I need to create new directories for branches. I don’t like that I can’t seem to pull commits from a remote repo without performing a merge (something I use sometimes to aide in certain merges). I don’t like that I have to use a more complex command to get the ‘real’ revision history (ie, the one that includes merges).

Bazaar is awesome. And I’m going to gladly continue using it for projects hosted in Bazaar. But for me, Git still wins.

Working with Resource Files on Visual Studio

| No Comments | No TrackBacks

I had an unusual problem recently that took way too long for me to solve. I was trying to add resource files to a Silverlight project for the purposes of future proofing our application to be localizable, and to make maintaining strings like Tooltips easier. However, even while following the official documentation from Microsoft, I couldn’t get the damn thing to work.

Specifically, when I tried to add the Resource file to my Silverlight project (using these instructions), I couldn’t have it generate code. It wouldn’t generate any code, but what’s worse, it didn’t provide an error (or even a warning or message) when it failed.

The problem appears to be that the instructions say to right click on the project and add the Resource file using the normal “Add new…” function of Visual Studio. However, at least on Silverlight projects, these files are not placed under the “Resources” folder like they’re supposed to be. You need to create the Resources folder, and right click on THAT folder when you add the Resource file.

I ended up basically finding this by accident when looking through examples and I finally noticed that these other people all had their resx files in Resource folders, so if you’re having trouble with code-generation of resx files in Visual Studio 2008, just make sure they were in the right location, because you’re not likely to get anything to help you from Visual Studio.

OpenSource .NET Concurrency

| No Comments | No TrackBacks

In talking a bit more about the concurrency issue I mentioned yesterday, I only alluded about one .NET threading concurrency library, Microsoft’s forthcoming PLINQ. Go figure that that same day Miguel de Icaza would link to another group who’s been working on this problem for years (and whom I should have remembered sooner).

MindTouch works on web-based enterprise collaboration tools built on .NET, but they’ve also developed a threading and concurrency model that, according to the Mindtouch presentation at the recent Monospace conference, vastly outperforms the existing thread pools in .NET. I’ve got a project I’m doing design work on that could benefit greatly from strong thread pooling, so I’m looking forward to downloading the Core version of MindTouch, and seeing what I can do with it.

video platform video management video solutions free video player

The Future of Systems Programming? Google's Go

| No Comments | No TrackBacks

The big G announced a new language being worked on internally today, that they hope will revolutionize systems programming. I was highly focused on systems programming when I started, and it’s still an interest, so I was curious what Go would have to offer beyond what was available today in other languages.

What I’ve seen, is very interesting. It’s similar in syntax to something like C, which is little surprise considering that Ken Thompson is a contributor, but like a lot of what Google’s been working on lately, it’s designed with concurrency and multi-core in mind. This is hugely important, since processors aren’t getting any faster, but we are seeing more and more cores on each processor.

Even modern languages, like C#, only provide easy concurrency support at the library level, and those libraries are mostly research projects which haven’t quite hit general availability yet. Having this built into a language as a consideration from the base level of the design stands to make certain classes of tasks much easier.

I’m probably going to have more Go posts in coming weeks as I play around with the language some more, and try to learn what it can do, but for now, the introduction video from the Google Tech Talk is a must watch.

YUI3 Gallery - Community Driven Development

| No Comments | No TrackBacks

Dav Glass has probably become one of my favorite people on the Internet. The work he’s done in the last year or so to make the Yahoo! User Interface library more of a community driven project has been really awesome, between the new forums, the transition to GitHub, and now reaching a new level with the YUI3 Gallery.

I’ve been using YUI3 since shortly after it was released, quickly recognizing the benefits of YUI3’s advanced architecture over YUI2, going so far as to submit a bit of code, in the form of the collection module, and the work I’ve done on the Chroma-Hash module for YUI3. And that’s just the code I’ve made public.

So, I was really glad to be able to begin contributing to the Gallery, having already uploaded two modules, with one or two in mind now that Dav’s mentioned the Gallery API. The great part about Gallery is that, if your module is free, licensed under the YUI BSD license, and you’ve signed a Contributors License Agreement, you can have it pushed to Yahoo!’s content distribution network. Global, high availability serving for JavaScript widgets? Hell yes.

The best part of the gallery is that it’s a dead simple way to make modules widely available for use, even if those modules will never really make sense in the context of the YUI framework itself, like my Chroma-Hash module, Luke Smith’s Konami Event, or Dav Glass’ quick and dirty port of the Simple Editor, but still might be useful to other people today. Plus, it’s an incubator for code that might someday make sense in the core (Dav’s YQL module being an example).

Yahoo!, and specifically the YUI team, have demonstrated exactly how a corporately backed open source project should run, as well as being a great example of why git (or really any distributed source control system) is so great for collaboration, especially for a growing team.

And it’s just one way to contribute. Dav does a great job outlining all the methods that exist today, and some still to come

Cloning XML Nodes from one Document into Another

| No Comments | No TrackBacks

Microsoft’s .NET Framework was designed in part to offer a powerful architecture for working with the Web. In the early 2000’s, when .NET was first being designed, that meant having strong support for handling and manipulating XML. Visual Basic.NET even includes support for XML literals. The result of this need was the System.XML Namespace, which contains all the methods and objects you’ll need to manage an XML document.

Almost. First, System.XML is kind of a pain to use, but that’s mostly because parsing XML with a statically typed platform is pretty rough, and frankly, the only languages where working with XML is usually even reasonable are dynamic, unless the XML format is very, very strongly defined, such as in SOAP.

System.XML, however, has no built in mechanism for cloning an element from one document (or document fragment) into another. Attempts to do so (even to copy simple attributes) will always result in exceptions because the elements were derived from different documents.

Recently, I was writing a simple set of MSBuild tasks to do xml file replacement on arbitrary XML files after reading a fragment in from a different document. This was in response to a problem I had using the web.config file replacement tasks from the Web Deployment Projects. Namely, the web deployment project’s task works by using the System.Configuration tools to do the section replacement, and that was causing me problems when referencing a non-GAC assembly in one of the pieces I was replacing when doing a build to production. Their task needs the file to appear to be a valid web.config, and errors out if it thinks it’s found a problem. Mine doesn’t care what you’re replacing with, so long as it’s XML.

My first attempt, was something like this:

As stated above, this is going to throw an exception, because the fragment comes from a different document than the document I’m trying to replace into. So, it because necessary to clone the fragment into a new node, but this is non-trivial.

XML Parsing engines are great, so that InnerXml property is a lifesaver, since otherwise I’d have to recursively clone the entire fragment tree in order to do the replacement.

Keen eyed observers will note that this is also incomplete. since it doesn’t take into account Attributes on the fragment element, and will in fact, no include them at all. XmlAttributes have the same weaknesses as XmlElements regarding your abililty to simply replace them with ease, so yet more code is required to clone them.

This is an awful lot of code to have to write simply to convert an Xml Fragment into a form that .NET will allow me to inject into a new document. But, now that it’s written, it can be pretty easily injected into a new static method you can use!

As always, the code samples on my blog are BSD-Licensed, feel free to use and remix them, just give credit where due.

Derived Property Data Binding in Silverlight

| No Comments | No TrackBacks

For our Silverlight-based Schedule Proofing application at work, we have a special requirement for Summer Session, where they have course ‘blocks’, or a set of predefined dates beyond just ‘full term’ and ‘whatever’. This required a few interesting blocks, but mostly, it required some interesting tweaks related to data binding, that unfortunately, I had to do in code.

The relevant XAML looks like this:

<my:DataGrid x:Name="Selector"
            AutoGenerateColumns="False"
            HeadersVisibility="Column"
            GridLinesVisibility="None"
            IsReadOnly="True"
            Visibility="Visible"
            FontSize="11"
            RowDetailsVisibilityMode="VisibleWhenSelected">
    <my:DataGrid.Columns>
        <my:DataGridTemplateColumn Header="Start Date">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding StartDate}" Margin="5,4,5,4"/>
                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
            <my:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <mye:DatePicker SelectedDate="{Binding StartDate, Mode=TwoWay}" />
                </DataTemplate>
            </my:DataGridTemplateColumn.CellEditingTemplate>
        </my:DataGridTemplateColumn>
        <my:DataGridTemplateColumn Header="End Date">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding EndDate}" Margin="5,4,5,4"/>
                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
            <my:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <mye:DatePicker SelectedDate="{Binding EndDate, Mode=TwoWay}" />
                </DataTemplate>
            </my:DataGridTemplateColumn.CellEditingTemplate>
        </my:DataGridTemplateColumn>
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding BlockName}" Margin="5,4,5,4"/>
                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
            <my:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding TermInfo.Blocks}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedBlock, Mode=TwoWay}" />
                </DataTemplate>
            </my:DataGridTemplateColumn.CellEditingTemplate>
        </my:DataGridTemplateColumn>
    </my:DataGrid.Columns>
</my:DataGrid>

The relevant portions of the data structure looks basically like this:

class SectionData
{
    private DateTime startDate;
    private DateTime endDate;
    private YearTerms termInfo;

    public YearTerms TermInfo
    {
        get
        {
            return termInfo;
        }
    }

    public DateTime StartDate {
        get { return startDate; }
        set
        {
            startDate = value;
            NotifyPropertyChanged("StartDate");
        }
    }
    public DateTime EndDate {
        get { return endDate; }
        set
        {
            endDate = value;
            NotifyPropertyChanged("EndDate");
        }
    }

    public SummerSessionBlock SelectedBlock
    {
        get
        {
            if (termInfo.Blocks == null) return null;

            var b = termInfo.Blocks.Where(q => q.Begin == startDate)
                .Where(q => q.End == endDate)
                .SingleOrDefault();
            return b ?? termInfo.Blocks.Where(q => q.Name == "Custom").Single();
        }
        set
        {
            var b = termInfo.Blocks.Where(q => q.Begin == startDate)
                .Where(q => q.End == endDate)
                .Any();
            if ((value.Name == "Custom" && b) || value.Name != "Custom")
            {
                startDate = value.Begin;
                endDate = value.End;
            }
            NotifyPropertyChanged("Block");
            NotifyPropertyChanged("StartDate");
        }
    }

    public string BlockName
    {
        get
        {
            return SelectedBlock != null ? SelectedBlock.Name : string.Empty;
        }
    }
}

public class YearTerms
{
    public ObservableCollection Blocks { get; set; }
}

public class SummerSessionBlock
{
    public int Year { get; set; }
    public int Term { get; set; }
    public string Name { get; set; }
    public DateTime Begin { get; set; }
    public DateTime End { get; set; }
}

Alright, that’s a lot of code, and most of it, I’m not really going to address here, since I’m assuming a basic understanding of Data Binding and Dependency Properties. Basically, all those NotifyPropertyChanged calls ensure that the UI gets updated. Also, the YearTerms.Blocks property will, in my case, be NULL for all terms that aren’t a summer session.

Now, since blocks don’t mean anything outside of Summer Session, I don’t want that column to be visible outside of that case. This isn’t a big problem, since all the sections which will be viewed on one instance of this data grid will, by definition, be from the same term, however, attempts to use XAML DataBinding failed with XAML parsing errors.

    <my:DataGridTemplateColumn Header="Block"  Visibility="{Binding BlockName, Converter={StaticResource VVC}}">

The VVC StaticResource just sets the Visibility to Hidden if BlockName is the empty string, Visible otherwise. As I said, this excepts with an obscure XAML parsing error. Unfortunately, things that can be quite simple in XAML can be a real pain in code when using Silverlight or (presumably) WCF. Partially because of how you have to identify the column. The solution is fairly simple, when the DataContext of the DataGrid is modified, I simply determine what the visibility should be and call a function that sets the visibilty.

public void SetColumnVisibility(string columnHeader, Visibility visible)
{
    try {
        Selector.Columns.Where(c => c.Header.ToString() == columnHeader)
            .Single().Visibility = visible;
    } catch (Exception e) {
        throw new ArgumentException("Column '" + columnHeader + "' does not exist.");
    }
}

Have I mentioned yet that I really love LINQ? This code is all wrapped up in a custom control, but I’m debating converting this function to an extension method on the DataGrid, since nothing quite like it is offered. This function is called from the web service callback responsible for setting the data context on this control, and it ensures that users only see this column when it makes sense to. Would have been nice to data bind this, but in reality, the binding works because I know that the data which determines the column visibility is technically shared among all members of the data, but the Silverlight Runtime doesn’t have any way of knowing that for certain.

More annoying is the second problem. The Date fields should not be modifyable directly by the user unless they’ve selected a special ‘custom’ option in the Blocks list. The ‘custom’ option is added at runtime, and is defined with start and end dates being just within the boundaries of the full term option. Which involves setting the IsReadOnly flag on the Columns for Start Date and End Date. Again, the Data Binding fails with a completely unhelpful XAML parsing error, and in this case, the data that I’m binding against is unique for the row, and doesn’t effect the rows around it, so I was kind of at a loss.

The problem with IsReadOnly on the DataGridColumn is that it effects all rows, not really what I want. So, really it’s out. But I don’t see a way to bind the IsEnabled flag on the Cell using a data binding (I’m fairly new to Silverlight, so this is likely my failing). So, to code it is. The problem I found was that, Silverlight doesn’t make it really easy to access the individual cells for a datagrid. You can get access to columns easily, and rows through a few events, but to access the cell….that’s non-trivial.

private void SetDateEditability(DataGridRow dataGridRow)
{
    var msi = dataGridRow.DataContext as MasterSectionInfo;

    // The fields should be editable if either of these are true, but not otherwise
    bool editable = msi.BlockName == "Custom" || msi.BlockName == string.Empty;
    // Should only except if Columns can't be found
    try
    {
        // I need these columns with these two names.
        var e = Selector.Columns.Where(c => c.Header.ToString() == "Start Date" || c.Header.ToString() == "End Date").Select(c => c);
        // For each column in the LINQ query above
        foreach (var column in e)
        {
            // Get the Cell Content for the argument row
            var el = column.GetCellContent(dataGridRow);
            // Get the cell itself, and set it's IsEnabled flag.
            (el.Parent as DataGridCell).IsEnabled = editable;
        }
    }
    catch (Exception) { }
}

Now, the question is, when does this method need to be called? It needs to be called anytime the selection for the Block column changes, which is accomplished through the CellEditEnded event on the data grid. For my purposes, I check that the edited cell is in the Block column, to save just a bit of time, but you can always decide how necessary that is in your own application. However, this isn’t sufficient, since it doesn’t effect the rows as they load, so you’ll also need to add a LoadingRow event handler which calls into this method for each row as it loads.

So, there you have it. How I created a virtual property driven by two backing properties, and tied the editability of the backing properties to the selection. I’ll be the first to admit, it’s not the prettiest looking solution in the world, and I’m sure it could be done better, but I was under a deadline, and really, this works pretty cleanly, for a solution derived from a Silverlight newbie.

About this Archive

This page is an archive of recent entries in the Programming category.

Politics is the previous category.

Reviews is the next category.

Find recent content on the main index or look in the archives to find all content.

Once You Know, You Newegg

μ-updates

  • No Updates!
OpenID accepted here Learn more about OpenID
Powered by Movable Type 4.21-en