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.

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.


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

  • Name
  • Address
  • City
  • State
  • Zip
  • PhoneNumbers[]
  • 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:

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();

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 %>;

alert(person.Name + ' is ' + person.Age + ' years old');

Cool huh?

Monday, July 20, 2009

Hooked On Linq

For those that don't know what Linq is, read this:
LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities. - http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

I've only mentioned it on my blog once a very long time ago, while I was attending CodeMash.

Well, I've been using it for a few months now (steady) and it's taken some time for me to really get used to it. I still find myself writing loops to find things inside lists, or else converting them to List so that I can use the Find() and Convert() functions freely. I've now convinced myself that Linq is my friend and I'm finally a huge fan of it. I've always been reluctant to Linq in my project because I felt like I was no longer "in control" of my collections and it added too much overhead.

Today, I found myself updating an old collection class with some new functionality and was able to shrink many of my methods down drastically using a single Linq query. In my case, I have a single collection class that offers multiple functions for extracting a subset of objects. For example, I might want to pass a parameter and only return a all objects whose member happens to match that parameter. Here is an example of one of the functions that I changed in my code to make it more readable:
public IEnumerable<PanelDefinition> FindByType(PanelType panelType)
foreach(var panel in this)
if (panel.Type == panelType)
yield return panel;
And I was able to rewrite it to this:
public IEnumerable<PanelDefinition> FindByType(PanelType panelType)
return from panel in this
where panel.Type == panelType
select panel;
To a non-geek, both snippets are very cryptic, I'm sure. However, to a geek (like myself) the bottom snippet is more "human readable"... or at least that's what we've been told anyway. :) Regardless, the second snippet has no squiggles or syntax rules to follow. Something else that's nice about the second snippet is that it's able to take advantage of all the framework niceties. I could go on and on about how cool and flexible Linq is, but go see for yourself if you're curious: http://msdn.microsoft.com/en-us/data/cc299380.aspx

Thursday, July 16, 2009

Present Like Steve Jobs

This is a bit corny, but very useful. I've done many presentations in my day, and it is not as easy as Steve Jobs makes it look.

Another good resource is a book called: Presentation Zen

Read it! It will show you ways to keep your presentations interesting. I never realized how many crappy presentations I've sat through until I read this book.

Wednesday, July 15, 2009

How to Become an Ultra Runner

What's with the Title?
I thought about naming this post "How to Enjoy Running", but decided on "How to Become an Ultra Runner" instead, because that's what I am today. I plan to talk about my journey and inject little tips along the way for anybody else that want's to start running (for whatever reason). The idea behind this post all started with a quiet and peaceful run today in the woods. While on my run I did a lot of reflecting and thought about how I got to where I was at that moment in time. Ever do that? While I was grinding on that thought, I realized how happy running makes me. I truly can't imagine life without running now. I thought about how I might answer someone who wants to know how (or why) I run so much. The "why" is easy, I do it because it makes me happy. The "how" is a little different, but it all started with a single step.

Why Ultra Running
My outdoor activity of choice is running long distances. However, there are oodles of outdoor activities that are just as addictive as my favorite sport (ie. kayaking, biking, swimming, hiking, or whatever). For me, I truly enjoy being outside and huffing and puffing across the earth. Therefore, my examples all include the sport of running. I would love to hear your journey or "how to" examples of getting into another addictive sport.

The first section of my post will be broken down like this:
  • Starting from Scratch
  • My Mission
  • We are Born to Run
  • How to Enjoy Running
Once that I finish rambling about theory and our purpose, I then get into the "how to" section. Which is more or less just me telling you what I did along my journey, sprinkled with what I would have done differently:
  • Getting Started
  • Sticking With It
  • Challenge Yourself
  • Reap the Rewards
Starting from Scratch
So, I've been "recovering" since my last race, and maybe even recovering a little too much. :) I've basically taken the last 2 weeks off of running and I'm now back to starting from scratch on a training plan. I can't believe how easy it is to gain weight. I know I've gained about around 5 pounds or more just from eating crap food. I've been living on hot dogs, beers, cake, pop, burgers, chips, you name it... I've injected a few healthy choices along the way (fruit smoothies - my fav, salads, yogurts, oreo's... oh wait). However, healthy food simply isn't a major part of my daily routine like it probably should be. I've always offset my eating habits with my running addiction. Honestly, I'm excited about getting back onto an actual training plan now. I get to enjoy the whole process of transforming my body back into running again rather than maintaining a running body. It's more fun when starting from scratch, especially when I have the luxury of time on my hands.

