Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Thursday, April 26, 2012

Dusseldorf, Germany - Day 18

Long, but fun day today. Woke up at 7:30 am and ate a relaxing breakfast down in the lobby. My hotel actually has an amazing breakfast selection. I get to eat breads, meats, cheeses, and eggs every morning with orange juice and coffee. The waitresses are very friendly and they are always so surprised when I bring my dishes up to them after I'm done eating. I think I'm supposed to leave everything at the table, but it makes them smile and they seem to treat me better every morning because of this. I'll continue to do it each morning. I think they appreciate it too, so... :)

I made it to Bob's around 8:30 am and we hung out for a while drinking coffee and just relaxing before opening the laptops. This pretty much defined the rest of the day though. We simply hung out and bounced ideas off of each other about features and changes in a complete no-stress environment. It was great to just speak up and bounce an idea off of Bob from time to time in between long running compiles. I don't get this luxury at home while I'm in the basement and sometimes spend too much time over thinking things. A lot of progress was made today.

Around lunch time, we headed to a really nice Pizzeria restaurant named Due Mila. Bob and I both ordered a pizza and some apple juice. About 45 minutes later, we found that we were the only ones in the restaurant talking... the owner actually came out and told us that they were closing the restaurant. We had to leave. :) While some might be proud to "close the bar", we were actually pretty proud that we got to "close the pizzeria".

From here, Bob and I drove down to pick up Michelle's car from the shop. This meant that Bob would drive her car back to the flat, and I would get to drive his car. I'll admit, I was a bit nervous, but anxious at the same time. This was the first time I've driven a car in another country (besides Canada). There were a few times that I had to rush through a traffic light because I had NO IDEA where I was and couldn't afford to let Bob out of my site. :) There was another section where we drove along a rail road track in the middle of the road, and I thought I was going to get rear ended by a train. As we got closer to Bob's flat, the roads got a little tighter and I was concerned that I would scratch his car. However, I did fine we made it back to the house safely without incident.

We worked and strategized til around 7pm. At this time, one of Bob's friends came over and we enjoyed a few beers on the back porch. His name is Heiko and I'd heard so much about him for many years. There were a few times when we almost met each other, but due to schedule conflicts, we could never quite be in the same place at the same time. It was nice to finally put a face with the name. The weather was great and we all sat out side and had a great time talking and laughing.

After Heiko left, we enjoyed a delicious spaghetti dinner. Michelle had cooked spaghetti, garlic bread, and salad for dinner. We also shared a bottle of red wine from Cologne. Michelle and I talked race strategies and shared various running stories and so forth. I'm very excited for the race this weekend, and I can tell that Michelle is too. I can really feel her excitement and nervousness when she talks about it and I love it! Tomorrow we're all planning to drive the full marathon course and pick up our race packets.


Shortly after dinner, Bob and I had to attend an online sales meeting. These meetings are really cool actually, because we get together over Skype and have video chats from all over the world. Kevin calls in from London, Patrick calls in from Paris, Bob and I called in from Dusseldorf, and Steve called in from Chicago. Technology is simply amazing.

Once the meeting was over, I headed back to my hotel room and was able to chat with Jennifer for a while before she had to go to her Volleyball game. She's been very busy with the girls and I think it helps her (and the girls) stay busy and not think about how long I've been away.

Tonight was their last game and it's unfortunate that I didn't get to see all their games. Jennifer told me that Lizzie has been doing really good and that Jazzy is able to serve overhand now!! <3 I can't wait for them to show me all they've learned when I get home. I really am missing them a lot. Especially at night when it's quiet and they're out enjoying their evenings doing fun things. Rumor has it that they are finally getting their pigs tonight! I'm anxious to hear what they name them (ie. Pork and Chop? Link and Patty?). :)

Now I'm surfing through channels deciding which news is old news and which news is new news. Basically, I have two options: MSNBC or CNN. They are the only two english speaking channels on TV in my hotel room. :) I've heard all the latest world news in English and all the stories are now re-runs of the same stories I saw earlier. Last night, I actually got caught up listening to some french news channel. It let me know how much french I've forgotten. I understood about every 23rd word or so.  

Sunday, March 25, 2012

Hosting My Own Websites From Home

Last December, I purchased a handful of servers, along with some switches and a 7 ft tall rack to house them all off of a buddy. A month later, I got them setup at another buddies office, but after a few delays and realizations, I decided to bring them back home and set them up in my own house.

Doing this presented some challenges in regards to everything that comes with hosting your own servers in your own house. For example, the servers require a dedicated 220 service. Not only that, but I needed to put the servers in a place where they will stay dry and cool. Oh did I mention, the servers are loud as hell? Like "jet engine" loud... Lastly, in order for them to be useful, I needed to have my own dedicated static IP address running to the house. This one was the big one; it required that I switch from one ISP to another! With this change came a new TV service and everything. Yes, I'm committed to my goal of hosting my own sites. :)

Another big obstacle that I have yet to hurdle is that there is (currently) no place in our house that is ideal for setting these servers up that is dry / cool / sound proof. Given all of these factors, I've decided to shelve them for a few months and figure out a plan this summer to get a sound-proof room built with it's own thermostat in the garage with it's own 220 service (more on that in a later post).

In the meantime, I've configured my old development machine to be my web full time webserver; it's working great so far. The server is an old 4gb RAM / 64bit AMD box with a 160gb HD. I've wiped it clean and installed Ubuntu Server on it with OpenSSH and a simple LAMP configuration. I installed Git and configured Gitosis so that I can easily manage new code repositories from anywhere without ever logging in and configuring users and directories. The site is currently only hosting one Ruby on Rails site so far (which isn't online yet). Once I get everything ticking like clock work, I will host a slew of websites. Some for friends and family, but some for profit of course.

Everything has been pretty strait forward so far. The hardest part for me has been configuring the static IP. In the last 12 hours, I've spent 8 (solid) hours trying to get my network configured correctly. I've been through books, websites, Unix man pages, and a few shot-in-the-dark attempts. All that, and I'm still not online with it. It's amazing that I've made it as far as I have in the computer industry without fully understanding NAT, DHCP, DNS, and "Port Forwarding". I've learned more about these terms in one day than I have in the last 12 years, I still have quite a bit to learn too...

For now, Jennifer is just happy to have her internet back up. :) Tomorrow, I plan to call my ISP and have them walk me though it once and for all.

Tuesday, January 31, 2012

Regular Expressions vs. Legacy String Functions

Back in the day of Visual Basic 6, when you wanted to find some information from a long string, you were (almost) required to write a function that parses your string section by section and use switches or if blocks. In today's world, regular expressions lighten the load quite a bit. As I've been developing apps over the years, I've learned to love regular expressions and figured it was worth mentioning in a post.

