How To View Inception Through Code

If you have not seen Inception yet, I highly recommend doing so before reading this post.

**** SPOILERS AHEAD ****

Inception Movie Poster

Inception combines the best elements of movies in the Simulism genre; such as Dark City, eXistenZ, The Thirteenth Floor and The Maxtrix Trilogy; and creates an original, thought provoking film.

Watching the film from the standpoint of a programmer, I could not help seeing the similarities between the plot devices and basic programming concepts.

The Kick

The Kick is the concept they use in the movie to return to a dream level above the existing one. For example, if you perceive that you are falling in a dream, you have a tendency to wake up.

The Kick can be portrayed in programming in several different ways:

Recursion

public bool Dream()
{
     kick = CheckForKick();
     if(kick) return true;
     return Dream();
}

* CheckForKick() implementation has been omitted.

In this recursion example, each call to function Dream() will call another sub-Dream – until the CheckForKick() function returns true, which can occur however many levels deep.

Exception Bubble

public bool Dream()
        {
            try
            {
                try
                {
                    try
                    {
                        throw new DreamException("Receive Kick");
                    }
                    catch(DreamException dx)
                    {
                        throw dx;
                    }
                }
                catch(DreamException dx)
                {
                    throw dx;
                }
            }
            catch(DreamException dx)
            {
                // Handle Kick thrown 3 levels deep.
                Console.WriteLine(dx.Message);
            }
        }

In this Exception example, an exception is thrown within a nested try block. Rather than handling the exception at that level, it’s bubbled up until is (hopefully) handled gracefully.

Stack

This can best be represented by the following infographic, which I reconstructed to be a stack. Here is the original source.

Inception Stack

A stack is one of the most fundamental data structures in computing. A stack operates in the following: items are added in a First-In, Last-Out (FIFO) manner. They are added via being “Pushed” onto the stack and removed via being “popped” from the Stack.

In the movie, each sub-dream is pushed onto the stack starting with reality. Our characters cannot return to a different dream level by popping the dream above off the stack.

Sedation

They use Sedation in the movie to prevent the dreamers from waking up any means other than “falling” on all dream levels above the first. At the first dream level, the only way to wake up is for the machine’s time to elapse.

Sedation in the movie can be explained through the use of Threading.

Threading