Lucky for me, I can probably pick up and be trained for a marathon a lot quicker than someone who's never ran before. Therefore, I don't recommend going outside and start running 5-7 miles a day with 10 mile long runs on the weekends right away. Doing so would put you down and out for a long time with some nasty injuries. I totally remember my early running addiction days. I remember my first mile was so painful and I literally hated it. I forced myself to stick with it and eventually I started looking forward to them. If I had to do it all over again, I don't know if I would have done it differently. I have always been one to learn from my mistakes. :)

My Mission
While on my run, and pondering all the things that led up to my running addiction. I decided it was only fair to share with others, the series of events that got me there. Perhaps reading my story would influence someone else to take similar steps to a happier life.

I feel that the key to a happy life is knowing that I am in control of what I will and will not do. We are all blessed with the ability to make simple decisions every day. Thousands of them! By making these little choices, you are creating your own reality, or deciding your our own destiny... Wait, this post just got waaaay too deep...? Just bare with me for a few more sentences please.

Begin Deep Thought
Disclaimer: My religious beliefs are just that... my religious beliefs. It's my blog.

Over the years, I've realized that I am in charge of my future. If not "in charge", then I can at least redirect it everyday towards a happier life. I live everyday knowing that today is the first day of the rest of my life... Every single decision counts! If I don't like how something is going, I change it. One decision at a time; it's really that easy. We all are capable of doing this.

Nobody is a victim! If you say "I can't do that because [insert excuse]", then you are absolutely right... [the excuse] has prevented you from even trying. Therefore you can't. However, if you say "Hell, I can do that!", then you are also right! Understand that it is up to you to decide how to react to a challenge; you will always be right.

If you are a person of faith, then you know that you have your God on your side to help you in your new journey. If you are a person of science, then please go watch "What the Bleep Do We Know" to understand that the human body is constructed of an amazing series of circuits (feel good vs. feel bad).
End Deep Thought

Still with me? Good... So, I wondered how I could help others find their knack to get healthy and realize how happy they will (in turn) become. While I'm by no means "healthy"! I can say that I'm much healthier today that I was 3 years ago though and I attribute most of that to running.

We are Born to Run
Human beings are built to walk (and run) on two legs. A vast majority of the human race is born with 2 legs and can walk effortlessly. The best part about running (to me) is that it's as easy as walking. Running requires very little preparation to get started. Just change a walk into a jog and there you go! You're running! Literally. If you can walk with no effort, then you can run with very little effort. I can't think of any other sport that is so convenient and easy to get started as running is.

You can run anywhere. By anywhere I mean... anywhere. Also, by anywhere, I (personally) mean anywhere outdoors. I would definitely suggest running outdoors as opposed to inside. Running inside on a treadmill or around a track is nice in worse case scenario's (ie. storms or late at night). However being outside in nature (including storms and late at night) is what really does it for me, and has kept me motivated to stick with it for these last 3 years. I feel sorry for the people inside the YMCA as I run by the gym and see rows of people running on treadmills staring at a "community television" worrying about how fast the person beside them is going. :( If only they would unplug and get outside!! They too might see that they are missing a lot. I would choose to run 5 miles in the pouring rain outside rather than 5 miles on a treadmill in the air conditioning any day!

How to Enjoy Running
This was the hardest part! I never ran in high school. I literally hated running! The first time I ever ran at my own free will was while I was attending my freshman year at Bowling Green. I only ran as a means to lose weight, but not because I enjoyed it. It worked very well, and I dropped 60 pounds in about 4 months. At that time I was only running 1 mile everyday and I pushed myself to run it faster and faster every day. As the weight came off, running became easier and required a lot less effort. People were starting to notice that my weight was coming off, and I liked that. However, I still didn't look forward to my daily runs.

Three years ago, I was up to a pudgy 230 pounds, and I decided it was time to do something about it. I started running again. It sucked! I hated it! My side hurt, I couldn't breath, and my entire body ached after I was done. In hind sight I should have started off slower, but at the time all I knew to do was tuck my head and pound as fast as I could until I reached 1 mile. The more I did it, I began to realized that I didn't have to go balls out fast. I also discovered that once I slowed down, I was able to go a lot farther and for a longer period of time. Eventually, I was starting to look forward to my runs. I found that after a while I was no longer running to stay fit; I was now running because it was fun, and it genuinely made me happy.

