Friday, December 08, 2006

Checking Error table with Powershell

One of our main web applications writes audit and error messages to the SQL database.  I was looking for a faster way to get a quick overview of the last few messages written to the table.  I could save a sql script, but seriously, where's the fun in that?  And besides, it would require me opening up SQL Query Analyzer. However, I do keep a Powershell window open at all times. 

Speaking of Query Analyzer, I had a significant breakthrough to a new level of keyboard zen with it last week.  More on that later. 

Onto the script:

   1:  $count = 50
   2:  if ($args.length -gt 0) { $count = $args[0] }
   3:   
   4:  $conn = new-Object System.Data.SqlClient.SqlConnection
   5:  $conn.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDatabase;Data Source=MySqlServer"
   6:  $conn.Open()
   7:   
   8:  $cmd = new-Object System.Data.SqlClient.SqlCommand
   9:  $cmd.CommandText = "SELECT TOP $count * FROM tblError ORDER BY ErrorID DESC"
  10:  $cmd.Connection = $conn
  11:   
  12:  $da = new-Object System.Data.SqlClient.SqlDataAdapter($cmd)
  13:  $ds = new-Object System.Data.DataSet "Errors"
  14:  $da.Fill($ds) | out-Null
  15:  $conn.Close()
  16:   
  17:  $ds.Tables[0].Rows | Format-Table -property ErrorID, errorTime, ErrorMessage -wrap -autosize
  18:   
  19:  rv count, conn, cmd, da

The first thing to do is to create a count variable that will be used to determine how many records to pull from the db.  It defaults to 50, but that can be overwritten in line 2 if you pass in a parameter to the script.  Lines 4-15, should look familiar.  They basically use ADO.NET objects to get the records from the db and place them in a DataSet.  Line 17 is responsible for displaying the results in the console.  I use the Format-Table cmdlet to filter out some of the fields and to make them look pretty by autsizing them and causing the cells to wrap their text.


In line 19, a bunch of variables are removed.  Normally, you wouldn't have to worry with this step as the variables will go out of scope as soon as the script finishes.  I did this, incase I ran the script in global scope.  You can accomplish this by inserting a ". " at the beginning of the command line.  In which case all of the variables would remain even after the script is complete.  In my case, I'm removing all the variables except the dataset.  That way, I can continue to manipulate the object and if I want to refresh it, I just re-run the script.

Friday, December 01, 2006

Wargames Influenced Powershell Hack

As a child, I love the movie WarGames.  Looking back though, it does seem kind of corny and maybe even improbable.  No matter, I still think its a great movie.  The movie introduces concepts that we still deal with today.  Things like system security, artificial intelligence and the concept of futility.  You prabably know that I love lists, so here are my favorite things about the movie.

The five greatest things about WarGames the movie:

5. That scene where Matthew Broderick phreaked a pay phone by sticking a pull tab from a soda can in the receiver.  Through the eyes of a kid, this was awesome.

4. The extensive use of the acoustically coupled modem to hack the Government's most secure network.

3. The 8 inch floppy drive.  Which at it's prime could hold 1200 kb.

2. Barry Corbin.

1. The cool terminal that would talk to you, a.k.a. Joshua.

Its the terminal that inspired my personallized use of this hack.  Below is an excerpt from my Powershell profile.  You may recognize some of the code from a previous post.

function say($script)
{
$v = New-Object -ComObject "SAPI.spvoice"
$r = $v.Speak($script)
rv v
}

#Say Hello
$Greeting = "Hello " + $env:Username + ". Shall we play a game?"
write $Greeting
say $Greeting
rv Greeting

The first thing I do is create a function named "say".  Inside the function I create a instance of the SAPI.spvoice COM object.  SAPI is the Text to Speech API that is installed with Windows XP by default.  You can administer it by going into your control panel and opening the Speech option.  The spvoice object allows you to pass in some text and it will convert it into audible speech and send it out to your speakers.  So the "say" function takes some text and speaks it.  Note that I took the time to use "rv" to remove the variable.  Don't need to hold on to that COM object longer than I need to.


Next you see where I get the user name of the person logged on and print out a greeting right before I speak it.  I've seen some articles on using this technology in ASP.NET applications.  Think of the fun you could have.

Thursday, November 16, 2006

Omitting the Byte Order Mark while saving XML Document

Have you every opened up an XML file in note pad and noticed those little gobbly gook characters preceding the XML declaration?  Well my friend you have encountered the ever elusive Byte Order Mark, or BOM for short.  I prefer Byte Order Mark because BOM sounds dirty, kind of like scrum.  Eck, dirty. 

The Byte Order Mark is basically three characters that are added to the beginning of xml files to denote their encoding.  I know... I know...  You can declare the encoding in the xml declaration.  That's what it is there for, right?  To declare stuff. 

Well, that is only partly true.  When an XML parser reads an XML file, the W3C defines the following three rules to decides how the document should be read:

  1. If there is a Byte Order Mark the Byte Order Mark defines the file encoding.
  2. If there is no Byte Order Mark, then the encoding attribute in the XML declaration is definitive.
  3. If there are neither of these, then assume the XML document is UTF-8 encoded.

I think that I remember reading an article once that claimed the Byte Order Mark was born out of Windows NT, but I can't find it now.  Either way, you are bound to come across some service somewhere that doesn't like it, probably because the service thinks that it is dirty.  All strings in .NET are encoded to UTF-16 by default. If you build and XmlDocument and save it, it will be UTF-16 encoded.  And by default, there will be a silly little Byte Order Mark.  Visual Studio, like most current xml editors, won't show it to you, but its there. 

Here's how I prevent the Byte Order Mark from appearing in my generated xml files.

public void WriteXmlFile(XmlDocument xdoc)
{
System.Text.Encoding enc = new UTF8Encoding(false);
XmlWriter w = new XmlTextWriter("NewFile.xml", enc);
xdoc.Save(w);
w.Close();
}




When I create the UTF8Encoding object, I pass in false for the encodingShouldEmitUTF8Identifier parameter.  This will omit the Byte Order Mark from the NewFile.xml file. 

Tuesday, November 07, 2006

Parsing CSV files with PowerShell

So there I was, looking at a Caliber requirement, basically a Word document, with a table of values that needed to get into a table in our SQL database.  We were still in development and there was no entry form in the application for the requirement writers to enter the values.  Faced with the prospect of having to manually build a sql script to insert all these values, I desperately called out to Necessity.  You know that Necessity is the mother of invention.  She carries a big purse full of invention, with which she immediately hit me over the head.  She told me that I already had Powershell, mumbled something about the boy that cried wolf and stormed out.  Powershell, eh?  The following is an abbreviated description of what I did to generate my sql script. My insert statement was much larger.

First, I copied the word table into excel, including the headers, and saved the file as a CSV file. The format looked something like this:

State, City, Type

GA, Atlanta, AB

GA, Albany, A

Now for the Powershell.  Check out this bad boy:

Import-Csv Test.csv | % { "INSERT INTO refTestTable (State, City, Type) VALUES ('$_.State', '$_.City', '$_.Type')"}  >> "Test.sql"

After opening up the new Test.sql file, I got this:

INSERT INTO refTestTable (State, City, Type) VALUES ('GA', 'Atlanta', 'AB')
INSERT INTO refTestTable (State, City, Type) VALUES ('GA', 'Albany', 'A')



Not bad for one line of code.  Powershell's Import-Csv command loops through all the records in the CSV file and generates objects.  Then for each object we build a sql string and insert the object's properties.  Notice how the properties were dynamically generated so all you had to do was call them?  Finally, I outputted the resulting string to a text file.  Using this method I was able to generate and run the sql script in less than 10 minutes. 


Monday, November 06, 2006

My first blog from Live Writer

This is my first blog post that I have generated in Windows Live Writer Beta.  Until now, I have used the online editor.  The fat client sports a cool WYSIWYG editor and a lot of great accelerator keys.  Publishing is a snap and seems to take less time compared with the web editor.

The team has provided an SDK and encourages the development of plugins.  There is a page dedicated to these here.  I found a neat one that helps insert code snippets.  Insert Code for Windows Live Writer supports C#, HTML, MSH, JavaScript, Visual Basic and TSQL.  I wish that there was a way to assign accelerator keys to the plugins.  For now, I'll just have to go through the menu.