Regular expressions are basically patterns that have their own parsing engine tied to them for stripping text-based information from a string of text. For example, say I want to strip a certain value from a nasty looking string, and I know that the string will be in a certain "format". By this I mean that there might be parts of the string that don't change, but the parts that do change, I want to use them for something else. Instead of cracking my knuckles and writing a loop to sift through the string character by character, I'm able to write an single expression to strip out "matches" one by one.

Consider the following connection string:


            Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\data.xls;Extended Properties="Excel 8.0;HDR=YES";

From this string, I want to be able to pull out the value of 'Data Source' (in this case c:\data.xls) and the value of 'HDR' (ie. YES or NO). Back in the day, I would write a few lines of code to Split() the string into pieces and then strip those pieces into shorter pieces and save them into variables. Something like this:

Dim filePath As String
Dim hasHeader As Boolean


Dim sections() As String
sections = Split(connectionString, ";")


For Each section As String In sections
  Dim pieces() as String
  pieces = Split(section, "=")
  If pieces(0) = "Data Source" Then
    filePath = pieces(1)
  Else
    If pieces(0) = "Extended Properties" Then
      Dim properties() As String
      properties = Split(pieces(1), ";")


      For Each prop As String in properties
        Dim values() As String
        values = Split(prop, "=")


        If values(0) = "HDR" Then
          hasHeader = CBool(values(1) = "YES")
        End If
      Next
    End If
  End If
Next

Look at all of that code!? Just to get two values from a single string. I used to write code like this in VB6 all the time. There are lots of assumptions in that code and it is not optimized at all, let alone understandable at first site. There are many chances for errors to happen in that code as well... Not fun.

Regular Expressions to the Rescue
When .NET was introduced, there was this new (to me) concept of regular expressions that allowed pieces to be picked out of the string as needed using a "pattern". This is very common in Unix and many other programming languages, but it was new to me at the time and intimidated me. It was one more thing I had to learn. I used to approach it with dread and felt like I had to relearn the syntax every time I used it.

Today, I actually think in regular expressions a lot of time. There are many special characters that allow the regular expression engine to understand certain functions. For example a "$" means "beginning of string". A "." means any character. A "+" means "one or more times". A "*" means "zero or more times". When you put these special characters together, you can do some very powerful things. There is all kinds of documentation on the internet to help you understand this language if you are interested. If you are new to computer programming, then I recommend that you learn this sooner than later. It will make your life much easier.

To get the values from the above connection string using regular expressions, it requires a very simple regular expression pattern:

provider\=microsoft\..+?\.oledb\..+;Data\sSource\=(?.*)\;Extended\sProperties\=\"".+\;HDR\=(?.+)\;\""

Once I've defined this pattern, I can use it to strip out the "filename" and "hasheader" values very quickly and efficiently. While this example is border-line elementary, consider stripping values from a 20kb Xml file or a huge Html string that you stripped from a web page. Better yet, consider the power that it offers you when parsing a 5mb log file for information. 

This might be over many peoples heads and it might be common knowledge for others. For me, it was way over my head for a few years. However, after using it so much and relying on it, it's become common knowledge; it is baked into my daily routines now. Regular expressions are a very common thing inside Vim, and many Unix command line programs. For example, if I were to paste the connection string into Vim, I could place my cursor at the beginning of the connection string and simply type "d/Data Source" and the entire string from "provider" all the way up to "Data Source" is removed.

Here is a killer utility application that you should put on your thumb drive and use if you need to parse a large text file for values: http://regexlab.codeplex.com/


It's free, and I've found it to be very very powerful when constructing complex regular expressions in my daily programming tasks.

Regular expressions. Learn them. Use them.

Tuesday, October 11, 2011

A Vague JQuery Template Error

I have been getting an error in JQuery Template, and it's one of those errors that is impossible to debug. It's an issue that can only be fixed by intricately checking your code line by line, character by character. Here is the vague error that I'm getting:
Uncaught SyntaxError: Unexpected token return
Actually, here is the full "stack trace" (if that's what you want to call it) of the error:



I get no js compiler errors or anything, I just get this javascript error when I click on a radio button, but nothing more. My page loads correctly with no problem otherwise. Because of this fact, I was forced to inspect my code over and over and over and over... I removed code, I added code. I reworked my html a few times as well, but still got the error every time. I was literally going in circles trying everything.

The problem? I had an extra jQuery template tag in the very bottom of my script like this:

{{/if}}

At one point I tried combining both states into a single template using {{if}} {{else}} {{/if}}, but then gave up on that idea... Clearly I missed the closing tag and then never bothered to look at the bottom of my script tag when things didn't work. I'ts kind of insane that so much time was wasted on such a silly oversight on my part... Oh the whoa's of a programmer. Back to the grind.

Wednesday, October 05, 2011

Ruby On Rails Fan

OK, so I've been going through the online Ruby On Rails Tutorial by Michael Hartl for the last few weeks in my spare time, and I'm a better programmer because of it. I've not taken any shortcuts and have learned quite a lot. The whole Model / View / Controller aspect of it came pretty easy to me since I'm a full-time ASP.NET MVC developer in my day job. Server side tags, module level variables, and helper modules are shared concepts from the ASP.NET MVC world (which I think they stole from RoR, but...). I'm really liking my new hobby.

I've learned quite a few tricks that make Ruby on Rails much more pleasing to work with than ASP.NET MVC. Namely, I like the built-in gem utilities (package manager for Ruby on Rails), I also like the command line utilities for defining database schemas, generating test records, and auto generating oodles of code. There are so many gems that work together to support testing controllers, models, and views on the fly as you code. I always thought of Unit Testing as a good thing, but it always felt like I was forcing myself to learn / practice TDD. I just never quite "got it"; when I would write unit tests I felt good about it, but as new features come into my project it is very easy to just code my projects without writing unit tests for every little thing. With Ruby on Rails, however, it feels very natural and is almost required due to the dynamic nature of the language. RSpec makes creating tests a breeze.

I'm currently hosting a few Ruby on Rails projects on Heroku, and even doing this is brain-dead easy. I literally auto-generated a Rails project from the command line, and then used the Heroku gem to "git push" my code to Heroku. It does the rest and builds my project and deploys it for the world to see.

Just the other night, I bought a domain and plan to run my very own Ruby on Rails project... I won't give away the domain name yet, but know that I'll be making a big deal of it within the next few months. In short, I love Ruby on Rails and everything that goes with it, including Vim (with rails.vim), Git, Autotest (with Growl), Spork, TDD, and everything else). I can now say that I'm a ASP.NET MVC developer by day / Ruby on Rails developer by night.

Fun!!

Friday, September 16, 2011

Visual Studio 2010 + Resharper 6.0 + ViEmu + AutoHotKeys = Developer Bliss