Running had become my own personal time. I let my mind become my sanctuary for meditating and thinking about whatever I wanted to. (Maybe I should have put the 'Deep Thought' brackets around that last sentence? :)) Honestly though, I am able to think about so many things and have solved so many problems while running. I contribute a lot of my sanity to running. I've solved many computer problems in my head while running, I've constructed large computer systems in my head while running, I've made lots of huge decisions while on runs as well. When my household gets stressful (trust me, it does), I put on my running shoes and go run. I find it's best to run in the woods with no iPod for maximum results. :)

I find that I get more joy by running outside in the elements. There is something about being out in the open air (hot, cold, windy, muggy, it doesn't matter) that just makes me happy down to my core. I take in so many sights and I've experienced so many different climates on my runs. I remember running in Novosibirsk (Siberia) in sub-zero temperatures with Scott through the Botanical Gardens. I also remember running in gale force winds here in my home town on a stormy summer night. Running in the rain is my favorite, and sloshing through wet snow in the winter time puts a smile on my face. Day or night doesn't stop me either; I purchased a head lamp and now don't have to rely on the sun to see when running. I've ran in blue jeans before, I've ran barefoot around the back property before too. No outside force can stop me from running. Injuries tend to slow me down, but I'm learning how to prevent them as well as I journey through this sport.

For me, the only way that I was able to enjoy running was to just do it... a lot. Once I figured out how to run, it became fun.

Getting Started
If you are still reading this, then you are thinking one of two things:
  1. Luc is stupid. I should stop reading this.
  2. How could I become a distance runner?
Luckily for you, I thought of a system on my run today that I'd like to share if you are thinking #2. :) If you've never ran a step (on your own free will) in your life then you should do this.
  1. Find a place where you are absolutely comfortable.

    If you would feel totally ridiculous running in public for whatever reason, then I don't recommend running in a crowded area (duh). I know first hand that it was kind of embarrassing for me at first. I would feel like I was jiggling all over the place when I ran. After a while I didn't care (and rightfully so), but being in a private area where I could experiment with my stride, and not worry about what I looked like helped me build my self confidence as a runner a lot.

  2. Go Slooooooow

    This is where I screwed up! I tried to run a fast first mile. For some reason, that is what I thought "running" was all about. Instead I should have done a walk, jog regiment and progressed to a steady "run". Here is what I would recommend having gone through the pain of my first run:

    - Walk for 1 minute
    - Jog for 10 seconds
    - Walk for 1 minute
    - Jog for 15 seconds
    - Walk for 1 minute
    - Jog for 20 seconds
    - Repeat... until I span 1 mile.

    Eventually you'll be able to jog a mile without stopping. When you get to that point, try jogging two miles. Feel free to walk whenever you need to. Don't ever feel like you can't walk. Believe me, there is plenty of walking at ultra running events.

  3. Run every other day. No matter what!

    This will force you to give "running" an honest effort. You will hate running at first; trust me. Your feet will hurt, your body will ache, you will experience side cramps, you will get blisters, you will stink, etc... Stick with it! Soon it will become easier and more enjoyable. I promise!
Sticking With It
This is the last step in my (awesome) Getting Started plan above. It is also the key element to becoming a runner. Whether you start running to get fit, or you just want to see why I like it so much, keep at it! You will get fit, and/or you will see why I like running so much. There is a lot of challenges that get in the way when picking up a new habit. The only way to appreciate running is really to give it an honest attempt. If you run every other day for 2 full months and still hate running, then stop running and try something else. Running is not for you.

However, I know that after 2 full months of sticking with an "every other day" running habit, you will begin to look forward to your run days, and dread your rest days. I did and still do.

Challenge Yourself
If you are one to push yourself in order to make something feel worth while (like me), then it may be a good idea to sign yourself up for a 5k road race (3.1 miles). You don't have to "run" a 5k, but I did. I decided that if I was going to sign up for a running event, then I was going to train for it and run it! My first 5k was an extremely rewarding experience. I will never forget how scared I was at my first road race. I didn't know what to expect. I just showed up with my family and put all of my humility on the line. I'll never forget how proud I was to cross that finish line though! For a measly $25, I attended a public "running" event and finished it. That $25 turned my life around.

After running my first 5k, I was hooked on the sport of running. Just pushing myself into unfamiliar territory is what did it. I wasn't afraid to be known as a runner anymore. I was able to be around other runners and I actually had something in common with them now. Running was no longer something that only "fit people" did, and it took a simple 5k road race to prove that point to me.

Reap the Rewards
As running became easier, I began running more and more. I signed up for more 5k's that first year and they too were becoming easier and easier. Running a 5k on a weekend became a normal thing to me. I was building a collection of running t-shirts, medals, and plaques. I was also beginning to lose a lot of weight and people were starting to notice. My race times got better and better and my energy was through the roof. I had become more happier in 4 months simply by sticking with it.

Eventually I realized that I liked running so much, that I started running longer distances and for longer periods of time. I signed up for a 20k trail run and then a 1/2 marathon road race. Eventually I was running marathons, and now I'm running ultra marathons. What's next? Even I'm not sure...

Please don't let my current distances fool you... I still push myself out the door every time I need to run. I do take comfort knowing that after mile 2, I'm in my element. I still treat my ultra marathons is the same as I would have treated a 5k 2 years ago. It took the same process to get to these distances and I still get the same jitters as I got at my first 5k.

You can't just go out the door and run 50 miles one day. You have to start somewhere. For me, it was a painful 1 mile stretch of blacktop. I would have never guessed it would have put me where I am today. Who knows where you'll end up in 3 years... It is really up to you. If you aren't happy where your at today, start to change it by making your first "change" decision.

Monday, July 13, 2009

What's Been Going On

I haven't blogged in a few weeks. I've been pretty busy around here. July is always a crazy month for us; Jennifer and Jazzy's birthday's are both in the first week of July. Toboso yard sales also take place in the first week of July, so there is a lot of preparation and planning that goes in to all of these events. This year, a new element was added with the wedding of a very good friend. So in the mix of all this chaos, I decided blogging wasn't a priority when I turned on the computer. :)

So what's been going on..
  • Jen turned 30
  • I got stranded in Cleveland
  • Training for Fall races
  • Jen gets injured while shopping
  • Yard Sale!
  • Jazzy turns 6 years old
  • Mike and Kelsey get married
  • Lizzie and Jazzy get a new swing set

Jen's Big Surprise
This year was Jennif'er's big "3-0". She turned 30 and I had to get her something cool. I had considered throwing a big surprise party for her a few weeks before. She warned me not to do it, and after considering all the hassle and work of it, I had to figure something else out. Therefore, I asked her best friend, Crystal, to take her out for a night on the town while I had my best friend, Tyler, come over and help me rip up the carpets in the living room. There was some beautiful hard wood floors underneath them, and Jennifer and I have been talking about doing it for years.

The day came for Crystal to take her out and get some drinks... I had kept my cool all day and pretended like I was going to be working all night while she was out. In reality, I had Tyler coming over around 7:30 - 8pm so we could get started on this EPIC project. We would have about 3 - 4 hours to get the carpet ripped up and move all the furniture back before she would walk in the door. Needless to say, she came home at 12 midnight totally unsuspecting anything and just fllllllipped out!! She saw the floors and just giggled and cried for about 5 minutes. It was priceless. I kicked ass this year, and she claims it's her best birthday ever! :) The next day, I invited all of her friends and our family over for cake and ice cream. I loved it! She was happy and I'll remember my feeling when she saw that floor for the rest of my life. I have NO idea how I'm gonna top this next year. :)

Bachelor Party in Cleveland
The next day, (ie. July 3rd) - I woke up and immediately headed up to Cleveland for my good friends' bachelor party at an Indians game. I had the entire weekend figured out: I was supposed to go up to the baseball game on Friday night, party down at the bars, sleep, then come home and enjoy fireworks with the family at my cousins for the 4th of July. As it turned out, I get up to Cleveland a full day early! The whole way up I wasn't able to get a hold of anybody in the party. I got to the hotel and there were no reservations... I got to the game, and still couldn't find anybody, so some super nice dude at the ticket desk gave me a free ticket to go in and find my party. He could clearly see that I was distressed because I was like 30 minutes late to the game and missing my buddy's party.

After getting into the game and finding the "help desk", some one was able to find that the tickets to my party weren't until "tomorrow night". It all made sense at that point (nobody answering their phones (ie. still at work), no reservations at the hotel, and no tickets to get into
the game. Therefore, I was forced to drink beer and eat hotdogs at the game, and then get a room in the Cleveland ghetto... by myself. The next day, I drove around Cleveland aimlessly waiting on "the crew" to show up, so I could do it all again. :) It turned out to be a pretty fun (but expensive) weekend. :)