Friday, November 03, 2006

Portable App Week - FastStone Capture

We've come to end of Portable Apps Week and I'm a little sad. But all good things must come to an end. For my last app of the week, I'm going back to FastStone and their Faststone Capture utility. Capture is a screen capture utility that lets you easily capture anything on the screen including windows, objects, full screen, rectangle regions, freehand regions, and scrolling windows. It comes with an editor that allows for cropping, adding text, highlighting and drawing. Not bad for 1.2MB. It's what I've been using to generate the images for all of this week's previous posts.

I know what you're thinking. How does this compare with Snagit. Well, it isn't quite as full featured as Snagit. It doesn't do text capture, menu capture or video capture. It does allow for freehand capture regions. I'm not sure if Snagit has that or not. FastStone Capture has a much smaller footprint than Snagit. Hmmm, what else? Did I mention that it was free?

Here is a capture I did freehand. It is supposed to be an octogon.

Thursday, November 02, 2006

Portable App Week - FastStone Image Viewer

When someone asks me to help them with their website, I have to remind them that I'm a developer, not a graphic artist. As a developer I strive to make pretty things, but I have no formal artistic training. I had a really good friend that was a professional graphic artist. His firm did work for Coke and Six Flags. I probably could have learned a lot from him, had my girlfriend at time not dumped me and ran off and married him.

Happy place, go to your happy place.

I am a big fan of the gimp. It's open sourced, free, powerful and difficult to learn. It's also really big and takes a long time to load. Since I spend most of my time editing pictures of the kids, removing red-eye and cropping, I don't always need the power of the gimp. So I was excited to find FastStone's ImageViewer.

"FastStone Image Viewer is a fast, stable, user-friendly image browser, converter and editor. It has a nice array of features that include image viewing, management, comparison, red-eye removal, emailing, resizing, cropping and color adjustments. Its innovative but intuitive full-screen mode provides quick access to EXIF information, thumbnail browser and major functionalities via hidden toolbars that pop up when your mouse touch the four edges of the screen. Other features include a high quality magnifier and a musical slideshow with 150+ transitional effects, as well as lossless JPEG transitions, drop shadow effects, image annotation, scanner support, histogram and much more. It supports all major graphic formats (BMP, JPEG, JPEG 2000, animated GIF, PNG, PCX, TIFF, WMF, ICO and TGA) and popular digital camera RAW formats (CRW, CR2, NEF, PEF, RAF, MRW, ORF, SRF and DNG)."


It's practically microscopic(3MB) compared to the gimp(40MB) and its fast. The full screen mode is really cool and intuitive, once you get the hang of it. There are a ton of shortcut keys that make browsing a little easier. Red eye removal and rotation are a snap. The cropping feature is cool because it allows for you to set the crop size to monitor resolutions. Great for getting a picture of my daughter in her bumble-bee costume for my wallpaper. It comes with dual monitor support, so you can do full screen on one monitor and look at the image viewer on the other. It will even let me link to an external program, if I want to edit the image in something more powerful.

And don't forget, this is a portable app. There are no ties to the registry. So next time you take your USB drive over to your parent's house to show them the pictures you just took of the grandkids, you'll have a great image viewer to view them in.

Wednesday, November 01, 2006

Portable Apps Week - FolderSize

It's an all to familiar proplem. Your favorite drive (HDD, USB, etc.) has filled up and you need to make some space. So you go into explorer and pull up your drive. Explorer shows you a list of folders and now its up to you to figure out which one is taking up the most space. This means a lot of right clicking. Enter FolderSize from RoteBetaSoftware. What a great play on words.

Folder size gives you a graphical representation of the folder sizes. Take a look at my ruby installation. You'll quickly figure out that the 'lib' folder is far and away the largest folder in the directory. You can even click directly on one of the bars in the graph to drill down into sub folders. Its a neat little utility (333kb) that comes in handy from time to time.

Tuesday, October 31, 2006

Portable App Week - WinAudit

Today's portable application comes to us from Parmavex Services. It took me a while to figure this company out. If I understand it right they have two main functions. They provide network services, software development, web hosting and IT services. And also, they supply spare parts for construction plant equipment. Kind of like a Barber shop that sells socks.
Despite their questionable lack of business direction, they have put out a pretty cool free-ware utility called WinAudit. WinAudit scans your machine and gathers up all the information it can find into a neat html report. Here is the description off the web site.


"The programme reports on virtually every aspect of computer inventory and configuration. Results are displayed in web-page format, categorised for ease of viewing and text searching. Whether your interest is in software compliance, hardware inventory, technical support, security or just plain curiosity, WinAudit has it all. The programme has advanced features such as service tag detection, hard-drive failure diagnosis, network port to process mapping, network connection speed, system availability statistics as well as Windows® update and firewall settings."


And when they say every aspect, they really mean it. It even read the serial number off my motherboard. You can save the results to an html file, a pdf, a chm, several flavors of text and XML. I wish I had this when I was still doing network support. It will come in handy the next time I'm troubleshooting on someone else's machine.

Monday, October 30, 2006

Portable Apps Week - Smart Undelete

I've been really keen on the idea of portable applications lately and last weekend I picked up a few more for my USB drive. So, I'm declaring a portable app week here at Mack the # implement. Let's get started with the only application that actually cost me any money.

I was tidying up some folders on my desktop at home, got a little 'Shift+Delete' happy, and accidentally deleted all the digital pictures from my son's first trip to the Georgia Aquarium. This is a bad place to be. My mind began calculating the odds that my wife would just forget that the pictures ever existed. Of course, NASA would have a hard time coming up with that number. Then it hit me, they aren't really gone. They're just marked as deleted.

After a quick search (on another machine), I found several recovery tools. I finally opted for Smart Soft's Smart Undelete. It was cheap, had a small footprint(<1mb) and could be used from a USB drive. It also has a 100% money back guarantee.

The UI is simple and easy to use. Just tell it where to scan. It also gives you the option to only scan for certain file types. In my case, .jpg files. I was able to get everything back. I even justified to expense to my wife by explaining how I could use it the next time one of our many relatives deletes something important. Yeah... that's the ticket. ;)

Monday, October 02, 2006

Pausing a PowerShell Script

I was having an issue while running my watir scripts where if I ran a script that saved information to the database on two or more machines at the exact same time, failure was sure to follow. This is really annoying and not likely to happen in the real world. However, in the alternate universe where I do my testing, this happens all the time. Alternate universes are cool.

We now have a lot of Watir scripts, and it is really tedious to run them individually. So I wrote a script that calls each one sequentially using PowerShell . With my new batch script, I am able to kick off all the Watir scripts from all of my test boxes at the same time and walk away while the website gets put through its paces. This works great until New York and DC try to save changes to the same story at the same time. One of the watir scripts will fail. Usually New York wins. Stupid New York.

I'm sure that there is a great solution, which involves messing with the database, but I don't have that kind of time, or patience or attention span. For the time being, I just wanted to put a pause in the execution of my PowerShell script that waited for me to press enter to continue. So here you go:

Code of Power:


[System.Console]::ReadLine()

Awesome!

Wednesday, September 27, 2006

How to generate a connection string

1 The other day I found myself trying to write my own connection string to a System DSN I had just set up. That was stupid and silly and I know that now. Seriously, who remembers the syntax for creating a connection string? No one. Why? Because we don't need to create these things every day. And also, it is stupid and silly.

So I donned the ceremonial robe and beseeched the great google for help. Of course, I was presented with a mountain of information on connection strings. But then it pulled out a large chest that looked like something right out of a pirate movie. I think this was because it happened to be International Talk Like a Pirate Day. The great google loves this stuff.

It spoke these words to me, "Avast! These examples be good, but ye have the noggin of a bilge rat. Perhaps ye be in need of some voodoo, ...some Windows voodoo." And it pulled a scroll from the chest and handed it to me with a twisted ferret look in its eyes.

