10,000 Monkeys - Harnessing the Power of Typing Monkeys

America's 2,672,401st Most Read Blog by Kevin Marshall.
in

March 2006 - Posts

LINQ'd Lists
It's Tuesday, which is double post day over here at 10K Monkeys. Exciting times for those of you reading along at home. Tonight's topic  is something I've been eagar to play with, LINQ and C# 3.0.  Although its been hard to find time between the frequent cat naps and reruns of Jag. So what is LINQ? MS defines it as Unified Language Features for Object and Relational Queries. But thats not all, you can also query objects using unified language features.
 
To get started, download and install the LINQ preview. Be warned, it's not for the faint of heart.  VS 2005 doesn't fully recognize all of the syntax in intellisense and the compiler will display errors like its Y2K. Step aside compiler, I'm an IT Professional.

So open up VS 2K5 and make a new LINQ console app using one of your newly installed templates.  Then paste this little gem into the Program.cs class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace LINQConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            GetEmployees();
        }

        static void GetEmployees()
        {
            var employees = new List<Employee>() {
                new Employee { Name = "Kevin", HireDate = new DateTime(2000, 11, 18)}, 
                new Employee { Name = "Jeff", HireDate = new DateTime(1999, 5, 7)},
                new Employee { Name = "Bryan", HireDate = new DateTime(1995, 1, 12)},
                new Employee { Name = "Ryan", HireDate = new DateTime(2003, 5, 1)}, 
                new Employee { Name = "Steve", HireDate = new DateTime(2002, 12, 1)}
            };

            var rookies = 
                from r in employees
                where r.HireDate > new DateTime(2001, 1, 1) 
                orderby r.HireDate
                select r;

            var veterans = 
                from v in employees
                where v.HireDate 
< new DateTime(2001, 1, 1) 
                orderby v.HireDate
                select v;

            Console.WriteLine(
"Rookies:");
            foreach(var val1 in rookies)
            {
                Console.WriteLine(
" Name = {0}, Hire Date = {1}", val1.Name, val1.HireDate.ToShortDateString());
            }
            Console.WriteLine(
"Veterans:");
            foreach(var val2 in veterans)
            {
                Console.WriteLine(
" Name = {0}, Hire Date = {1}", val2.Name, val2.HireDate.ToShortDateString());
            }
            Console.ReadLine();
        }

    }

    class Employee
    {
        public string Name;
        public DateTime HireDate;
    }
}

Don't worry about the errors, it'll run. 
Tell the compiler "You will respect my authoritah!" (Or not depending on the location of your cubicle)

Here is the output if you don't believe me



How great is that?  So let's check out some of the new syntax. First off is the new var type. You might be thinking, at long last, the power of Javascript in C#. But no, it allows the compiler to infer the types. employees is initialized in the right hand side as a generic list of employee objects. Notice also, how the employee class doesn't need a constructor. The declartion of the list also includes several new features like populating the list directly within the curly braces without having to call add on the list and employees are created by explicitedly setting the fields (object initializers). Note, you can also set only a subset of the fields if you are too lazy to set them all. But wait, there is more, check out the sql like syntax to query a list. Behold, the same SQL syntax from 1965, is now in C#.  The great feature of the var keyword is that it allows the sql-like keywords to infer what type the query will return.

This seems like it will be a very cool addition to the next version of C#. It makes getting specific items from a list very simple.  No more for loops and if checks to find items. LINQ also has some cool syntax for creating table objects directly from a db that you can query or syntax for querying XML.  I didn't have time yet to check out performance, but I imagine it's probably not good to use huge lists.  Although being able to use object querying on a table's data is almost like having an object oriented database. When are those coming out anyway? Its amazing how slow database technology is to change. Oh, wait we can have XML in databases.  Thats a recent addition from the 1990's. I wonder what it's like to use DLINQ to query a table that has XML so that I can XLINQ that.  The possibilities are endless.

This could make a great addition to the Foos Server.  Watch out Foos DBA, I can now write inefficient queries INSIDE my app. 
ASP.NET 2005 Annoyances #00003 - Treeviews and Sitemaps with Cookieless Sessions
I hate cookieless sessions.  I don't really have many good reasons.  Perhaps its the eye sore of a url that gets put in the browser.  Or maybe its the fact that they break the treeview control.  Is it too much to ask that the treeview would be smart enough to generate links with the 2054 character session id in there?