I just got a new work machine. It's strictly for work, so my job paid for it. My boss helped me configure it and allowed me to get a few mods that make it even more bad-ass. It's a Lenovo ThinkPad W520 with 8gb of RAM, 500gb 7400 RPM HD, and he also got me a 128gb SSD drive that I plan to swap out for my main drive. It's already fast, but when I'm done with it all, it's gonna scream. :) Thanks Bob!!

My MacBook Pro is still the bee's knees, but it just wasn't cutting it for my day-to-day Windows programming solution. I'll absolutely be using it for all of my personal use and Ruby on Rails development. It has gigs of music, movies, and photos on it, along with my Quicken and lots of other personal documents and files. It will continue to be my Unix playground and I'm very excited to use it for just that... It has retired from the hustle & bustle of the daily grind, and plans to live the high-life now as a "personal computer". It's earned it!

During my transition to my new laptop, I was able to configure my development environment to be exactly how I wanted it. Since my new machine has 8gb of RAM, this allows me to trick my VS2010 environment out to the max without having to worry about slow downs. My biggest problem with Parallels was that I could only (safely) allocate 2gb of RAM to my Win7 VM. I had to disable the nice Aero / translucent theming, and lots of other goodness. Even after doing all of that it still came to a crawl whenever I'd be flying along with my coding. There were times when would literally just have to put my laptop down and walk away or else I would throw it against the wall. This new laptop should curb those impulses. :)

One of the main problems with switching to any new laptop is learning a new keyboard layout. This is especially important for programmers who rely heavily on hot keys, like CTRL, ALT, HOME, END, INS, DELETE, PGUP, PGDN, F[1-12] keys, and the 4 arrow keys. There is no real "standard" for these key locations, and it seems like every computer manufacturer has their own idea of where they "should" go. My personal opinion is that the Microsoft Ergonomic Keyboard 4000 nailed it! I actually own this keyboard and it has moved with me through a few different computers. The function keys were laid out perfectly; they were exactly where they were "should" be.



As you might imagine, it was a hard transition to move to the Mac and learn the key combinations. Especially since the mappings were even altered in order to pass through into Parallels. There was no DELETE key, no INSERT key, no HOME key, no END key, no PGUP, and no PGDN key!! I had to use a combination of other keys to get to those "functions" using Mac's 'fn' key (ie. the fun key). Even the function keys were different; for example I had to know that F[1-7] worked as expected, but F[8-12] required that I press the Mac's 'command' key. After 2 full years of learning these nuances and mastering the different key mappings, I'm now back to the beginning with a new layout of hot keys. Ugh!!

While I can't fully alleviate the pains of switching keyboard layouts again, I can take comfort in knowing that I'm a Vim junkie and Vim doesn't use most of the hotkeys for editing text.
  • [h] = {left arrow}
  • [j] = {down arrow}
  • [k] = {up arrow}
  • [l] = {right arrow}
  • [0] = {home}
  • [$] = {end}
  • [x] = {delete}
  • [ctrl+d] = {pg dn}
  • [ctrl+u] = {pg up}
  • ... and MUCH, much more!
I just needed to find a way to switch up my keyboard mappings to mimic the keyboard mappings of Vim. Luckily, someone has already thought of this!! There is a product out there called ViEmu that extends Visual Studio's text editor with all of the Vim goodness that I've so pains-takenly learned over the last year. I'm currently running an evaluation version of it, but I can already predict that I'll be forking over the $99 for a license very soon. It's simply genius! Thank you Symnum for this wonderful product. :)

Once I installed it, I had to re-enable my ReSharper keyboard mappings going to ReSharper - Options... - Visual Studio Integration - Keyboard Shortcuts and selected the 'Visual Studio scheme'. This allowed me to continue to use things like [ctrl+T], [ctrl+R+R], etc..). There are a few nuances that I need to work around, but in the grand scheme of it all, this is much more fluid than looking at my keyboard every 2 minutes for simple navigation. I'm loving it!



To help further keep my hands on the "home row", I found a post by another fellow-Vim'er by the name of Jean-Paul S. Boodhoo. Jean-Paul described how he used a tool called AutoHotKey to map various key combinations to be more "Vim-like". This way I don't have to use [ctrl+shift+alt+up] to move code up and down. The first three keys are easy (bottom right corner of every keyboard layout), but the [UP] key changes and takes my hand far off the home row. Instead AutoHotKey allowed me to map it to [ctrl+shift+alt+k]... Very Vim-savvy.

I finally feel comfortable writing code on my new laptop. Yesterday was a LOOOOONG day, because I was forcing the new layout onto myself and it slowed my coding down so much. I'm used to coding at the speed of thought, and felt crippled. With ViEmu and AutoHotKey both configured now, I'm flying. The last 2-3 hours have been simply painless.

Now if only Blogger had a Vim editor...

Wednesday, June 29, 2011

Code Jams and The Columbus Ruby Brigade

I've been dabbling in Ruby quite a bit lately. I've worked my way through the Ruby Koans (twice now), and I've been reading like crazy (in my free time) trying to learn Rails. It is a very easy technology... once you learn it. That's where I'm at now; I'm just trying to learn it.

Things that would take me 2 hours in C# and ASP.NET MVC, take only seconds or minutes in Ruby and Rails. The big difference is that I'm familiar with all the complexities of the .NET framework and the tools that I use. Whereas I'm trying to dumb my skills down to learn something totally different now in a whole new environment. Ruby doesn't have a tool that allows me to do the rafactoring that Resharper allows me to do in C#. The Terminal.app doesn't have all the shortcuts that I'm used to that Visual Studio offers me. I can't step through my programs, I can't jump to files as easily (yet). Everything is command line, and this is very new to me!!

The biggest struggle so far has been moving away from the Visual Studio IDE. My new IDE is a simple green and black terminal screen. There is no intellisense, no syntax highlighting, no pre-compilation warnings, no nothing. I'm trying to learn all of the Unix commands that go along with managing source files. For example, if I need to make a solution wide change across multiple files, I can't just say [CTRL]+[R] / [CTRL]+[R] anymore... I have to run a grep command and manually inspect each file, one by one. I'm sure it will get easier with time, but for now, I'm struggling...

Anyway, tonight I'm attending a Code Jam that was announced on the Columbus Ruby Brigade website. The meeting is in Columbus, OH and I'm hoping that someone will sit down with me and show me some tricks. :)

Monday, March 14, 2011

NuGet Package Management to the Rescue

I've seen the light.

I am working on a project and needed to include a reference to Castle.Windsor. I thought about all the pain that goes with this. In order to even get Castle.Windsor working, I have to first download it. Place it into a directory on my file system. Then I have to add the reference to my .NET assembly. Once that's done, I have to then modify my web.config file to ensure that everything get's mapped up correctly. Then (and only then) can I try to do a compile and hope I didn't screw something up along the way.