Hmmm... voodoo, eh? Sounds iffy. But then again, not all windows voodoo is bad. There have been books dedicated to the subject. And I think we have all been in situations where we would gladly rub our computer monitors down with a fried drumstick from KFC while chanting the names of the 12 dwarves in reverse alphabetical order, if it would just keep IE from spewing random "Operation aborted" errors at our users. But that is another blog post. I wasn't that desperate, yet. I opened up the scroll, read the instructions and said to the great google, "This may be the grog talking, but I like sheh way you sthink." What follows are simple steps to get windows to generate a connection string that even a bilge rat could perform after a couple mugs of grog.

  1. Create a new file, the name doesn't matter, and give it a .udl extension.
  2. Double click on your new file. This will bring up the Data Link Properties dialog
  3. Select the "Use connection string" option and then click the "Build..." button.
  4. Your connection string will show up in the connection string text field. You can also access it by opening up your udl file in a text editor.

Thursday, September 14, 2006

Mouseless Firefox

1I just got back from vacation and I guess I left my mind on the beach, because I forgot to pick up my mouse on the way out the door. No biggy, I still have my laptop's touch pad and I don't really use the mouse much anyway. I was even able to pick up a new short cut key, just because I had to.

In Query Analyzer:
Shift+F6 - Switch between panes.

I think this is a good time to talk about some "mouseless" features and extensions that I have found very useful in Firefox. Here are some of my least known/most favorite shortcut keys for Firefox:

F6/Shift+F6 - Cycle through the frames on a page.
F7 - Enable/Disable caret browsing. The caret browsing is great for selecting and copying text.

One of my favorite Firefox add-ons is Mouseless Browsing. It takes some getting used to, but now I don't know what I would do without it. This extension enables browsing in Firefox using only the numpad keys. The extension puts a number next to each control or link on the page. All you have to do is type in the number and hit enter to browse to that link or control. You can even hold down the alt key while entering the number to open the link in a new tab. The numbers do mess with the formatting on the page, but it is really easy to turn them on or off. Just use the period key on the numpad.

Friday, September 08, 2006

Portable Apps are cool!

I'll be going on vacation next week to the beach and then to visit some family. That means I'll probably spend some time on their computer. Now, I like my little utilities that I use from day to day, and I would like to use them but I don't want to take the time to install them. I remembered that Hansleman was looking for a portable browser and it got me searching for other portable applications.

What is a portable application? Here is the definition from the PortableApps web site:http://portableapps.com/

A portable app is a computer program that you can carry around with you on a portable device and use on any Windows computer. When your USB flash drive, portable hard drive, iPod or other portable device is plugged in, you have access to your software and personal data just as you would on your own PC. And when you unplug, none of your personal data is left behind.

So, what kinds of portable applications are out there? About everything you could want and then some.

Luckily for me I had just picked up a shiny new Verbatim 512MB USB Flash Drive. It was just over ten bucks at Office Max. Its light and feels a lot sturdier than my last one. Here is a list of some of the apps that I have installed on my USB drive.

SysInternals:
Go to SysInternals while you still can and at the very least get:
Process Explorer
FileMon
RegMon
Autoruns
TCPView

Internet Stuff:
Browsar - Private browsing in IE. http://www.browzar.com
TorPark - Ultra private browsing in FireFox. http://torpark.nfshost.com/
Gaim Portable - IM Client. http://portableapps.com/apps/internet/gaim_portable

File Stuff:
7-Zip portable - Have you ever been stuck without a way to open up a zip file? http://portableapps.com/apps/utilities/7-zip_portable
ClamWin Portable - Portable virus scanner. http://portableapps.com/apps/utilities/clamwin_portable
FileZilla - FTP utility. http://filezilla.sourceforge.net/
Foxit Reader - Smaller and faster than Acrobat reader for pdfs. http://www.foxitsoftware.com/pdf/rd_intro.php

Just for fun:
Sudoku Portable http://portableapps.com/apps/games/sudoku_portable

Unclassified but cool:
PStart - PStart can be configured to start up when you plug in your USB drive. I creates an icon in your systray that acts like a start menu for your drive. Giving you quick access to the applications in a menu.

All these utilities only added up to 77MB. I wonder what it would take to get everything that we need to do our jobs as developers onto a 1GB USB drive. We wouldn't have to worry about dragging around laptops as long as we had a clean XP install to plug our drive's into. You wouldn't even require an internet connection for some of the apps. 1
I'll be going on vacation next week to the beach and then to visit some family. That means I'll probably spend some time on their computer. Now, I like my little utilities that I use from day to day, and I would like to use them but I don't want to take the time to install them. I remembered that Hansleman was looking for a portable browser and it got me searching for other portable applications.

What is a portable application? Here is the definition from the PortableApps web site:

A portable app is a computer program that you can carry around with you on a portable device and use on any Windows computer. When your USB flash drive, portable hard drive, iPod or other portable device is plugged in, you have access to your software and personal data just as you would on your own PC. And when you unplug, none of your personal data is left behind.

So, what kinds of portable applications are out there? About everything you could want and then some.

Luckily for me I had just picked up a shiny new Verbatim 512MB USB Flash Drive. It was just over ten bucks at Office Max. Its light and feels a lot sturdier than my last one. Here is a list of some of the apps that I have installed on my USB drive.

SysInternals:
Go to SysInternals while you still can and at the very least get:
Process Explorer
FileMon
RegMon
Autoruns
TCPView

Internet Stuff:
Browsar - Private browsing in IE.
TorPark - Ultra private browsing in FireFox.
Gaim Portable - IM Client.

File Stuff:
7-Zip Portable - Have you ever been stuck without a way to open up a zip file?
ClamWin Portable - Portable virus scanner.
FileZilla - FTP utility.
Foxit Reader - Smaller and faster than Acrobat reader for pdfs.

Just for fun:
Sudoku Portable

Unclassified but cool:
PStart - PStart can be configured to start up when you plug in your USB drive. I creates an icon in your systray that acts like a start menu for your drive. Giving you quick access to the applications in a menu.

All these utilities only added up to 77MB. I wonder what it would take to get everything that we need to do our jobs as developers onto a 1GB USB drive. We wouldn't have to worry about dragging around laptops as long as we had a clean XP install to plug our drive's into. You wouldn't even require an internet connection for some of the apps.

Thursday, September 07, 2006

Decode ViewState with PowerShell

We have been screwing around with ViewState lately, trying to resolve some issues and shrink down the size. In the process, we've downloaded several utilities to decode the viewstate. However, even these were failing to decode if the Viewstate was over a certain size or if it had non-native datatypes. Since we didn't have access to the source code, we couldn't fix the problems with the utilities. So yesterday, at approximately 3:57 pm, I thought to myself, "Gee, how hard could it be to write my own decoder?" But who wants to create a new VS project for a dinky little utility that you may never use again. Time for a PowerShell Script. It's one file with no compiling necessary.

This script reads the contents of a text file containing the viewstate in question. Then it decodes it, replaces the non-printable characters with pipe symbols and writes the results to another text file. You could easily rewrite this to pass in the viewstate string as a parameter to the script, if you wanted to. You're the kind of person who isn't afraid to paste a +50kb string into your command line of choice. Get down with your bad self!

A note on the non-printable characters: As of .NET 2.0, the viewstate is now delimited with non-printable characters. To learn more read Fritz Onion's blog on the subject.

Now, onto the script:

# Get the file from the arguments and read it into the x
$x = Get-Content $Args[0]

# Parse the string into a byte array
$byteArray = [System.Convert]::FromBase64String($x)

# Create a new encoding object
$enc = New-Object System.Text.ASCIIEncoding

# We need a charArray with the same length as the byteArray. I am having a
# hard time finding out how to create an strongly typed empty array of a given
# length in powershell. If you know how, please let me know. For now I just
# make charArray a copy of byteArray that will be overwritten later.
[System.Char[]]$charArray = $byteArray

# Do the decoding.
$enc.GetDecoder().GetChars($byteArray, 0, $byteArray.Length, $charArray, 0)

# Build the result string.
$charArray | ForEach-Object { $result += $_ }

# This is a neat regex to replace all the non-printing characters with something else.
# Then the result is written out to ViewStateDecoded.txt.
$result -replace "[\x01-\x1F]+", "|" | Out-File ViewStateDecoded.txt

