All posts in C# Hacks

All credits to the original author for doing this. Although I’m trying to extend it in the coming days, but props to Adam for finding this one out!

Go to and follow his other tutorial as well.


The #1 request I get for the Xamarin.Forms in Anger is for a Google or Facebook like card view. Today is the day that I fulfill those requests.

To be completely honest, I’ve been thinking about how to do a card view for a while and let me tell you, it’s not easy. Especially when you try to stick with the “in the box” components of Xamarin.Forms. My first attempt at it was hideous.

Hideous Forms

Hideous would be the most polite way of saying it was crap. I started off using BoxViews to draw the lines and contain the whole thing in a Xamarin.Forms Grid. Ouch, yes hideous.

The Grid was becoming a nightmare with all the extra rows and columns needed for lines. What I wouldn’t do for some HTML Tables with a borders = 1 in Xamarin.Forms. I thought of putting in a feature request to the team, but didn’t. I don’t want them to laugh at me. 😉

Waffle Fries to the Rescue

With the BoxViews not working out, I went to lunch to clear my head and to think. I love lunch and I don’t miss a meal. That day, I decided to go to Chick Fil A and get a chicken sandwich with a side of epiphany fries.

There I was, eating my chicken and dunking my fries in ketchup (Sauce de American). When I dipped a waffle fry into the ketchup, the ketchup squeezed through the holes and made a red checkerboard on top of the fry. Then it hit me. Bam!

I was going about the card UI backwards or forwards. Either way, it was the wrong way. I had to do an about face and approach it in another way. The way the ketchup came up through the fry not by putting ketchup onto the fry.

A Grid of Lines

As soon as I got home, I worked up a Xamarin.Forms Grid with some padding, row and column spacing. In addition to those settings, I also set the background color of the grid to a medium dark grey. Then added ContentViews with white backgrounds into each cell of the Grid. This is what it looked like when I finished.


The white panels acted like the ketchup on my waffle fries and the borders are the potato. Yes, I know, it’s strange to describe Xamarin.Forms design techniques using food, but stay with me; it gets better. Now that I knew the technique worked and was a heck of a lot less messy, I pushed on.

Content View Panels

Each CardView is made up of 5 ContentViews with a background color set to the designed color. Here are some of the background colors for each panel.


The CardView.cs file would have been gigantic if I kept all the code in the same file so I broke it up into different ContentViews. Here are the names for each ContentView that makes up the CardView.


The CardDetailsView has a column span of three to horizontally bridge the two IconLableViews and the ConfigIconView. The CardStatusView has a row span of two to complete the vertical lefthand status bar.

The CardView Code

For the demo, I put a couple of CardViews in a vertical StackLayout. If I had a lot of cards, I would prefer to use a ListView. Hopefully a reader will let me know how well this design works in a ListView. It should be ok, especially while using the Grid and not a bunch of nested StackLayouts. I’ve learned my lesson.