Welcome to NuGet!

With NuGet, I simply go to the Package Management Console toolwindow inside Visual Studio and type:

Get-Package MyProjectName | Install-Package Castle.Windsor -Version 2.5.2


This means:
- Set MyProjectName as the default project
- Pipe that output as the input to the Install-Package command
- Install Castle.Windsor (v2.5.2) along with anything it might depend on

Viola, all that stuff is done for me automagically for me. I see a slew of output in my console window with a final "Done." at the end. Looking through my solution explorer, I see that the references have been added and a few config files were updated. Castle.Windsor is installed and configured.

Since this was so easy, I went so far as to install Elmah next. Installing these two projects into my solution took me less than 10 seconds. Without NuGet, this would have taken me 20-30 minutes and lots of docs-diving.

I'm a NuGet fan!

Wednesday, February 23, 2011

Hacking Together Good Code Quickly

I'm kind of a perfectionist when it comes to writing good code. I'm not saying that I write amazingly perfect code all the time. However, I do take pride in writing good code and always over-analyze (not in an OCD way, but...) my architectural choices when designing systems.

Well, it's officially crunch time on a project that I'm working on, and I'm forced to add features into the application with the quickness (ie. hack). :( It's not bad code. It works. However, it is not written to my standards and has some majore "code smell" to it.

Things like this:


DoSomethingCoolHere();

foreach(var form in Application.OpenForms)
{
if (form is AnalyzerForm)
((AnalyzerForm) form).RefreshDisplay();
}


I would much prefer to NOT use the 'Application.OpenForms' static property, nor would like to cast objects to specific types to call a method on them. However it works for now, and can be refactored later. At least I can take comfort in knowing that I get to refactor as soon as the "facade" is working.

These are all the secrets that I'm going to expose right now about our amazing software. :)

Tuesday, February 15, 2011

Hacking Like Neo

Have you ever wanted to skin your entire computing experience to be completely monochrome green and black like the Matrix? If you are a Mac user, you can.


Honestly though, I do a lot of coding in the dark and use this display a lot. I don't like sitting under bright lights. However, I used to get nasty headaches when looking at a glowing white screen in the dark. To solve this problem, I used to use a shortcut key combination built right into my Mac that would turn "White on Black":
> [CONTROL]+[OPTION]+[COMMAND]+[8] (try it now)
> or navigate through System Preferences -> Universal Access -> Seeing -> Display

Unfortunately, this would just negate all of the colors much like a negative from an old 35 mm roll of film. This wasn't very useful actually. My colors would all be out of whack with some pretty crazy colors (magenta, baby blue, purple, pink, lavender, yellow, etc..) and when I would visit a page that was originally black, then I would get the nasty white glare again.

A few months ago I stumbled upon a cool utility that allows me to do a lot more than just turn "White on Black". The utility is called Nocturne and it has been a dream come true for me. It works by adjusting tints and hues rather than just inverting all of the colors.

Here is a before pic:


Here is an after pic:



Not only does it look bad-ass for anybody looking over my shoulder, but it saves my eye sight when I'm coding in the dark. Best yet, you are not just limited to monochrome green and black. You can configure it to be any color you'd like. I can set my tint to red and it makes my Mac look like a submarine terminal. Check out my iTunes display:


So there it is. If you code in the dark, or want to code like a real hacker (:P), check out Nocturne (it's free)!

Sunday, January 16, 2011

CodeMash v2.0.1.1 (Recap)

As I mentioned in my last post, Codemash is a top notch event.

Live Concert on Wednesday NightWednesday night ended rather perfectly actually. After the Pre-Compiler sessions, Chris Castle and The Womack Family Band showed up to rock out the attendee party in the grand hall area. These guys were awesome! I purchased a CD of the Womack Family Band after their set, and purchased Chris Castle's CD directly off of iTunes. They had a great sound, and best of all they were fairly local (Norwalk, Ohio).

I got to talk with a lot of people at the party, and Jennifer came to join me after she got the girls out of the water park. We had a great time and she got to see me in my element (true geek talk). I ran into a few people and we would just start talking about programming languages and different technologies. She was a sport and stood by my side with a smile the entire time. :) After the attendee party, we walked around and ended up sitting at the bar for another hour before calling it a night.

Chad Fowler KeynoteThat next morning, the alarm went off fairly early for me and I was out the door for breakfast around 7:30 am. Chad Fowler was the keynote speaker this morning and he did an AWESOME job. He talked about what defined "quality" in code and showed lots of different examples. One story that caught my attention was a discussion about a chunk of code that he looked at and thought it was horrible, but then later discovered that the code has not been touched in 20+ years and was still working... That little story gave me a whole new definition for "code quality".

Kids Programming - Aydin Acksu

After the keynote, I attended a session by my good buddy Aydin Acksu, titled "Kids Programming". Of course, my girls all met me there for it and they got to control me around a grid using commands: step, step, right, step, left, step, etc.. This taught them how how computer programs worked. Once they ran the the commands once, they would navigate Aydin back through the course to "test" the program, and then they "edited" the errors out to make it faster, and "tested" it again, etc... Basically everything a programmer does with a keyboard and a debugger. It was really cool how he approached the talk and all the kids in the class had a blast!

Rails A to Z - Matt Yoho
After that session I attended Rails A to Z by Matt Yoho (from EdgeCase). I learned quite a bit at this session and was amazed at how little code is required to make a Rails app. With about 10 lines of Ruby code, a user can connect to a database (build its schema), add records, and then disconnect (and destroy the table). This would take about 50 - 100 lines of c# code. Wow! Matt did a great job and he had my undivided attention for the entire hour.

WebMatrix 1.0 Product Launch - Josh Holmes
For lunch, we got to see WebMatrix 1.0 be launched to the world along with a lot of other amazing technologies (details). Codemash ain't no joke no more. This event has had all kinds of top notch speakers, and this year Microsoft had live streaming video from the conference to developers all over the world about this long awaited product launch. Congratulations to Codemash organizers for outdoing themselves each year. See Scott Guthrie's blog post for a list of everything that was announced today.

After the keynote, I skipped the next sessions, as there was nothing being presented that sparked my interest. I used this time to get in a quick run and workout in before the rest of the evening got ahead of me. I actually met a guy in the gym (ironically named Jim), who is close friends Mark Goodale (a local ultra-marathon hero). What a small world! We talked for about 30 minutes while we ran on treadmills next to each other.

