PHP

I’ve been doing enough PHP work lately that this blog post really speaks to me. Here’s a good quote:

PHP isn’t so much a language as a random collection of arbitrary stuff, a virtual explosion at the keyword and function factory.

I kind of like Drupal, which is of course written in PHP, but I think I’d like it more if it was written in… something else. I’m not sure what.

You can certainly write good things in PHP, and Drupal is an example of that. CodeIgniter seems like a good thing too,  though I haven’t had much experience with it.

I recently had to do some work on what I’d call a “legacy” PHP site, which was basically all PHP spaghetti code, poorly done HTML, and questionable JavaScript. I wonder how many sites like that one are out there, written 5 or 10 years ago, possibly by an amateur, and working *just* well enough that nobody wants to pay to rewrite it from scratch. Probably a lot!

ASP.NET AJAX Control Toolkit bugs

We make fairly extensive use of the AJAX Control Toolkit at work. When I first started at my current job, I wasn’t quite sure about it. In practice, most of the stuff we used seemed a little buggy and kind of kludgey. As I learned more about it, though, I started liking it. When used correctly, it’s quite useful, and holds up well, in terms of cross-browser compatibility and stuff like that.

However, once in a while, I stumble across an annoying bug. The most recent one cropped up after upgrading to a newer version of the ACT on a client site. I’m always a bit leery about upgrading the ACT, since it does often expose bugs that weren’t present in the prior version, and that don’t surface in casual testing.

In this case, we encountered a bug that occurs when you have a ValidationSummary control and a ModalPopupExtender on the same page.

If you Google the problem, you will find multiple mentions of it on StackOverflow and on the ACT bug tracker on CodePlex. The solution, basically, is to inject a script with just a semicolon in it, right after the ValidationSummary. (See here for a simple explanation.)

There are indications that the bug has been fixed, but then other indications that it re-surfaced again later. I can tell you that I was using the latest ASP.NET 3.5 version of the ACT at the time, and it’s definitely still a problem.

I don’t necessarily mind having to use these kinds of workarounds. These days, it’s fairly easy to Google an error message, and find multiple links to your problem on StackOverflow and in CodePlex bug reports, and in various other places. (I’m old enough to remember the days when we didn’t have Google or StackOverflow, so I don’t take these things for granted!) But, I would really like to encourage anyone reading this to please do one little thing for me: If you’re implementing a non-obvious workaround like this in your code, please document it with an explanation and/or a link back to the bug report or StackOverflow page. There’s nothing quite like having to do maintenance programming on a system created by someone else, finding something like this workaround on the page, undocumented, and trying to figure out what the purpose of it was.

I think that this is a problem that plagues many ASP.NET and PHP systems, especially ones that were developed with fairly loose coding standards, no peer review, and that have been around for a few years. There are often oddball workarounds in the JavaScript, CSS, and server-side code that aren’t documented and that are often fragile if tampered with. Every time I have to do maintenance programming on a system like this, I try to leave it looking at least a little bit better than it was when I started. If I can remove some unnecessary workarounds, change some non-obvious variable names to useful ones, and add some comments to explain what’s going on, I try to do that.

Speaking of the ACT, I see that a new version was released this month. Stephen Walther has been doing a lot of work on the ACT lately. This most recent release includes major revisions to (or perhaps a complete rewrite or) the file upload control. Trying to get file upload functionality working nicely on a page that’s doing a lot of tricky async stuff is pretty difficult. I used the older ACT file upload control on a page recently, and it works OK, but it required a few… workarounds. (All of which I tried to document, of course.) I don’t think that this new one will require fewer workarounds, since the basic limitations inherent in doing a file upload from a browser will still exist, but at least it will allow for some nice feedback through HTML5 upload progress events, as mentioned in the blog post.

ASP.NET ListView notes

I jump around between projects a lot, and I often don’t get deep enough into any particular thing to really learn it inside and out. I got a chance to work on a fairly complicated ASP.NET page recently, though, and I picked up a few new things.

The approach I took with this page, since it had a number of independent parts, was to try to keep them isolated and only spin things up when needed. So, in one panel, where I had a ListView, I wanted to get it working without using a declarative data source. This turns out to require a little bit of extra work. I found this article helpful in getting the DataPager working correctly. And this post had the best advice on how to control the visibility of the DataPager.

I think I could probably write up a couple of more posts with hints on the AsyncFileUpload control, but I’ll save those for another day.

Drupal 7

After staying out too late Tuesday night, then going to bed at 8:30pm last night, I finally had some free time after work tonight to play around with Drupal. I installed Drupal 7 on my MacBook, following these instructions. The only real trouble I had was in making sure that every host reference was set to 127.0.0.1 rather than localhost, or anything else.