I was pretty good with my running last week. I ran Monday, Tuesday, Wednesday, and Thursday. They were all short mileages (2 - 4 miles), but they were enough to get me back out and running agian. I need to start training for my fall race line up. I'm doing the Indian 60k Trail Run, Columbus Marathon, and a new Bobcat Trail marathon. I think I'm going to sign up for the Mohican 50 miler again next year if I don't find a fun 50 miler this fall / winter. I gotta figure out my stomach issues with this 50 miler so I can attempt the... No I'll save it for a later post. :)

Anyway, I've been trying to watch my diet as I prepare for these ones so I can actually lose some weight and run easier and with less effort. Jen hates my new diet! :) Typically when she gets too much food, she'll give me what she can't finish. Now she's forced to either finish it herself or throw it away. The other day she ordered a huge Angus Swiss burger meal from McDonalds and I got a friggen Fruit Parfait and a water. It goes without saying that I was pretty hungry later, but I'm learning to accept these pains and try to stay busy until they pass. :) We'll see what this week brings... It's harder to turn up junk food than I thought!!

Jen's Foot!
This last weekend, Jennifer had her first shopping injury. :) She was in Gabriel Brothers (her all time favorite store) shopping for some last minute items and the rest is history. It went like this, I took the girls to town with me to visit a buddy, then go get ice cream with my 3 girls. As we were wrapping up our adventure in town and heading back out here to the house, I get a call from Jennifer and she's very upset.