Top Ten Tips for Moving from WinForms to WPF - Michael EatonThis session was pretty informative. Michael broke down all the differences between WinForms and WPF. I actually dabbled in WPF for a few weeks last month and got so frustrated with it. It was such a paradigm shift from everything I'd ever learned about windows application development. Buttons with click events and coordinates get's thrown out the window. Now developers use DataBinding to UIElements on various types of LayoutPanels through MVVM... Yeah!? Anyway, Michael's session confirmed that it wasn't just me. :) He gave some tips and suggested some 3rd party tools to help ease the pains. Great talk!

A Modern Open Source Development Environment - Gary BernhardtThis session was one that I was REALLY looking forward to even days before the conference. Gary uses terminal app and Vi as his development environment. This is what would eventually like to do as well so that I don't rely so much on VS2010.

Unfortunately the session was more about him showcasing how fast he types and navigates through different commands inside terminal. He didn't really focus on useful tips for users to do the same. It kind of turned into a "look what I can do" session, as opposed to a "here's how I do it" session. Don't get me wrong, I did learn something; I learned that I need to just bite the bullet and use vi exclusively outside of my day job. All in all, nothing very "constructive" came from this session (for me). He moved too fast, and assumed everybody in the session was familiar with Vi, Pyton, shell scripting, Git, and zsh.

He did answer a lot of questions about how he got so fast, but again he didn't explain anything with hard examples. It was mostly just pre-recorded videos of him typing in vi while he commented about his typos in real time, and then summed up the video with a benchmark. It wasn't what I thought it was going to be... :( I'm still a Gary fan though, and will continue to follow his blog: http://blog.extracheese.org/

Ford Fusion Keynote - Tj GiulliFor dinner, we all got to hear a developer from Ford talk about some of the new technologies that they are putting in cars, and it was pretty cool. Tj showed some of the new GUI's for the upcoming nav screens. He showed how traveling with a group of other drivers can be more "interactive" in that each car can talk to one another to know how low they are on fuel. Lots of other cool stuff was in here too, where the car could actually tweet it's status at any point along the route (ie. "Pulled into Taco Bell" or "I need fuel soon"). Pretty cool stuff really. Best yet, there was an API that was available to allow developers to tap into the engine and interface with it. However, I must admit that the API was a bit kludgy with their use of multiple yield keywords inside of a single void method. (?)

Cocktail Party, Jam Session, & Water Park Party
This is where it got fun! We all got to loosen up and mingle for the rest of the night. My good buddy, Greg Malcolm helped me setup my drums this year for the jam session. We had quite a turn out this year. Best of all Chris Castle and The Womack Family Band came back to the Kalahari to jam with us. They brought their gear back with them too. Of course, Carl was there and he's always a great entertainer. Again, we had quite a little crowd gathered up at a few points. There are a few videos on YouTube that showcase some of the shenanigans. :)

After the Jam session, Jennifer came to retrieve me so that we could all go to the water park and swim. The girls were so excited that I got to go with them and we had a blast!! We played water basketball, we hung out in the wave pool, and just relaxed and had a great time. After the water park, we split out separate ways and I went back to the grand hall to gather my drumset. As it turned out, I sat down and talked with Carl and Richard for a while on a couch and then we all headed back to the water park to mingle with other devs and get some drinks. There I met Justin Etheredge, and we talked for about 30 minutes about Ruby on Rails, and various javascript utilities that we used.

I didn't get back to the room til about 1 am.

Developing High Performance Web Applications with Javascript - Timothy FisherWell... I wanted to go to this, but couldn't. :( I slept in and rushed down to the breakfast area with moments to spare, then had to turn around and head back up to the room to get it back in order. Checkout was at 11 am and there was a LOT to do. Jennifer and I got it all done around 10:45 am. I kissed them all good bye and headed back down to the sessions... Jennifer was going to get some candy from the candy hut and then make the drive back home.

Rules for Good UX Design - Joe NuxollThis was a great session. Joe is an old Borland, turned Apple developer who now does other things I guess (?). Anyway, he had lots of useful information on what NOT to do with user interfaces (avoid "assy-ness"). :) He showed me some old user interfaces that mimicked some dialogs that I once (or twice) built that make end users cringe. He also showcased many user interfaces that were simply beautiful, and that hid a LOT of underlying complexity. This guy clearly knows his stuff and everybody in his session learned quite a bit about good UI design.

GitHub Keynote - Scott ChaconThe lunch keynote on Friday was pretty interesting. A developer from GitHub.com came to keynote about how they run their business. Basically, there is ZERO business processes or management structure across the entire company. Clearly it's working for them, but it has disaster written all over it in my eyes. From what he explains, people just kind of do whatever they want, whenever they want and for whatever reason. It's a very "open source" environment and sounds rather risky to me...

Everybody in the company has full trust of the entire enterprise. Everybody has the ability and permissions to do whatever they want. This means that anybody at GitHub.com (from the new guy to the CEO) could delete the entire site if they wanted to. Of course, this would never happen (or should never happen anyway), but the fact that there are no checks in place to prevent such a disaster seems a little haphazard to me. Scott indicates that everybody at GitHub gets the same pay. There are no vacations; you can just do what you want, whenever you want. No meetings, no deadlines, no feature list, no time frames, no nothing... It's amazing to me that they've had no problems yet. Good for them, but I (personally) like having a little bit of structure and credibility for my actions. Perhaps I'd feel different if I was put in this environment and saw it work. To me it seems a little chaotic and unpredictable.

How? It's because each employee is passionate about what they're doing.

Infinitely Extensible - Alex PapadimoulisThis was a great session. I follow Alex's blog (ie. The Daily WTF) and knew that this guy has seen it all. People send him code snippets from some of the most crazy logic puzzles. Many are just bad programming, but some are really funny dialog prompts that developers thing users would never see. Check out his blog to see what I mean. :)

Anyway, the session talked about how to keep it simple and avoid over-engineering simple problems. We as programmers do this by default; we over complicate everything and try to prepare for future enhancements that may never see the light of day. I really enjoyed his talk because it showed me things to look for when I sit down and start over engineering simple problems.

Anatomy of an E-Commerce Website - Joe WirtleyI was pretty excited about this session too. Joe is a really nice guy that I run into quite often around various events throughout the heartland area. His session was great and he basically just described how an international e-commerce site is setup to deliver real time results using caching and highly optimized data services across multiple databases. I learned quite a bit before I had to sneak out of his session...

Node.js - Open SpaceUnfortunately I had to sneak out of Joe's session because I was really interested in learning about node.js. It was an open space idea that somebody posted on the board and I wanted to see what it was all about. As it turned out, I got there way too late and didn't really get anything out of it. :(

Awards and Wrap-upAnother year passes, and I don't win a damn thing. GRR!! I guess I'll just have to come back next year and try again. :)

I'm now extremely excited about Ruby, Rails, Git, Shell scripting, Vi, and all things Unix. I plan to consume myself with knowledge of everything Ruby until I'm comfortable with all that it has to offer. While learning Ruby, I'll need to learn terminal app and vi pretty extensively. But that goes with the territory and hopefully I'll "get it" so that it can just get out of my way and I can focus on being productive on my Mac.