public class CardView : ContentView
public CardView (Card card)
Grid grid = new Grid {
Padding = new Thickness (0, 1, 1, 1),
RowSpacing = 1,
ColumnSpacing = 1, 
BackgroundColor = StyleKit.CardBorderColor,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = {
new RowDefinition { Height = new GridLength (70, GridUnitType.Absolute) },
new RowDefinition { Height = new GridLength (30, GridUnitType.Absolute) }
ColumnDefinitions = {
new ColumnDefinition { Width = new GridLength (4, GridUnitType.Absolute) },
new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength (100, GridUnitType.Absolute) },
new ColumnDefinition { Width = new GridLength (50, GridUnitType.Absolute) }

grid.Children.Add (
new CardStatusView (card)
, 0, 1, 0, 2);

grid.Children.Add (new CardDetailsView (card), 1, 4, 0, 1);

grid.Children.Add (
new IconLabelView (
, 1, 1);

grid.Children.Add (
new IconLabelView (
, 2, 1);

grid.Children.Add (new ConfigIconView (), 3, 1);

Content = grid;

With all the refactoring; the CardView looks small and plain but the devil is in the ContentViews.


Final Layout:


The code for this sample is up on GitHub in the “In Anger” repository. For this post, I broke the code out into a separate directory and solution to make it easier for you to reuse the CardView without getting confused with all the other code and resources from other posts.

Moar Epiphany Fires

Who knew that a humble waffle fry would be the answer to the Xamarin.Forms CardView? Not me; I go for the chicken. Don’t you worry dear read, I will continue to go to “Chick Fil a” to get more Xamarin.Forms design inspiration in the future. Stay tuned to this blog and, if you have a design challenge, just put it in the comments below or email me at adam [at] adamjwolf dot com.

Xamarin.Forms in Anger Series

Can Xamarin.Forms produce good looking cross-platform UI from a single codebase? Each “In Anger” blog post will tackle a single page of a beautifully designed iOS or Android application. My job will be to reproduce the design in Xamarin.Forms as faithfully as possible.

Article Image

Software development is a tricky business. We spend most of our day breaking down complex problems into smaller tasks and then we write machine code. We often have to analyse code that someone else has written. We need to read so much documentation in order to get acquainted with a new API. Every day is an uphill battle against a new framework, language or library. In the end, we write our own code, solve the problem and move on to the next task.

Writing clean, concise code is a lot harder than it sounds. It requires experience and a good understanding of how code hangs together. The larger the system, the bigger the challenge. As a developer, there is nothing worse than having to support and troubleshoot badly written code. Sometimes, it’s us that write that code. I can attest that I have produced some code ‘gems’, and I’m sure I’ve written some awful code that’s still running on a server in a basement somewhere. I’ve worked hard, learnt from my mistakes and I hope that I’ve come a long way since those darker days. I also understand that I have a long road ahead of me, and I strive to learn and improve my coding skills every day.

Over the years I’ve picked up some good practices, tools and standards to help me become a “Clean Coder”. By the way, the principles of clean code have been thoroughly covered by Robert C Martin (also known as Uncle Bob) in his two homonymous and highly recommended books:

In this post I’ll try to touch upon some of the basic Clean Code principles and show you how to write clean, readable and easily maintainable code. Your future self, your colleagues and successors will be certainly grateful for it!

Naming things

Lots of things have been written on the subject of naming in programming, but there’s nothing that captures this better than this quote by Phil Carlton:

“There are only two hard things in Computer Science: cache invalidation and naming things.”

Working with badly named code can seriously affect your productivity and your ability to fix bugs or add features. All code should be self-describing with meaningful and easy to understand naming. There’s a big difference between:

var x = 3; and
var maximumLoginAttempts = 3;

The larger the scope, the more important to get the name right. Don’t concatenate your variable and function names, you’re not going to run out of bytes! But self-describing code is just about understanding the intent. It’s also about refactoring and improving your code flow. Imagine if you did a standard “Search & Replace” for all references of variable “x” or even worse “a” or “b“. A world of fun awaits as you undo your changes and revert to manually changing all instances of that variable.

Naming consistency

Camel-case, Pascal-case, any case. If you chose a method, you’ll have to stick with it. Having consistency across you code makes things predictable and easier to understand. When you work alone, this can be easy to enforce. However, this is a much bigger challenge in the context of a bigger team. Fortunately, there are tools that can help enforce consistency. I use different tools such as StyleCop, JSHint, JSLint, JSCS (all open-source and free) and they work great. Make sure that the whole team arrives at a consensus on which rules work, or you’ll just end up back where you started. StyleCop for example tends to be overly eager (aggressive) in the way that your code should look, and some of the rules don’t make sense. Feel free to run through many trial-and-errors until you’ve refined the config enough to meet your needs. Again, it’s important to discuss this with the rest of the team. Other IDEs will have similar tools but if there’s none that can support your technology stack, just write them down somewhere and try to enforce them during code reviews or pull request (PR) acceptances.

Code comments

Code comments tend to be a sensitive subject and I’ve seen people defending both sides. I’m with Uncle Bob on this one. Unless your comments are treated as active code (with reviews, PRs etc) then they should be avoided. Code comments add noise to your code, distract you from your task and, in most cases, tend to be unrelated and out-of-date. Describing what the code does is the responsibility of the code itself. As the code evolves, the comments go stale and developers rarely go back to fix inconsistencies. Apology comments of the style: “//TODO: hacky workaround, will fix later – CM”, are all too common and they sound more like an apology than a valid comment. If someone took time to write the comment, they could have taken a bit longer to come up with a proper fix. Finally, there are always exceptions to every rule and for me comments are useful when used to document public APIs. If you’re interested in reading more about code comments, have a read here.


Your code should read like a well-written story. The code should have a natural flow (a bit like Behaviour-Driven Developer) where each method describes an operation that has an entry and exit point. Each method should add to the overall story and written in such a way that it would make sense even to non-programmers. Some people believe that methods that describe a “story” should be clustered together, but this may come in conflict with some tools (Resharper, StyleCop) or design patterns (the scissors rule). You just need to decide what works better for you, but in my experience when working through code to trace an issue, it’s much easier when I have everything closely together rather than having to jump in random places in the code to follow the workflow.

S.O.L.I.D. is your friend

I won’t try to explain or redefine what S.O.L.I.D. is, as you can read about it here. The important thing is that by applying the S.O.L.I.D. principles, you’re also working towards Clean Code nirvana. Building upon the rules and best practices described by S.O.L.I.D., your code and the overall system become easy to maintain and extend over time. The guidelines will help you reduce or eliminate code smells and make code refactoring easier.

Size matters

Following S.O.L.I.D., the next item on the agenda is size. Class size and method size both matter. Would you prefer a 3000-line class over a 250, and respectively a 150-line method over a 15-line one? Uncle Bob has this to say when it comes to method lengths:

“The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.”

Some may claim that this promotes fragmentation and can lead to large projects with lots of files, but this is usually an issue for younger, inexperienced developers. With experience, the fear of oversized, overcomplicated projects is replaced by the understanding of how one can leverage the S.O.L.I.D. architecture to create both a testable and maintainable solution.

Writing “clever” code

There’s usually more than one way to solve a problem. The same idea is valid for writing a routine, method or function. Some people enjoy making their lives and the lives of those working with them difficult by writing “clever” code. Yes, it works, and yes, they’ve managed to compress 10 lines of code into 2 by using short variable names and nested Lamda expressions inside an anonymous function. Unfortunately, this will not be as testable as you may think. Whenever I’m presented with a similar dilemma, simple always wins, hands down. I believe that Brian Kernigham’s words capture this better than me:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” Keep your code simple and easy to read and maintain.

Test-driven Development (TDD) or testing in general

TDD and testing are not directly related to clean code. Even the act of making your code testable will force you to think about the design and patterns to follow. TDD, on its own, is a subject that the development community can be particularly passionate about. However, the overall moral of the story is this: no software can be considered resilient, adaptable and manageable if there are no tests to cover it. It doesn’t really matter if you practice TDD religiously or if you write your tests (unit and integration) after the fact. Testing is an invaluable discipline and will ensure that the code functions in a predictable way and generates the expected output. There have been lots of books, posts and articles written about the importance of testing so I hope that your code has the right test coverage.


Some of the things I’ve written about are common sense and readily available knowledge. Some of you may have learned the hard way, and some may have escaped you until now. It’s never too late to start writing clean code and it should be your goal to improve every single day. If you find yourself writing the same code you did a year ago, or even 6 months ago, then you should definitely consider changing your priorities and look at how you can improve. There are many resources available to help you improve and the community is there to support you, so join me in this quest to rid the world of technical debt and write beautiful, functional code.


Have you ever had a reference book that you HAD to keep near you? This list of must-have books are required reading and should always be within your reach.

Top 10 Books Every .NET Developer Should Own

Everyone at one time or another reached for that specific book to find out how that one design pattern works or just needed it as a refresher on how to do that one routine better.

When you grow in your career, you start to notice that tutorial books don’t line your bookshelf anymore. Nor do you own “how to code in ASP.NET in 5 minutes.” Coding becomes easier. As I’ve said before, a language is a language is a language.

These books are a testament to the authors experience. It just goes to show you that these books I list below are exceptional in every way and have stood the test of time in the lines of development and design.

My post about What Books are Within Your Reach? was dated in 2010 and you know what?

To this day, a majority of those books are still within my reach and quite valuable. They never accumulate dust.

Now I know what some people are saying. You have the Internet at your fingertips, why not use that? While the Internet is a great resource, there is something to be said for a solid book that I KNOW has the answers (and sometimes more) within arms reach. I’m not saying all material on the Internet is bad, but it does take time to research that topic. When I’ve gone through these books and trust the material, I would feel more comfortable reaching for one of these following books/authors.

My preference of book publishers are Wesley-Addison Signature Series, APress, and O’Reilly. In That Order.

On with the list!

  1. Patterns of Enterprise Application Architecture By Martin Fowler

    It’s true that this book is a little pricey, but Mr. Fowler has put his experience and knowledge into enterprise application development and this book is an exceptional mark of that programming experience.

    On the inside cover of the book, they provide you with a list of programming thoughts and then provide you with a pattern to apply to that thought. It’s kind of like trying to remember the name of that song and all you have is a lyric.

    A quarter of the book gives an intro on layering, organizing domain logic, sessions, concurrency, and mapping to databases. During each of these sections they discuss a topic and use a number to refer to the pattern used in the book. These pattern numbers are in the remaining 3/4 of the book and I’ve used this strictly as reference when needed.

    Most of the Wesley-Addison Signature series books have this format which I absolutely love. This is what sets Wesley-Addison Signature Series apart from the other publishers. The book provides you with an intro, a description of a pattern, and a reference number to the pattern in the book. When finished reading it, you have the black tabs on the book to use when you have a particular pattern in question.

    A number of patterns are listed in the inside front cover. Most of the patterns are used today in the corporate world. On the back inside cover is a cheat sheet that helps with picking the right pattern for your particular approach.

  2. Refactoring: Improving the Design of Existing Code By Martin Fowler, Kent Beck, John Brant, Williams Opdyke, and Don Roberts

    The functionality of ReSharper is based on this book. For those not knowing about ReSharper, it’s a Visual Studio extension that gives developers a significant boost in productivity by assisting with refactoring their code with confidence.

    Just like Patterns of Enterprise Application Architecture, this book goes over the basics of taking your code from spaghetti to lasagna (wait…is that better?). The first part of the book discusses “bad code smells”, how to identify bad code, and ways to fix it. Such refactorings include Long Methods, Large Class, Long Parameter List, Duplicated Code, and Switch statements to name a few.

    The code examples in the book are either Java or .NET or both and are extremely clear to understand each refactoring concept.

  3. Refactoring to Patterns By Joshua Kerievsky

    After you read the two books above, make sure you add this one to the list as well. If you thought both books were extremely valuable, then I highly recommend this book because it combines enterprise patterns with refactoring.

    For example, let’s say you have a huge if..then..else from hell. One refactoring called Replace Conditional Logic with Strategy Pattern takes the if..then..else and makes classes out of them while creating an abstract pattern to handle the heavy lifting.

    This is just one of the many great refactorings in this book.

  4. The Design of Sites: Patterns for Creating Winning Web Sites (2nd Edition) by Douglas K. van Duyne, James A. Landay, and Jason I. Hong

    You may be wondering why I’m recommending this “design” book to developers. I’ve always been of the mindset that designers are developers and vice-versa. You always need a good understanding of CSS and JavaScript/jQuery/Angular to build websites along with knowing what happens on the backend when someone clicks Submit.

    This book provides a catalog of “design patterns” for building websites. If you are looking for an ecommerce site, here are the components you need to make it successful to your audience.

    It’s basically a catalog of website standards that I use as a basic checklist for building sites from scratch and I also use it as a reference for evaluating the design of existing websites.

  5. Microsoft .NET – Architecting Applications for the Enterprise (2nd Edition) (Developer Reference) BY Dino Esposito and Andrea Saltarello

    I know I’ve discussed enterprise patterns with the Patterns of Enterprise Application Architecture book above, but this is geared more towards a .NET readership.

    The book is broken down into the following categories: Design Patterns and what is a design pattern; The Business Layer; The Service Layer; The Data Access Layer; and the Presentation Layer.

    If you’ve been coding with .NET in a corporate environment for a while, this may be the only book in the list that I suggest you pass on and purchase any one of the other books.

  6. Don’t Make Me Think, Revisited: A Common Sense Approach to Web Usability (3rd Edition) (Voices That Matter) By Steve Krug

    This is another design book that every developer should read. It includes a number of different ways of look at things when it comes to usability. When I was reading this book, each chapter gave me a different perspective of how to design a web page to get the most efficient use for my audience.

    Also, the book is doing extremely well because they are on the 3rd edition.

  7. Information Dashboard Design: The Effective Visual Communication of Data By Stephen Few

    If you’ve ever built dashboards in your experience, you’ll find this book very helpful. I’ve used it to develop 3 dashboards in my career and they seem to be getting easier and easier. 😉

    If you would like a better review of this book, check the post titled Book Review: Information Dashboard Design.

  8. Design Patterns in C# By Steven John Metsker

    Just as the Design Patterns book from the gang of four was a masterpiece, this book focuses on design patterns from the viewpoint of C# developers. It covers the original 23 patterns including Singleton, Strategy, Flyweight, Factory, and others.

    This is one of those fundamental books that should be used in colleges.

  9. Any O’Reilly Pocket References

    The O’Reilly Pocket References books provide a lot of critical information in one small package. I currently have and use the following pocket reference books: jQuery, JavaScript, SQL Pocket Guide, and Regular Expression.

    The funny thing about these pocket references is that I’ve had web professionals come over and borrow them for a couple of days when the Internet was at their fingertips.

    That tells me how much these pocket references are worth.

  10. The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin Series)By Robert C. Martin

    Everyone knows “Uncle Bob.” His coding experience is also apparent in this book. He covers Saying Yes, Saying No, TDD, Professionalism, Tooling, Craftsmanship, Mentoring, and Pressure just to mention a couple of chapters.

    It’s more of a combination of programming philosophies, how to handle your programming career, and how to write code properly.

Translating SQL to LINQ can prove difficult for new and experienced C# developers. This post contains common SQL queries written in LINQ. I hope it’ll serve as a reference when writing LINQ queries. I’ll use a MS SQL database and Entity Framework for my examples. However, these examples can be extracted to other ORMs and databases. Also, consider reading why LINQ beats SQL to learn how to think in LINQ terms rather than translating SQL to LINQ.

Data model

We’ll use a simple data model that contains books and authors for our examples.

Books authors and articles data model

Entity Framework data context


See the data model and Entity Framework data context to understand the setup for the following examples.



single column

multiple columns


See the data model and Entity Framework data context to understand the setup for the following examples.

single condition





Inner join

See the data model and Entity Framework data context to understand the setup for the following examples.


See the data model and Entity Framework data context to understand the setup for the following examples.




See the data model and Entity Framework data context to understand the setup for the following examples.


See the data model and Entity Framework data context to understand the setup for the following examples.


See the data model and Entity Framework data context to understand the setup for the following examples.

single column

multiple columns


See the data model and Entity Framework data context to understand the setup for the following examples.


See the data model and Entity Framework data context to understand the setup for the following examples.


See the data model and Entity Framework data context to understand the setup for the following examples.