One way to fix this is to add a handler for the NodeDataBound event of the treeview control.

protected void treeNode_OnNodeDataBound(object sender, TreeNodeEventArgs e)
{
   e.Node.NavigateUrl = Response.ApplyAppPathModifier(e.Node.NavigateUrl);
}
Posted: Mar 28 2006, 10:21 AM by kmarshall | with no comments
Filed under:
Default Buttons on ASP.NET 2.0 Forms
First I want to welcome the new reader I gained from my Coding4Fun article.  Perhaps your dog accidentaly jumped on the keyboard and clicked the link to my site or maybe you're new to the english language and you were looking for the German Coding4Fun site.  Willkommen.  I'm sure you'll find a wealth of literary delights 10-15 minutes of mindless reading here.

Anyway, how do you set the default button when you have multiple buttons on a form?  My first response would be "Just build a winform app and stop trying to hack together desktop app like functionality on the web"  (Note: Several explatitves were removed since this is a family friendly site)  Now with ASP.NET you can set the default button on forms and panels so that if you click Enter in a text box, it'll submit with that button.

So if you have two different sets of inputs with save buttons, you can place them in a panel and set the default button for input fields in that panel.  Like so:

<html>
<body>
     <form runat=“server”>
          <asp:panel defaultbutton=“btn2” runat=“server”>
              <asp:textbox id=“Name” runat=“server”/>
              <asp:button id=btn2 runat=“server”/>
          </asp:panel>
          <asp:panel defaultbutton=“btn3” runat=“server”>
              <asp:textbox id=“Address” runat=“server”/>
              <asp:button id="btn3" runat=“server”/>
          </asp:panel>
     </form>
</body>
</html>

Now you can fire off different events all over your form with a simple click of the Enter key!
Posted: Mar 16 2006, 08:39 AM by kmarshall | with no comments
Filed under:
Visual Foos 2005 Update
So the article I wrote for MSDN's Coding4Fun got posted over here and the installation instructions are over here.  This could be the begining of a monthly column.  Now if only I could think up 11 more topics and the motivation to write more than 8 sentances.  I predict that this could increase my readership from 12 to 16 readers.  Speaking of predictions, I made some updates to the foos prediction engine aka The Swami to track prediction accuracy.  Right now its about  90% accurate in predicting the winner, 70% of the time it gets the score within +/- 1, and 50% of the time it gets the score perfect.  It's so good it's almost erie.  I'm thinking of transfering the logic into an NCAA predictor.  It can't be any worse than my current bracket picking skills.  Typically my grandma's brackets out perform mine and I don't think she has watched a college basketball game since she was in college.  Here is a screenshot of the player admin site and the Swami.



Other updates include the Shutout monkey which starts appearing when you're up 5-0.  It's tough to keep the shutout going with the monkey taunting you.



Yes, I probably do have too much free time invested in this game.  I'm also in the process of rewritting the Instant Replay engine to use only DirectX.  Unfortunately DirectX isn't the easiest API to work with.  I found a good start over here though.  I also added All-Time Losing Streak to the stat categories.  Now I'm finally in the Top 5 in a category.  I'll update the code posted here with the changes sometime tonight.
Posted: Mar 13 2006, 02:25 PM by kmarshall | with no comments
Filed under:
ASP.NET 2005 Annoyances #00002 - Gridview HyperLinkFields & Javascript
So this morning I come into work early and I'm in the coding "zone", fixing defects like a machine.  I'm, dare I say, en fuego.  Then BAM! ASP.NET 2005 puts the smack down on me. 

Let's reenact the scenario without using real code or client names.  So I wanted to you use EnableSortingAndPagingCallbacks="true" on a gridview since it makes the UI experience so much cleaner without the constant Postbacks each time you sort.  One of the columns needed a javascript function.  In the old datagrid you could do something like:

<asp:HyperLinkField HeaderText="Fund" DataTextField="itemName" DataNavigateUrlFields="itemName"
    DataNavigateUrlFormatString="BLOCKED SCRIPTalert('{0}');" />

Much to my shock and dismay, this does not work in 2005. The obvious work around for this is to use a templated column.  Unfornately, you cannot set
EnableSortingAndPagingCallbacks="true" with templated columns.  Which sucks.  So after giving my monitor the middle finger several times, it dawned on me to just use the OnRowDataBound event.  Perhaps it would have taken another developed only one showing of the middle finger to come up with a solution, but it took me several to get the creative energy flowing. 

Here's what I did: (I just whipped up a sample which may have some syntax errors)

 public void myGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
 {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
         e.Row.Cells[0].Text = "<a href=\"#\" onclick=\"alert('" + ((DataRowView)e.Row.DataItem)["itemName"]         +  "');\">Click Me!</a>";
    }
 }

And then I did the Tiger Woods fist pump.

Posted: Mar 10 2006, 09:18 AM by kmarshall | with no comments
Filed under:
Fun with C# and nullable ints
Sometimes the 10K monkeys staff is too busy on mission critical projects like foosball stat trackers and comic book managers to keep up new C# syntax like nullable ints.  How did I not notice earlier that you could declare an int as "int? in"  Plus how great does "int?" look?  I previously felt there wasn't enough use of the question mark in my code.  So how is this useful and why did you waste 10 minutes blogging about this?  Well to answer the first question, I personaly found them useful in data access classes where I have an update stored proccedure may update value that can be null.  For example:


public void UpdateEmployee(int employeeID, int? age, string firstName, string lastName)
{
    Database db = DatabaseFactory.CreateDatabase();

    string sqlCommand = "UpdateEmployee;
    DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);

    db.AddInParameter(dbCommand, "@EmployeeID", DbType.Int32, employeeID);
    db.AddInParameter(dbCommand, "@Age", DbType.Int32, age);
    db.AddInParameter(dbCommand, "@FirstName", DbType.String, firstName);
    db.AddInParameter(dbCommand, "@LastName", DbType.String, lastName);

    db.ExecuteNonQuery(dbCommand);
}

Now I can just pass null into my data class and let the db field stay null.  I've also been working with the MS Enterprise Application block lately as you can see from the sample code.  I'm sure I'll have much to complain about there in future blog entries.  As for the second question, I have no idea.
Retro Progamming: Top 10 DOS Commands
Someone today asked me about a DOS command. So for all 17 DOS users still out there, I thought I'd throw in a lunchtime oldschool DOS Top 10 list. I struggled a bit with the placement of PAUSE. I was tempted to place it 8th, but @ isn't as exciting.  It was also a tough battle between the 5-6 spots.  Arguably FOR has the edge with its iterative power.  Clearly SHIFT holds down the last spot, just a truely worthless command. Nothing messes up the clear, procedural style of a well-layed out .bat file like SHIFT.  I hate SHIFT.
  1. GOTO
  2. ECHO
  3. CALL
  4. CHOICE
  5. FOR
  6. IF
  7. PAUSE
  8. @
  9. REM
  10. SHIFT
The Developer Diet: Day 2
Its now been 48 hrs without red meat.  I'm starting to shake like an alcoholic in withdrawl. I think I've begun to lose vision in my right eye.  

Does brocolli actually have calories?  I mean it must take me 50 calories to chew/digest a stalk of brocolli which only contains about 20 calories.  Am I losing weight with each stalk of brocolli eaten?  At two brussels of brocolli per day, I could be sub 2 Bills by next tuesday.  Cruiserweight developer division here I come.
Mac Security?
I came across this article today about mac security and it got me worried. My baby is sitting at home all alone.  What if my firewall breaks?  I feel like I should remote in and check on it.  One of those 3 mac viruses out there may be ready to strike.

Some tips pointed out are enabling the firewall/stealth mode and turning on secure virtual memory.  I must say after using the Mac firewall, it's quite nice.  The windows one care firewall annoys me with its constant popups and it isn't as easy to configure.  On a side note, I still don't know how I feel about Microsoft selling firewall/antivirus software.  Doesn't it seem wrong that they will sell additional products to protect their OS?  Shouldn't that be included?  Why do I have to pay more not to get viruses?  Can't you architect the OS to not be as virus friendly like *nix or OS X? 

And if you're bored, which you must be if you've read this far, here is another good article about computer security.


The Developer Diet
In order to keep our consultants in top coding form (As opposed to the 3bill heavyweight status I currently enjoy), a few of in the office have started a diet/detox plan as recommended to us by one of our coworker's friends.  Look at this thing.  WTF am I suppossed to eat?  Bee Polen? I'm alergic to bees.  Aloe Vera?  Really?  You can eat that?  I'll just pretend I didn't see "Enema/colonic Therapy" on there. 

Let's revise this a little.  I think I'll go with raw fruits/veggies and nuts.  So no coffee, alcohol, or cigarettes [My favortite three food groups]  I actually gave up smoking a few weeks ago, I'm still bitter about that so we'll just move on.  "
Fasting Lemonade?"  Seriously, who wrote that document.

Anyway its day 2 and I've sustained with my rabbit like existence of apples, bananas, carrotts, spinach, and H20. 

I'm a little weak, but I should be able to last a week.  If I don't blog for a few days, call a medic, I'm probably passed out under my desk.
More Mac Mini Fun
First, some big news, last night at 12:42AM, 10K Monkeys had its 10th Web Hit!  Double digit readers!  I'd like to thank my loyal fan base who has been reading since the beginning 2 weeks ago.

Anyway, the remote with my new mac mini is great.  It kind of looks like an ipod shuffle.  I give it three days before its lost in some dark recess of my aparmtment. 

There is a great post here about some things you can do with the remote like:

  • Click any button on the remote to wake your Mac from Sleep
  • Control the volume of your Mac with the +/- buttons
  • Control your QuickTime Movies, including Play, Pause, Fast Forward, Rewind, and Skip to the Beginning; Pause the movie and click the Next button to step through the movie frame by frame
  • Control DVD playback
  • Use the Next and Previous buttons to control slides in Keynote
  • Use the Next and Previous buttons to move between songs in iTunes; Play and Pause songs with the Play button
  • Next and Previous buttons move you through the Source pane in iPhoto.
  • Click the Play button to start a slide show using that source; click again to pause the slide show, and the Next and Previous buttons will move to the next or previous slide; Click the Menu button to exit the slide show
  • Click and hold the Play button and a “snoring” image of the remote will appear on screen. Continue holding the Play button and your Mac will go to sleep
  • Check the remote's battery life by aiming it an iSight camera and looking at it in PhotoBooth
Gotta love all that functionality from a 6 button remote. Luckily, I also added an iSight this weekend to the 10K Monkey's pantheon of gadgets.  I don't know why I purchased one, but it was 50% off at the Apple Store this weekend.  It was like a siren on a deserted island calling to me.  I was powerless. Oh, well, now I have a $70 method of checking my remote's battery life.  I mean how else would I do it?
Posted: Mar 07 2006, 09:30 AM by kmarshall | with no comments
Filed under:
Visual Foos 2005
Soon after the release of CLibrary, 10K Monkeys is proud to present the second MonkeySource release, Visual Foos 2005.  I know, the name of the app sucks, but I was in a hurry.  Visual Foos is a foosball scoreboard witten in VB.NET with a SQL Server DB for tracking stats on our foosball table at work.  I wrote an article for MSDN's Coding4Fun that should be posted on March 10th, so check it out. 

Let's jump ahead a few days and assume you've read the intro on MSDN and you'd like to download the code.  Even better, you want download it, make it better, and send it back to me <g> 

So on to the install instructions. Let's just say this isn't ready to run out of the box.  You'll need Visual Studio 2005 to build this app and you can download the code here.

The Visual Foos solution file should open 3 projects and the website code.  The FoosSP Project contains all the stored procedure scripts and the table creation script. You'll need to setup a SQL Server DB or use SQL Express.   After you run the create table script in your foos database, you can then add all the stored procs.

The next step is to configure the FoosDataAccess project to point to your foos db.  If you right click on the project, go to properties, then settings, then you can add in your connection string.

The scoreboard app and website are configured to use the FoosDataAccess project.  You'll also need to install the fonts that are in the fonts directory of the Visual Foos project folder.

Now all you need is a foosball table to attach to the computer, or you can just manually track goals using the keyboard.

The website allows you to login and view stats, upload personal sound files, and change your nickname/picture.