This all starts now!

Wednesday, January 12, 2011

CodeMash v2.0.1.1 (Pre-Compiler)

The time has arrived! I'm here at CodeMash and loving all the stuff that I'm learning so far!

I arrived yesterday around 1pm. When I arrived, I ended up geeking out in my room for a while, learning KnockoutJS. KnockoutJS is a very slick little javascript library that allows developers to integrate the MVVM architecture pattern into an Html page fairly easily. Anybody that is familiar with Silverlight or WPF will have no problem using it. However, for me it has been quite a learning curve since I'm not fluent in either. I've only been using the MVVM pattern (in my head) over the last month or two. I've never actually applied it until now.

Around 4pm, I headed down to the conference area and helped stuff the shwag bags with many other volunteers. They setup all the fliers and pamphlets on a table, and about 10 of us made a loop where we would walk around the table and grab one sheet at a time... At the end of the table, we would put the papers into a bag and start all over. I hung out in there for about an hour and a half before sneaking out the door.

After volunteering at the table, I got checked into the conference, then walked around the Kalahari for a while. While walking around, I actually ran into Carl Franklin from .NET Rocks. I stopped and talked to him for a little while, and was pretty surprised that he remembered me. After that, I went to the water park area and sent some water park pictures to my girls via Picture Mail.

Then around 7pm, I headed down to the gym to get my sweat on. I met a few guys (Chad and Bob) who were doing the P90X. They were on their 3rd month of the program and stated that they have noticed great results as well. We talked off and on for a while, then I headed back up to my room to get a shower before going down to the bar to "network" with some other geeks.

As it turned out, I actually ran into Chad and Bob again. We talked for quite a while, and then along came Greg Malcolm. Greg and I sat and talked and drank til about midnight. We talked about all things geeky, including Ruby, Rails, Javascript, Perl, Python, C#, ASP.NET, Git, SVN, and I think Scala actually came up once or twice. Around midnight, we both had our buzz on, so we went our separate ways to prepare for the big Pre-Compiler day.

Pre-Compiler
Whoops, I slept in a little. I had my alarm set for 5:30 am with hopes on getting a quick run in before breakfast. Instead, I woke up at 8:15. :) I scurried around and got ready to try and get a bit of breakfast before they took it away (@ 8:30). I made it! Barely, but I made it.

From breakfast, I went to the Ruby Koans lab hosted by Joe O'Brien and Marc Peabody of EdgeCase. I learned so much!! I basically learned that Ruby is the shit (this is a compliment for all my non-English speaking readers). I dabbled in the Ruby Koans last year at CodeMash, from a friendly tip. However, this year I dedicated myself to a full 3 hours of NOTHING BUT RUBY! Again, I can't say enough about Ruby. Joe and Marc are very passionate about the language and they are really good at getting people excited about the language and developer culture. I've already committed to attending the Columbus Ruby Brigade meeting on Monday. I made it through about 80 of the 274 Koans, and plan to finish them before Monday's meeting.

I had some great conversation with some smart people at my lunch table around Silverlight and WPF. Then from lunch, I decided to attend the Git Immersion presentation by Adam McCrea and Jim Weirich (also from EdgeCase). They did a great job explaining how Git is different from SVN and how it is an invaluable tool for all developers. Jim presented the Git system in such a way that made it easy to understand. I have it installed and will be using it quite often from now on.

The best part about both sessions today was that I got to use my crazy cool Bash and Unix knowledge in both sessions. Both sessions were 100% command line driven via Terminal.

Yeah, I'm having fun!

Thursday, November 18, 2010

Upgrading to Visual Studio 2010 and SQL Server 2008 Express R2

I made the jump yesterday to finally install and configure my dev machine to run the latest bits. I upgraded from Visual Studio 2008 to Visual Studio 2010. I also upgraded from Sql Server Express 2005 to Sql Server 2008 R2 Express. I must say that I'm very excited to start using all the new stuff. Rather than installing everything side by side, I decided to scrap the old apps and fully commit to the new pieces.