I could probably get this down to 5 lines of code or less, but it more readable this way.

Wednesday, September 06, 2006

Set Window Title in PowerShell

1 It's been a month since my last post, and I'm sure that you were thinking I was dead. Not quite, just really busy. Here's a little time saving tip that I implemented last week in PowerShell. I was working on several issues and had multiple PowerShell windows open. Its kind of hard to find the instance of PowerShell that you are looking for while alt+tabbing through TaskSwitchXP. TaskSwitch even has a preview window, which helps as long as your window isn't minimized. The problem was that I had 3-4 PowerShell windows all titled "Windows PowerShell".

Wouldn't it be great if I could change the window title to something more meaningful? No sweat, PowerShell gives you access to the window through the $Host variable. The command looks like this "$Host.UI.RawUI.WindowTitle = 'My New Title'". Of course, I'll never be able to remember this and it does seem like a lot of typing. So I added the following function and alias statement to my profile.

function Set-WindowTitle($title)
{
$Host.UI.RawUI.WindowTitle = $title
}

set-alias swt Set-WindowTitle

Notice that I tried to mimic the verb-noun convention used by the rest of the PowerShell commands. Now, to set the title I can type in "swt 'My New Title'".

Wednesday, August 09, 2006

RDoc Documentation for Watir

In my dealings with Watir, I have been overlooking a very useful reference tool. The kind Watir developers have conveniently compiled class documentation with RDoc. RDoc is the Ruby version of NDoc (R.I.P.) This is great for when you want to see what the IE object really does. You can access this documentation here.

Your Install Dir\Watir\doc\rdoc\index.htm

Wednesday, July 19, 2006

Edit IE Address Bar with PowerShell

Lately, I've been doing a lot of testing of our web app. And for the last month or so, its all been on the same page. Being a shortcut key addict, I would type the url to the page in IE's address bar and then use F4 and the arrow keys to call it. As long as I kept going to that page, the url would always be at the top of the list. However, if I started going to other sites, the address bar's list would get long and my test url would get lost somewhere inside. It's a real pain the rump to go searching for it.

So I put together this little PowerShell script. It clears the address list and puts in the test urls that I want.

#1
$regpath = "HKCU:\Software\Microsoft\Internet Explorer\TypedURLs"
$xmlpath = "C:\Allen\PSScripts\AddressBarLinkList.xml"
cd $regpath
#2
(Get-Item . ).GetValueNames() |
Where-Object {$_ -match "^url\d+"} |
ForEach-Object { Remove-ItemProperty . $_ }

#3
$xml = New-Object xml
$xml.Load($xmlpath)

#4
$xml.urls.url |
ForEach-object {
New-ItemProperty -Path $path -Name $_.name -type string -value $_.link
}
cd c:

Let's look at each step and see what's going on. In step #1, I create 2 variables, $regpath and $xmlpath, and load them with some paths. Note that the regpath uses the registry key HKCU as a drive. In PowerShell the registry keys are treated equivalent to folders in the File System and registry values are treated equivalent to files in the File System. All you have to do is change directory to HK whatever and your in.

In step #2, we see a string of commands piped into each other. First we get the names of all the values in the key. Next we use Where-Object to pull only those values that match a regular expression. Then I delete all the values in the result set.

Step #3 starts with the creation of a new variable, $xml, of type xml (of the .NET xml's). Pretty much, what I'm doing here is creating a new Xml.Document object. On the next line I call the xml object's Load method to load an xml file from a filepath. The xml file contains a list of urls that I want loaded into the address bar. Take a look:

<urls>
<url>
<name>url1</name>
<link>http://localhost/Application/test.aspx?ItemId=70946</link>
</url>
<url>
<name>url2</name>
<link>http://DevServer/Application/test.aspx?ItemId=70946</link>
</url>
</urls>

In step #4, I get a list of all the url nodes. What is really interesting is the notation I used to get them, "$xml.urls.url". It reads like an XPath statement, just with dots instead of slashes. Next I use the New-ItemProperty command to create a key value for each of the urls in my xml file.

So this script edits the registry, reads an external file and parses an xml document. That's a lot when you consider that it took what amounts to 6 lines of code. I put in some line breaks and formatting to make it easier to read. Also note, that I didn't use any aliases in the script. It could be rewritten as:

cd HKCU:\Software\Microsoft\Internet Explorer\TypedURLs
(gi . ).GetValueNames() | ? {$_ -match "^url\d+"} | % { rp . $_ }
$xml = New-Object xml
$xml.Load("C:\Allen\PSScripts\AddressBarLinkList.xml")
$xml.urls.url | % { New-ItemProperty -P HKCU:\Software\Microsoft\Internet Explorer\TypedURLs -N $_.name -t string -v $_.link }
cd c:

Friday, July 14, 2006

Access your classes in PowerShell

In this example, we will build a small class library and "shell out" to it in a PowerShell script. I know that it is dinky and lame, but bear with me. We will build on this knowledge in a later post. Here are the steps to reproduce the example.

Fire up your favorite text editor and paste in the following code. I'm using Notepad2 http://www.flos-freeware.ch/notepad2.html. It has c# syntax highlighting. Save your file as "Person.cs". For me, the full path look like "C:\Allen\Spikes\PSClassAccess\Person.cs".

using System;
using System.Text;

namespace Person
{
public class Phrases
{
public Phrases()
{
}

public static string Hello(string Name)
{
return "Hello " + Name;
}

public string GoodBye(string Name)
{
return "Goodbye " + Name;
}
}
}

Open up an instance of the Visual Studio command prompt. Then browse to your folder and enter the following command. If all goes well, you will now have a Person.dll file.

csc /target:library Person.cs
Open another instance of your text editor and paste in this code.

# This loads the dll into memory
[System.Reflection.Assembly]::loadfrom("C:\Allen\Spikes\PSClassAccess\Person.dll")

# Write a blank line for aesthetic reasons
echo("")

# Here we call the static method directly from the class.
[Person.Phrases]::Hello("Allen")

# Now lets create an instance of the class.
[Person.Phrases] $Greeter = New-Object -TypeName Person.Phrases

# Here we call the non-static method GoodBye.
$Greeter.GoodBye("Max")

Save your file as "HelloGoodbye.ps1". The "PS1" extension is PowerShells default extenstion for scripts. The first thing that we do in the script is load our dll into the shells memory. A couple of lines down we call the static Hello method. Notice that the type is enclosed in square brackets. Next we use the New-Object commandlet to create a new instance fo the Phrases class as $Greeter. In Powershell, all variables begin with the $ character. Finally we use the new object to call the Goodbye method.

So lets see what we get. Open up a PowerShell console and browse to the directory where you saved your script. Run the script by typing "./HelloGoodbye.ps1". Your results should look like the following:

PS> ./HelloGoodbye.ps1

GAC Version Location
--- ------- --------
False v2.0.50727 C:\Allen\Spikes\PSClassAccess\Person.dll

Hello Allen
Goodbye Max

Sweet! The first thing we see is the result from loading the dll. You'll quickly determine that it is not in the gac and was compiled with version 2 of the .NET framework. Then we see the results of our script. Its a beautiful thing.

This really shows the power and versatility of PowerShell. How many uses just popped into your head?

Thursday, July 13, 2006

Just Upgraded StarTeam

I just upgraded to StarTeam 2005 and here are my initial thoughts. The first thing I noticed is that it doesn't look all that different. That's probably smart. No need to burden the users with a learning curve. Aesthetically, they prettied up the icons in the toolbar and sported a new splash screen.

They must have read my earlier blog post, because the All Descendants functionality is now available in the Change Request and File Menus. There still isn't a dedicated shortcut for it, but you access it quickly using "Alt+L, A" when in the file view and "Alt+C, A" when in the Change Request view.

The biggest item on my StarTeam wish list is the ability to easily extend the application. Maybe I'm spoiled from using Visual Studio, where I can assign keyboard mappings and add plugins. One thing that gets me is Borland's willingness to give us access to the SDK, but not let us use it to extend StarTeam directly. I have functionality that is still missing. I can write it, but I can't run it from inside StarTeam.

Wednesday, July 12, 2006

List files based on number of lines.

1I was working on a javascript error in IE which returned the line number of the error but not the file where the error occured. The page was accessing half a dozen seperate js files. This particular page doesn't do to well in FireFox, so using Venkman was out. However, there was something unusual about the error. The line number was 1202. I thought to myself, "How many js files could we possibly have with more than a thousand lines of code?" It actually isn't that many. But how to find this out? I'll tell you how! Powershell!

I opened up a powershell console, changed the directory to the directory where we keep all the js files, and typed in this little ditty (after several revisions, of course).
ls *.js | where {(gc $_).length -gt 1200}
Which returned:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/11/2006 2:12 PM 53520 JScript.js
-a--- 6/15/2006 1:43 PM 43806 StoryDescription.js
-a--- 7/11/2006 2:12 PM 88027 StoryDescriptionEdit.js

Let's look at what just happened here. At first glance, you'll notice that the line is pretty terse. That's because I used predefined aliases for the functions that I called. In PowerShell, every command that you call is actually a small application known as a commandlet. PowerShell also lets you alias these commandlets, in order to save you some time. There are many predefined aliases. To see a list of the aliases, just type "alias" at the prompt. If you pass in an alias then it will limit the results to that alias name. So if you type in "alias ls", you'll see that you're actually calling Get-ChildItem. It has just been aliased to make it easier for Unix/Linux users. It is also aliased as "dir". In fact, the entire line could be rewritten without any aliases as
Get-ChildItem *.js | Where-Object { (Get-Content $_)
.length -gt 1200 }

So the first little bit of the string returns a list of all the files in the current directory that have a ".js" extension. Then the pipe symbol, "|", passes the results to the next code statement. The where-object commandlet acts like a filter and only returns the items that meet the specified criteria. In this case we're making sure that the number of lines in the file is greater than (-gt) 1200.

We determine the number of lines with the Get-Content commandlet. This commandlet returns an array of all the lines in the file. You can even loop through the array, but that's another blog post. We just need to get the length property off of the array object.

And there you have it. Only three files in the directory have more than 1200 lines of code and my page only uses one of them. Even though I'm just a newbie, I'm loving PowerShell. Unlike most of my peers, I refuse to believe that it is only for system admins.

Tuesday, July 11, 2006

Random Thoughts

It's been a slow week for blogging. I've been pretty busy with the latest push. Here are few of my random thoughts that occured to me as I worked on StarTeam tickets.

9:05 Apparently, there is no "I" in "StarTeam".
10:38 If I were a pirate, my favorite word to say would be "Scurvy".
11:07 Mmmmm... Rosa's
1:43 The new nickel really creeps me out. Stop staring at me!
2:05 Stupid Farpoint! What would the magic eight skull do?
2:06 Walk the plank? ...riiight.
2:10 I just had a great idea for a blog post.1

Friday, July 07, 2006

Translate Time values with Javascript

11 On my current project, I have a need to convert a string to a valid time format. The user wants to be able to enter time in several formats. For example military time(1400), hour followed by a or p(2p), etc... I had a solution that got the job done, but it was getting long, was covered with bandaids and smelled like spaghetti. So I refactored it and came up with this approach. If you take out the comments, it has less than half the lines of code in the previous version. I use a trim string function to trim the spaces off the front and back of the time string, so I'm including it at the bottom.

Let me know if there is a better way to do this or if this might solve a problem you are having.


function fixTime(strTime)
{
var dayHalf = "a";
var Hour = "";
var Minute = "00";

// Drop the case
strTime = strTime.toLowerCase();

// Trim the spaces from the front and back
// of the string
strTime = TrimStr(strTime);

// Check for a|am|p|pm.
var amMatch = /(am|a|pm|p)$/.exec(strTime);
if(amMatch != null)
{
if(/p/.test(amMatch[0]))
dayHalf = "p";
}

// Remove a|am|p|pm
strTime = strTime.replace(/[a|p|m|:|\s]*/g, "");

// Now we should have nothing left but numbers.
// If the length of the string is 1 or 2,
// then we are dealing with hours only.
if(strTime.length < hour =" strTime;" hour =" strTime.slice(0," minute =" strTime.slice(-2);"> 23)
Hour = Hour % 24;

// Convert the hour and dayhalf.
if(Hour > 12)
{
Hour = Hour - 12;
dayHalf = "p";
}
else if(Hour == 0)
{
Hour = 12;
dayHalf = "a";
}

// This line ensures that the Hour variable is
// converted to a number type so the result
// won't have any preceding zeros.
// ex. "02" would loose the first zero.
Hour *= 1;

// Build our return string
strTime = Hour + ":" + Minute + dayHalf;
return strTime;
}

function TrimStr(str)
{
var sResult = new String(str);
var re1 = /(^\s+)/
var re2 = /(\s+$)/
sResult = sResult.replace (re1, "");
sResult = sResult.replace (re2, "");
return sResult.toString();
}

Wednesday, July 05, 2006

SQL Tip: Union vs Union All

A co-worker gave me a SQL tip today.

TIP: Whenever possible, use UNION ALL, instead of UNION, because it is faster.

This is a great tip and here's why. UNION eliminates all duplicate rows and sorting results. This requires that it create a temp table, storing all the records and sorting them before generating the result. So its not the most efficient way of doing things. A potential issue with using UNION is the danger of loading the tempdb database with a huge temptable.

UNION ALL, on the other hand, doesn't eliminate duplicates. It just performs the first select and then appends the second select onto the first result set. There is no temp table or sorting involved. This is much more efficient. If you don't expect duplicate data, then this is the way to go.

Friday, June 30, 2006

Coin Shrinker!


Today's totally rad technology is the amazing coin shrinker. That's right, a machine that can actually shrink a quarter down to the size of a dime.

How do they do it? Simple, they just pass about 1 million amps of electrical current through the coin. To put things in perspective, that is enough power to run a large city. The whole process takes approximately 25 millionths of a second. The coin only shrinks in diameter. It gets thicker, so the actual weight of the coin doesn't change. If this thing were a Master Card commercial it would run something like this:

Coin: 25¢
Electricity Bill: $1,000,000*
Ruining a perfectly good quarter just to impress your physicist friends while you hang out in you mom's basement: priceless

* I'm sure its not that high, but anything lower would lessen the comedic effect.

The salivating coolness factor on this is way up there. I don't even know why. My theory is that is a guy thing. Try asking your wife if you can install one in your basement. You should refrain from using phrases like "high-velocity metal forming", and "bullet-proof blast case".
I'm pretty sure the WAF on this is extremely low.

I'm sure that there are millions of industrial uses for this kind of technology. I even believe that we can end world hunger. Follow me here.

You can cook food with electricity. When I was in college I had a physics professor who showed us how to cook a hotdog with nothing more than a 12volt outlet and two pieces of wire. The shrinking process uses electricity and makes things thicker. Therefore we should be able to go from a couple of pieces of steakums to a 1 in. thick steak(medium well) in 25 millionths of a second. Talk about fast food.

Corrolation: There is something to be said about throwing massive amounts of effort to accomplish a goal in a relatively small amount of time. However, the end product isn't necessarily any better because of it.

Wednesday, June 28, 2006

StarTeam Productivity Hints

If you've spent 5 minutes in a room with me, you know that I'm almost fanatical about keyboard shortcuts. Don't get me wrong, I love the mouse. I need it to play UT. However, when it comes to just about everything else, I always feel more productive the less I use the mouse. Micheal Hyatt, CEO of Thomas Nelson Publishers and part-time productivity guru, once blogged:

"I have never met anyone really productive who relied on the mouse. It’s just too inefficient. ...few people take the time to really learn the standard operating system shortcuts (Mac or Windows). If you haven’t learned these already, I would urge you to do so. Over time, you will see a major boost in your productivity."

So today I was asked indirectly about how I use StarTeam. I was able to mention a shortcut or two, but there just aren't that many. StarTeam is a great system, but the UI is grotesque and not very customizable. And yet I can get 99% of what I need done accomplished without the mouse. Here is a list of shortcuts that really increase my productivity in StarTeam:

NAVIGATION
Ctrl+F6 - cycle through open projects
Ctrl+Shift+F6 - reverse cycle through open projects
Alt+W, num - Takes you to the project by its number in the Window menu
Tab - cycle through open panes
Shift+Tab - reverse cycle through panes
Ctrl+Tab - cycle through tabs in current pane
Ctrl+Shift+Tab - reverse cycle through tabs in current pane

FILES
Alt + i, i - Add files
Ctrl+g - Check out files
Ctrl+i - Check in files
Ctrl+l - Lock File

When you check in or add a file, StarTeam requires that you fill in a comment on the Check In dialog. I often just use a space. Pressing the Enter key doesn't close the dialog. It acts like a word processor and sends you to the next line. To combat this, I use the following combination of keystrokes. I don't even think about them anymore. Its all muscle memory now.

Ctrl+i, [space], Shift+Tab, Shift+Tab, [space]

One of my biggest problems with the StarTeam UI is that there is a button on the toolbar with no matching menu item or available shortcut. Of course, I'm talking about the "All Descendants" button. It's the only thing I haven't figured out how to do without the mouse. This has disturbed me to the point of insanity. There. I am insane now.

If you know how to accomplish this, please let me know.

Friday, June 23, 2006

Lasik @ Home!

Are you tired of wearing those glasses? Do you think that Lasik surgery is way out of your price range? Well let me introduce you to the Scal-Pal. That's right, for the measely price of $99.95, you too can reap the benefits of expensice Lasik surgery in the privacy and comfort of your home.

The Complete LASIK@Home Kit (patent pending) includes everything you need to complete the procedure.
  • Scal-Pal™ Hand-Operated Combination Femtosecond/Excimer Laser - A real laser!
  • Mild sedative (diazepam 4mg) - I'd pay the $99.95 for the sedative alone.
  • No-Blink™ brand Eye Drops - Don't Blink!!! More on that later.
  • Detailed Instructions and QuickStart Guide - Just four easy steps.
  • Protective Post-Op Sleep Mask - You're going to need a lot of sleep after this.
From what I can tell, these guys are serious. However, you won't find me shooting a laser into my own eye. What if I had an itch? As you can see in the below instructions, which are in cartoon form, even blinking can be disastrous. I like how every page has a footnote that reads "*This statement has not been evaluated by the FDA."



The instructions also show the added benefits of diy Lasik. Apparently, the laser shoots past your eye and into your brain. As it etches information into your gray matter, you will be granted enhanced archery, piloting, romantic and artistic skills.

I think my biggest question is, what do you do with the laser after you're done with your self-surgery. I'll bet you can cut stuff with it. That would be cool. Do you have any ideas?

Correlation: When you are trying to implement a process change without the proper support, DON'T BLINK!!!

*This post has not been evaluated by the FDA.

Thursday, June 22, 2006

Little known Sql String functions

We are all familiar with SQL string functions like LEFT and SUBSTRING. Here are some of the lesser known Sql string functions:

PATINDEX lets you search a string for the first instance that matches a given pattern. The pattern must begin and end with % signs. So the following code selects all the last names in the table that contain the pattern 'ack'.

SELECT LastName FROM tblPersonnel
WHERE PATINDEX('%ack%', LastName) > 0

STUFF inserts a string into another string. It can delete a specified number of characters from the start position before inserting the string. Here is some code that starts at the second letter in the string, deletes the next two characters and then inserts the phrase 'ack'.

SELECT STUFF(LastName, 2, 2, 'ack') FROM tblPersonnel

SOUNDEX and DIFFERENCE can by used to compare how much two strings sound alike. SOUNDEX takes a string and returns a four-character that can be used by DIFFERENCE to determine if two strings sound alike. Here's and example:

SELECT SOUNDEX('Barnett') --> B653
SELECT LastName FROM tblPersonnel
WHERE DIFFERENCE('Barnett', LastName) < 4

Notice that I didn't have to use the SOUNDEX function in the difference parameters.


Here are two where I can't think of a reason to use:
REPLICATE returns a string that is composed by repeating a string for a set number of iterations. Heres a sample:

SELECT REPLICATE('A', 5) --> 'AAAAA'

REVERSE produces a mirrored image of the string. So if you want to return all the names in the table spelled backwards, you could use:

SELECT REVERSE(LastName) FROM tblPersonnel

Like I said, I can't think of any real world examples where those last two would be useful, but they are cool anyway. If you can come up with an example, let me know.

Monday, June 19, 2006

I pwn'd it!

I stumbled across a highly addictive brain teaser from Cambrian House titled PWNIT. It is aimed at coders and technologists and was a lot of fun. It took me about 4 hours, but I got through it all on my own. Oh, and with a little help from the Great Google. I didn't ask the Great Google for the solution, I just looked up reference materials, like the Hebrew alphabet.

When you complete all the puzzles you get to download this graphic to prove that you solved it. Yay me!

I have to give Cambrian House some credit, this is a pretty cool attention grabbing device. I even like their business plan. I guess a bunch of programmer types got sick of their jobs and decided to start their own software company. But wait, they didn't have any idea what software to create. So here is their scheme. They solicit cool and innovative ideas from you, the web audience. You provide them with a great idea and they will make it happen. And if by some chance your idea actually makes some money, they will give you some of the profits. This is brilliant. I think Microsoft should adopt this model as well. I have some great ideas for them and they owe me a refund for all the zeros that they have sold me anyway.

Thursday, June 15, 2006

Rounding in .NET

I was having an issue on at work, where I needed to determine how tall to make a Farpoint Spread row to display some text. I would calculate the size of some text to be entered into a table cell. Then I would take the length of the text, based on the font and divide it by the width of the cell and voila, I should have the number of lines that need to be displayed. However, I was having a problem with some of my tests. About half of the time, I ended up missing a line.

As I looked closer I noticed that all of the variables in my calculation were integers. A ha! .Net was rounding stuff for me, using its default Banker's Rounding system.

If you are unfamiliar with Banker's Rounding, or aren't a banker, then this way of rounding may seem insane to you. Let me explain. In Banker's Rounding everything works just like in regular rounding, except when dealing with halves. So anything less than .5 will always round down and anything greater than .5 will always round up. But when we have exactly .5 then we round to the closest even number. You are probably used to .5 always rounding up. This is a little known, yet extremely important behavior and I hope to have saved you some heartache. Lets see some Bankers Rounding in action:

1.49 ==> 1
1.50 ==> 2
2.50 ==> 2
2.51 ==> 3


Back to my issue. I needed a way to always round up, no matter what the decimal. Enter the Math.Ceiling function. The Math.Ceiling function returns the next whole number greater than the decimal that you started with. Here it is in action:

System.Math.Ceiling(1.0) ==> 1
System.Math.Ceiling(1.3) ==> 2


Alternatively, if you want to always round down, you could use the Math.Floor function. It returns the next lowest whole number from the starting decimal.

System.Math.Floor(2.0) ==> 2
System.Math.Floor(1.9) ==> 1

Thursday, June 08, 2006

Internet Explorer's Progress Bar doesn't stop when the page is finished loading.

I have an asp.net page that is loaded with Farpoint controls and I use Anthem to make callbacks everytime something is changed in any of the cells. So every once and while, I experience an issue where a callback starts up the progress bar. Really, this isn't a problem. The problem is that the progress bar continues to progress slowly, even after the page is complete and ready to use. This gives the users that the page is still doing something and they should wait, a long time, before they start making more edits.

A quick look in google reveiled that the Internet Explorer progress bar was apparently developed by a group of snails, who are not only slow but also of subpar intelligence. At least that's what the community thinks. Google also reveiled this support document. Even Farpoint recognizes this problem and you can read about it here. Here's the gist. When you dynamically insert behaviors in your page, the progress bar gets dazed and confused. If you use the Farpoint spread, you know that this happens a lot. We can set the progress bar back on the right track by writing something to the status bar. I'm guessing that this resets the whole footer in IE.

I am now reseting the status bar on the window.load event and everytime I handle a callback in Anthem. It seems to have corrected my issue.

Monday, June 05, 2006

Reign in the track wheel in IE

I work on a lot of ASPX pages and IE is currently the default browser for the enterprise. I'm sure that you have workied with IE before too. Here's a little quirk that has been especially troublesome for my team and I lately.

Have you ever clicked on a dropdown box, made a selection and then moved the mouse out of the dropdown box and started to scroll the page with your mouse's track wheel? Then you know that in IE the page doesn't scroll, the items in the dropdown do. This can be a real headache since everytime the dropdown list item changes it fires off an event. And God help you if that event is tied to an AJAX callback.

Luckily, there is a way around this. A buddy of mine on the team found this article to explain everything. You just have to handle the 'onmousewheel' event. See the sample:

<select name="mylist" onmousewheel="return(false);">

Note: You don't have to worry about this in FireFox

Friday, June 02, 2006

Cellular Squirrel!


I have received several positive comments about the Badonkadonk post, so I thought I might make a segment out of it. From here on out, every Friday, I will try to bring you yet another demonstration of technology run amuck. And to keep it relevant, I'll draw a correlation of some sort. I have yet to come up with a good name. Maybe my loyal readers will offer some suggestions (this is a blatent attemp to get you to comment on this post). Now onto the good stuff.

Before we get to the finished product, let's take a look at the underlying technology which is really cool. Stefan Marti at the MIT Media Lab has developed an intermediary conversation agent for use with your cellphone. Basically it acts like a call screener. When you get an incoming call the agent picks up the line and interrogates the caller. If the caller is on a whitelist and they don't seem too agitated, then the agent will alert you that you have a call that you want to take. It's like having your own personal secretary. I've always wanted one of those.

Now, let's get creepy. As with all good projects, if you get too intense you run the risk of going insane. Case in point, Apocalypse Now. I think the designers walked right up to the line and boldly crossed it without looking back. Let's listen into the designers as they deal with how to package their new technology.

[Designer One]: We've created a cool technology that will forever change the way we use our cell phones!
[Designer Two]: Brilliant!
[Designer One]: Look I'm getting a call right now. Hello?... Hi Timmy... You did what?... I thought I told you never to play with the beakers... but... alright, I'll clean it up when I get there. <click> Looks like we're going to need another Timmy!
[Designer Two]: Brilliant!
[Designer One]: I know, lets take our new technology and stuff it into an animitronic plush toy fashioned in the image of a cute, cuddly squirrel. Except we'll give the squirrel red, beady eyes and make it shake uncontrollably while we say scary things to Timmy through it.
[Designer Two]: Brilliant!
[Designer One]: HAHAHAHAHA... (Maniacal laughter lasting well into the night.)

And so was born the Cellular Squirrel. Take a look at the pictures, it actually has blood red, beady eyes. There is also a plan for a bunny version.

Todays Correlation: As developers we often take a cool technology and wrap it in a cute and cuddly UI. Maybe I'll give my next UI beady eyes.

Thursday, June 01, 2006

Music and Productivity

Last night our team got together in a war room type setup where we all converged into one room with our laptops to help solve some of our outstanding issues with our current project. One of the guys used his laptop for a jukebox so we would have some background noise. It was a pretty eclectic collection and I enjoyed all of the selections, especially Queensrÿche's Silent Lucidity. Queensrÿche Rules!!! And as much as I like the Beastie Boys, I couldn't help feel more relaxed and focused during songs like Silent Lucidity. So it got me thinking about music's affect on my mood, concentration and productivity.

Can music actually make you more productive or help your concentration? In his article, "Does listening to music improve productivity", Michael Setton shows that it does. He sites a study that showed people who listened to music while they worked actually increased productivity by 10%. Listening to music with an upbeat rhythm can reduce stress hormone levels by as much as 41%. Apparently even cows produce more milk when listening to the right music.

In the spirit of Listibles, I have compiled my top 5 Artist/Albums for increasing my concentration and productivity while I work. They are all What are yours?

Chroma Key - Dead Air For Radios
OSI - OSI
Tool - Aenima
Pink FLoyd - The Delicate Sound of Thunder (I know its a double cd)
Porcupine Tree - Stupid Dream

Wednesday, May 31, 2006

Javascript Debugging Hint

Often times I feel like I have to be a cross between Gil Grisom and Sherlock Holmes when I'm trying to debug a javascript error. So I get very excited when I find a tool or technique to help me. So far my favorite tool is the Venkman javascript debugger, despite rumors that it crashes on some machines.

The other day a co-worker mentioned that enabling the script debugging in Internet Explorer allowed Visual Studio to debug javascript in your site. You can do this by going into IE > Tools > Iternet Options > Advanced and unchecking the "Disable Script Debugging (Internet Explorer)" option. This was very exciting, a way to debug javascript directly in the IDE. It still didn't get rid of those cryptic IE errors, but at least you would break in the IDE. If you want to get better error messages, use Venkman.