Right now, I've commented out the instant replay code since I'm rewritting it with DirectX.

Since I wrote the Coding4Fun article, I've added a prediction engine.  Initially I wanted to use Analysis Services, but that seemed like a bit of overkill.  I included what could be considered one of the worst stored procs that I have ever written, which surprisingly does a fairly good job of predicting outcomes.  After several games worth of data it usually gets the winner right and now has become quite good at giving the spread.

If anyone actually uses this
or if you have any ideas for furture enhancements, I'd love to hear about it. 

Some things I have in the works are a RSS Feed of games played, finger print or rfid scanners to identify players, force sensors to measure shot speed, and a more advanced announcer.

I have no idea how to measure force/speed of a foosball so any ideas would be much appreciated.  I am currently ranked as the worst offensive player, but I have monster shot and I'd like to brag about being tops in at least one category <g>

As for the announcer, I'd like to have some sort of animated character or maybe a photo of real announcers with animated lips.  I'd also like them to make comments based on game situations.  Kind of like Sega Talking Football, only less annoying.

Check back for updates!





h.264 - High Quality Compressed Video in Only 36 Hrs!
In honor of the academy awards, I thought I'd talk about encoding videos.  I was going to live blog the oscars, but I lack the hard hitting journalistic skills of industry heavyweights like John Tesh, Joan Rivers, and the staff of US Weekly. If I did, it would have been something like:

8:15: Selma Hyak on stage, she's hot

8:30: Saw a glimpse of Kiera Knightly, she's hot

8:32: Reese Witherspoon, also very hot

8:45: Dolly Parton, hot for a 70yr old.

9:00: Jessica Alba, sooooo hot

9:05: Lily Tomlin is wearing a hideous dress by fashion maverick, Coco Channel.  Just horredous.  I can't believe she even left the house with that drapery cut into some sort of neo-kimono.  Bow to your sensei.
Bow to your sensei!

9:10: Who is Robert Altman?

9:15: Most surreal moment ever on the Oscars, seeing "Its hard for a pimp" in old fashioned hollywood lights.  The 3-6 mafia was an inspired choice to follow up Dolly Parton and Yitzak Perlman.

9:17: Jennifer Garner, post pregnancy, still hot.

9:20: Why is Keanu Reeves in the front two rows?  Is he seriously in the top 50 hollywood celebs?

9:55: Why did Quentin Tarantino have to resurect John Travolta's career?

10:00:  Still as hot as she was at 8:32


Anyway, H.264 is one of codecs slated for use in HD-DVDs and Blu-Ray discs.  It offers high quality and high data compression.  Apple has been touting h.264 video as the future for digital media. Sounds great, I'm on board. My dream setup would be to encode all my DVDs and be able to browse them in an iTunes-like interface.  No more getting up to change discs.  Just imagine, I could sit on the couch for 22hrs and and watch an entire season of Smallville without having to be troubled to move.  Apple frontrow is close, but it won't play dvd isos or video_ts folders.  It does however play h.264 encoded videos. No problem, pop in a disc and encode to my terrabyte NAS device, right?  Of course not.  First of all there is the unbreakable content protection system.  Oh wait, that was cracked like 2 weeks after it came out.  Why do I even have to worry about copy protection?  I bought the disc, why can't I copy it to my pc if I want to?  I don't even want to get started on the MPAA/RIAA, thats a 20K word blog entry right there.

Lets just skip right past the copy protection and go with an unencrypted disc.  There are several encoders like Quicktime 7, handbrake, x264, and Nero Digital. Doom9 has a good guide here. All of them appear to downmix 5.1 channel audio into 2 channel audio.  Sweet, now the other 7 speakers just hang out and take up space.  I tried several and in my opinion, Nero's rencode 2 has the most polished interface.  Bonus points for handling 5.1 audio.  So I woke up this morning, got some coffee and tried to encode spiderman.  14 hrs later, I've reached the halfway point.  Just brutal.  At this rate, I'll be able to encode my whole collection my 2008 when a better codec comes out and it's time to start over.  My pc isn't exactly a powerhouse, but a p4 1.6 ghz with 1.5GB of RAM should be able to encode a movie with a day.