public void Inception()
{
     Machine mach = new Machine();
     Sedation sed = new Sedation();
     Thread machineThread = new Thread(new ThreadStart(mach.Start());
     Thread sedationThread = new Thread(new ThreadStart(sed.Sedate());
     try
     {
          sedationThread.Start();
          machineThread.Start();
          sedationThread.Join();
          machineThread.Join();
          ReturnToReality();
     }
     catch(Exception ex)
     {
          // Limbo ???
     }
}

* Machine implementation omitted. Sedation implementation below.

In this example, you can think of the sedation and starting the “dream machine” as being two separate threads – both induce unconsciousness, but in different ways.

The sedation occurs first as indicated by the sedationThread.Start(), followed by the machine start machineThread.Start(). The Sedation.Sedate() implementation may look like the following:

public void Sedate()
{
        Thread.Sleep(36000000); // 10 Hours
}

By calling join on the threads, the ReturnToReality() function will not get called until both the sedation wears off or the machine time elapses.

Limbo

Limbo is defined in the movie has a mental state where your mind doesn’t know if you are in reality or not. The only way out is to realize that Limbo is not reality.

I already hinted at how Limbo could be represented in code in the previous example – if there is an exception (i.e. death) during the running of the threads that does not allow them to complete. Also, Limbo could also be represented by the following:

Infinite Loop or Infinite Recursion

while(!IsAwareOfReality)
{
     CreateBuildings();
     CreateFromMemories();
     QuestionReality();
}

Most of the time that we are programming and find ourselves in an infinite loop, we are not aware of it until we start to question:

  • Why is this taking so long?
  • Why is my memory decreasing?
  • Why is my CPU pegged at 100%

Fortunately in programming there are ways to identify that we are in an infinite loop state.

If you are not aware of these conditions, you will stay there until your program runs out of memory or crashes (dies) or you realize you are in a loop (meet a condition) – by calling the QuestionReality() function.

Architect

Ellen Page

The last item I will mention is the role of Architect. In the movie, Ariadne (Ellen Page) is responsible for creating the dreamscapes. This shares similarities with Software Architecture. As a software architect you responsible for knowing the systems (the main characters in movie) that you work with and to create the best solutions (e.g. Never Ending Staircase) to new problems that need to be solved (Inception). Being able to see the world around you as objects with state and behavior is a useful skill for both understanding Object Oriented Design/Programming; and as a Software Architect.

I was surprised how many people shared similar thoughts with comparing the movie with programming. If you enjoyed my post, please read their perspectives:

5 Comments

5 Types of Comments to Avoid Making in Your Code

Have you ever been reviewing code and come across a comment that you deemed was unnecessary? Commenting your code is meant to improve the readability of your code and make it more understandable to someone other than the original developer.

I have identified 5 types of comments that really annoy me and the types of programmers who make them. I hope after reading this you won’t be one who falls into one of these categories. As a challenge, you can try to match up these comment programmers with the 5 types of programmers.

1. The Proud Programmer

public class Program
{
    static void Main(string[] args)
    {
        string message = "Hello World!";  // 07/24/2010 Bob
        Console.WriteLine(message); // 07/24/2010 Bob
        message = "I am so proud of this code!"; // 07/24/2010 Bob
        Console.WriteLine(message); // 07/24/2010 Bob
    }
}

This programmer is so proud of his code that he feels the need to tag every line of code with his initials. Implementing a version control system (VCS) allows for accountability in code changes, but at first glance it won’t be so obvious who is responsible.

2. The Obsolete Programmer

public class Program
{
    static void Main(string[] args)
    {
        /* This block of code is no longer needed
         * because we found out that Y2K was a hoax
         * and our systems did not roll over to 1/1/1900 */

        //DateTime today = DateTime.Today;
        //if (today == new DateTime(1900, 1, 1))
        //{
        //    today = today.AddYears(100);
        //    string message = "The date has been fixed for Y2K.";
        //    Console.WriteLine(message);
        //}
    }
}

If a piece of code is no longer used (i.e. Obsolete), delete it – don’t clutter your working code with several lines of unnecessary comments. Besides if you ever need to replicate this deleted code you have a version control system, so you can recover the code from an earlier revision.

3. The Obvious Programmer

public class Program
{
    static void Main(string[] args)
    {
        /* This is a for loop that prints the
         * words "I Rule!" to the console screen
         * 1 million times, each on its own line. It
         * accomplishes this by starting at 0 and
         * incrementing by 1. If the value of the
         * counter equals 1 million the for loop
         * stops executing.*/

        for (int i = 0; i < 1000000; i++)
        {
            Console.WriteLine("I Rule!");
        }
    }
}

We all know how basic programming logic works – this is not “Introduction to Programming.” You don’t need to waste time explaining how the obvious works, and we’re glad you can explain how your code functions – but it’s a waste of space.

4. The Life Story Programmer

public class Program
{
    static void Main(string[] args)
    {
       /* I discussed with Jim from Sales over coffee
        * at the Starbucks on main street one day and he
        * told me that Sales Reps receive commission
        * based upon the following structure.
        * Friday: 25%
        * Wednesday: 15%
        * All Other Days: 5%
        * Did I mention that I ordered the Caramel Latte with
        * a double shot of Espresso?
       */

        double price = 5.00;
        double commissionRate;
        double commission;
        if (DateTime.Today.DayOfWeek == DayOfWeek.Friday)
        {
            commissionRate = .25;
        }
        else if (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday)
        {
            commissionRate = .15;
        }
        else
        {
            commissionRate = .05;
        }
        commission = price * commissionRate;
    }
}

If you have to mention requirements in your comments, don’t mention people’s names. Jim from sales probably moved on from the company and most likely the programmers reading this won’t know who he is. Not to mention the fact that it everything else in the comment is irrelevant.

5. The Someday Programmer

public class Program
{
    static void Main(string[] args)
    {
       //TODO: I need to fix this someday – 07/24/1995 Bob
       /* I know this error message is hard coded and
        * I am relying on a Contains function, but
        * someday I will make this code print a
        * meaningful error message and exit gracefully.
        * I just don’t have the time right now.
       */

       string message = "An error has occurred";
       if(message.Contains("error"))
       {
           throw new Exception(message);
       }
    }
}

This type of comment is sort of a catch-all it combines all the other types. The TODO comment can be very useful when you are in the initial development stages of your project, but if this appears several years later in your production code – it can spell problems. If something needs to be fixed, fix it now and do not put it off until later.

If you are one who makes these types of comments or would like to learn best practices in comment usage, I recommend reading a book like Code Complete by Steve McConnell. This is one of the books that I recommend all programmers should own.

Or Perhaps you can learn how to stop commenting your code altogether.

Do you see any other unnecessary or annoying comments in your code? Please feel free to share.

51 Comments

ASP.NET – Access To Path is Denied

If your ASP.NET program is attempting to read, write and/or delete a fie it can display the error “Access to Path … is Denied”. If this is the case, the directory may have the incorrect security settings.

Here are the steps to add the correct the user security settings on Windows Server 2003:

1. Find the folder or file that you are trying to access.
2. Right-click the folder
3. Select Properties
4. Click the Security tab
5. Click the Add button

6. Enter the user: <SERVERNAME>\IIS_WPG
7. Click Check Names button

8. Click OK button
9. Verify user has correct permissions (Read/Write)

10. Click OK button

Other Windows operating systems (XP, Vista, 7) may require the user: <SERVERNAME>\ASPNET to be added.

Leave a comment

Do-It-Yourself Free XML Tool Suite

If you ever had to work with XML documents and XML schemas, it can be pretty challenging if you don’t have the right tools. If you are creating/modifying XML through code (e.g. XML Web Services), it can especially be difficult searching XML nodes or trying to create a validated XML document.

Personally, I believe that XMLSpy from Altova Software is one of the best tools available if you are going to be dealing with a lot of XML documents. However, this tool does come at a price. A few years ago, they used to offer a free community edition of their software – this has since been discontinued.

I’ve recently needed to create and modify some XML and was searching for some tools that fit the criteria:

  • Windows Based
  • Non-Trial Editions of Software
  • Free

I have come up with a list of three tools that perform a majority of the tasks in commercial products like XMLSpy and are a good alternative.

1. XML Notepad

XML Notepad 2007

XML notepad makes it easy to edit XML nodes without the need to edit the XML syntax directly. By attaching an XML Schema, your XML document is checked for validation as you input values.

Although this tool has not seen an update since 2007, it is still one of the better free XML editors with a simple, yet powerful interface.

2. XPath Visualizer

XPath Visualizer

If you’ve ever had the need to query XML to find specific nodes, XPath Visualizer provides a way to test XPath queries against an XML document. With the ability to include XML namespaces, the XPath expressions can easily be imported into code environments like Visual Studio.

3. XML Sample Generator

You have an XML Schema, but now you need to create an XML document based off this schema. If you don’t have a tool that helps you visualize a schema graphically, it can be a daunting task to traverse an XML Schema and create an XML document manually. Thanks to the XML Sample Generator, you can import your XML Schema and export a well-formed, validated, XML document.

XML Sample Generator provides a good starting point if you need to start from square one.

Do you have a free tool that you use? Please share in the comments.

1 Comment

SharePoint 2010 Development Resources

Implementing SharePoint 2010 is an idea that is being thrown around at my place of employment right now. As a developer, there seems to be some significant differences between WSS 3.0/MOSS 2007 and SharePoint 2010 (SharePoint 2010 Sandbox Environment) and I wanted to make sure that my skills were updated for the latest release of SharePoint.

For everyone who is already developing or those who will start, I put together this list of resources that are available.

Videos

There are a few hands-on videos if you are a visual learner.

Books

If you prefer to learn from a book, there are many more resources available for SharePoint 2010 than there were previously for WSS 3.0 or MOSS 2007.

Pro SharePoint 2010 Solution Development: Combining .NET, SharePoint, and Office

Ed Hild and Chad Wach


SharePoint 2010 as a Development Platform

Joerg Krause, Martin Daring, Christian Langhirt, Bernd Pehlke, Alexander Sterff


SharePoint 2010 Development with Visual Studio 2010

Eric Carter, Boris Scholl, Peter Jausovec


Beginning SharePoint 2010 Development

Steve Fox


Professional SharePoint 2010 Development

Tom Rizzo, Reza Alirezaei, Jeff Fried, Paul Swider, Scot Hillier, Kenneth Schaefer

1 Comment

My Experience at Orlando Code Camp 2010

This post is long overdue but I thought I would share my experiences with attending my first code camp: Orlando Code Camp 2010.

Code Camp is something that always interested me, I thought it would be cool to experience some of the bleeding-edge technology and also receive some “free” training in the process.

If you are not aware of what a Code Camp is, it is an event where developers volunteer their time to present on several different topics – typically related to Microsoft products and technology and is sponsored by local technology companies.

Here is a breakdown of each session I attended:

Session 1

What to Know About WF 4.0

Presented by: Bayer White

I have just introduced myself to Windows Workflow Foundation (WF) since I have been teaching myself Windows SharePoint Services – so I thought I would get some exposure to what’s new in WF 4.0.

Take Away: WF 4.0 is significantly different from it’s predecessors, but there are some features that make it more productive: activities. A lot of the information was a bit over my head for being a novice at WF; however, once I get a good understanding of WF 3.0, I will migrate my skills to WF 4.0.

Links:
www.humanworkflow.net
www.flowfocus.com


Session 2

Building a Data Warehouse Using Sql Server 2008

Presented by Wes Dumey

The topic of Building a Data Warehouse is not new to me. I have taken graduate-level classes on the subject and actually built a Data Warehouse for a hospital as a team project – back in the days of Sql Server 2000. However, since taking this class, I have not had much exposure to the topic and the tools from Microsoft have changed significantly.

In the week previous to Orlando Code Camp I had attended several webinars by Pragmatic Works on Business Intelligence, so a lot of the information was review.

Take Away: Wes shared some ‘best practices’ that his firm adopted, such as storing the extracts after each step of the ETL process to verify the data.

Links:
Durable Impact Consulting
www.dayofdata.com


Session 3

Developing OLAP Solutions with SASS 2008

Presented by: Adam Jorgensen

One of the webinar sessions I missed with Pragmatic Works, was this very same presentation with Adam. So it was a treat to see Adam present this in person and demo the BI tools in Sql Server 2008.

Take Away: Since I have not used Sql Server 2008 BI Tools or even Sql Server 2005 BI Tools for that matter, I think there was an assumption that the audience had prior exposure. Adam frequently referred to the differences between 2005 and 2008 and also shared his pet peeve of naming dimensions with underscores.

Links:
Pragmatic Works


Session 4

Getting Started with WPF

Presented by: Shervin Shakibi

I haven’t had much exposure to WPF, so I thought I would check out this session for beginners. The presenter Shervin Shakibi is very comical and made the session pretty enjoyable.

Take Away:
From what I understand about WPF, is that it add additional functionality to creating Windows Forms and is primarily driven by XAML. It is possible to create web apps using WPF, but Shervin suggested to use Silverlight for that purpose.

Links:
www.computerways.com


Session 5

Silverlight Viewer for Reporting Services

Presented by: Jeremy Groves

This had to be the most unproductive session that I attended. It seemed as if the presenter was there against his will – the session only lasted about 10 minutes.

Take Away:
Silverlight Viewer for Reporting Services is actually a product by Perpetuumsoft and this session was nothing more than a marketing presentation to buy their product.

Links:
www.perpetuumsoft.com


Session 5.5

Stream It! Live + HD + Silverlight

Presented by Kevin Rohling

Since I had some time to kill, I went to this session since it was the location for Session 6.

Take Away:
Kevin Rohling made note of a video (that I had never heard of before) that is available in the public domain: Big Buck Bunny.

Links:
www.perpetuumsoft.com


Session 6

Dissecting a Real-World Silverlight 4 Application

David Silverlight

I really wanted to see Silverlight development in action and I was provided this opportunity in David Silverlight’s session.

Note: I have to admit I once thought that Silverlight was named after him.

Take Away:
David presented a User Group Website Starter Kit software package that was developed using Silverlight, and is available to download via CodePlex.

Links:
Silverlight User Group Website Starter Kit
www.perpetuumsoft.com


Overall, I was exposed to a lot of new technology at Orlando Code Camp. I look forward to attending Tampa Code Camp later this year.

More Blogs about Orlando Code Camp:

1 Comment

How to Network in the Information Age

How to Network in the Information Age

Have you networked with individuals at a conference or some other event (e.g. Code Camp, User Group, etc.)?

If you have, were you able to follow up the people that you met?

The means of following up with a network contact have changed. You can start networking in the information age by using many of the tools that you probably already use today.

Constants

The process and purpose of networking has remained pretty much the same over time.

1. We attend venues for conferences, training or seminars.
2. We use our social skills to speak with and interact with others at these venues.
3. We hope we can use our new networking contact for a new job reference, professional reference or friendship.

What has changed in networking – is the way that we follow up with our contacts.

The Old Way (Dark Age Networking)

Before the information age how did people follow up with their networking contacts? Most likely, it was done by snail-mail, e-mail or telephone.

Let me put into perspective how effective these means of follow up are. Say you receive one business card for every business card that you hand out. Unless, you have either a unique business card or an unforgettable personality – people are going to have a difficult time remembering you based on your name.

I suppose you could but your picture on your business card, but that is something that is probably best left to real estate agents.

The New Way (Information Age Networking)

In the information age, you will still give out business cards, but the contents of those business cards will be “links” to your contact information. The information on your business card is a way for your contacts to remember who you are without having to make an impression based on personality.

Contact Information Tools

There are many tools that you can use for your contact information. I recommend at least these three:

1. LinkedIn

Posting a link to your LinkedIn profile is probably the best tool that you can provide to your networking contacts. Especially if you are looking for a new job or to validate your background. LinkedIn provides the following:

  • Allows contacts to see your professional job history and projects
  • Allows contacts to see any recommendations you’ve given or received
  • Allows contacts to see a profile picture to put a face with a name

2. Facebook

Facebook can be used for the right reasons and the wrong reasons. If you currently use Facebook for the wrong reasons (e.g. posting drunk pictures, complaining about work, etc.) – I suggest that you don’t use Facebook as a networking tool.

However, Facebook can be used for the right reasons – to provide an insight into your personal life.

By sharing the following on Facebook, a networking contact may find out more about you on on a personal level:

  • Interests
  • Hobbies
  • Events in your life

I would also suggest using Facebook’s privacy settings, in case someone else posts a picture or writes something inappropriate to you.

3. Twitter

Most new users of Twitter don’t see the value of it. What Twitter can provide is a way to share daily information with your followers both professionally and personally.

Nobody wants to follow someone who posts mundane posts that add little value (e.g. “Just woke up”, “Eating breakfast”, “Showering”). Instead, use Twitter as follows:

  • Posting insights on life
  • Posting links to interesting articles or web sites
  • Conversing with others on a particular subject

All of these tools allow for continuous networking beyond the initial connection.

How to Get Started?

1. Create a profile on each one of these networks.

2. Create two sets of business cards

  • Sales Business Card – These will be the typical business cards with name, email, and phone number
  • Networking Business Card – This will only contain your name and links to your profiles (LinkedIn, Facebook, Twitter)

3. Start attending events and networking!

* Picture courtesy of Joe Pemberton

Leave a comment

The Presentation Secrets of Steve Jobs: Video Reference

I just finished reading The Presentation Secrets of Steve Jobs: How to Be Insanely Great in Front of Any Audience by Carmine Gallo – this book is ideal for anyone who regularly delivers presentations, speaks for a living or wants to become a better speaker.

The Book

The book was filled with tips to help you develop and enhance your public speaking skills. Carmine Gallo effectively points out the techniques used by Steve Jobs that make his presentations both entertaining and effective.

The Presentation Secrets of Steve Jobs

How To Be Insanely Great in Front of Any Audience

Carmine Gallo

The Videos

Gallo references several notable speeches and presentations by Steve Jobs to illustrate his points. While Gallo does provide links to the videos in the book’s reference – I thought it would be helpful to provide direct links to the videos.

1 Comment

Miscellaneous Steve Jobs’ Presentations

Computers Are Like Bicycles for Our Minds

Leave a comment

How to Get Started with Windows SharePoint Application Development

I’ve made it a goal to become certified in Windows SharePoint Services 3.0 – Application Development by the end of the month.

MCTS Exam 70-541

The Setup

I am fortunate to have access to Microsoft DreamSpark, which provides students access to full versions of the latest Microsoft development tools. I believe the only requirement is that you have an active student email address.

To setup my environment, I installed the following:

Learning

My primary source of learning will be reading the following book (available via Amazon.com and through ACM subscription:

Inside Microsoft Windows SharePoint Services 3.0

Ted Pattison and Daniel Larson

The book also contains a companion CD with examples.

1 Comment

Subscribe to RepeatGeek

Subscribe via RSS

Enter your email address: