Tuesday, 26 June 2012

Binding To Event At Runtime In Windows 8 Metro

So I wanted to use the MVVM pattern in Win8 Metro WPF, but was without the classes and functionality I would use in WPF4. So I decided to create my own, but I got the error:

Adding or removing event handlers dynamically is not supported on WinRT events.

I found a blog post on the MSDN where some guy posted about using the WindowsRuntimeMarshal to get around that, but he didn't post a code sample. So, I decided to figure it out, and let everyone know!

So here's the code:

var eventName = "Click";
var myButton = new Button();
var runtimeEvent = myButton.GetType().GetRuntimeEvent(eventName);
var handlerType = runtimeEvent.EventHandlerType;
Func<RoutedEventHandler, EventRegistrationToken> add = (a) => { return (EventRegistrationToken)runtimeEvent.AddMethod.Invoke(myButton, new object[] { a }); };
Action<EventRegistrationToken> remove = (a) => { runtimeEvent.RemoveMethod.Invoke(runtimeEvent, new object[] { a }); };
RoutedEventHandler handler = (a, b) => Command.Execute(b);
WindowsRuntimeMarshal.AddEventHandler<RoutedEventHandler>(add, remove, handler);

So that's how we can add an event handler to an event at runtime in WinRT. Pretty simple, really. The one limitation of this code is that if you are trying to bind to an event that isn't a RoutedEvent, you're going to have to re-do the code. But I'm sure this is able to become a generic function with a little bit more work.

Monday, 12 March 2012

Implementing IDisposable Properly

I just found out that I haven't been disposing correctly. Here's my newest IDisposable implementation:

        //Stores whether everything has been disposed or not. It's possible
        //to call .Dispose() on an object and then try to use it again. With
        //this field, you can check before trying to access a resource.
        //Default is false (as per all booleans)
        private bool _disposed;
 
        //This is a C# finalizer, called when the garbage collector is going
        //to clean up an object. This is kind of expensive, but we need to
        //make sure we are disposing of objects. Having a finalizer makes
        //sure we dispose of our resources even if we forget to call .Dispose().
        //Finalizers force the garbage collector to keep track of who has them
        //and makes the garbage collector require two passes to erase an
        //object: one pass to call the finalizer, one pass to release memory
        ~SampleClass()
        {
            //Calls a private method we have made, telling it to only release
            //unmanaged resources. Managed resources will have been cleared out
            //already, since the CLR keeps a reference count.
            Dispose(false);
        }
 
        //Implementation of the IDisposable interface
        public void Dispose()
        {
            //Calls our private method, letting it know that we need to let
            //go of both managed and unmanaged resources
            Dispose(true);
            //Tells the garbage collector that we don't need to run the
            //finalizer for this class, since we are going to clean up
            //ourselves. This prevents the costly running of the finalizer
            GC.SuppressFinalize(this);
        }
 
        //A private method just for us. The parameter determines whether
        //we clean up only unmanaged resources, or if we also include
        //managed resources
        private void Dispose(bool disposing)
        {
            //Checks if the disposals have been done already
            if (_disposed)
            {
                //No disposal done? OK. Fair enough. Are we disposing of
                //only managed resources?
                if (disposing)
                {
                    //We take care of only managed resources in this block
 
                    //If the resource is still around, dispose of it.
                    if(_managedResource != null)_managedResource.Dispose();
                }
                //Unmanaged resources need to be cleaned up for sure, so
                //let's do that here. Call the code to clean up the
                //resources here. In this case, let's pretend we have a
                //COM object to be cleaned up.
                Marshal.ReleaseComObject(_unmanagedResource);
 
                //We set everything to null to remove this object's
                //references for certain.
                _unmanagedResource = null;
                _managedResource = null;
 
                //Set the disposed flag to true to let the rest of the class
                //know.
                _disposed = true;
            }
        }
Once we implement IDisposable like this, we are guaranteed to have our objects cleaned up properly no matter how our code is being used, which is the goal of even using IDisposable :)

Any tips to improve this code? Leave a comment!