From a sample I encode earlier, the quality is awesome.  There isn't really a difference from my dvd original and the h.264 video except that the h.264 video is only 1.2GB vs. 5GB for the original.  If only it took 2 hrs or less.
Get Your Gadget On: The Intel Mac Mini
The latest gadget to join the 10,000 Monkey gadget collection is the intel Mac Mini.  Not that I or my credit card needed another computer, but after the recent demise of my iBook, a roster spot opened up.  I have a queue full of projects in the works for the mac mini, time permiting. 

Project #1: Digital Picture Frame

So another vetern of the 10K Monkey gadget collection, the successful 3Com Audrey was sitting unused.



A bagrain at only $400, on its release, I got it for $50 on ebay about a year later.  There are lots of hacks you can apply to the Audrey, most of which are shown here. With its 6inch sceen and small form factor it makes a perfect picture frame.  The web browser on the Audrey goes into fullscreen mode  so nothing besides the page is displayed.  My plan was to point the web bowser on the audrey to a web page that auto refreshes and loads a random picture every 15 seconds. 

I enabled Personal Web Sharing under the Sharing section in the Mac Minis preferences. Next was enable PHP.  Mac OS X has PHP installed but not enabled by default on its apache web server.  To enable PHP:

1.  Open the Terminal app located in the utilities folder.
2.  Type "cd /etc/httpd"
3.  Type "sudo pico httpd.conf" and enter your admin password
4.  Locate this line: # LoadModule php4_module libexec/httpd/libphp4.so and delete the "#"
5.  Locate this line: # AddModule mod_php4.c and delete the "#"
6.  Restart apache by typing "sudo apachectl restart"

Now PHP is enabled so we can build a random picture script.  There are tons available, so save yourself some coding time.  I found this one to be pretty good.  You can copy this file into a new folder called slideshow under /Library/WebServer/Documents (root dir of apache) and change the extension to php.  Now make a new page called index.html and put the following code:

<html>
<head>
<META HTTP-EQUIV="Refresh" CONTENT="15">"
</head>
<body bgcolor="black">
<center>
    
<img border=0 height=603 width=461 src="rotate.php">
</center>
</body>

By setting the dimensions of the image to 603x461, you can put the audrey in fullscreen boweser mode and there won't be any scrollbars.  The next step is to set execute permissions on the rotate.php file by typing "chmod 755 rotate.php" in Terminal from the
/Library/WebServer/Documents/slideshow directory. 

In iPhoto you can export all you photos to the the slideshow directory and resize them to 640x480.  Then point the Audrey's web browser to the index.html on the Mac mini and voila, a digital picture frame that displays a new random picture every 15 seconds.  Now I need to take some more pictures so it can stop rotating between the two I took when I first bought the camera.

VSTS Complaints
So this morning I starting editing a file for a project using VS 2005 with Visual Studio Team System.  I checked out the file, made a bunch of changes,  and whecked it back in.  Oh, one problem, I didn't edit the latest and my coworkers made a bunch of changes yesterday.  Half of the stuff I changed was already changed.  Why didn't I have the latest even thought I checked it out?  The VSTS PM explians why here.  Whatever, maybe I just need to get used to the difference.  Still though, there should be an option if I want to get the latest on checkout.  VS has 9 million other options and context menus, they couldn't fit that on there somewhere?  Oh wait, i stand corrected, it does write a little line out to the output window saying a newer version is available.  Well isn't that helpful.  It always nice to have the output window open, the solution explorer window, and 4K menu icons, giving me 20% usuable space to code. Seriously, the output window?  That was added in a later build because I don't think beta 1 had it.  So people complained and this was the bone you threw them? That resolution conflict window has become almost as demoralizing during my work day as a the good old BSOD.

I downloaded the VS SDK and tried to see if I could write a plugin for VS to auto get the latest.  I didn't see any events out there that would allow me to get the latest on a checkout.  I'll look into it more this week and see if I can come up with something. I could just try to change my habits and get the latest myself before editing.  But now its a matter of principle.

And I swear it doesn't always get the latest when I click on the project and say get latest.  Randomly it justs skips a file.  I have no solid proof or anyway to recreate it, but sometimes it just skips files.  I think it's just toying with me.
More Posts Next page »