It’s truly a pleasure to announce that as of Friday last week I am a published Pluralsight Author! The course that I published is called MSIL for the C# Developer, read more about it at the end of this post. There’s been some radio silence on the blog lately, it’s mostly due to a lot of effort that has gone into the production of the newly released course and also our move to Australia.
Win a Pluralsight Annual Plus Subscription
To celebrate that I just published my course I’m raffling away the following:
Pluralsight One Year Annual Plus Subscription + Signed copy of C# Smorgasbord + C# Smorgasbord Shirt
2 Signed copies of C# Smorgasbord
3 digital copies of C# Smorgasbord
How do I win?
It’s Simple!
Leave a comment on the blog telling me Why you should win a one year subscription for Pluralsight and why you’d like to see my course. A bonus is if you tell me why you also want to read my book!
Last but not least, share this post in your social medias! Tweet it!
Raffle ends on Wednesday June 26th 18.00 CEST
What’s the course about?
In this course we look at MSIL; the code that is generated when you compile C#. We explore MSIL so that you get a better understanding of how C# works and how it is compiled. Ultimately after completing the course you will feel like a better C# developer as you will know much more about what happens behind the scenes when we compile our C# applications.
Recently I came across a problem where I wanted to allow combinations of a certain criteria so I immediately thought of bit bit fields. This lead me to an interesting answer on StackOverflow for a question on how to use the FlagsAttribute with Enums.
What I mean about combinations of certain criteria is that let us say that we have a set of colors and I’d like to define that my pants have more than one color. Then somewhere in my application I’d like to check whether or not the pants had a certain color or not. This could of course be solved in many different ways. One other way could be to just store a collection of colors on the pants class. That would however make this article less fun. So let’s take a look at how to use bit flags. Both the answer on SO and the link to FlagsAttribute above which has some examples use colors for their demonstrations, this is because it’s a very common and easy scenario.
Let’s say that we define RGB, Red, Green and Blue by using bits. This could mean that we have three colors with bit representations as followed:
Now let’s say that we have all colors together, that means that we have the following bits:
Red, Green and Blue added together! So why does this matter? If you don’t know your bits and bytes it’s going to be quite difficult to understand. There’s an older article that I’ve written about bits and bytes, check that out if this is all Greek to you!
As you see it just “added” the bits together, but how do we do this in C# then? It looks “so easy” on paper! First we need to fine an enumerator for this.
[Flags] enum Colors {
Black =0,
Red =1,
Green =2,
Blue =4 }
If you’ve peeked at the StackOverflow answer linked above, you might already know that using the attribute Flags doesn’t do anything at all. Except it’s handy if we use reflection and it changes the output when we print the value.
Now, how do we use this enum? It’s also easier than you might think!
By using something called “OR” we can add values together and get a nice bit representation. OR is written with a single | like this:
Colors color = Colors.Red| Colors.Green| Colors.Blue;
The value of color will now be 7. Why? If you add the numbers together in the figure which shows the bit representation of Red + Green + Blue, you’ll see that you will get the value 7!
If we go back to the original “Problem” now, how do we check if a certain color exists in this bit representation of colors? Let’s talk a bit about OR first. What OR does is that it checks two bit representations and once a 1 occurs, a 1 is set in the result. That might sound confusing. So let’s say that we have 0001 | 0010 the result of this would be 0011. So the 1 is dominating here, if there’s a 1 in either of the two bit representations that you are “OR”-ing then there’s going to be a 1 at that bit in the result.
As there’s something called OR, there’s most likely something called AND, right? There sure is! That however works a bit different it checks if there’s a 1 in both representations. AND is written with a single & and you use it pretty much like OR. So if we use AND on the following 0001 | 0011 the result would be 0001 because the first bit is the only one that has a 1 in both the representations.
Now you might have already jumped the gun and figured out how to find out if one color occurs in the combination of colors however I’ll just expect that you haven’t! It’s quite easy though when you think about it for a while. If you can use AND to “filter” out everything that is not exactly as the representation that you want, then you can probably use this to check if there’s an occurrence of our bits!
So let us say that we have all the colors 0111 now if we AND this with the color red, which is represented with 0001 the result of this AND operation will be 0001 and thus we found the color red! In C# this would look like this:
var hasRedColor =(color & Colors.Red)== Colors.Red;
As of .NET 4 you can also use Enum.HasFlag which work like this:
if(color.HasFlag(Colors.Blue)) {
Console.WriteLine("Oh Hai there Blue!"); }
Here’s a more complete example of how you can play around with this:
class Program { [Flags] enum Colors {
Black =0,
Red =1,
Green =2,
Blue =4 } staticvoid Main(string[] args) {
Colors color = Colors.Red| Colors.Green| Colors.Blue;
if((color & Colors.Red)== Colors.Red) {
Console.WriteLine("Oh hai Red"); } if((color & Colors.Green)== Colors.Green) {
Console.WriteLine("Oh hai Green"); } if((color & Colors.Blue)== Colors.Blue) {
Console.WriteLine("Oh hai Blue"); }
This post is in a more personal manner than what you might be used to from this blog so if you’re just interested in lines of code you can stop reading now.
In 2006 I had my eyes on working abroad and thus I figured that in order to do this I needed to at least have a bachelor degree in Software Engineering. Now 7 years later I’ve had my bachelor degree for a while and I’ve gathered a lot of experience along the way; but what I have not done so far is work abroad.
While there are a lot of interesting things happening in my professional life and in my personal life with my lovely fiancée Sofie, there’s still something that I feel I want to do.
If you’ve missed it, I was recently accepted as a Pluralsight author and my first course is in the works and is going to be about MSIL for the C# Developer. I’m truly honored to do this and I’m really looking forward to getting this out there to all of you.
However, over the years a lot of things have changed. I met my better half and the things that I had previously prioritized changed and the dreams about working abroad were put aside. Now both I and Sofie are in a place in life where we feel that we want to try something completely different. I’m really happy to announce that Sofie and I will share the dream that I once had, which was the fundament of me studying for my bachelor degree; we’re moving to Sydney.
I was offered a position as a senior developer at Readify in Australia and the company is completely in line with what I value and they work exactly as I want. It’s going to be a great experience and I hope that I will meet a lot of new friends and get a lot of new knowledge.
We are both really excited about this opportunity and we are certain this is going to be a blast.
We are moving towards a new era where more and more people want to offer the possibility to expand the system with widgets and plugins. By utilizing Compilation as a Service can make it easier for all parties to create plug-ins. For instance operations performed at certain events in an application.Roslyn exposes a C # and VB.NET compiler and we can use this to implement something along those lines. Listen to me give an introductory talk about what Roslyn has to offer and how we can use Compilation as a Service to enable the next level of plugins.
Check out my talk from dotnetConf on the subject and let me know if you’ve got any cool ideas on how to utilize compilation as a service (Roslyn).
The following article is an article that I wrote duing my studies for a bachelor degree in Software Engineering. Minor changes might have been made to make it more suitable on this website. It was originally posted on my old blog in 2008 but have now been re-processed.
Both my experience and writing style has changed since I wrote this article, but I still want to share my thoughts from 5 years ago.
Let me know how you prefer teaching others and how you prefer to learn!
A teacher knows that there are no straight answers on how to teach. There are multiple ways giving people new information and helping them adapt this in their current work. One of the preferred learning method by me is the Problem Based Learning, I will take up more about this in the upcoming topics. It’s also very important to take the age of the student in mind, how do they actually see on you as a teacher and does your and their age really matter?
Introduction
By passing on knowledge to new generations we somewhat evolve into a new and different kind life form. This not being as deep as it sounds, every day we somehow pass knowledge to someone. It might be the neighbor, a child, a sibling, a parent or anyone else for that matter.
The important thing to remember is that all new or old knowledge is dangerously important to pass on to those concerned. There are a million ways of teaching something, not all of them are good and not all of them are bad, being old or being young doesn’t matter, all the age gives us is perspective and understanding of how to pass on knowledge and whom to give it to.
By viewing the aspects of teaching, who needs to know what to be able to survive, complete a task or just continue living their life. Of what importance is all the facts, does one give the window of failure or does one give all the fact so that there is nothing left to learn?
Different generations
This might actually be a sensitive spot to touch, but I’ll be short in these words. There is actually a big difference between teaching 2 different generations. Imagine having a student which was born somewhere around 1960 and a student who was born 1980, depending on the age of the student and the age of the teacher, both these persons will take the information in two whole different ways.
If we would’ve taken me as a teacher example, I’m born 1987 which makes me not very old for being a teacher. Some of my students today are actually a lot older than me, which might give in to complications.
The different generations doesn’t only differ in age but in the attitude and the way of learning. A person born in the 1960:ies might have a harder time actually learning new things than someone born in the 1980, this is because, when this text was written it was the year 2008 which makes someone born in the late 1980:ies somewhere around 20 – 25. In this age, you have much easier to learn and take in new information.
Now this does of course not mean that someone born in the 1960:ies is stupid, rather that there are a big different and when teaching a group with a lot of different generations, this has to be taken into mind when planning a course.
Take another example such as a work place where your co-workers are much older, being young you rarely have anything to say on a work place where the stuff have been done in a certain way for very long.
So when trying to teach an older co-worker, you really need to sell the new information so that the older generation will be more interested.
But going back to the topic of teaching in a class room, it might be a benefit of being older, because older generations have much easier to focus and having a different mindset which will help them succeed.
It’s very important to respect each other, despite the age difference, if a younger person knows something that the older one doesn’t, it’s very important that the senior gives the younger person a chance to actually come forth and tell the information, that might in fact help production or whatever the work space might need.
Teaching differentials
There are a lot of different ways of teaching and what should be kept in mind when talking about different methods and where they apply is that everyone is different. I might not find it as amusing as you would, if I were forced to be taught with the old style teaching methods.
Thus, as stated in the upcoming topics, there are benefits of the both methods and there are of course a lot more out there, but the ones that you mostly see in action, would be these two.
Problem Based Learning
I would certainly say that PBL; Problem Based Learning, is my favorite method of learning. Ever since high school this has been a method that I’ve worked with.
The principles are that a student is given an assignment and there are known factors of failure which will somehow help the student learn what is necessary. After working with the problem for an amount of time, the solution will somewhat appear and the student has learnt something new.
There’s also another aspect of this, or rather, another explanation. Let’s take implementation of the sorting algorithm quicksort as an example. This is a fairly hard algorithm to master and it requires some base knowledge in the field. So when given this assignment, the first obvious part from the teachers perspective is that the student will somehow search for information about the algorithm.
Using internet or a special course literature, both should work very well. This gives the student an opportunity to master this assignment on his or hers own means.
When all the information is collected and the next phase in the learning process begins, which in a programming line of work would be to put up a structure of your software, in this case the software won’t be huge but having a pattern when working is always good, no matter the size.
As a result of this method, the student will have taught him or herself something new and by the individuals own needs.
Old Style Learning
As a matter of fact, the “Old style” in from my point of view might not be what you would suggest as an older style. And I am not talking about the old school tutoring where the teachers would be rude and make students learn by force and learn by fear.
In my eyes the old style would be where all the answers are somewhat given and there is no room for self teaching or in any way, a path given where the student can choose to learn just what is needed or learn so much more.
This old style can be seen at many high schools throughout, in my experience, Sweden. Now, the old style, what exactly defines this and are there any benefits? Well to start off, the old style learning method is where the students are put down at a desk, everyone directed to a whiteboard, and the teacher is using a pattern of teaching, where the pattern repeats itself. The old style pattern is when the teacher enters the room, greets the students, and starts talking and then when a question is stated an answer will be provided directly.
Now this point of view might be a little bit dull and it certainly has its good parts, they are just somewhat harder to find than the good ones in a problem based situation.
We have to keep in mind that everyone learns differently and that it’s important to give everyone what is needed to succeed. Thus, this method works in some cases but I would say that it wouldn’t work in most cases.
A benefit of the problem based learning system which the old one lacks is that you give a broader room for questions and thoughts and it’s fair to say that it requires a totally different mindset and maturity.
Which is best?
Giving an answer to that question would be somewhat impossible. Just not because everyone differs from each other so much, but in some situations I would also prefer to be tutored using the old style method.
The assignment stated in the PBL-example a couple of words back is a great example of how you can absorb new technology and new point of views. Programming itself is very broad and there are hardly any similar solutions out there. And the quicksort implementation sure is a defined structured algorithm but it can be implemented in so many different ways, it doesn’t matter if there are fewer rows or more rows, and they are just all different.
Which in the end would make you to consider how others are implementing it, what are the benefits?
Using the old style method, the tutor would just present some ways of implementing it and not giving you as a coder any room for own thoughts. A teaching method is always abstract in my eyes, you can’t tell someone to just go with a method, because “implementing” PBL differs from time to time.
Team work is important
You might think “What does Team work has to do with everything?”; Well actually team work has everything to do with learning. By being a tutor on various programming sections I’ve reached to the conclusion that team work is the most important part of learning and teaching. Now, team work isn’t all important only in the case of teacher to student teaching. This is also very important when we talk about teaching in a workspace.
Since I generally work as a programmer, the examples of programming workspaces suits me the best, so here goes. Imagine having a workspace where there are 10 – 20 developers, 5 graphical interface programmers and a couple of designers. These all parts need to co-operate for the development to work. If some of the staff has knowledge that someone else doesn’t, it’s very important that if this knowledge will help the company produce more, then this person needs to convey this to the rest of the staff. This is where the team work is important, if someone on the staff feels insecure with conveying the knowledge; this person is probably not right for the position.
I always say that when I work somewhere, I don’t want to be the brightest and the person with the most experience, this is because I want to learn, learning is very important and knowledge is worth a lot.
And if you’d come to a workspace where people is unwilling to co-operate, sure this workspace lacks team work and this will be disadvantage when you want to learn and grow professionally.
Sharing is caring
Not only does sharing rime with caring but it goes very much hand in hand, almost every time that is. In this case, sharing knowledge to your co-workers, students and family is very important. Especially when you work as a teacher, the sharing part is not only important but it’s a factor for you, keeping this job.
I’ve met teachers who felt threatened by me as a somewhat quick learner and bright student, not to sound too self-righteous this was actually a problem for me when I went to high school. I had teachers that, somehow, felt threatened by my knowledge and therefore didn’t want to share new knowledge with me.
This is a dangerous way for thinking and teaching, you always need to take the student, no matter if it’s a coworker or an actually school student, you always have to see the people you are tutoring new things, to be your student.
And a student is to be handled with care; your personality will in the end reflect in this student and will show everyone, how good of a teacher you are. Of course some people like to learn themselves, but, put your mind around this, initially how do you give someone inspiration? It’s by showing the person what skills you have and maybe how you’d do some things.
Sharing knowledge is in the end a vital factor for evolution, what if Einstein or other important people for our evolution, wouldn’t share their findings? How would this affect our current living environment and our current ways for thinking?
Feeding answers is dangerous
However, when sharing information it’s very important that you do this correctly. As mentioned in the previous chapter, all people learn differently. This is probably one of the hardest parts by being a teacher; you need to find a common spot which almost all students like.
Of course this is often impossible, thus there are more than one path to take and there are almost always presented two or more ways for the students.
One important thing to always keep in mind is that you can never ever just give out an answer to a question without somehow providing a solid explanation or a proof why it works.
Why you might ask, this is because when being a student, you are almost certain to always take the easiest path and not thinking clearly about consequences. By being spoon feed you will never really care about how or why the solution is what it is.
And being a programming tutor, this part is very important, what if I were to give all the students the correct answers to all assignments, and tell them “Here are the answers, go find out why”. Maybe a couple of percent would actually find out why the answers are as followed but the majority wouldn’t. So to keep in mind is that when a solution is presented, always give out a good and pedagogic explanation to why.
This topic actually doesn’t just apply to students, it’s also very important not to just give co-workers the answer and let them be happy about it. I know that sometimes I just want a quick answer, but when I actually encounter the problem the second time, and not knowing how to solve it, I regret not doing more research the last time.
Giving inspiration not motivation
Not to feed answers and giving inspiration is actually something that we can see go hand in hand. When you actually want to teach someone something you want to give the person inspiration and give them the mindset of wanting to learn.
So why wouldn’t you want to give someone motivation? Motivation isn’t something that can just be handed out, actually motivation is something that I would say comes hand in hand with inspiration, when someone is inspired, the motivation might peek and giving coworkers and students inspiration on a regular basis might in fact help the persons succeed and somehow indirect force them to teach themselves.
When open source helps programming tutors
Talking about open source could be a completely separate paper and take up many pages of explaining why this is a good way of learning and working. First of all, what is open source? Open source is a way for providing your product open and free, not only the software itself but also the source code, which defines the business logic, the graphical programming and other aspects of the program. This is a definition from Google on open source:
A program in which the source code is available to the general public for use and/or modification from its original design free of charge.
This is actually interesting, companies, people and organizations giving out their source code for free, so how does this actually help a learning process? Well for starters, there are software available for development and making office work more easy and there are so many softwares out there that can and will help you learn new ways.
The topic on open source now is very programming tutoring oriented and might not really be of interest if you work in a construction site. But think of it like this, what if there were some free ways to actually make your construction work easier?
When teaching programming we often come to points where we do reference an open source project, Linux is one of those; Linux is a kernel for the GNU / Linux operative system. This kernel has from the start been open source and the community which uses it has always been very helpful and made this a better product.
Now, working on a project like linux might not be very easy, but it does in fact give you knowledge, this is an very important time to take up that you always have space for new knowledge and you are never too old to be learning new things.
Programming on linux or any other open source projects might require that you actually have some experience from the start but you will also gain so much from being a part of this process.
The following article is an article that I wrote duing my studies for a bachelor degree in Software Engineering. Minor changes might have been made to make it more suitable on this website.
Both my experience and writing style has changed since I wrote this article, but I still want to share my thoughts from 4 years ago.
Let me know in the comments below what your most common project startup difficulties have been!
Abstract
There are a lot of usual suspects in the terms of risks, problems and other aspects of failure that you need to take in mind, worry less about the customer and more about the communication. This is highly important for success; you must find your way of communicating.
Be prepared; There will be problems
In the writing moment of 2009 I am currently in a development project of which I have the benefits of being System Architect. Having this position in a project is not something that is totally new to me; in 2008 I had the same benefit.
This experience of mine will be used as a reference point, so keep in mind that my points of view is not strictly from a developers eyes. Being the System Architect you have a lot of responsibility such as keeping track of each developers work process, extending each person’s views of the project and being a leader which never falls apart.
Starting a project, not just development projects but generally speaking you face a lot of common problems; team-work issues, financial issues, third-parties, customer issues and many more. I will not focus on the financial issues because the project we current work on is strictly, as they would say in the world of lawyers, pro bono; which is what we mortals would call free.
So not having to worry about the financial problems, we can focus more on the other areas, which in my eyes actually does cause problems and have as it does in many cases, caused problems in our project. Problems don’t always mean that the project fails or that everything falls apart, it just means that we have something to handle. We also have problems that are planned or more likely anticipated more than planned; a planned problem would be fixed before it became an issue.
The usual suspects
As mentioned in the previous part there are a couple of problems that you might anticipate in your project. There is no common solution that’s widely used on all projects. As a lot of other things in this world; things are different depending on the situation. This is the case of projects as well. I will merely give an overview of what could be expected and how I would like them to be handled.
Team-work issues
Reflect over the following; is there anything like perfect team-work? I once said: Team-work comes from willing to cooperate it is not something that can be forced. It doesn’t matter how different you are; as far as we know, everyone is different. I would like to say something like: just work together, what is the problem?
However that statement is bold and doesn’t apply to reality. As mentioned earlier I work in a project, the project consists of 9 other developers where 7 of them are security experts and two of them are, just as me, software engineers. If you look closely enough you can see that there are a couple of things on both sides that resemble a similarity. The security experts have one way of solving problems and the engineers have another, what we need to achieve here is a common ground of both problem solving and the way of communicating.
Our project started out great, there were no direct flaws in the team-work, all parties liked to work together and we solved communication and other future problems very fast. However, as the project has evolved so has the teamwork, but has it evolved enough? As there is no direct answer to that, I can only speculate on the different outcome of today’s progress if we would’ve evolved more with the project.
As of the beginning, there were no issues with the team-work, we did not even argue about small things which can be a big problem in many projects. However as everything evolved and third-party problems came in place, we did come to the stage where we had to raise voices and stand ground.
Not all projects start out with a nearly perfect chemistry between its participants. And maybe it would be for the better to argue it all out in the beginning, finding all these communicational problems from the start and work from there? The outcome from our project is that you start to take things for granted, which is a dangerous path to take.
Customer related issues
The first thing that really comes in mind when I write “Customer related issues” is a direct link to money. No matter how you bend on in, when it comes to the customer, it’s always a matter of money. As for our project, this is somewhat a problem as well. Now, you might recall that this project is what we call it “pro bono”; free; gratis. So, what could possible be customer related that has to do with money? Well in our case the customer buys hardware for us, which they want to be further developed, this hardware is in a development stage and therefore not well documented. This means that we need to contact the producer of the product to get information. However, the producer being one of the world’s biggest companies; they do know when to ask for money.
Now this gives us a big problem, since the project doesn’t have any revenue we can’t afford this, so we need to ask our customer to pay for this. This results in a great problem;
The customer places an order
The customer expects everything to be done according to plan
The customer is expecting everything free of charge
Now, the last two stated points above in the work-flow is where our problem is. Is there a solution to this? The project could be delayed, we could be put up in a workpool for other projects to gather resources from meanwhile the producer evolves the product and set up a proper documentation for it. However, we don’t have that time, so what has to be done is either brute-forcing the system gathering all information possible to solve it, or we ask the customer to pay for the education needed by the producer.
In our case the customer actually paid for this education, because this product is very important and scheduled to be delivered and sold after the summer 2009.
There are however a lot of problems not related directly to money, you can see these other problems a lot in the IT Consulting business where I usually work;
Non-cooperative customers
The all-knowing customer
The non-paying customer
The customer who says one thing and the customer who wants something else
I’m going to state something that many would disagree on; never trust the customer. You might get a surprised face when reading that, but in fact you should trust anyone than yourself; if you can even do that.
Now this is becoming fairly abstract but stay with me on this. If you really think about it, if you start trusting people you suddenly start relying on others to do what they say, always assume people are going to be late and if the customer says “How long will x take to develop?”; The first ting you need to think about is, does it take T hours? Does it take T – 100 hours? What’s the most accurate time? Before you say that, add a factor of 2. So, why add the factor of 2? Because you always over-estimate your skills, you might think that it takes 10 hours, but it takes 20 hours or even thirty hours. If you over-estimated and said for instance 50 hours, and it took only 25, your customer will be very satisfied. But if I take 100 hours and you said 50, you will have a big customer problem.
Managing the Team to avoid these problems
A great leader is one that makes the workers think they are doing everything that will benefit themselves. In my eyes a project manager is, or should be, very much like a great dictator; A great leader. If you were to revise the book The Deadline3 you would see how they speak of their mangers and what really makes a good project manager. Some of the points that you would consider is:
The co-workers speaks well of you
You are considerably good at understanding people
Not scared of taking chances
Risk your job every day
As a project manager you might need to risk your job every day, this meaning that you must do things that will benefit the group or the project in longer terms but might not be so good for yourself in the current situation. Managing a software project is just a game of risk management, if you were to find all casual risks and manage them, what else would there be to worry about?
Deadlocking is really something you need to avoid and in case you don’t know what a deadlock is here’s a great illustration of a “real life deadlock”:
Basically what has happened here is that all the roads are full with cars and all the cars try to cross the road at the same time. Let’s translate this into computer terms; the cars in this case are the threads and the cross-over is the “thing” that handles these threads. In the illustration above all the cars have driven into the cross-over at the same time and they can’t really back up, hence there’s a deadlock and there’s no way to go.
What happens in a computer program when you get a deadlock is that it freezes and there’s no where to go because all paths are occupied or waiting for something to finish. Let’s say that process X waits for process Y and process Y waits for process X and both of these lock up the GUI thread, this means that the application will die. Hence deadlocking is something you want to avoid.
Normally you solve this by introducing locking and semaphores. As discussed in the article linked above (where I got the very nice illustration) a semaphore can be seen as a traffic light which handles how the cross-over is loaded with cars.
A while back I wrote an article called “Avoid shooting yourself in the foot with Tasks and Async”, I suggest that you should always return a Task from your asynchronous methods and you really should. What I am about to tell you below though is what you should avoid when doing this.
When a method is marked as asynchronous and the await-part is reached, the method will “exit” and return the “awaiting Task“, which means it’s not the Task that runs inside the method but in fact a Task that keeps track of the status of the asynchronous operation.
Let’s look at a basic code sample!
Consider that you have the following basic asynchronous method, all it does is that it waits for 2 seconds and then prints something to the debug window:
private async Task RunAsync() {
var run = Task.Factory.StartNew(()=>{
Thread.Sleep(2000); });
await run;
Debug.WriteLine("Execution done!"); }
Once await is reached, what will happen? A Task will be returned, but which one? Not the one named run! A Task that keeps track on the state machine will be returned.
Now what happens if we call this method on the GUI thread and asks to wait for it to finish? Calling Wait freezes the current thread and since we are on the GUI thread this will freeze the GUI thread, but for how long? When is Wait happy enough to proceed? In fact it will wait for the asynchronous task that handles the state machine to give it a signal that it’s now ready.
However that Task can never be marked as done until the entire method has been completed. Which means that it needs to access the GUI thread again, since we’re back on the calling thread (GUI thread in this case) after await!
This means that all we have to do in order to deadlock is this:
RunAsync().Wait();
I hope that makes sense to you and gives you an insight into what really happens when you use async and await. As with everything: use it wisely and know what it is that you’re doing.
Over and over again I see developers re-implementing error tracking, I’ve been there myself. One of the reasons to this I think is because many of the tracking tools out there add too much noise and are just cumbersome to use. In many cases the biggest problem is that you need error logging too late, meaning that you want the logging once the error has already occurred. It’s of course cleaver to say that you should always think about potential errors from the start, because let’s face it we all write applications that may have unexpected exceptions.
Another problem is that if we do decide to log errors in our applications, where do we store them and how do we collect the logs? Luckily there’s tools out there that can help us on the way. One that I most recently came across called Raygun. Raygun is a product from the company Mindscape that have some very interesting products in their family.
Error handling just got awesome!
The punch line of Raygun is quoted above, a tool that makes error handling awesome. Let’s clear something up right before we take a look at Raygun , there are multiple providers supplied for Raygun: JavaScript, .NET, Java, PHP and Cold Fusion. Didn’t find the language you work with? Don’t worry, there’s a REST API for you RESTafarians!
So there are providers for Raygun, but what does it actually do?
Imagine that you have your web application written in PHP, ASP.NET or just something that is using JavaScript. Now you want some centralized place where you can store errors in either of these applications, be it severe exceptions or just notices about something unexpected.
If you’ve found yourself writing an error tracker where you just dump the Stack Trace and the exception message into a database, then this is certainly something for you. Imagine that if your customer calls up and says that he recently got the yellow screen of death but don’t know what he was doing or really exactly what time it was.
Now imagine that you were to access your centralized error tracker and you’d have all of the information that you would need to find the error in the code base including:
Time of error
How many times the current error have occurred
Information about the system the user is using
The exception message
A Stack Trace
That is Raygun! A way to track your errors in a very easy way and the presentation is just beautiful.
The information you’ll get out of each error report of course depends on the data that you supply Raygun with. Take a look at the REST API to get an idea of all the data that you possibly could supply Raygun with.
Enough with what, let’s look at the how! Let’s look at some code!
For this demo I’m going to setup 2 things an ASP.NET MVC 4 Application and a Class Library that will simulate a data store where I can search for people. The web front will allow me to search for people inside my collection and when I wrote this example Raygun actually helped me detect one of the errors I were getting, let’s call this “TrackCeption”.
First of all let’s look at the library. There’s a very easy class that represents the person, it simply has a property called “Name” inside it.
publicclass Person { publicstring Name { get; set;} }
Secondly there’s a class that handles the search requests, I call this RequestHandler. To set this up we need to create a new list of people, in this case it’s just going to be a static collection of people as you can see here:
privatestatic IEnumerable<Person> _people; public RequestHandler() {
_people =new Person[]{ new Person { Name ="Filip"}, new Person { Name ="Sofie"}, new Person { Name ="Johan"}, new Person { Name ="Anna"}, }; }
Now we need a way to retrieve all these people and I like creating asynchronous methods where the operations might be time consuming and in this case I know that it will take 2 seconds to retrieve the list of people:
public Task<IEnumerable<Person>> GetPeopleAsync() { return Task<IEnumerable<Person>>.Factory.StartNew(()=>{
Thread.Sleep(2000);
return _people; }); }
This leaves us with implementing a method that lets us search for people in the collection. So far we don’t care if the list has been empty or not but when we search we want to report an error when there’s no people in the list. Let’s just assume that this is an exception in the application and the end user will always search for people that are in the list.
Let’s install Raygun!
Installing Raygun is as easy as saying “I’ll soon blast all my errors with this Raygun!”; simply bring up the NuGet package manager and write the following:
PM> Install-Package Mindscape.Raygun4Net
This will install Raygun into your class library! There’s a couple of more things that we need to do in order to get Raygun up and running:
Creating a Raygun account is free for 30 days and you’ll need to do it in order to start tracking your errors. Once you’ve setup an application on Raygun you can retrieve the API Key from the “Application Settings” menu like you can see in the following image:
We don’t need to add the API Key just yet, we’ll add that in the application configuration file of the project that will use our library later on (in this case the MVC 4 project).
Now, bringing in Raygun into our application using NuGet will allow us to write the following:
new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name)));
That will create a Raygun client and send a new exception with the message you can see to the Raygun servers and passing it the API Key that we will provide later on. So let’s take a look at how the method that will find people in the colleciton will look like. This one also takes 2 seconds to execute so we will have this one asynchronous as well, we don’t need to do it but I take every chance I got to play with asynchronous programming.
public Task<IEnumerable<Person>> FindPeopleAsync(string name) { return Task<IEnumerable<Person>>.Factory.StartNew(()=> {
Thread.Sleep(2000);
var people = _people.Where(x => x.Name.Contains(name)).ToList();
if(people ==null||!people.Any()) { new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name))); }
return people; }); }
The method will look for people with the name of the value that we passed to the method and if there’s no people found it will send this notice to Raygun. You might think to yourself that this isn’t really a good exception at all, but for the purpose of the demo, let’s just look pass that. Also a bird whispered into my ears that Mindscape is working on adding other message types than exceptions to Raygun, but that’s in the future.
This leaves us with a structure looking like the following:
We are now ready to use our library!
Create a new ASP.NET MVC 4 Application, I named mine RaygunDemo. The first thing that we are going to do is to add Raygun to this project as well, install it into the ASP.NET MVC 4 project using NuGet as we did before and open up web.config once this is done.
In order for us to get Raygun working we need to add our API Key. To do this we first need to add an element inside <configSections>:
Remember I said that Raygun helped me find an exception in my application when setting up the demo application? This is because I told Raygun to submit all the application errors. In the ASP.NET MVC 4 project, open up Global.asax and add the following method, this one will be run every time there’s an error in the application:
protectedvoid Application_Error() {
var exception = Server.GetLastError(); new RaygunClient().Send(exception); }
This means that every time that we get an application error Raygun will be noticed of this and the entire Stack Trace, Computer info and such will be passed into Raygun!
All there’s left to add now is the Home controller and the view, the Home controller consists of two asynchronous actions that will use the library we just created. One will return a view and the other will return a Json result:
public async Task<ActionResult> Index() {
var requestHandler =new RequestHandler();
var people = await requestHandler.GetPeopleAsync();
return View(people); } public async Task<JsonResult> Search(string search) {
var requestHandler =new RequestHandler();
var people = await requestHandler.FindPeopleAsync(search);
return Json(people); }
The view is equally simple, it only has a text box that allows us to search for names and then it has a list that shows all the people. Once a key is pressed inside the text box an event is fired that requests the people that have a name containing that part:
@model IEnumerable<RaygunDemoLibrary.Person>
<div> <span>Search: </span> <span><inputid="search"type="search"/></span> </div> <h2>People</h2> <divid="people">
@foreach (var person in Model)
{ <divclass="person"> <span>@person.Name</span> </div>
} </div>
If I start this and search for a name that exists and one that doesn’t it will look like the following:
Funny thing is that we didn’t actually notice anything when we searched for something that didn’t exist. So how do we know that this worked?
Raygun comes with an Amazing dashboard that will give you an overview of everything including all the recent errors, how many errors/ignored errors you have and much more like you see in this image (click to enlarge):
Finally this is what it looks like when you go into details about an exception, you’ll have a graph over how many times and when it occurred and then you have very much details that will help you Raygun the errors!
If you’re unable to add code to your current website you can simply add a HTTP Module and a config value! Which means you could simply add this in your web.config provided you have the dll as well of course!
We always have interesting discussions at work, both philosophical and mostly programming discussions. Sometimes the things people say make you think a while longer.
The other day a co-worker of mine asked me:
If a tree falls in the forest and no-one is there, will anyone here it?
I quickly responded with this:
No, no-one will hear it but it will still make a sound.
The fact that it will make a sound is proven by science but that’s beside the point. It’s a trick question that leads you to say “No” but if you view the problem differently you’ll soon have a pretty good answer.
While my co-worker was stunned and rather mind blown by my fast and quite accurate response, I think that most of us developers think logically about most of our problems and try to see solutions to puzzles much harder than this particular one.
If we look at problems from more than one perspective and think about all different outcomes, we can and most likely will do better solutions.
I felt kind of smart for a moment there, don’t you just love that feeling?
When it comes to software engineering I try to think outside the box as much as possible. For example I reflect over the following:
Is there anything I can do to increase the value to the customer in a timely fashion?
If we spend X amount of time refactoring this, how much will we have saved in the long run?
If the visitors of the website will never use a mobile device, is it a smart move doing a mobile version?
Is the problem parallelizable?
Can we add asynchronicity to increase the end user experience without messing up the code?
This new feature in .NET seems very cool, but will it add value to the product? (Most times, yes!)
What can I do to decrease the memory imprint of the algorithm?
Can we use any patterns to make the solution more solid and less error prone?
Just about an hour ago I came back from my first ever run where I didn’t stop to walk even once and ran longer than I’ve ever done before. Even if the time nor the distance is important to someone that is an experienced runner, but to me this is a huge deal.
About 3 minutes after I started running my pulse started increasing a lot and I got the feeling that I just wanted to go back home and lay back in the couch having yet another piece of chocolate cake. However I didn’t, I told myself that I’d at least have to beat my last time and my last distance no matter if it was by 2 seconds and 2 meters; I just had to.
This isn’t and will never be a blog about running, but bear with me, there’s value for any software engineer coming soon! About 3 months ago I was asked at work if I wanted to join and run a half marathon, that’s 21 kilometers and I’ve never even ran a fourth of that distance. For some reason though I said yes because I really need to get in shape to feel better, anyone that have a desk job (probably 100% of the readers here) know that it doesn’t really do the body justice just to sit still for the majority if the day.
So I said yes to this half marathon and as I am a very determined person I am going to finish this race, no matter what time or in what condition; I am going to finish this race!
Here’s why: I believe that challenging yourself over and over again will make you challenge yourself out of habit in the end. This might sound weird but think of it in engineering terms instead. If every day that I sat my foot at work, no matter if it’s for developing trivial tasks or not I would challenge myself into writing one better line of code than the day before. Or even better, I would challenge myself into going back to the previous days work and improve what I had then developed.
In the long term challenging yourself will make you question your solutions and you’ll start to think if this way is the best which ultimately will make you do very good solutions from the start; but there’s always room for improvements! It might sound like a cliché but frankly I think too many of you forget to challenge yourselves or rather you forget to ask or take the time to do so. A friend of mine told me that he tries to optimize his coding performance so that he will output high quality code in a shorter time period so that he then have time to go back and refactor pieces of the solution. This is exactly what challenging yourself helps you do: Improve, Improve and Improve!
In the end, don’t we all just want to be awesome at what we do? No matter if it’s software engineering, running, catering or anything else for that matter?
Tomorrow when you get to work challenge yourself into something like the following and tell me how it felt:
Refactor a method that you wrote this week that you’re not entirely happy with
Find a class, method or property that you feel needs to be explained better and add a comment or rename it completely
Dare to make a breaking change for the better of your product
Ask your boss for a license to ReSharper, JustCode or any other productivity tooling
Personally if I hadn’t challenged myself into doing things that scares me I would never had stood in front of a group of people talking about programming, I would never have written my book and I would never have started my own company.
You can be awesome if you just put your mind into it, remember that you’re just as awesome as you see yourself.
Filip Ekberg is a Senior Software Engineer working in the country with all the polar bears, author of a self-published C# programming book and overall in love with programming.
Check out my recently published book.C# Smorgasbord covers a vast variety of different technologies, patterns and best practices that any C# developer should master.
All printed copies include access to the e-book bundle (PDF, ePub and Mobi!).