Friday, 3 February 2012

Priorities And How They Can Get Away From You

We all prioritize. We have to. The demand for us as a person is strong. People demand our attention, our money, our time, and our brainpower. They all are asking for something from us, and we ask for something in return. We find something we can do easily (think, speak, lift, lead) and we offer that service to others, prioritizing to get what we want. You can spend your time on an open source project or you can stare at the sun. Both bring benefits and both have downsides. You probably would like to see a great tool for X technology instead of damaged retinas, but that's only because you're a developer and I am assuming that you don't want burned eyes. We do this trading all the time, and most of the time we don't even know it.

Our output is measured in how much we can finish in a period of time. If Guy A can do 3 things a week, and Guy B can do the same 3 things plus 2 more, Guy B is considered a better guy. Whatever the skillset they possess, that's typically how it works. One's ability to do something is much higher the more motivated they are, and intrinsically motivated people are not swayed easily from their motiviation. The challenge a lot of employers face is how to motivate people enough to make money off of them.

So when we sit down and think "What should I do?" (as those who are self-directed tend to do quite often), we tend to think about our highest priorities and act on those. Now, most people have a obstacle where they haven't established priorities or they aren't clear, even to the person setting them. If you are looking to be continually improving, I have noticed that there are a number of people who have the energy and want to advance their interests, but they still aren't able to move forward. One thing I am still learning is that almost as important as having priorities is keeping that list small. A large list of priorities that isn't written down can distract you from your goal. Similar to a software project, if your priorities are always shifting and never nailed down, you will suffer from having 30 half-finished goals at a time, which really lowers your output.

I got a tip from a mentor once. He told me that every decision you make to advance a specific priority is an automatic decision to not advance a different priority. Additionally, you might not know exactly which priority is going to suffer, but it's going to happen. And that's because we only have 24 hours in a day and only so much energy. So by reading a good book, I am investing time in my career, but that also means that I won't be investing in my skill of Internet trolling. It's always a tradeoff.

So what do you do? How do you beat the system? The key is in making sure you are prioritizing correctly. Because really, if your priorities are not clear to yourself, then you are liable to make the decision that invests time in the priorities you want less than the one(s) you sacrificed for. So make a list! Write down all your priorities. I have such lists for all sorts of things. I consult a list when I want to decide what I should do to become a better developer. I also consult a list of things when I would like to furnish my bare apartment with. I consult a list when I'm trying to decide where to eat (I have prioritized a list of places I want to try). I tend to have lots and lots and lots of lists, all meant for a specific mood. I even have a list when I'm not in a particular mood! And it works. I find my top 10 choices laid out nicely and it's just a matter of maintaining that list and then acting on it when the time comes.

The reason this works is because we tend to forget lists like what we want out of life. We can't keep track of what to get on the way home from work as well as the 3 things we want to work on to become better devs. Something has to give, and we forget something in there. As well, lists can help you focus on a goal. Consulting a list is really taking the time to decide where to put your time (or money or whatever), and taking a couple seconds and thinking about a decision is typically a good idea. God knows I could make use of doing that more often :P

So make some lists! Get everything down and out, and get used to using the lists. Phones are a great place to stash lists, and there's some neat ways to share them with the people you need to.

Wednesday, 18 January 2012

Video: Introduction to WPF Templating


WPF templating is a method that you can use to create quick and easy modifications to your controls. This can allow you to style your controls in a new and fresh way or to modify behaviour. Whatever your reason, learning to template WPF controls will help you with your Silverlight, WPF, and WP7 apps!

Saturday, 7 January 2012

10 Tips To Lasting Longer (aka. "A Tale Of Two Stresses")

It's Saturday morning. I got up a tad early to write this. I might go back to bed or relax and watch a movie. I won't go work out, though. No siree, I am exhausted. My body aches, my brain is slow and tired, and my stomach demands food, even after eating before bed last night.

This is me after what I would consider my best week ever despite only being 4 days because of a holiday. My current client work is doing much better after I was able to implement most of our reporting solution in a single week. I wrote 3 blog posts this week. I booked two appointments for giving presentations. I scheduled appointments at the local school for interviewing potential co-op students (pretty much interns). This might not sound like a lot, but it's more than I've ever done in a week.

The most interesting thing about this week was that it was pretty much stress-free. When I say stress, I mean the kind of stress that keeps you up and night. That kind of stress is called "distress". It's stress that causes you problems. If put under enough of this stress, you will fail. It's guaranteed. You will start losing the ability to cope, and you will slowly become more unhappy. We've all been there. And really, when most people say "stress" they are referring to distress. They don't know any other kinds.

But there is another kind! I'm not sure where I first picked this up, but there is a type of stress called "eustress". Eustress is defined as (from Wikipedia):
...Stress that is healthy, or gives one a feeling of fulfillment or other positive feelings. Eustress is a process of exploring potential gains.
Sounds like something I want! Looking back on my week, it's really the kind of stress that dominated my week. Eustress is the kind of stress that comes from working hard at what you love. Sure, I was stressed. There was a lot being asked of me. But I loved every minute of my last week. Eventually, I would have to take a break or I would enter the realm of distress. But that's what weekends are for! And honestly, it happened as an accident. But I think I know how to duplicate it. Soon, you will too :)

So the first thing that kind of comes to mind is "why now?". Why is it that right at this moment I am thinking "Man, what a great week!"? Why didn't I think this before? The answer lies in that my "goal scope" (I call it that. Not a real term.) that I'm currently in. Now, let's rewind 6 months. I'm sitting down, probably winding down a project and getting ready for a new one. My goal at the time was to learn unit testing, continuous integration, and how to really architect an application. The reason? I was sick and tired of slogging through my own garbage code to write more garbage code. I had gotten the hang of client interaction and distilling requirements. Now it was time to make some headway and stop turning my days into "slog-fests" (Again, my own term. Probably not real.) and into what I imagined everyone else's day was. And I didn't fail. In fact, I think I did quite well.

But what happened in that time? In that resolution to produce better code, I inadvertently increased my goal scope. No longer was I worried about the next 4 hours of my day, I was going to start worrying about a full day at the least. Probably closer to 3 days. I had to. I couldn't succeed without it. My resolve to do better forced me to start thinking ahead a full day instead of to the end of this class file! As a result, my thinking was re-aligned. I stopped primarily worrying about little things (eg. whitespace and little style things on a one-man project) to bigger things (eg. how will my web service class file hold up when I need to add 2 methods a day?). It's not to say I no longer worried about the little things, it's just that when you start to realize that the web service decision will make more of an impact over the course of the project than the whitespace issue, you start to realize that lingering on a decision can be bad. The whitespace decision is small, and therefore requires a small of amount of time to make that decision.

Unfortunately, we can only worry about the whitespace on a small scale when we have bigger fish to fry. And those fish get much bigger! Today, whitespace becomes almost a non-thought when compared against the task of trying to bring a project in under budget or on time or, if you're really lucky, trying to do both. Now those are some issues! Worrying about whitespace suddenly becomes something that you never imagined could be so small. Yet, only 12 months ago, I found myself sitting at my desk and worrying about the whitespace like it was going to destroy the world tomorrow if I didn't make the right decision.

So I realized that as goal scope increases, my priorities start to become more realistic. If we follow this logic, we can find that learning how to worry about more aspects of a project turn us into better developers! In my developer space, a good developer isn't just someone who can write code. Pretty much anyone can do that. A good developer is someone who sees and thinks beyond just the code on the screen and immerses themselves in budget, team cohesiveness, architecture, maintainability, and the hundreds of other points that make a project a "good one". The best developer will be able to do this, and all he gets is eustress.

Words are nothing without action. Here's something to try: Find out what your bosses concerns are on this project. Is he stressing about budget? Timeline? Both?!? Make those problems your problems. You are a part of the larger picture of an organization, so figure out how to be the best part you can be. However, remember to chase what you love. Maybe you love budget. Go for it! Perhaps it's another aspect. Find an aspect about your project that gets your fired up and improve it. Next thing you know, you're the developer who knows how to fix the problems of aspect A, and that sounds an awful lot like your fun is part of your work :) Yeah, it might be stressful, but turning that distress into eustress will allow you to kill every project you touch simply by becoming the dev you want to be! Win-win-win-win

Thursday, 5 January 2012

The Great MVP Debacle of 2012

Latest thing in the news:


Rob Eisenberg made the post above. (tl;dr - Rob gave back his MVP designation after being denied despite his open source work, then made a blog post outlining his reasons. People reacted). I just wanted to take a second out of my day, go a tad off-topic, and make a response from the position of a developer that's still coming up in the IT world.

When I see this program and the points Rob made about it, I think we're seeing the same problem that plagues other areas like certifications, and that is that it's inherently difficult to judge the measure of a developer in a standardized way. The MVP appears to be geared towards a corporate mentality, not open source. Rob's contributions to the open source community are legitimate and are advancing .NET open source. But should we sit here and complain when MVP status isn't awarded? Not at all. We should applaud it! The reason is that the MVP program was never designed with open source in mind, and it while it claims to showcase the best and brightest in a specific technology, the MVP program is meant to gather feedback for the purposes of learning how to better serve customers, and Microsoft's development efforts have always leaned towards business applications. Rob's moving towards open source. I don't see the problem here...

Granted, there are some serious problems with the MVP award. But these problems aren't just the domain of the MVP award, they are problems we face all over the place! I blame letting too many people into any given program. MVP should be something difficult to get into, and we as a community should start stepping up and making the MVP program what we want. If people are being awarded MVP status when it's not appropriate, we should be letting Microsoft know and let them fix it. It's hard to do, man, and that's where the weakness lies. It's easier to sit back and let the MVP program crumble than to do the hard thing and risk hurting someone's feelings. But if those developers are any good, they will be welcoming the opportunity for feedback! So really, the key here is policing the MVP program ourselves. Let's take the power into our own hands. I can't imagine Microsoft would turn down an offer to help make the sweetest recognition program on the planet. Let's make that offer, because it seems like no one else is. 

We should all start blogging our experiences. Let's talk about it, and discuss it. Let's link to each other and provide a clear picture of the problems with the programs we are a part of, and then let's all sit down and talk solutions. I'll go first.

I mentioned before that I felt certifications were in the same boat as MVPs. Too many people, myself included, download a list of questions off the Internet to study for an exam. We sit there and memorize the questions, then walk in and pass with 980. Let's be honest: It's cheating. I didn't learn the concepts behind the questions I'm answering. Sometimes, I don't even know what the question is referring to! The exam's goal, to prove my knowledge of a technology stack, is completely missed. The 980 really becomes an indication that the exam questions, despite being under an NDA, are out there and are of very high quality. The time it's going to take me to complete an exam and ultimately a certification has gone from a couple months to just a few weeks.

I didn't used to do it this way. I don't think anyone really set out to make a certification program that rewarded the lazier people. But it ended up that way. I caved because I'm trying to balance my clients, my extra roles at work, my pet projects, my boss who's set a company goal of becoming a Gold Partner and my home life. That's tough! And that's not even considering where I want to go with my career. If I want to avoid locking myself into a vendor, things get twice as hard. Really, why wouldn't I take the easy road? It feels like everyone else is, and I have 53 other things I want to work on.

Obviously, this isn't a good way to do things, and continuing this pattern will only make things worse. I'm not going to profess I have every answer, but I have some ideas. I would start narrowing the scope of the MVP program, clearly laying out what's required to gain that status, then look at filling the gaps for things like open source work. Narrowing the scope and increasing difficulty will turn the program from a "diploma from a local college" status to a "Master's from Harvard".

I would also increase communication. It's entirely possible that Rob's post was the first inkling MS is getting that there's problems with MVPs. Combine this with the reality that there's always people talking smack about your ideas, and it's easy to get caught in this "No one seems to be happy, so we'll just keep going and eventually they will see the dream we are trying to achieve" mindset. I get that all the time myself. It's a great strength (the ability to blaze my own trails), but also a great weakness (I'm stubborn as heck). I think we need to listen to Microsoft and try to understand the pressures they are under. Only then will we be able to work together and make a better industry.

I've gone on long enough. Suffice it to say, this is a complex issue and neither side is wrong. We just need to calm down, listen to each other, and try to fix it.

I always like to leave with one thing to try and be better at, and I think it's this: Let's start asking for more difficult exams. If you waltz into an exam and ace it after studying for only a week, tell them! Take the survey and let them know just how much work you put into it. Use the feedback mechanisms supplied to let them know your dissatisfaction. It will sting for a bit if it works, but we won't be stuck in a rut.

Wednesday, 4 January 2012

Using StackOverflow Like A Boss

By now, I'm sure you've stumbled upon StackOverflow, SuperUser, or any of the other various StackExchange network sites. If you haven't, take a couple minutes and check all 3 links out if you already haven't. The Q&A format is very effective, and the StackExchange network takes it to an entirely different level.

Approaching these sites as simple Q&A sites is a great way to get value right now. Questions are answered pretty quickly, and the audience is gigantic. Some of the more obscure questions are posted that can really add to your own knowledge base, and there are lots of more general questions that can really shed light on getting started with a particular topic.

However, I find the most value is derived from digging into what makes these sites unique, and leveraging those features. In this post, I want to go over some of the features you may not have seen before, and I want to show you the approach I feel has given me the most bang for my buck (even though it's free, I'm spending time, which means as I get more value from my time, the value of my time increases).

When StackOverflow (SO) was newer, it was a great site to go to, since you has a pretty good chance of answering a tough question and getting some of that almightly reputation. However, as the site's traffic increased, it's become a race to answer questions quickly in order to secure the first answer the asker will typically see. Honestly, though, the race isn't what you should be focused on. If reputation solely determined your worth as a developer, then yeah, I'd go for it. However, it's never that simple. You're out for the knowledge, not the rep. Ironically, though, it's once you start chasing the knowledge and helping others do so that you'll find yourself rep rollin'. A look at the habits of the top members shows clear, concise answers that others will upvote above the first post. If your answer is crap, then SO will let you know by downvoting you to oblivion. But at this point, you've just been shown a blind spot in your own learning, and now you have something to learn! Win-win, baby!

Probably the greatest thing I have come to embrace about SO is that you can just throw answers out. You can post as many comments as you want! Stumble upon a question that's not totally clear? Ask! Have a quick comment to make? Make it! If you're right, people will probably tell you, and if you're wrong, people will go out of their way to make sure you know it ;). But that's really what being a developer is all about, right? It's not necessarily about being 100% correct, it's about learning what tools are out there and the best situations to use them.

So bring the downvotes! Bring the criticisms! Tell me where I'm wrong, and through the haze of being called a n00b and the -1's, I know there's a better me-as-a-developer waiting to be unleashed, and someday I will be able to return the favor, and that, my friends, sounds like an IT future that I can get excited about being a part of.

Tuesday, 3 January 2012

Making Ideas

I'm sitting here, struggling to find a topic to write about. So I decided to write about thinking up ideas! I think coming up with ideas is a skill that, in today's hustle-and-bustle world, is getting lost. Ideas are becoming a premium commodity, with people making idea generation into a career. Here's my take on making ideas, and why it's becoming even more important to make sure that you are able to come up with ideas when you need them.

Probably the thing I hear the most from others about idea generation is this:

"I can't just sit down and make up ideas, I need to let them come to me. Chasing ideas will just scare them away"

Most people agree, nod their heads, and move on with their day, waiting for that one great idea to descend from the heavens and solve their current problem. And more often than not, the clouds do not open and no ancient knowledge is bestowed upon them and the day becomes just another day where you struggle to solve a particular problem and end up with a decent solution to it.

But you're not a decent developer, you're a superstar! You need superstar ideas to go with your superstar skills. And superstar ideas are never generated in middle-of-the-road conditions. As master of your own destiny, it is your responsibility to make those conditions a reality. If they already are your reality, then you can always do better. Perhaps you just need a superstar idea to help create superstar conditions. Yes, that's it! I'll just think of a great idea and that will start the ball rolling, right? You probably hate me right now, and I'm fine with that. I would encourage you to keep reading, though, and bear with my catch-22 jerk opinions for just a little bit longer...

In my experience, ideas are hardly ever one big package. If there's one thing I am learning, it's that the small stuff is where the action's at, and it's important to listen to the little ideas as much as the big ones. Big ideas are really a collection of small ideas, so start small and move up. Starting small is easier than starting big, too. Small ideas come from small things, so let's figure out how to find the small ideas. It's easier than you think!

As a developer, when I find a problem, I hit Google. I will search and try to find the solution I want. However, sometimes the stuff I find isn't what I want, so it's time to make my own. My first thought is always "I know the solution that exists inside the box, but I want a solution that's outside of the box". I come up with 3 or 4 things that would be better than the in-the-box solution, then I sit down and think. I just think. Sometimes 5 minutes, sometimes 30. But I just sit and think, and most importantly:

I dream

I dream of classes and how I might structure them. I dream of features that would make my life easier, I dream of things that would "wow" my client. I think up ways to implement my new feature, and how it would fit in with the rest of my application. I dream of what I could change in the rest of the app to make this task easier. I dream all this up, and then I decideI don't always pick my own solutions. Sometimes, I go back to Google and keep searching for a solution. Sometimes I use a hybrid of Internet code and my own. Sometimes I just put that task in limbo and move on, waiting for later so I can think about the solution. But I always try to make a decision within a decent amount of time. After a couple of hours dreaming and thinking, there isn't a whole lot that can happen to influence your decision. You gotta move on it and prevent that task from becoming a constant reminder of something you really should tackle.

Of course, there are obstacles. I find my biggest one is fear. I get scared to try something new, or to attempt my own solution. Sometimes I find myself scared of changing something for fear of breaking something else. Every once in a while, I get scared of investing time and coming up with nothing. But I can tell you one thing: None of these fears get things finished. So tackle them and move on.

More often than not, you need to overcome an obstacle that isn't in you. But these obstacles are overcome in what some might consider an anti-climactic way: dreaming up solutions. Dream up the fixes to the problems that prevent you from dreaming. This is really just as simple as asking:

"If I could change one thing about my immediate surroundings to make myself more comfortable and therefore conducive to dreaming, what would that be?"

Of course, easier said than done, but we just apply the concept we learned before, and that is to remember that big steps are really just small steps that complement each other. In other words, think of something small you can do right now and do it. Turn on some music, or stand up, or sit down, or go running, or dress up like a clown go shopping. The more you enjoy it, the better it probably is.

Once you get this process down, you'll find you imagine bigger and better things. You imagination muscle will be getting bigger and bigger. Fancier solutions, more elaborate features, even more cool components. On and on you need to go. Keep dreaming. Dream of solutions to problems that aren't related to development. Think up solutions to other people's problems. Think up solutions to problems you know you're never going to solve. Think up elaborate solutions to simple problems. The point?

Keep dreaming. Never stop.


Some day, you'll wake up and realize that you are a factory of great ideas. They flow from you, and you almost dream without effort. Every idea you have is steeped in the same tea that makes the rest of your ideas great ones, made of other great ideas to make something greater than the sum. They will interconnect. You will start to see opportunities and have ideas that include several of the skills you possess, development-related or not.

And that's when you will realize that you have superstar ideas, worthy of your superstar talents. And superstars tend to gravitate together, bringing you together with other superstars with other superstar talents and their superstar ideas. And if you thought it was great to take great ideas to make superstar ideas, imagine taking superstar ideas to make... well, ultra-superstar ideas! Those fit together like Power Rangers to make something that stretches minds and changes the world.

Still mad at me for the catch-22 stuff? The same catch-22 that will trap you will make you the best.


Have fun dreaming!