Here, she was shopping and a huge metal rack fell on her foot!! Not only that, but she was wearing flip flops and it was a direct hit on the bridge of her foot (yeah, the soft part). Ouch!! When the girls and I showed up, it looked pretty nasty and she was clearly in a lot of pain. We spent the remainder of the evening in the Zanesville hospital getting her foot taken care of. She now walks around with a cool limp and has a sexy, hospital-blue boot to show for it. :) She was even more upset because the next two days were both big days that we've been planning for all spring. :(

Yard Sale & Jazzy's Birthday Party
Friday morning, we all woke up early (after a 2 hour nap on my part) and setup our driveway for the annual Toboso yard sales. Jen was hobbling around, I took a personal day from work, and people were strolling in and out all morning / afternoon. Jennifer couldn't move fast, so she had me and her sister to help her.

As the yard sale was dying down I busted out my cousins' inflatable water slide because Jazzy was having her 6th birthday party tonight. It went great, we had so many people show up to celebrate it with her and it was so good to see her smiling and having a good time. The party died down around 10pm and we got them all ready for bed. Jen and I had an early morning...

Mike and Kelsey's Wedding
A good friend of ours (the bachelor from last weekend) was getting married in Cleveland the next day (Saturday). Jen and I had to get the girls to her moms, then drive to Cleveland before 3:30pm. We arrived around 2pm and was able to just relax for a while. The wedding was absolutely beautiful and we had a great time. Mike and Kelsey are a damn cute couple and I wish them years and decades of pure happiness. It's free and we all deserve it, especially them!!

Jen and I partied like it was nineteen ninety nine. She hobbled around on her boot all night and I hobbled around on a slurred speach. :) We were able to meet up with some old-school friends and we just had a great time! We got about 6 hours of honest sleep then it was up and at'em with the alarm so we could head back home for one final project...

New Singset
Jen and I had a date to meet a guy in Hilliard to purchase a very nice swing set from a fella on Craigslist. It was an absolute steal at $100!!? Jen offered him $120, because it helped lock in our "bid" and also was still a hell of a steal. These things typically go for around $600 or more. Needless to say, the swingset is sitting out in our yard right now just waiting to be put back together. That sounds like a good Tuesday or Wednesday project. :)

Til next post.. I'll be relaxing....