Recent CodeSOD

Code Snippet Of the Day (CodeSOD) features interesting and usually incorrect code snippets taken from actual production code in a commercial and/or open source software projects.

Feb 2009

A Man's Array

by in CodeSOD on

It's always a little frustrating when you're trying to write the most beautiful code you can, but because of a limitation in the programming language you have to roll up your sleeves and brute force it. As programming technologies mature, I find this to be rarer and rarer.

Sadly, Dan M. inherited a project in which some cutting-edge features weren't available. For example, the cutting-edgiest feature conceivable: arrays!


Dividing by Zero for Fun and Profit

by in CodeSOD on

When the Web Applications Group and the Distributed Applications Group were merged into one, it should have been a joyous day for Greg Beech. After all, Greg would finally get the chance to see first hand the "Enterprise CMS" system that the Distributed group had been bragging about for so many years. It was built by a team of elite consultants and billed "the quintessential collection of best practices."

After downloading the source code, following the seventy-two steps required to install the Enterprise CMS on a development workstation, and spending an entire afternoon fiddling around with his computer's settings, Greg finally had the software running. But when he fired it up in up in debug mode through Visual Studio, he noticed something strange: a preposterous number of exceptions were being thrown, many of which were of type DivideByZeroException.


The Path to WTF is Paved with Good Intentions

by in CodeSOD on

Let's say that I have a stupid report that needs constant attention and maintenance because of waffling business requirements.  Rather than buying a fruit bouquet for the server admin because of all the promotes I'd be doing, one solution might be to dynamically fetch the SQL for the report from a table. That way, all I would need to do is run a single UPDATE statement, COMMIT, and it's done!

Better yet, what if I wrote a generic procedure that could call any of the SQL my query table.  How enterprisey!!  This seems to be the general intenet of the original developer behind a web app that Patrick Magee recently inherited. 


Some Crazy Reason

by in CodeSOD on

One time, out of boredom, I wrote a little utility called BitVerifier. It would loop over a folder and check every bit of each file. If the bit's value wasn't one or zero, it would prompt the user for the correct bit. At least in theory. I somehow never encountered a file with a "two" bit. But I got one key component right – an understanding of the valid range of values.

Rob K.'s colleague didn't even get that far.


The How, Not the Why

by in CodeSOD on

Habits, good or bad, are easy to gain but hard to break. Often, the way one learns to do something is the way they keep doing it, sometimes never questioning if there is a better approach.

One of Lance K.'s colleagues had one habit that was well-intentioned – thoroughly commenting his code – but he apparently didn't realize that comments are meant to explain the why rather than the how:


Zipping Files - The Matryoshka Doll Way

by in CodeSOD on

Upon reading the code submitted by Eric Williams, the first thing I thought of was a series of Matryoshka Dolls.  You know, those little Russian dolls where the one doll has a smaller doll, which has a slightly smaller doll which in turn and so on...

The Windows-based application that Eric inherited from a previous developer needed to zip the contents of a folder full of files.  Normally, this functionality is a little difficult to implement without a third party library.  However, the original developer thought "outside the box" and wrote up the following implementation.

CreateZipFromFolder(CString m_outfile, CString outfolder)
{

 CString m_outputfilename = m_outfile;
 CString outpath = outfolder;
 CString p;

 TCHAR lpPathBuffer[BUFSIZE];
 TCHAR lpPathBuffer1[BUFSIZE];
 DWORD dwBufSize=BUFSIZE;

 DWORD dwRetVal;
 //find temp directory;
 dwRetVal = GetTempPath(dwBufSize, //buffer length
     lpPathBuffer); //path buffer
     
    if (dwRetVal > dwBufSize || (dwRetVal == 0)) {
        printf ("Failed to get temp path (%d)\n", GetLastError());
        FILE *fp = fopen("C:\\Zip.vbs","w+");
    }
   
    FILE *fp ;
    strcat(lpPathBuffer,"zip.vbs");

    CString fileName = lpPathBuffer ;

    if((fileName[0] != '\0'))
        fp = fopen(fileName,"w+");
    else(fp = fopen("C:\\Zip.vbs","w+"));
        p.LoadString(RESID_30);
       
    fprintf(fp,"Dim fso, winShell, MyTarget, MySource, file \n") ;
    fprintf(fp,"Set fso = CreateObject(");
    fprintf(fp,"%s",p);
    fprintf(fp,"Scripting.FileSystemObject");
    fprintf(fp,"%s",p);
    fprintf(fp,")   \n");
    fprintf(fp,"Set winShell = createObject(");
    fprintf(fp,"%s",p);
    fprintf(fp,"Shell.Application");
    fprintf(fp,"%s",p);
    fprintf(fp,")    \n");
    fprintf(fp,"MySource =");
    fprintf(fp,"%s",p);
    fprintf(fp,"%s",outpath);
    fprintf(fp,"%s \n",p);
    fprintf(fp,"MyTarget =");
    fprintf(fp,"%s",p);
    fprintf(fp,"%s",m_outputfilename);
    fprintf(fp,"%s \n",p);
    fprintf(fp,"Set file = fso.CreateTextFile(MyTarget, True)   \n");
    fprintf(fp,"file.write ");
    fprintf(fp,"%s",p);
    fprintf(fp,"PK");
    fprintf(fp,"%s",p);
    fprintf(fp,"& chr(5) & chr(6) & string(18,chr(0)) \n");
    fprintf(fp,"file.close \n");
    fprintf(fp,"winShell.namespace(MyTarget).CopyHere winShell.namespace(MySource).items    \n");       fprintf(fp,"do until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count    \n");
    fprintf(fp,"wscript.sleep 1000 \n");
    fprintf(fp,"loop \n \n");
    fprintf(fp,"Set winShell = Nothing \n");
    fprintf(fp,"Set fso = Nothing");
    fclose(fp);

    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    CString filename;
    filename = p + lpPathBuffer + p;
    CString szCommand;
   
    BOOL ret = Is64Bit();
    if(ret) {
        DWORD dwRetVal;
        //get the windows directory;
        dwRetVal = GetWindowsDirectory(lpPathBuffer1,dwBufSize); //path buffer
        strcat(lpPathBuffer1,"\\syswow64\\");
        szCommand = lpPathBuffer1;
        szCommand +="
cmd.exe /c cscript //B ";
    }   else {
            szCommand ="cmd.exe /c cscript //B ";
    }

    szCommand += filename ;
    if(CreateProcess(NULL,szCommand.GetBuffer(szCommand.GetLength()),NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&si,&pi)) {
        WaitForSingleObject( pi.hProcess, INFINITE );
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }
   
    return 0;
}

Stupid Coding Tricks: A Batch of Pi

by in CodeSOD on

It's high time for the second installment of stupid coding tricks! As we learned from the T-SQL Mandelbrot, a stupid coding trick isn't really about obfuscation per se... just, well, stupid awesomeness. Kinda like a quine, except even more useless.

Don Cross was gracious enough to provide today's example, which teeters on the edge of what many consider "code". It's a Win32 batch file. Unlike the analogous *nix shell script, batch "programming" comes with an incredibly limited syntax and a miniscule number of commands. While one can certainly do far more in batch than ever should be done, the technology works well foa shortcut for typing in a bunch of commands.


For a Good Time, Call...

by in CodeSOD on

Let's face it; being a developer doesn't really foster a great social life. Late-night coding and sitting still for days makes our eyes bloodshot, our bellies large, our breath toxic, and our postures almost parabolic.

So sometimes we have to get creative to become more popular, or to at least get more phone calls. Maybe it's time to take a cue from one of Josh's colleagues.


#WHO WROTE THIS JUNK

by in CodeSOD on

Justin de Vesine was less than thrilled with his internet service. On a good day, his high-speed would pretend to be dial-up; usually, it seemed that things would just give up loading half-way through. Through some trial and error, he narrowed it down to the brand-name DSL modem that his ISP gave him. Since it was running a stripped down version of Linux, and supported telnet administration, Justin decided to log in and poke around some of the scripts and config files to see if he could find the source of his problems.

When he came across this gem of a start-up script, Justin was not surprised that his DSL modem was the source of his troubles.