Most of the obvious stuff seems to be working.  I haven’t figured out clean URLs yet though.

xAMP on the Mac

I’ve been trying to learn a bit about Drupal recently. It looks like we might be getting some Drupal projects at work, so it seemed like a good idea.

To get a working setup for Drupal on my Mac, I wanted to get all the pieces in place — Apache, PHP, and MySQL, basically. Apache is, of course, already there, and I already had that turned on, so no problem.

PHP was already installed, but apparently got turned off during the 10.7 upgrade. All you need to do to turn it on is edit httpd.conf, and uncomment one line, per this SO page.

For MySQL, there’s an installer that works pretty smoothly, per this page. One odd thing I stumbled across at one point is that you usually need to refer to your local server as ‘127.0.0.1’ rather than ‘localhost’. Long story, but something worth noting. Also, if you’re not sure how to set the root password, take a look at this SO page.

I tested to make sure that MySQL was working from PHP using this little test script:

<?php

$db = mysql_connect("127.0.0.1:3306", "root", "password");

if (!$db) {
    die('Could not connect' . mysql_error());
}
    echo 'Connected successfully';
?>

I can’t remember exactly where I found that, but it’s a pretty basic script.

I then got a little ambitious and decided to try to get phpMyAdmin working. I made a couple of simple mistakes here, including not quite understanding that config.inc.php needed to be in the root phpMyAdmin folder and not in the config subfolder.

Also, the warning from phpMyAdmin about mcrypt not being installed was bugging me, so I decided to try and fix that. That turned out to be kind of complicated. I followed these instructions, and they worked, but only on my second try. I must have gotten something wrong on the first try. Also, I found another page with similar instructions, so referencing that may help if anything on the first page seems confusing.

In the end, I think I really should have just gone with MAMP, but of course I was doing this as a learning exercise, so it was valuable to go through all this, even if it took a lot longer than was probably necessary.

And I still don’t have Drupal installed. Maybe tomorrow!

fun with modal popups

At work, we frequently use the ModalPopupExtender from the Ajax Control Toolkit in our projects. I’ve got mixed feelings about this control, and about the ACT in general, but for better or worse, I do use it a lot. I discovered some functionality in the control this week that I was previously unaware of, so I thought I’d write up a blog entry on it, along with some related stuff that I stumbled across.

I needed to attach some JavaScript to the show and hide events for the popup, but wasn’t sure how to do that. It turns out that there are add_shown() and add_hiding() events that you can hook into, as described here. I initially found out about add_shown() at this StackOverflow page.

I then tried to hook up the event in the pageLoad() routine as shown in an example there. What I didn’t realize was that you can only have one pageLoad() function, and there was another one in a master page that was in my hierarchy, so my version didn’t get called. I then found out that I should change both of those to use Sys.Application.add_load() via this SO page.

Then, I followed up by learning a bit about the differences between pageLoad() and $(document).ready() at Encosia, which is one of the best sites out there for figuring out some of the trickier stuff when working with ASP.NET and JavaScript.

P.S. I just noticed that this is post # 1500 on my blog. There’s no real importance to that, but it’s always nice to hit a milestone.

Fractions!

I haven’t posted much code to my blog lately, so I thought I’d pass along some general-purpose C# code that I recently used in a project. I’m working on a system right now where the original author made some, shall we say, interesting decisions about how to store data in SQL. Specifically, he used varchar fields for most of the numeric data. And, in those fields, he sometimes stores the data in decimal format (e.g. “1.5”), sometimes as fractions (e.g. “1 1/2”) and sometimes as explicitly-signed fractions (“+1 1/2”).  I, of course, need to do LOTS of math on these numbers. The decimal fields can be dealt with using good old TryParse and ToString of course, but there’s no obvious parse routine for fractions, nor is there an obvious way to turn a decimal number back into a fraction string.

The internet, of course, provides. Here is a VB.NET function to turn a fraction string into a decimal and there is some C# code to convert a decimal into a fraction string in this thread. I converted the VB.NET to C#, and cleaned both of them up and put them in a utility class.  Here it is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace MySuit.MySuitV2.BLL
{
    public class Utility
    {
        public static decimal FractionToDecimal(string frac)
        {
            // this method should convert a fraction, e.g. "12 1/4" to a decimal, e.g. 12.25.
            // based on http://amrelgarhytech.blogspot.com/2008/03/fraction-to-decimal.html
            // TODO: not sure how best to handle exceptions here. (parse errors, div by zero, null/empty string input...)
            decimal rv;
            int numerator, denominator, wholePart = 0;
            int sign = 1;

            if (string.IsNullOrEmpty(frac))
                return 0m;

            // deal with signs
            frac = frac.Trim().TrimStart('+');
            if (frac[0] == '-')
            {
                frac = frac.TrimStart('-');
                sign = -1;
            }
            frac = frac.Trim();

            if (frac.IndexOf("/") > 0)
            {
                if (frac.IndexOf(" ") > 0)
                {
                    wholePart = int.Parse(frac.Substring(0, frac.IndexOf(" ")));
                    frac = frac.Substring(frac.IndexOf(" "));
                }
                numerator = int.Parse(frac.Substring(0, frac.IndexOf("/")));
                denominator = int.Parse(frac.Substring(frac.IndexOf("/") + 1));
                rv = sign * (wholePart + ((decimal)numerator / denominator));
            }
            else
            {
                rv = decimal.Parse(frac);
            }
            return rv;
        }

        public static string DecimalToFractionSigned(decimal value)
        {
            // always put a sign (+/-) in front
            string rv = DecimalToFraction(value);
            if (rv[0] != '-')
                rv = string.Format("+{0}", rv);
            return rv;
        }

        public static string DecimalToFraction(decimal value)
        {
            // taken from here: http://bit.ly/tHaKrK and modified to work with negative numbers too.

            int sign = 1;
            if (value < 0)
            {
                value = Math.Abs(value);
                sign = -1;
            }

            // get the whole value of the fraction
            decimal mWhole = Math.Truncate(value);

            // get the fractional value
            decimal mFraction = value - mWhole;

            // initialize a numerator and denominator
            uint mNumerator = 0;
            uint mDenominator = 1;

            // ensure that there is actually a fraction
            if (mFraction > 0m)
            {
                // convert the value to a string so that you can count the number of decimal places there are
                string strFraction = mFraction.ToString().Remove(0, 2);

                // store the number of decimal places
                uint intFractLength = (uint)strFraction.Length;

                // set the numerator to have the proper amount of zeros
                mNumerator = (uint)Math.Pow(10, intFractLength);

                // parse the fraction value to an integer that equals [fraction value] * 10^[number of decimal places]
                uint.TryParse(strFraction, out mDenominator);

                // get the greatest common divisor for both numbers
                uint gcd = GreatestCommonDivisor(mDenominator, mNumerator);

                // divide the numerator and the denominator by the greatest common divisor
                mNumerator = mNumerator / gcd;
                mDenominator = mDenominator / gcd;
            }

            // create a string builder
            StringBuilder mBuilder = new StringBuilder();

            // add the whole number if it's greater than 0
            if (mWhole > 0m)
            {
                mBuilder.Append(mWhole);
            }

            // add the fraction if it's greater than 0m
            if (mFraction > 0m)
            {
                if (mBuilder.Length > 0)
                {
                    mBuilder.Append(" ");
                }

                mBuilder.Append(mDenominator);
                mBuilder.Append("/");
                mBuilder.Append(mNumerator);
            }

            if (sign == -1)
                mBuilder.Insert(0, '-');

            return mBuilder.ToString();
        }


        private static uint GreatestCommonDivisor(uint valA, uint valB)
        {
            // return 0 if both values are 0 (no GSD)
            if (valA == 0 && valB == 0)
            {
                return 0;
            }
            // return value b if only a == 0
            else if (valA == 0 && valB != 0)
            {
                return valB;
            }
            // return value a if only b == 0
            else if (valA != 0 && valB == 0)
            {
                return valA;
            }
            // actually find the GSD
            else
            {
                uint first = valA;
                uint second = valB;

                while (first != second)
                {
                    if (first > second)
                    {
                        first = first - second;
                    }
                    else
                    {
                        second = second - first;
                    }
                }

                return first;
            }
        }

    }
}

(This is also in a Gist.)
I hope this helps anyone who might be looking for something similar. Also, I want to reiterate that I didn’t write this code from scratch. I took two existing functions, one in VB and one in C#, converted the VB to C#, cleaned them both up a bit, and put them together.

Luckily, by the way, all of the fractions I’m dealing with resolve to simple decimal numbers; everything is x/2, x/4, or x/8. I don’t have to deal with converting 1/3 to decimal and back. If you need to do that, you probably want a class that stores the fractions as numerator and denominator, and does math on them, as fractions.  There are a couple of those out there, if you look around.

iOS programming

I’m more than half-way through my iOS programming class at NYU. I’ve missed one class due to a flat tire, and I’ve been a bit under the weather during a couple of classes, but I’m definitely getting something out of the class.
I’ve made a Hypotrochoid generator the basis for my previous two homework assignments, so that’s been kind of fun. I didn’t figure out the code for this myself. Rather, I took the C# code found here, and converted it to Objective-C / Cocoa.
All of my homework code is up on my Github page, if anyone wants to look at it for some reason.
And here’s a quick screencast of my app. Not that exciting really, but fun to write.