During this process I had no real problems. The only real problem I had was getting SQL Server 2008 R2 Express configured correctly. I've tried various things to get the new database management tools working inside the SQL Server Management Studio 2008 R2 and couldn't quite figure it out (still can't). No matter what I do, I can't create a new 2008 R2 database without using VS2008 Server Explorer. Whenever I right click and 'Create Database', it always creates a SQL CE 3.5 database instance. This version is missing a lot of functionality. For instance, I'm not able to create views and the designer for this is very kludgy IMO. I'm sure it's something simple, but I just can't figure it out yet.

While trying to get it fixed, I completely uninstalled SQL Server Development Edition 2005. This still didn't solve my problem, so now I'm without Analysis Services 2005 and no full blown SQL Engine. It's all good, I've read that they sit side by side nicely even when installing SQL 2005 after SQL 2008.

The good news is that I can create a 2008 R2 database instance from inside my new VS2010 IDE. That's a win in my book and I'm content with this. The process was pretty simple


  • Uninstall SQL Server 2005 Express

  • Uninstall Visual Studio 2008

  • Install SQL Server 2008 Express R2

  • Install Visual Studio 2010 Professional

  • Reinstall Resharper 5.1

  • Test that everything worked...

  • Convert Projects to VS2010

  • Blog about the new goodness



I did have one pretty nasty problem when converting my ASP.NET MVC project to the 4.0 framework. Visual Studio provided a nice little wizard to do this, but when it did this there were some things that didn't work as expected.

The first problem was that it didn't add System.Core to the references. Without this library referenced, all of my Linq queries were brokent (+100 source files)! While this looks like a pretty simple thing to fix, it turned out to be a little tricky. I couldn't just add it as a reference from inside the IDE like I thought. When I tried to do this, I got an error stating:

"A reference to 'System.Core' could not be added. This component is automatically referenced by the build system."

Hmm... The way I was able to fix it was to:


  1. Right click on my Web Project

  2. Unload Project

  3. Edit the .csproj file

  4. Add <Reference Include="System.Core" /> in the appropriate ItemGroup

  5. Save the change

  6. Right click on my Web Project again

  7. Reload project



Voila!

I also had (and still have) a problem debugging my web project. When I try to run my project, it does not actually start debugging like it should. The project compiles and starts the ASP.NET Development Server, but it doesn't actually load the URL in my default web browser. When I open the system tray icon and click 'Show in browser...' it crashes. I tried all kinds of things to get it to work, but nothing is working. I've installed a few patches and restarted IIS a few times after each one, but nothing. I've tried running aspnet_regiis -i against the new framework. Again, to no avail. As a test, I ran the project and then went to my web browser and typed in the appropriate URL. It works. I set some breakpoints in my code, and they work too. This works well enough for me.

Next steps I think are to convert my entire project to .NET 4.0 Framework so I can take advantage of all the new goodness with C# 4.0. I also plan to upgrade our web solution from ASP.NET MVC 1.0 to ASP.NET MVC 2.0. I'm also anxious to start using GrapeCity ActiveAnalysis 2.0 Silverlight control.

Upgrading to new development environments is so much fun... I'm actually excited to work a full day tomorrow! :)

Tuesday, August 17, 2010

Configuring ASP.NET MVC on Window Server 2003 x64 with IIS6

I'm posting this because it could save somebody hours or days of searching. I wish I had written this before I ran into the problem... (?)

At work today, I was trying to install our ASP.NET MVC web application on a Windows Server 2003 box that was running a 64 bit version of IIS 6.0. I had set everything up just as I have for every other test server that we were using, but this particular machine was giving me big fits.

I would map everything up and no matter what I did, I would get 404 Page Not Found errors from IIS. I made sure that my aspnet_isapi.dll was mapped for a wildcard filter, but still nothing. I was able to get the site to work if I added a custom route inside my Global.asax file to use {controller}.aspx/{action}/{id}. However, I wanted an extension-less approach to our pages that didn't use the "aspx hack" (as I so call it).

After looking all over MSDN, on every ASP.NET MVC guru's blog, and scouring StackOverflow, I finally got the tip that I needed deep within a list of random comments from an old haacked blog entry:
As an additional tip, please make sure you pick the correct version of aspnet_isapi.dll when you are running a 64-bit version of Windows/IIS. Sounds obvious but trust me, it'll give you a major headache if you don't.

Erik Burger
At the time it didn't make sense to me because there's only one aspnet_isapi.dll... or so I thought. The user was very vague and provided no additional information as to what he meant. However, this comment got to thinking that perhaps there was another aspnet_isapi.dll specific to 64bit web sites. I went searching, and in less than a minute, I found that there was!

For 32bit websites use this in your wildcard mapping:
C:\WINDOWS\microsoft.net\Framework\v2.0.50727\aspnet_isapi.dll
For 64bit websites use this one:
C:\WINDOWS\microsoft.net\Framework64\v2.0.50727\aspnet_isapi.dll
Once I did that, things started working… You're welcome.

Friday, August 13, 2010

Software Architect or Software Developer

Not sure which is better: designing complex systems on the whiteboard or coding and debugging the implementation on my computer?

I honestly think that I like the software architecture aspect of my job more than the actual coding. Nothing beats those glorious "AHA!" moments. Sometimes they take hours, sometimes days, and sometimes even weeks to figure out. I just had one hit me that has taken me almost 2 years to figure out!!? It's not like I was trying to figure it out for 2 years and couldn't, but more like I have been blind to it and didn't give it much attention. I'd been working around my own nasty design for 2 years and I finally sat down and figured it out tonight.

This system I'm building has been extended so much over the last 2 years, and I'd complicated a particular piece of our product so much that every change I was making was adding to the headache. We are constantly adding new functionality to our product, and it's usually done is such a manner that it needs to be done sooner than later. The core foundation of our solution has been refactored a few times in the last year or so and it is very solid. I have squeezed in a week or two here and there to ensure that it is able to scale as needed. However, as things got further from the core, they seemed to get more convoluted and I was breaking out into multiple branches of (very) similar logic. Tonight I was able to doodle up the entire system on my whiteboard with letters, circles, arrows, rectangles, reds, blacks, and blues. Then once I had it all visually mapped out, I did a few swipes and connecting of objects with my dry-erase markers and was figured out!

Who am I kidding though? Tomorrow, I get to sit down and apply the code to make it happen and that's pretty damn fun too. It's always nice to see your ideas go from a concept to an actual working system. Especially when that working system is a more efficiently designed working system.

I love my job.

Monday, June 07, 2010

Projects and Fresh Ideas

Jennifer and I were sitting at the kitchen table after a stellar egg breakfast this morning talking about vacation and other stuff. We were also discussing where we saw ourselves in a couple of years, etc... You know, husband and wife talk.

We came up with some really cool ideas that would generate some steady income outside of the ol' 9-5. Jennifer came up with an idea that got my wheels spinning. It got me excited, and I decided to post something about it. The idea is to fill a gap that no other website has done yet and trust me we've looked. It would not only benefit local home owners, like ourselves, but would also benefit local businesses in the area. If we could advertise it and exploit it enough here in Newark, then there's no reason it wouldn't work in Columbus, or any other big city for that matter. I need to do a little more research to see what other gaps we could fill with it, but for now, the idea is very slick, and (most importantly) extremely valuable to all users that would log on. Remember, eBay was started up from a wacky idea to auction off a broken laser pointer. The underlying code was built in a weekend:
Omidyar was 28 when he sat down over a long holiday weekend to write the original computer code for what eventually became an internet superbrand — the auction site eBay. - Wikipedia: Pierre Omidyar

Twitter began in a "daylong brainstorming session"... - Wikipedia: Twitter
Check out the first sketch an idea that later became Twitter: http://upload.wikimedia.org/wikipedia/commons/b/bf/Twttr_sketch-Dorsey-2006.jpg

Stories like this keep me believing that our idea isn't so far fetched... Our idea is a service that everybody would be able to use, and would have a cool little twist on it that would keep people logged and coming back, much like they do on any other addictive site (eBay, CraigsList, Facebook, Twitter, My blog :), etc..). I'm very excited to sit down and visualize it's underlying architecture and start building the first set of pages. This will be my perfect excuse to master Ruby on Rails and MySql in my spare time. I also need to interview some of my friends and family who own their own businesses to see what I'm missing...

If I can come back from vacation with this much excitement, then it WILL happen. Sorry no more information right now. Feel free to post comments of ideas for such a website though. If that's no a vague request, then I don't know what is. :)

Wednesday, February 17, 2010

Hi, I'm a Mac

Jennifer and I broke down and got ourselves some MacBooks. She got a standard MacBook for her photo taking, Facebooking, eBaying, and CraigsListing. We got all the photo's moved over to her machine, since she's the one that manages the pictures. They sync up to our Time Capsule so we have a pretty solid backup solution now. She switched from Picasa to iPhoto and she seems to like it. Other than that, she mainly uses Safari for everything else...

I on the other hand got a MacBook Pro, and it acts as my new development machine. Already, I'm loving it. It took a while to get used to the new keyboard setup, but I'm getting better each day. As a programmer, I rely very heavily on key combination's, and the Mac keyboard is quite a bit different from what I'm used to (to say the least). I installed Windows 7 on a second partition through BootCamp. I then purchased a license for Parallels 5.0, and run my BootCamp partition through a virtual machine. My Windows 7 setup has everything needed to be a full blown development machine. I have SQL Server 2008 with Analysis Services, Visual Studio 2008, Office 2007, SubVersion, Total Commander, Daemon Tools, Paint.NET, Reflector, ReSharper, etc...

