Savvas On Software

My thoughts on software development, particularly testing strategies, CQRD, Event Sourcing and DDD

Ugly as a feature

First things first. What is a unit test?   For the juniors out there: a unit test is a test run

First things first. What is a unit test?

For the juniors out there: a unit test is a test run against a “unit” of source code. While this definition is a bit vague, some important characteristics of a good unit test are the following:

  • Tests a single public method of a class
  • You should have complete control over the unit
  • The unit must have the minimum number of third dependencies (ideally none)
  • The test must be consistent (produce the same result in all subsequent tests)
  • The order in which unit test are run must not make any difference in the outcome

Additionally to the above there are some other non-functional requirements to a unit test, which are also extremely important. These include:

  • The tests must be automated and run after a build and before deployment
  • The tests should run fast
  • The tests should be readable and maintainable

These represent my understanding of the rules and guidelines and are based on my experiences and practicality\reality. Note the use of must and should.

Unit tests can become really ugly…

Before anything else, let me define what an ugly test is. An ugly test is one that has the following characteristics:

  • Is not easily understandable what it is doing
  • It is difficult to maintain
  • It has complicated build-up

This can happen much more often when you are doing code-first development (instead of test-first) since usually when you are authoring the test first, you tend to change design when some idea would lead to a complicated or ugly test. It still happens though  especially in cases where the class being developed has state and even more so in the cases where state is complicated.

… but this can be useful.

Ugly unit tests are a code smell. When I see one I immediately think that something is wrong. For example complex state in a class should be avoided in favour of simple state or, even better, no state at all. If you need to do a number of complicated steps in order for a bug to occur then it probably means that your class is probably breaking the single responsibility principle and should be refactored immediately.

In this sense, the ugliness of unit tests are actually a feature to be grateful for. If somehow, lets assume for now magically, the ugliness would be gone without the code under test changing, then we would be losing a valuable thing as we would not know the problems with our code until we would need to refactor it, for example due to a change in the requirements, or even worse due to a bug coming in. Not a good place to be :)

How would you “magically” remove the ugliness of bad unit tests? The two ways I can think of are:

  1. By encapsulating the complexity of unit tests in utility classes in the unit tests projects.
  2. By using a framework that allows you to write a unit test in the Given…When…Then format (with frameworks like XBehave or BDDfy)

The first one is easy to understand, but the second is a bit tricky. The problem with writing unit tests with BDDfy and XBehave (or similar frameworks) is that things are much more readable and understandable then, even when they shouldn’t be. Due to this, these frameworks, while really useful for behavioural testing, they are very bad for uni testing. I would strongly advice against using such frameworks for this, and keep to simple stuff for your unit tests.

Embrace the ugly!

Do not artificially make unit tests easier to read or maintain, instead go fix the right problem by refactoring your code. You will definitely benefit in the long run.

Thank you.

This was initially published at Savvas on software here:

Yield return and Linq for responsive applications

This is an article for keeping your applications responsive to user input and not responsive to orientation or screen size changes. I am going to explain how to search an in-memory collection for some matches to a condition and explain why this is ALMOST useless if you are already using good practices.

The example problem.

Say you are developing a reporting application that stores users with their names and addresses and purchases. Lets assume that you have cached the resultset with all the clients in a helper as the code below:

   1: class Address
   2: {
   3:     public string City { get; set; }
   4:     public string Country { get; set; }
   5:     public string RoadName { get; set; }
   6: }
   8: class PersonName
   9: {
  10:     public string Name { get; set; }
  11:     public string Surname { get; set; }
  12:     public string MiddleName { get; set; }
  13:     public string Title { get; set; }
  14: }
  16: class Telephone
  17: {
  18:     public string Phone { get; set; }
  19:     public PhoneTypeEnum PhoneType { get; set; }
  20: }
  22: class Person
  23: {
  24:     public PersonName Name { get; set; }
  25:     public IEnumerable<Telephone> Phones { get; set; }
  26:     public IEnumerable<Address> Addresses { get; set; }
  27: }
  29: class Cache
  30: {
  31:     public static IEnumerable<Person> People { get; set; }
  32: }

OK, so at the end of some operation, Cache.People holds an IEnumerable<Person> with all the persons that we are caching. Maybe we want to do this because we are retrieving this information from a web service and we know that such results are worthy of caching. Now, part of our requirements are to provide for a means to search these person data. Searching through a large set of data like this on a mobile application (or even a desktop application given a large enough dataset) can be very CPU consuming and if done incorrectly, it can hog resources and cause our application to become less responsive to input (even if we are doing this on a background thread depending on our setup and amount of resource required).

Yield return to the rescue!

So, one of the best ways to minimize the required resources is to return the results only when it was required. There is a very good way to achieve this and it is through the use of the Iterator pattern (the iterator pattern is implemented in C# using IEnumerable and IEnumerator interfaces and their generic counterparts). Through this pattern, a consumer could request an IEnumerator that would enumerate each entry in the resultset one-by-one and stop and resume as needed. So it could for example iterate and only get the top three search results and only fetch the rest if the user wanted to scroll down (for example). Actually, I bet you are already using this pattern without knowing it; every time you are doing a foreach in C# or a for(type item : itemList) in Java, then you are using the iterator pattern. Also most of Linq is implemented over IEnumerable collections, so if you are using Linq, you are most probably using the iterator pattern.

So how do you get an IEnumerable in C#? Aside from Linq methods (we will see why in a minute), C# provides a very easy way to create an IEnumerable through the use of the yield return keywords. You can use yield return in methods that return IEnumerable<T> to return the results iteratively instead of authoring the IEnumerator-IEnumerable classes yourself to do the same thing. A simple example follows:

   1: static IEnumerable<int> GetEven(IEnumerable<int> numbers)
   2: {
   3:     foreach (var num in numbers)
   4:         if ((num & 1) == 0)
   5:             yield return num;
   6: }

For more information on the yield return keywords you can see the MSDN article.

For maximum happiness, use this with async methods :)

And what about Linq?

Well, Linq to objects actually makes use of IEnumerator to yield exactly this type of results. So if you can use Linq, then by all means do! The problem with Linq however, is that it is limited by the available providers. It will not work (for example) if you had to cache your resultset onto local storage due to its size. For this, yield return is still very much useful, for example to return the first three matches without deserializing everything into memory.

It is however quite interesting to see how brilliantly simple, but at the same time absolutely powerful of this pattern is. The C# reference document on the topic is absolutely beautiful in its simplicity.

Thank you for reading.

I consider this post targeted to new developers interested in software design and application architecture, but it may be useful to remind the rest of us the beauty and power of simple, but good software design.

This post was originally published on

OOA&D For the new developer: 1 of n

As I started to plan this series out I realized a couple of things. Firstly that OOA&D is a subject that I am particularly fond of Smile and secondly that aside any courses taken, to get good at it, you need experience and it is precisely due to this that I have found myself teaching new developers about this subject more than any other. In this first post in the series, I am going to talk about some general tips and rules about designing your classes.

I would like to again remind you that this series is meant for developers which are already reasonably fluent in an object oriented language like C# or Java.

Classes and state

I am obviously going to be talking about classes and interfaces a lot throughout this series. I am going to start however with something that I do not see mentioned enough in my opinion: the relation between classes and state. I am using the word state in a broader meaning to describe both the set of data that we are acting upon and also the data that may describe the temporary configuration of the class.

Since in OO languages everything can be a class (and very often is), classes with function can 1) act upon or process a state or 2) have a state.

  1. Classes that act upon a state are classes that do not hold references to a state, but are simply passed the state (a set of data) through a public method or delegate and process it. Examples of this is a command processor, with a public method that accepts a queue of commands as a parameter which dequeues each command and executes it, returning the results.
  2. Classes that contain a state are classes that contain (have a hard reference to) a set of data that are used for calculations or configuration of the instance. Examples of this is a repository which holds a reference to the entity context and a set of methods to use the context for their functionality.

By state I mean a class or structure which represents a set of data, like a date or a list of purchases.

None of the above is “wrong” nor is any “correct” or a good practice. On the other hand while designing your solution and assigning responsibility to the classes, it is best to be fully aware in which of the above categories your new classes will be as each is best suited for different purposes.

A class that acts upon a state without holding a reference to any state allows objects of that class to be more easily shared (between threads and objects) as there are no concerns about synchronization. Classes with state however must handle synchronization to protect against state corruption and race conditions. For classes that act upon a state, it is best to pass the state in the constructor and store the state in a read-only immutable data type to bypass these issues.

While the above is reason enough to make you carefully consider which to use in a scenario, I have found out that this is something best thought about and designed early in your development cycles.


It is important to name your classes so as to be easy to understand its function. A class with a name like MessageParser is pretty explanatory (depending on the situation), while a class simply named Handler leaves too much for the imagination. Naming may not seem very important, but it is my strong opinion that it is often one of the most important (and often difficult) decisions about a class. A well-chosen name can mean time off when debugging and significantly less time when revisiting the code after some time. Do not underestimate naming.

About method visibility and static

One of the questions that I hear more often is what visibility to use for the methods of a class and when to mark them as static. When designing a class I always follow the following process:

  • Mark the methods relating to the interface of a class as public.
  • Mark helper methods as private static. Static methods, do not have access to any state the class may hold or any instance methods, so they are inherently thread-safe. Marking them as private prevents use by other classes which is essential for static methods, as they can lead to spaghetti code.
  • Mark the method as private when the method needs access instance methods or state.
  • Mark the method as internal when the method makes sense to be accessed within the declaring assembly, but not outside. This is more often the case with properties rather than methods since properties represent a state, to which we may want to prohibit public access.

Anything else is code smell. I will talk a bit more about this when talking about the single responsibility principle when talking about SOLID.

Avoid static classes

Static classes are a problem since they are accessible from everywhere in the assembly. Apart from the issue with crosscutting concerns that arises and the spaghetti code that may be the result from excessive use of static classes, another very important issue is with testability. Since methods in static classes are accessed by class name, there is a hard dependency on the class which cannot be abstracted to an interface. This in turn makes creating a stub of the static class impossible, which means that any classes that use it cannot be isolated for testing.

Keep methods short

One of the more important rules that you can follow is this: Keep the body of your method short. I see in lots of places some numbers (like 10 lines max) for your method body, but I do not believe that setting hard limits is practical. It is however good when you do not have the experience to recognise how long is too long. I usually say that developers inexperienced with OOA&D should be afraid to write methods longer that 10 lines. Tips to keep your methods short:

  1. Put your loop bodies into a new method (see visibility tips above).
  2. Put the body of if.. statements into a new method.
  3. If you have a series of actions that essentially does one things (for example getting the top and average score from the db) then even if this is just 5-6 lines,  if you have other code in your method, then put them into a new method. (We will see the repository pattern as it applies to the EntityFramework soon)

Avoid nested if statements

I avoid nested if statements like the plague. I can handle two nested if's (rarely and barely) but any more than two nested if’s is a no-no. The trouble with nested if’s is not so visible at first. The code works (presumably) and stepping through the code during debug is an easy task to follow. However, in reality it is very easy to create code that will be easy to follow if you revisit the code after some time. The reason of course is due to branching, and our brain is not too good at keeping a large map of possible paths of execution in memory. Even if you are capable of such a task, it doesn’t mean you should. Instead of branching internally, send execution off to a method with an easy-to-understand name. This way you will be able to follow the execution easily in place and step into the method to drill down deeper without the need for keeping the context (previous operations) in mind.

Again, if you don’t agree with this point, just write a couple of methods with more than 2 nested if’s and talk to me again when you revisit the code…

Also, on this subject, please see my previous post about a stack overflow question with more if’s that I could stand.

Avoid long switch statements and large series of if…else statements

This is another problem that I see semi-regularly from new\junior developers. I guess this happens both due to a lack of experience to help identify why exactly this is bad, but also due to the fact that if…else and switch statements are so easy to implement that you rarely even think about alternatives. Some of the problems that these lead to are:

  1. They are hard to follow. It is significantly easier for the switch statement, where conditions are always constants, but only if the case bodies are short, few in number and goto is not used. As a rule of thumb, if I see 2 else’s I consider it as a candidate for refactoring, and 3 or more else’s prompt an immediate action. Similarly, if I see a switch statement taking more than 10-15 lines or uses goto, I consider it for refactoring.
  2. Since all cases in the switch share a scope and all if and else statements all have access to the method scope variables, they can be tightly coupled with the variables declared inhibiting reliability.
  3. They are error prone. Missing an else in a series of if… else if… else if… else, very often will result in radically different results than expected, and it will be very difficult to detect, as there is no help from the compiler about this. If you do not use goto statement (pro tip: DON’T), then switch statements are not as error prone, however, they still have their problems.

A much better solution would be to create a chain of responsibility or a pool of typed handlers to process each case (ideally using IoC to load the handlers into place), both are patterns we will explore with greater detail in later articles. This will greatly increase readability and maintainability, and abstract code to a dedicated,easy to find class.

Programming fonts

I believe the subject of fonts is something that is rarely discussed, especially in the .Net world, but is of major importance. A good font can increase readability and make working much easier. In my experience as a developer I have come to the following conclusions:

  1. Find a font that works for you and stick with it. You will get used to it, and you will be able to read it faster.
  2. Use a monospace font. I think this goes without saying, but I mention it for newer developers to save them some time from experimentation. It is important during some editing procedures (like the alt-left click and vertical drag gesture to make a multi-row selection or edit), but also crazy important for readability. Possibly this is the most important feature of a development font.
  3. The perfect font is one which is a sans serif, but with two character exceptions: the lower L must be “serifed” and the upper case i. This is so as to be easy (or even possible) to distinguish between the number 1, the lower case L and the capital i. These are things that are relatively easy to make out from context when reading, but it does require some effort, no matter how minute. I find that this it makes scanning source code a lot easier and I would never use a font which does not have these features.
  4. For the same reason as the above, I always prefer a font which clearly distinguishes between capital letter O and the number 0.

Given the above, I recommend one of the below three fonts (in no particular order):

Consolas (get it here, also comes free with Office, Visual studio and other Microsoft applications)

Consolas is my default font. Scratch that, it is my only font! It is the font I have been using ever since Visual Studio 2010 introduced me to it. It is really a beautiful font, easy to read and easy to the eyes. Also consolas has an extensive coverage of Unicode. Since Consolas if a commercial font, you may want to look for Inconsolata as a free alternative.


Vera Sans Mono and DejaVu Sans Mono (get DejaVu here for free)

The font I used before Consolas. I saw this font when I was still in the university and working on Linux. DejaVu is a font heavily “borrowing” from Vera thanks to Vera’s liberal license. Both are extremely good fonts and from what I can tell, almost identical, except that DejaVu supports a lot more of the Unicode standard than Vera. Truth be told, I would probably still be using DejaVu, but immediately after installing Visual studio 2010 (following a format) I was left without internet, so I made due with Consolas for a couple of days, and came to like it and never switched back.


Segoe UI Mono (get it here, also included with newer Windows and other Microsoft applications)

I have had a windows phone ever since it came out (and a Windows Mobile before that), and Segoe WP and Segoe UI are essentially the same font with some very minor changes. It is a font with inspiration from Arial, but a bit more modern. Segoe UI Mono is especially easy on the eyes and makes for a good developing font in my opinion, but I have not yet seen any significant mention of it on various articles around the internet (with the above being regularly mentioned as good fonts). I would like to change this, as I am somewhat of a fan of this font. I confess, it is not the font I use (I have a big problem with this font, see later), but it is a great font to read on, and I am more than happy with how it works in Windows Phone.

Update (17/07/2014) : I did not mention the issue with the number 0 that Segoe has. Read below for more info.

I do have a major issue with this font however, as the number 0 is not easily distinguishable from the capital letter O. It is not an issue most of the times, but it is a huge problem in cases where colouring does not work in VS (for example when authoring T4). Aside from this (big) problem, it is such a good font that I feel obliged to recommend it regardless of not meeting requirement 4; it is a font with just the right thickness of the letters, just enough curvature to be good, but not inhibit readability and barely enough “serifness” to make some letters distinguishable, but not be a problem.


Honourable mentions

While I would not personally recommend them, some fonts that are being used for development and I believe are worthy of mention are Source Code Pro from Adobe, Lucida Console and Anonymous Pro.


If I were to start fresh again, without habits and being used to some fonts, I think I would still go for Consolas, with Segoe being a close second. DejaVu is a good font, but the unnecessary curviness of the lowercase L (my main issue with this font) and the pointy edges of the letters s and c (especially) prevent it from being a favourite. So, what is your favourite font?

Someone is wrong on the internets!

OK, I just love StackOverflow. It is a great site and I have used it quite a lot in the past. Howeve

OK, I just love StackOverflow. It is a great site and I have used it quite a lot in the past. However answers like these:

Do not really help anyone.

The answer, while it will work and function as promised, is seriously faulted in my opinion. Just some of the reasons I do not like the above answer:

  1. It is not readable. Nested if's are not a good idea and will not help readability. I mean, imagine if the question was about IPv6. I shudder to think about how would the answer look like then!
  2. It works in the limited domain of IPv4, while  my answer is a solution that can very easily work for any configuration.
  3. It does not adhere to DRY (it looks like a series of copy-pastes).

If you feel similarly, please consider upvoting my answer (please be kind, this is the first time I write in StackOverflow) so as people coming to that question can view a better solution than the currently accepted one.

OOA&D For the new developer: 0 of n

I put a lot of thought into what to write next. Last time I wrote that I decided to blog about topics geared to new developers. By that I meant people that already comfortable reading code written in an object oriented language, know how to recognise what is what, how to write a basic class, etc. but do not know how to design and architect their source code to be maintainable, extensible, easy to read and understand and (perhaps most importantly for new developers) easier to debug.

1. OOA&D first

For the first series I had to decide between “OOA&D for the new developer”, “SQL just-above-the-basics” and “C#  and .Net advanced”. C# was the easier to decide to postpone, as OOA&D is far more important than knowing how to write a bit better performing code, and while extremely important, knowing your way around the basic parts of the .Net framework means little when you cannot maintain what you have developed. SQL was more difficult to reject. I consider the data layer as important as the middle layer  (the one between the UI and the data layer), while for some reason being noticed less that the rest.

2. Series outline and roadmap

I see this series being a little bit long, and some topics being re-visited in the future, but it is in my opinion one of the most important lessons a developer learns and one of the most overlooked subjects. Moreover, I feel that in some cases, it is not so much a science as an art, as usually there are more ways than one to solve a problem and there is always the trade-off of quicker solution and one which will take more time to develop. I have not completed the course yet, but the basic outline of this course is as follows:

  1. Classes and state
  2. Goals of OOA&D
  3. Interfaces #1
  4. SOLID #1
  5. SOLID #2
  6. Interfaces #2
  7. Essential Patterns #1
  8. Essential Patterns #2
  9. Common Patterns
  10. OOA&D and ASP.Net MVC
  11. Real world problem #1
  12. Real world problem #2
  13. Real world problem #3

If you are interested, please reach  me through twitter, subscribe and share (share buttons coming real soon!)

That’s it for today, but the next post in this series is coming very soon! Stay tuned.

A direction

Maintaining a blog is not easy.

I know Scott Hanselman holds the strong position that we must not be dark matter developers. I have tried not to be one of the unseen 99% and this is evident from the fact that this blog is actually my third attempt in blogging. I got a good start in my previous attempt, did quite a bit of research before publishing each post and everything, but then I stopped. First, for a prolonged period of time, this was due to health issues, but what really killed that attempt was that XNA (the Microsoft framework that I was using to blog about game development) came to be the wrong choice for the very long series of posts that I had in mind, after an official announcement from Microsoft saying that it would stop not release any new versions of it.

What I got out from that attempt was that it was really difficult (at least for me) to actually write something that will be interesting to many and useful. The amount of work required to publish something seemed to me, at the time, to not be worth the actual effort put into writing the articles. I understand that the subject of my initial articles (game mechanics and gameplay design focused in developing a game that will be used for revenue creation) is not actually a super-interesting one for developers (for many reasons), but still I had a miserably small number of subscribers to my blog (exactly three if you are wondering). Aside from that, I attribute my lack of subscribers to my blog in part to my (bad) writing style, but mostly due to being mostly theoretical in a field where people wanted practical examples and a fun writing style. Basically I consider my previous attempt at blogging as the exact opposite of the absurdly excellent book on game development Level Up! The Guide to Great Video Game Design.

A direction

After some careful thought I decided that from now on, I will have a prevailing theme on this blog.

In the past couple of years, as the head of the software development department in the company I work for, I had the chance to interview approximately 350 different persons applying for a junior developer position that I had open in my department. From them, approximately 40% (a percentage that includes local and foreign applicants) did not have any noticeable software development skills regardless of the degree they had. A very large portion of the rest had very serious deficiencies in many required fields (pointers was a common theme). Even the people that I recognised to truly have potential (still talking about junior developers) and I ended up hiring, lacked some knowledge in a particular field and\or important skills; something vey understandable for a junior developer. Specifically I saw a lack of skill in database design, knowledge of good programming practices and software design. Due to this I decided that for the foreseeable future I will blog about:

  1. Database design (because everything has a data layer).
  2. Introduction to software design with C# and Java.
  3. Good programming practices.
  4. Common software patterns.
  5. Common, real world problems faced by junior developers and good, easy to understand solutions. Patterns that apply to certain solutions.
  6. Useful tools and frameworks.

To serve as a central repository of required knowledge that a junior developer is supposed to acquire on his\her own.

Creating enums from the database and using them in Entity framework 5 and later in model first

Similarly to the need for enums in C#, description tables (tables with an integral identity column a

Similarly to the need for enums in C#, description tables (tables with an integral identity column and a textual description field) serve the need of type safety and to replace meaningless magic values in a query into easy-to-understand descriptions. I tend to use them all the time and also I use the description column as a key to a translation table before presentation.

There has been support for enums in Entity framework since version 5.0, but the truth is that it is limited in model first approach since there is no way for the entity framework to automatically populate created enums with data from the database. There is an easy way around it though by using T4 templates. We use T4 templates to automatically create enums for the tables that we want to replace, and then bind these enum to the correct properties of the entities.

Creating the enums

First we create the enums. For that we use a T4 template to connect to the database and output the enum to a created file. The code of the template is below, just right click in your project folder, expand "Add" and select "New Item", them in the "General" category select "Text Template" and paste the code below in your new *.tt file.

  1. <#@ template debug="false" hostspecific="false" language="C#" #>
  2. <#@ assembly name="System.Core" #>
  3. <#@ assembly name="System.Data" #>
  4. <#@ import namespace="System.Linq" #>
  5. <#@ import namespace="System.Text" #>
  6. <#@ import namespace="System.Text" #>
  7. <#@ import namespace="System.Collections.Generic" #>
  8. <#@ import namespace="System.Text.RegularExpressions" #>
  9. <#@ import namespace="System.Data.SqlClient" #>
  10. <#@ output extension=".cs" #>
  11. <#
  12.     string connectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NovaDb;Data Source=TELECONNECT\SQLEXPRESS";
  13.     string nameColumn = "Description";
  14.     string idColumnName = "ID";
  15.     string tableName = "BalanceEntryTypes";
  16. #>
  17. namespace <#= System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint") #>
  18. {
  19.     public enum <#= tableName + "Enum" #> : byte
  20.     {
  21. <#
  22.         using (SqlConnection connection = new SqlConnection(connectionString))
  23.         {
  24.             connection.Open();
  26.             Regex pattern = new Regex(@"\W");
  28.             SqlCommand command = new SqlCommand(String.Format("SELECT {0}, {1} from {2}"
  29.                 , nameColumn, idColumnName, tableName), connection);
  30.             using(var reader = command.ExecuteReader())
  31.             {
  32.                 while (reader.Read())
  33.                 {
  34.                     string key = (string)reader[0];
  36.                     key = pattern.Replace(key, "");
  37. #>
  38.         <#= key #> = <#= reader[1] #>,
  39. <#
  40.                 }
  41.             }
  42.         }
  43. #>
  44.     }
  45. }


Before using it, please remember to replace the connection string, table name, id column name and the description name. I have added some (very) basic functionality to replace illegal characters from the enum keys, but it really needs to be improved further if you are to rely upon this. I have actually found that it in similar cases it is better to fail and let the developer know early on that a mistake exists outside of agreed norms. After that we save the above text template, an action that automatically runs the template in Visual Studio, and now we should have our enum created and ready to add it to our entities.

Use of enums in Entity framework model first

I will assume that you have already created a model and you are ready to connect an entity to the enum we created above. It is important to remember not to include the table that you used to create the enum in our entity model so as to not pollute our namespace. Once we have the entity ready, the process is simple: right click on the integral (byte, short, int and long) property that you want to turn to an enum and select “Convert to Enum” as shown in the image below:

A dialog box will appear. You can use this to create a new enum manually with custom values if you want, but we want to assign it to the enum we created in the previous step, so that the enum updates from values from the database whenever we make changes. To do this instead of adding values we simply complete the "Enum Type Name" and the fully qualified name of the enum in the "Reference External Type" field we created, as seen below.

And that’s it! every time we make any changes in the db, saving the template immediately applies the changes and everything just works.

Why would we want to do this?

To the more experienced audience, the benefits of binding an enum, with values automatically retrieved from a database, to an entity framework entity, are self-evident. For the less experienced among my readers, I would like to point out that the benefits are the same as with using enums in any other case: readability and value constraints. That is, something that would otherwise not make any sense (like balance.BalanceTypeId = 3), now are much more understanable (balance.BalanceTypeId = BalanceTypes.TellerPayment) while at the same time, making any errors less possible, as it is far more difficult to put a wrong value in the database.

This blog post was originally posted at

Android service closing unexpectedly.

At my work, the most of my time is spent managing and developing a communication application which c

At my work, most of my time (in the past year or so) is spent managing and developing a communication application which currently supports normal voice calling (but cheaper to the local carriers). We did that part first because it was easy, but also allowed us to experiment with UI and UX and find out the requirements for a modern voice application (we had the luxury to change the UI entirely three times so far) but also to experiment with provided services, such as call log editing and outgoing call rewriting (adding a prefix to a user-initiated call to a number). We have just finished the call rewriting service and we are about to release a new version of our application (more on the actual application on a future release after we meet the v2.0 milestone), but the last issue we had that stopped us from release was an interesting (if a bit common).

The problem and the source code.

The service that handled the outgoing call rewriting would work fine, but after some unspecified and random amount of time, it would fail taking everything down with it.

The problem was traced to a small piece of code that looked like this:

  1. CallStateChangedListener myListener = null;
  2. private void setupNewListener(Context ctx)
  3. {
  4.     if (myListener == null)
  5.     {
  6.         myListener = new CallStateChangedListener();
  7.         //This is innocent enough simply pulling some date from the db.
  8.         myListener.setup(ctx);
  9.     }
  11.     TelephonyManager tm = (TelephonyManager)ctx.getSystemService(Context.TELEPHONY_SERVICE);
  12.     tm.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
  13. }

The solution

The unfortunate thing was that the setupNewListener method actually gets called multiple times, causing the listener to be registered multiple times (ouch!). This caused some problems that got missed at first because our operation (rewriting the log file) completed actually very quickly in our testing phones (I am guessing due to the small size of the log file). Adding some logging immediately revealed the problem and as soon as I knew what to look for, it was an easy fix (simply include the listen registration inside the if statement).

The interesting part of the problem may actually be eluding you however: the multiple calls to the event listener was not the source of the service-closing problemSmile. There is a period of approximately 10 seconds, where telephony-related listeners can act (it actually may be much less than that, but this period is the one I have found written in docs), and all the calls completed in less than a second.

The explanation

To give you a small hint before the actual explanation, consider this: what would happen if a different context would be provided each time to the above method?

It would cause a memory leak. Why? Because as per the note on the bottom of the getSystemService documentation here, some system services are closely tied to the context. This means that when we got the telephony service reference from the context and then set up the listener, a hard reference to the context was being kept internally to serve call state change notifications, and this happened every time the method was being called, keeping all memory kept by each context (usually a lot) alive.

Lessons learned

I have seen this types of errors a lot in my career. Object lifetime is something that new developers take some time to grok, but errors like these usually serve as tough lessons and stick to memory.

In any case, learn to live by the following golden rules:

  1. Use WeakReferences whenever possible (a post is definitely coming very soon about weak references). The above problem could not have been solved with weak references, but a lot of memory leak problems can be solved very elegantly with them.
  2. Do not hold hard references to system services or to contexts.
  3. Do not copy-paste code from elsewhere, even if it worked perfectly where you took it from. (yup, this is what happened).

This blog post was originally posted at

Basic Sockets programming in C# using TcpListner and TcpClient

No man is an island John Donne Introduction Most&amp;nbsp;software and apps&amp;nbsp;we use nowadays help u

No man is an island

John Donne


Most software and apps we use nowadays help us communicate and reach other people, meet other people, communicate with co-workers and compete against a remote player. Even software that serves no apparent social function provide a better user experience when allowing for communication with a server to pull centralized data, this goes for games allowing multiplayer functionality to enormous online movie databases and encyclopaedias with more data that could possibly fit in any of your devices. I don’t think that I need to make the case for connectivity. No application should be built without connections to the server.

Web applications are inherently online and the means for communication are built-in to the very technologies that make it up, but what about the rest of our apps? I find myself  regularly developing windows and mobile applications and there are a lot of ways to communicate with a central server. In the .Net ecosystem we could connect using:

  1. Web services developed using ASP.Net Web API
  2. WCF
  3. Messaging through MSMQ and similar services
  4. Sockets

I will not go into a comparison between the four in this article, suffice it to say all four have their pros and cons. Specifically, selecting socket for development makes sense when we need to create highly efficient, problem-specific solutions and we can afford the overhead in development time and extra support that will be required. If you are pressed for time, but require high throughput and efficiency, consider WCF with tcp binding, it is a very good solution, but WCF deserves a post on its own.

Source code

Basic socket usage in C# is extremely easy, all thanks to the TcpListener\TcpClient helper classes which wrap the Socket class and hide a lot of the complex configuration that would otherwise be required. A server is set up by instantiating a TcpListener, setting the listening port and by listening for incoming connections. After this, a client can connect to the server through the connect method of a TcpClient. All communication (on both ends) is handled through a NetworkStream which can be wrapped by a BinaryWriter or BinaryReader to provide easier serialization of data.

A brief example is shown below:


//TcpClient implements IDisposable, so declaring and instantiating 
// it in a using statement is a best practice and guarantees it will 
// get disposed in the end
using (TcpClient client = new TcpClient())
    //Connect to the server (running at thelocal machine)
    client.Connect(serverIp, Server.Program.SERVER_PORT);
    //We are now connected.

    //More code...

    //We send data through the socket using the underlying stream.
    // We can also wrap the stream with a Reader or Writer depending on
    // our needs
    using (var stream = client.GetStream())
    using (var writer = new BinaryWriter(stream))


TcpListener server = new TcpListener(IPAddress.Any, SERVER_PORT);


//Blocking call.
var client = server.AcceptTcpClient();

//Again we use Stream and use it through a stream helper.
using (var stream = client.GetStream())
using (var reader = new BinaryReader(stream))
    //Read an int from tcp
    var data = reader.ReadInt32();

The full project (and all future projects and examples) can be downloaded from codeplex here.


If you are in the process if deciding what technology to use for communicating anything to a server or client, there are a couple of things to consider about using low level solutions like TcpClient and TcpListener (and Socket as well).

1. It will take longer

It should be common knowledge that when selecting a low level solution, getting the job done will definitely take longer. In many cases significantly longer. In this case it is due to the lack of any automatic serialization of data  in the server and client. This is actually something that you want; doing the serialization and deserialization manually leads to significantly lower payloads and hence less traffic.The last is true however mostly in packages that contain a lot of small pieces of info or have a small total size, where the extra information required by the serialization process is more than you need.

2. It is not secure by default and security is an issue

Security is an issue because it is all too easy to think that securing using XOR with a pre-shared key is OK.It is not! Use certificates to secure your communication or consider another solution if security is of prime concern. Also the overhead of using certificates may make WCF a more tempting solution (if you are only targeting Windows platforms).

3. Most often than not it is not worth it

The time needed to develop your communication using low level solutions is much more than the gains in performance. It is better to chose this only when you are sure of what you are doing.


That’s everything for this time. Vote and comment please, I am very open to topic suggestions. This blog post was originally posted at

Next time I will probably cover tcp a little bit more.