Anyway, back to the task at hand. I noticed the other day that Visual Studio's CallStack window works while debugging javascript. Let's perform an exercise to see how useful this could be. Suppose you have a javascript function that is called from several different places. If that function threw an error, the call stack information could help determine what called it. Take a look at this simple page:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test Page</title>
<script type="text/javascript">
function runtest1()
{
test(true);
}
function runtest2()
{
test(false);
}
function test(x)
{
if(x == false)
throw("New Error");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button"
onclick="javascript:runtest1();runtest2();"
value="Push Me" />
</div>
</form>
</body>
</html>


When you click on the button, runtest1 will execute successfully and runtest2 will throw an error. Now pretend that you don't know exactly where the error was coming from. Take a look at the stack trace and see if you can figure it out.

Tuesday, May 30, 2006

I Love Lists

Everyone loves a list, right? Well, a lot of us do. We watch Letterman because his top ten lists are funny. We go Hanselman's website for his ultimate list of tools. We love to see what other people find important and compare their lists with our own. I find that lists are a great way to find out about tools and sites that I wouldn't have found otherwise.

For the most part, lists are cool. This is why Listible is cool. Listible is kind of like Digg and Del.icio.us got together and had a really cool baby, and named it Listible. Here's how it works. Basically, someone requests that a list be created to cover a topic. Then the public is free to add items to the list and tag them like in del.icio.us. But what makes this site special, is the public's ability to vote for an item thereby driving it up the list. The public sets the relevancy of all the items in the list. So when you view a list, you can be relatively confident that the best stuff is at the top.

You can even vote for the relevancy of the list itself, which will determine how that list ranks compared to other lists. However, I'm a little unclear about this. I can understand one site being a better .NET reference than another site. But, can you really say that a list of .NET reference sites is more important than a list of Wedding Planning sites? It seems to me that importance is in the eye of the beholder.

Thursday, May 25, 2006

IE/Clipboard Security Risk

Have you ever wondered what information a web server can glean from you when you visit a site? You can find out on the Project IP web site. I was really surprised at some of the stuff the site found about my pc and web session. Sure, I expected it to know my IP address, browser version, whether or not cookies were enabled, etc. However, I was surprised to find a list of all the plugins I have installed in my browser and the number of pages that I have viewed in my current web session.

But here's the real kicker, the last text item you copied onto your clipboard! Only works in Internet Explorer on the Windows platform. If you aren't using FireFox by now, maybe this will sway you. It reportedly works with varied success when IE is running in an emulator such as VMWare on another OS. Have you ever copied a password or credit card number or ssn and pasted it into anywhere? Hopefully, it wasn't right before you browsed a site that took advantage of this.

Luckily there is a fix:
Go to Tools > Internet Options > Security > Select a security zone > Custom Level > Scripting > Allow paste operations via script and set it to Disabled or Prompt.

Wednesday, May 24, 2006

Windows Shortcut Keys

I'm always looking for cool keyboard short cuts to help me be more productive in my applications. For example, Visual Studio has a gazillion shortcut keys that enables you to do just about anything without the mouse. I find that while I'm coding, the less time I use switching back and forth between the keyboard and the mouse the more I get done. But what if you aren't in your favorite development environment. Here is a great list of windows shortcut keys from CodingHorror.

If you wish to expand on this list, you might want to try Winkeys. Winkeys allows you to use the Windows key to create keyboard shortcuts for your favorite applications. Here is a list of the ones that I have added. For example, I use Windows + Shift + V to open Visual Studio 2005.

Monday, May 22, 2006

The Orange Movie project has just released their animated short, The Elephant's Dream. The project was sponsored by the Blender Foundation, an opensource community around the Blender 3D modeling, animation and rendering application. The Orange Movie Project's stated goals were to create an outstanding movie short, and to research efficient ways to increase quality of Open Source projects in general.

The short is nothing less than awesome. I've already downloaded it, you can get it and the project files that were used to make it on their web site. It makes me want to try my hand at 3d modeling and animation.

I had to download and install MPlayer to get it to play. MPlayer is currently a console application for Windows. However, there are frontends available for download. Here is one.

Thursday, May 18, 2006

Ba-donk-a-donk!


Now what I'm about to share with you is either a testament to marketing genius or my stupidity. But if loving this stuff is wrong, I don't want to be right. I came across this site by NAO Design, who describe themselves as, and I quote:

"...a multidisciplinary design firm with a focus on automotive design, architecture, pyrotechnics, lighting, furniture, electronics, signage, and web and graphic design, and often the fusion of several such diverse elements."

Wow, there's a mouthful. So what makes these guys so special? One word, "Badonkadonk". The Badonkadonk is a personal motorized, armored transport with head/tail lights, turn signals, accent and underbody lights, 400 watt premium sound with PA system, and... Oh yeah, and an optional pyrotechnic system that shoots flames out the top. This product became so popular(how?) that it garnered its own web site. I think the inception went a little like this:

Designer 1: I'll bet I can fit my fist in my mouth.
Designer 2: I'll bet I can sell a go-cart on Amazon for 20 grand.
Designer 1: How the hell are you going to do that?
Designer 2: Easy, I'll just armor plate it and throw in a stereo.
Designer 1: You know what would be cool? If it shot fire.
Designer 2: eh, eh... fire... sweeet.

SideNote: I can't not talk about the PneumatiPak 2, also found on the NAO Design website. Basically a pneumatic powered handheld cannon. So what makes this so much better that your average nail gun that you could pick at Homedepot? I swear I'm not making this up. "With a removable 1.5L liquid reservoir for shooting water, paint, beer, etc. New rotary reloading breech-loader mechanism allows for very rapid reloading of solid ammo, such as hotdogs, marshmallow, batteries, tampons, and carrots. With a maximum range of 100 yards." Priceless... Speechless...

Back to the Badonkadonk and why it inspired this blog. The Badonkadonk is cool, but I don't need all that stuff. Have you every used a piece of software that made you feel the same way? Have you every coded software that made you or the client feel that way? We sometimes have the tendancy to gravitate towards flashy things with lots of cool features that we never use because we don't need them. Gordon Moore recently noted that software has become so complex that it prevents the users from making effective use of the underlying power of their computer. It may be too late for a new years resolution, but the Badonkadonk and my Badonkadonk project, have me picking up and dusting of the old development ethos: "Keep it simple stupid."

Tuesday, May 16, 2006

Cool Atlas information from Jeff Prosise

Yesterday we had a very interesting lunch and learn session on the topic of Atlas. The speaker was Jeff Prosise, co-founder of Wintellect. Jeff was an excellent speaker. I learned a lot in the little time that we had. Here is a breakdown of Jeff's presentation.

1. Introductions
Jeff started out the presentation with a brief overview of Atlas. Atlas is Microsoft's upcoming AJAX framework. It is only compatible with ASP.NET, so you have to serve it from IIS. It is also only compatible with .NET 2.0 and higher. There will be no backwards compatibility with .NET 1.x. I was under the impression that Atlas was a mostly server side technology. However, using the XML scripting language, you can do just about everything on the client side.

2. Ajax support already built into ASP.NET
Jeff demonstrated that there is already support for AJAX built into ASP.NET 2.0. You just have to do a little bit of coding to get it to work. Basically you implement the ICallBackEventHandler interface on your page and then grab a reference to the javascript function that you wish to return to. Here is a page and the code-behind that demonstrates using AJAX in an ASP page.
ASPX:

<html>
<head>
<script language="javascript" type="text/javascript">
function MultiplyByTwo()
{
var tb = document.getElementById("txtNumber");
var value = tb.value;
CallServer(value, "");
}
function DisplayResult(rValue)
{
document.getElementById("lblResult").innerHTML = rValue;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="txtNumber" type="text"> * 2
<input onclick="MultiplyByTwo();" value="=" type="button">
<asp:label id="lblResult" runat="server">>
</asp:label></div>
</form>
</body>
</html>



Code-behind:
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{

protected string returnValue;

protected void Page_Load(object sender, EventArgs e)
{
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "DisplayResult", "context");
string callbackScript = "function CallServer(arg, context){" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}

#region ICallbackEventHandler Members

public string GetCallbackResult()
{
return returnValue;
}

public void RaiseCallbackEvent(string eventArgument)
{
if (!String.IsNullOrEmpty(eventArgument))
{
int arg = int.Parse(eventArgument);
arg *= 2;
this.returnValue = arg.ToString();
}
}

#endregion
}


3. Framework
When a page containing atlas controls is requested, Atlas sends a copy of its framework down to the client machine. The framework is written completely in javascript. Since most browsers cache javascript, the framework should only be downloaded once, instead of everytime you hit page with an Atlas control. Jeff also mentioned that the release version will contain a browser abstraction layer. This layer will be responsible for making sure your code runs correctly no matter what browser it is displayed in.

4. Clientside Focus
For the clientside, Jeff focused on Atlas' XML scripting language. Most of the examples used very little server side code. The framework parsed the script and generated the necessary javascript to perform the actions. Here is an example of some XML script that displays a panel when you click on a button.

<script type="text/xml-script">
<button id="showButton">
<click>
<setProperty target="panel" property="visible" value="true" />
</click>
</button>
</script>


5. Serverside Focus
For the serverside, Jeff showed off some "Extender" controls. Most noteable the MSN Earth control that hits the same servers as Windows Live Local. There isn't a lot of documentation out there for these, but they seem really cool.

WinFX SDK killed my download

I am extremely keen on XML technologies. I don't claim to be an expert, but I think that they are pretty cool. Recently I have become more and more interested in the prospect of using Flash like technologies to boost the user experience on my web sites. My search led me to XAML. XAML is cool. I haven't actually written anything in XAML, but the demo's on the web are sweet.

What's that you're saying? Why haven't I written anything in XAML yet. I'll tell you why. Because it took almost 4 freak'n hours to get the stuff installed and return my machine to working order, that's why! I don't that kind time. Sure I love watching paint dry as much as the next guy, but seriously! James Robertson has any excellent Squidoo lense for XAML that includes a section on what you need to download and the installation order. Here's a break down of the installation steps and how long it took for each one.

1. WinFX Runtime Components - couple of minutes: This is all you need to view XAML files on your machine. But if your like me, and want to actually write an application you'll need the...

2. WinFX SDK - 3+ hours: Holy creeping downloads Batman! Its a good thing my hard drive had an extra gig of free space. I kid you not, 1.2 gigs. Maybe I should have limited what I wanted to install, but it all looked so delicious. This is why they shouldn't let me eat at buffets. The only thing that I turned off in the install was the 64-bit processor support and Monad (more on that later).

3. Optional Development Tools - 30 minutes: The install took longer than the download.

At this point I am already frustrated with the SDK install, but I made it through and thought that a reboot was in order. You don't have to reboot, I'm just weird. Anyway, I tried to open up a Powershell instance after the reboot and recieved an error. That's odd. Powershell was working before. Wait a minute, where's my powershell install directory?!!! I guess when I told the SDK not to install Monad (because I already had Powershell installed), THE SDK UNISTALLED POWERSHELL!!! I don't even know how. Monad installs under a completely different directory. So that led me to...

4. Microsoft Powershell RC1 - 5-10 minutes: PowerShell rules! Reinstalling sucks!

Alright now its time for a "hello world" application. Wish me luck.

Welcome to my blog

One of my new job "requirements" is to blog to an internal blog. But I thought that some of my more technical and less jobby posts should be shared with the rest of the world. And since I am so cheap, I started this blog for free.

A little about me. I'm an Advanced Software Engineer working with C# and creating mostly web applications. I love xml technologies and am trying to give up the mouse while I'm programming. This is turning out to be very difficult when working on web apps. So expect to see more blogs in those arenas.