Aside from my Windows VM, I also installed Ubuntu on a separate VM so that I can play around with MySQL and learn the basics of Linux. My goal is to use it as a database server while I play with with Ruby on Rails. I'm using SSH for the first time in my life, and it's quite the learning curve for me. I'm forcing myself to to keep my Terminal.app console on my Mac open. I'm also forcing myself to NOT install TextMate and learn VI. I think it's safe to say that I've been spoiled with Visual Studio's IDE for waaaaaay too long. :)

Also, I purchased a family pack license of the iWorks suite and I'm really liking it so far. Numbers has some pretty cool functionality in it. I especially like how you can add multiple tables on a blank canvas and size them independently. The summary feature is slick too; it allows me to highlight a range of cells, and drag / drop one of the summary values into a new cell to build a separate table of summaries however I see fit. The presentation options are much better than Excel in my opinion, and it's much easier to get a spreadsheet into a "report mode" using Numbers than Excel as well... again, in my opinion.

Of course, the girls really like the Photo Booth app. Of all the things this Mac can do, they ONLY want to play with Photo Booth. Both Jennifer's and My MacBook are polluted with pictures of little warped kid faces. :)

Tuesday, January 12, 2010

I'm LogMeIn Savvy

I just signed up for LogMeIn. This totally solves so many problems for me. Ever since my Toshiba died, I've been stressing out about getting my new laptop setup with all the software I need in order to attend CodeMash.

After a few minutes of stressing, I realized that I don't need to have everything installed on the new laptop. I can just use this computer while I'm away at the conference. The only downside to this little epiphany is that I have to have an internet connection to be productive. This causes problems when I fly, and when I'm at a location that doesn't have internet. I do know that CodeMash has had spotty wifi at times due to the mass amounts of geekery going on. However, that's ok, because I'll probably only be logged into my computer when I'm back at my room anyway. While I'm at sessions, I'll just have my man-purse to take notes, and will probably be developing in Notepad as I learn how to become a Ruby guru.

For those that haven't heard of LogMeIn, you should definitely check it out. It was blazing easy to setup and best of all, it is FREE! It took me about 5 minutes total to get setup; I created an account, installed a little application on my desktop, and then went upstairs to test it out from my laptop. Viola!

Technology kicks butt!!

Friday, September 04, 2009

Castle.Windsor Tip

You must specify the assembly name in both the Type and Service attributes when defining a component in a config file. I wish somebody would have told me that tip yesterday. I've wasted my entire morning figuring it out myself... I'm finally smiling again. See:

:)

Now, let's get productive!

Tuesday, July 28, 2009

Serializing Objects to Json in ASP.NET MVC

I've been working like crazy lately, and haven't been doing much blogging at all (reading or writing). I have a slew of blogs that I want to catch up on. I've barely checked my twitter lately, but reading my blog roll has completely fallen to the way side. The good news is that I've been learning a lot of jQuery, ASP.NET MVC, Linq, and overall enterprise application architecture in a very short period of time! This means that I have a brain full of geekiness just dying to get out.

Building this type of application is really a totally new type of programming for me and has really been putting my brain (and whiteboard) through the some long nights. Over the last few weeks I've really been able to see it all come to light. I'm shooting at a moving target (so to say) and there are changes that pop up along the way that change the system at it's core, where I'm forced to change how objects are constructed and so forth. While I could go on and on about the application I'm working on and all of the problems I've been faced with recently, the topic for this post is strictly related to how easy it is to serialize server side objects to the client.

Problem
I needed a way to represent server side memory objects as client side javascript objects. I have a set of div tags that need to be represented on a canvas (another div) and the user needs to be able to interact with them. Most importantly, I didn't want to re-invent the wheel entirely in javascript by creating all new classes and so forth.

Solution
Json.

Example
Let's say I have an object called "Person" that has a few properties and a collection of PhoneNumbers.

Person
  • Name
  • Address
  • City
  • State
  • Zip
  • PhoneNumbers[]
PhoneNumber
  • Type
  • Number
Now to the meat! In order to serialize these objects to Json, simply create a nested class (ie. a class that is defined within the parent class) that inherits from JavaScriptConverter:

class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public IList PhoneNumber { get; }

public class JsonSerializer : JavaScriptConverter
{
// override SupportedTypes, Serialize(), & Deserialize()
}
}

class PhoneNumber
{
public string Type { get; set; }
public string Number { get; set; }

public class JsonSerializer : JavaScriptConverter
{
// override SupportedTypes, Serialize(), & Deserialize()
}
}

Inside the 'SupportedType' member, simply return a new enumeration of the parent type. For example the SupportedTypes member inside Person.JsonSerializer would look like this:

get { return new[] { typeof( Person ) }; }

Inside the 'Serialize' method, simply cast the obj parameter to your type, and then begin setting each property like so:

var result = new Dictionary();
var person = obj as Person;
if (person == null)
return result;

result["Name"] = person.Name;
result["Age"] = person.Age;
result["Address"] = person.Address;
result["City"] = person.City;
result["State"] = person. State;
result["Zip"] = person.Zip;
result["PhoneNumbers"] = person.PhoneNumbers;

return result;

Inside 'Deserialize' do the same thing, only backwards (not covered here)... In order to take advantage of the Json data, let's initialize a PersonViewModel class. This class will be used by our View pages. Here is a quick example of what this class might look like:

class PersonViewModel
{
public PersonViewModel(Person person)
{
Person = person;
Json = string.Empty;
}

public Person Person { get; private set; }
public string Json { get; set; }

}

This class will be initialized by an Action method on our Controller class. Inside that method is where I initialize the Json property. In order to serialize our data to Json, we need to register our custom JavaScriptConverters with an instance of the JavaScriptSerializer. Let's do that now!

User calls:
http://mywebsite/Person/Edit/123

This will call the 'Edit' action on the PersonController; this will be where all of the things glue together.

public ActionResult Edit(int personID)
{
var person = _repository.GetPerson(personID);

var converters = new List();
converters.Add(new Person.JsonSerializer());
converters.Add(new PhoneNumber.JsonSerializer());

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(converters);

var viewModel = new PersonViewModel(person);
viewModel.Json = serializer.Serialize(person);

return View(viewModel);

}

Inside the Edit view, we can now simply use a server tag to initialize a variable to be used by the page (in javascript notation). Here is the best part!!

var person = <%= Model.Json %>;

$(document).ready(function(){
alert(person.Name + ' is ' + person.Age + ' years old');
});

Cool huh?