Why provide interface with your library?

In daily programming activities some of use have the pleasure to use TDD approach 馃檪 Going deeper we can introduce the concept of mocks/stubs/shims. For the sake of this article let’s call it mocks.
Quite often we use 3rd party libs becuase they offer some functionalities we need. For example:

  • Email Client
  • FTP Client
  • Currency Rates Provider

Simple use-case scenario could be “Take all email from mailbox with subject “ERROR REPORT”. So we have:

public class ErrorEmailHandler
{
    public List<Email>GetErrorEmails()
    {
     .......
    }
}

Let’s say we have a test case: 5 out of 10 emails in mailbox have “ERROR REPORT” subject and those should be returned by GetErrorEmails() method. We don’t care what is the underlying source.

Solution 1

One, pretty naive, test case solution could be to:
1. Send 10 e-mails where 5 have “ERROR REPORT” subject
2. Test that we receive 5 back in GetErrorEmails()

Works? Works 馃檪

I hope that you feel the pain of this solution. We are not interested in testing host connection, mail server or even mail client library that we use. We just want to test that our method return only emails with particular subject.

Of course we could have a local process that will act as a mail server… or ftp server… or currency rates server if we need…..

Solution 2

Much wiser would be make a wrapper on the 3rd party lib we use. Our wrapper could look like following

interface IEmailClient
{
     List<MailMessage> GetMessages();
}

class EmailClient : IEmailClient
{
     public List<MailMessage> GetMessages()
     {
          return ..........
     }
}

Having that in place we can just mock IEmailClient and return those 10 messages were 5 are with “ERROR REPORT” subject in our tests. You should also add some extra tests for the wrapper class (it’s internal state).

Solution 3

Yet there is even better solution. Imagine if IEmailClient interface would be provided by the 3rd party dll. You can skip writing the wrapper class as well. All that can be mocked. This includes FTP Clients, Currency Rate Providers and tons of other services.

I would recommend (also to myself) providing public interfaces for out libraries as often as possible.

Cleaner code-base leads to better quality.

Learning from different types of books

In the past there were myths and legends passed between generations. Later Gutenberg introduced printing… a the knowledge started to spread across the world rapidly. This days books are main sources of transferring knowledge. Open-minded people read a lot. I try to stay open-minded….

It’s a sin to know how to read and don’t use that craft!

Said that I have a goal to read 10-20 books a year. Sometimes more sometimes less. I do that for many years now I some patterns started to show up.

Book types

For the sake of learning I’ve recognizes so far following types of book:

  • Classics
  • Extra technical
  • Soft skills
  • Other POV/industries
  • Biographies
  • Diaries

All above are complementary types to improve your software engineering skills.

Classics

The key feature of Classics books is that they are still up to date over time. They don’t get outdated. If you consider yourself a professional software engineer, system architect or somebody with programming embedded in your DNA you have already a list of those in your head.

I would even recommend to come back to those kind of books from time to time.

Examples:
* Algorithms (4th Edition)
* Design Patterns: Elements of Reusable Object-Oriented Software
* Clean Code: A Handbook of Agile Software Craftsmanship
* Test Driven Development: By Example
* Working Effectively with Legacy Code
* Hackers & Painters: Big Ideas from the Computer Age
* Code Complete: A Practical Handbook of Software Construction
* Rapid Development: Taming Wild Software Schedules
* Object-Oriented Software Construction

Extra technical

Extra technical books are focused of certain topic. Like .NET 2.0 or WPF 4.0. When I was raising my BizTalk programming skills I read plenty of those kind of books. Good thing here is that they provide very focused knowledge in specific topic. They describe particular software/platform/framework. Usually they get obsolete after few years or need an update when new version of the software is released.

Examples:
* WPF 4.5 Unleashed
* C# 5.0 Unleashed
* C# in Depth, 3rd Edition
* CLR via C#
* Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries

Soft skills

Humans are social persons. It’s in our genes. Especially for teams that act together – play football, produce software or do any other activity where 1+1>2 馃檪 Learning about humans and understanding yourself is a substantial asset. This enables you to be more effective.

Examples:
* The Mythical Man-Month: Essays on Software Engineering
* Peopleware: Productive Projects and Teams
* The Pragmatic Programmer: From Journeyman to Master
* Coders at Work: Reflections on the Craft of Programming
* Soft Skills: The software developer’s life manual

Other POV/industries

Those kind of books extend self awareness. At least this is how I feel it. Reading about economics or medicine is quite interesting it you understand all the keywords 馃檪 Abandon the book if you feel lost 馃檪

Here are no example. Pick something that interests you and will extend your knowledge. Law, economy, innovation. Generally if book has 200 pages you should finish it in 3 days.

Biographies

I like reading biographies. They uncover people’s wins and loses which allowed them to be who they are. Achieve what they achieved. You can connect the dots and deduct yourself what factors were in place for those people. What drives Elon Musk? How Socrates became famous?

Choose people who inspire you.

Examples:
* Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
* Einstein: His Life and Universe
* Tesla: Inventor of the Electrical Age
* Losing My Virginity: How I Survived, Had Fun, and Made a Fortune Doing Business My Way
* My Life & Work – An Autobiography of Henry Ford

Diaries/histories

This type of books is quite similar to biographies except it focuses of companies, brands, products and other business/social initiatives. Generally it uncover again aspects that allowed particular companies to raise or die. How Inter, Ford or Microsoft became who they are. What happened to Kodak. Why .NET Framework was introduced. Why Tesla is so recognizable and so on 馃檪

Examples:
* Moneyball: The Art of Winning an Unfair Game
* Renegades of the Empire: How Three Software Warriors Started a Revolution Behind the Walls of Fortress Microsoft
* Masters of Doom: How Two Guys Created an Empire and Transformed Pop Culture
* Death March

Reading recommendations

I have even made a list of my books recommendation available here: http://blog.klimczyk.pl/books/.

Autofac, DataContext and MemoryCache issue

Prolog

In one of my web application I use MemoryCache to improve performance. The code looks like this:

public class CurrencyRepository(DbContext context)
{
    private DbContext context;

    public CurrencyRepository(DbContext context)
    {
        this.context = context;
    }    

    public List<Currency> GetList()
    {
        /* read data from context*/
    {
}

public class CurrencyService(ICurrencyRepository repo)
{
    public List<Currency> GetList()
    {
        /* read data from MemoryCache*/
    {

    private void InitCache()
    {
        /*populate MemoryCache from repository*/
    }
}

//Autofac module configuration (only relevant part)
     builder.RegisterType<CurrencyRepository>().As<ICurrencyRepository>().InstancePerLifetimeScope();
     builder.RegisterType<CurrencyService>().As<ICurrencyService>().SingleInstance();

This configuration works. CurrencyRepository reads data from DbContext when CurrencyService wants to populate the cache.
Next time request is coming to CurrencyService the cached version is served. This is excellent!

Problem

The problem is that because CurrencyService is SingleInstance it will always keep reference to CurrencyRepository. That implies reference to DbContext with all data changes tracking information. For small pet-projects this is not an issue. We can live with that. But logically CurrencyRepository is needed only when reading data from persistence layer. The issue will be more visible when cache grows because DbContext will also grow.

Solution

What is needed here is CurrencyRepository creation and disposal when cache is populated. I was thinking how to achieve that with Autofac, but I failed.

What I did instead is following:

public class CurrencyService()
{
    public List<Currency> GetList()
    {
        /* read data from MemoryCache*/
    {

    private void InitCache()
    {
        CurrencyRepository repo = new CurrencyRepository(new DbContext());
        /*populate MemoryCache from repository*/

        repo.Dispose();
    }
}

CurrencyService is responsible for creating and disposing CurrencyRepository. It happens on demand, so the reference is not kept all the time.

TDD – there is no TDD? WTF!!!

Solution presented above is difficult to unit test. I agree with that. This line:

CurrencyRepository repo = new CurrencyRepository(new DbContext());

violates tons of rules 馃檪

One stupid simple refactoring would be to pass the Autofac container as a parameter in CurrencyService contructor (and some brain cells are again screaming WTF!!!). This way we achieve **true TDD*.

I will discuss TDD aspect for this specific problem in more details in the future posts.

Epilog

The take away from this post is following note:“Do not copy blindly the code. Think how it will work. Adjust “how it will work” to “how it should work”.

GeekWeekWro #2

During my daily work I’m creating an integration system using Microsoft technologies like BizTalk. There is a lot of exciting challenges to meet 馃檪 System health monitoring, message archiving and modular structure are just some of them. Apart of that I’m involved in wrocnet.org. Last week our monthly meeting was a part of GeekWeekWro #2 – week of IT events in Wroclaw.

GeekWeekWro

geekweek_wyb_duze_cs3
GeekWeekWro (GWW) is an initiative that combines many (hopefully all) IT groups in Wroclaw. When we, as groups, join forces we are stronger. This year I was one of the GWW organizers. In particular I was involved in WrocNET organization and hack4culture hackathon.

#2 Edition

Here is the timeline
timeline-vertical
As you can see a lot was happening last week 馃檪 I was attending events every evening except Thursday (I was already tired then :P)

Some pictures

hac4culture
hack4culture hackathon – organized by Unit4

techsaturdays
TechSaturdays – startup geeks in Wroclaw

wrocnet
WrocNET – .NET in Wroclaw:)

azure
Global Azure Bootcamp 2016 – with Tomasz Wi艣niewski on stage (organized by 艁ukasz G膮sior)

software-talks
Software Talks – organized by PGS

Wroclaw IT

This is why I love Wroc艂aw 馃檪

NET Developers Poland FB group [PL]

This post will be in polish since it is totally related to polish .NET group on Facebook

Geneza

Grupa .NET Developers Poland (dalej w skr贸cie NETDPL) powsta艂a w celu dzielenia si臋 wiedz膮 na temat nowo艣ci ze 艣wiata .NET.

W pewnym momencie przesta艂em ogarnia膰 ogrom wszystkich news贸w pojawiaj膮cych si臋 w setkach miejsc i uda艂o mi si臋 stworzy膰 lokalny (polski) eko-system do dzielenia si臋 warto艣ciownymi informacjami jako grup臋 na Facebooku.

Dlaczego chcesz do艂膮czy膰 do grupy .NET Developers Poland?

Jest to standardowe pytanie zadawane 99% os贸b, kt贸re chc膮 do艂膮czy膰do NETDPL. Ma ono na celu zweryfikowanie, 偶e dana osoba na prawd臋 jest zainteresowana tematem. Najwa偶niejsz膮 rzecz膮 jest sprawdzenie czy osoba X pasuje do profilu grupy i czy wniesie co艣 warto艣ciowego od siebie.

Nie interesuj膮 mnie osoby, kt贸re b臋d膮 informowa膰 o nowych postach na swoim blogu – do tego jest RSS. Albo osoby m贸wi膮ce tylko o konferencji, kt贸r膮 organizuj膮.

Je偶eli kto艣 wys艂a艂 pro艣b臋 i nie zosta艂a ona rozpatrzona niech napisze do mnie na FB wiadomo艣膰 prywatn膮.

Wyj膮tki

Czasem, w drodze wyj膮tku, przyjmuj臋 do grupy osoby nie b臋d膮ce programistami. Jest rekruter, kt贸re czasem wrzuca linki do ciekawych post贸w rekrutacyjnych. Jest prawnik ds. IT (jak kolwiek by to nazwa膰). Chodzi o to, 偶e ich posty i komentarze s膮 wg. mnie przydatne dla nas jako programist贸w. Oni maj膮 te偶 jakie艣 plusy dla siebie (chocia偶 nie pyta艂em o to).

Zasady

Grupa przeznaczona jest dla programist贸w. Nie tylko programist贸w .NET. Uwa偶am, 偶e warto da膰 mo偶liwo艣膰 wypowiedzenia si臋 kazdemu – je偶eli ma do powiedzenia co艣 warto艣ciowego. Zasady s膮 do艣膰 rekstrykcyjne, poniewa偶 w przeciwnym razie NETDPL sko艅czy艂a by jak 99,99% grup na FB – jak spam placeholder. Nie interesuje mnie anarchia 馃檪

Grupa posiada regulamin. Ka偶dy z cz艂onk贸w mo偶e zaproponowa膰 jego ulepszenia. Do wersji 1.0 jeszcze daleko, tak偶e my艣l臋, 偶e razem co艣 ulepszymy 馃檪

Podgrupy

Wraz z rozwojem NETDPL zasz艂a potrzeba wyodr臋bnienia “logicznie niesp贸jnych element贸w”. G艂贸wnym celem jest dzielenie si臋 wiedz膮 i porty o pomoc albo “n臋kania” rekruter贸w spowodowa艂y, 偶e wyp膮czkowa艂y dwie podgrupy:

  • DevHelp – do pomocy w problemach programistycznych;
  • JobMarket – dla programist贸w szukaj膮cych zlece艅 i rekruter贸w szukaj膮cych programist贸w.

Ka偶da z powy偶szych grup ma sw贸j ma艂y regulamin, 偶eby wszystko trzyma艂o si臋 jakich艣 zasad.

Usuwanie post贸w i follow-up

Facebook ma przynajmniej jeden do艣膰 nurtuj膮cy problem. Ot贸偶 ci臋偶ko odwo艂a膰 si臋 do usuni臋tych post贸w.

Przyk艂ad:
Osoba dodaje post niezgodny z regulamin po czym wywi膮zuje si臋 “walka w komentarzach”. Przychodz臋 po kilku godzinach na pobojowisko, gdzie dogorywaj膮 waleczni programi艣ci broni膮cych swoich racji i…… chce usun膮膰 post bo 艂amie regulamin. Nie czuj臋 sie z tym dobrze, bo w zasadzie wrzucam wszystko do /dev/null… bez wyt艂umaczenia itp. Nie chc臋 robi膰 tego tak ostro, ale FB nie daje innej mo偶liwo艣ci na t臋 chwil臋. Dlatego prosz臋 piszcie do mnie jak uwa偶acie, 偶e co艣 nie zosta艂o do ko艅ca wyja艣nione.

Podsumowanie

Mam nadziej臋, 偶e uda艂o mi si臋 wyja艣ni膰 o co chodzi w grupie .NET Developers Poland.

Czekam na ewentualne sugestie.

Nuget and strong-signed dll

Idea

Nuget is very good packed manager tool for .NET projects. We all use Nuget to get all necessary dependencies in our project. Usually our projects are installed in Program Files or inetpub, which is perfectly valid 馃檪 Referenced dlls will be installed along with our projects. Everything is great!

The problem appears when we want/need to deploy our project to GAC. In such a case we have to sign assembly with strong-key. Here it’s explained why all assemblies have to be strongly signed. We can configure signing our assemblies (Project properties->Signing in VS) and we are ready to go…. except referenced assemblies have to have strong-name too.

Pain

So we ended up with very useful, but not signed assembly from Nuget… We have at least 3 options how to relief the pain:

  1. Search in Nuget for a signed version of our assembly. I was lucky with RestSharp because there is a signed version
  2. Recompile referenced dll and add a strong-name to it. This solution has a number of side-effects. Compiling extra project, updating and so on….
  3. Sign assembly without recompiling (link). I didn’t try that yet, but it seem to mitigate some pain from 2nd point.

Our assembly in Nuget

When we also have some tiny assemblies in Nuget available for other developers, we should consider providing singed-version. Once I had to replace one assembly with something else just because it was not signed.
Missing strong-name version problem also applies to my tiny HandyLib project, so I’ve added it to my TODO already 馃檪

‘SOLID for Adults’ session at WDI 2016

On wednesday I’ve attended Warsaw IT Days (Warszawskie Dni Informatyki in polish). This time as a speaker :). It took me one year to jump back on stage :). I was giving a talk called “SOLID for Adults” as a part of DevTalk – Deep Dive track.

WDI-2016

I’ll not describe all the details, but here is the link to presentation so everybody can have a look what is it about.

In summary: SOLID is good when applied but make use of Occam’s law (assume as less as possible and don’t multiply abstractions) and don’t overcomplicate things 馃檪

Link to download https://github.com/pawelklimczyk/Presentations/blob/master/SOLID%20for%20Adults/2016-03-23%20Warszawa/SOLID%20for%20Adults%20-%20Pawel%20Klimczyk.pptx

Notes from meetings – my approach

TL;DR;

Write down everything from the meeting 馃檪

Day after meeting we remember 20% from it

That’s a statement from some research. If you don’t practice, don’t train you muscles or brain to perform particular actions, it will forget how to remember.
Recently I was involved in several different projects. They were not related each other. I had huge problems with remembering everything I should remember….

Paper notes to the rescue!

On some point I decided to take notes of key things I though I would need later. I used A4/A5 paper sheets and pen/pencil. While discussing I’ve spend little time to write down short sentences, keywords, web addresses etc. If you don’t know what to write down – write everything you can.

Every note has a header with title and date. Some of the notes have also page numbers. Usually I don’t try to compress as much text as possible on single piece of paper. I like rather to have some extra space free just in case later I would have to add more to that particular context.

Depending on the meeting some notes have one page and some ten 馃檪

Writing without looking

One thing that would help me a lot is ability to write without. For the moment I have to take a quick break to write down something. Sometimes I need extra time to jump back to meeting 馃檪 It is quite inconvenient and annoying. I guess I’ll master writing without looking with more and more practice.

Sections in paper notes

I have mentioned that already above, but I’ll elaborate it bit more.

What I mean by section is usually rectangular area with some text and some free space. Section is something like context.

Taking notes has to be fast. Fast mean with bigger probability to introduce errors. That’s why I like to leave some empty space in section. To rewrite something or to add. Additionally sometimes during conversation we are coming back to the topic we’ve already discusses. Then I just jump back to particular section. If section is becoming bigger I like to add a header to it.

After meeting

So meeting is done. Things are discussed, maybe agreed 馃檪 It’s time to take actions with paper notes!

I usually take every section one by one. Handle it (read below), cross it out and when all sections are handled throw away the paper note.

When it comes to notes/sections handling It deserves separate blog post. In short I do one of following:

  • Do the action in note (like visit a webpage or send email)
  • Move note to Evernote/Trello
  • Move note to weekly TODO list

One more thing worth mentioning here is tagging. When I have to handle a multi pages note I tag similar sections with color markers. This helps me to do batch work after. I focus on one tag 馃檪

Good pen

Advice: always have a handy pen. One that you like to write with. That fits your fingers. Of course wear second as a backup.

Summary

In short summary I think that taking notes and handling them improved my daily work. I don’t have to remember tons of information and be worries if I forgot something. I think it’s a habit right now 馃檪

WROC# 2016 – by engineers, for engineers

Intro

I was waiting for this event for a year. With some anxiety thoughts about tickets… and so on. But I made it! This is my point of view.

TL;DR;

Objectivity did excellent work with this event focused on delivering world-class value to programmers. Now, dear reader, read the rest 馃槢

Pre WROC#

At WrocNET we took the opportunity to organize our local event day before Wroc#. We had +150 participants (this is how many finally signed up on meetup). We had visitors from 艁贸d藕, Warszawa, Krak贸w, Zielona G贸ra, Katowice, Bielsko-Bia艂a and Rzesz贸w (at least from those) – amazing. Our sponsor PGS provided drinks and pizza!. I think it went pretty well.

WROC# boosted local .NET community, that’s for sure 馃檪

Speakers and sessions

I’ll not describe all the sessions here. You can find other blog posts about it:

Generally my overall sessions score on survey was 4.5/5. Every session brought something new to me – which is perfect!

Engineers

There were tons of signs that conference is held by engineers. Agenda printed on punch card. Integral calculation as on of the tests in contest. Retro-games.
You can just feel that you are in the correct nest, with correct people. I was even satisfied that there is room for improvement for the organizers. That implies finding a bug in the conference, giving feedback how to reproduce… and wait for the fix….. till next year 馃檪

All fits together very well!

Computer museum

This deserved extra paragraph! It does not matter who you are, what you do, where you go. You should know the culture and history of the passion you sacrifice substantial amount of you life. If you ask Messi who is Maradona or van Basten, what will he answer? The answer would probably be: “Great football players and in addition both of them are left footed, like me :)”.

On WROC# we could have a look and touch computers used 20, 30 or even 40 years back. Computers made before some of us were even born. We need to know our origins.

You as a software engineer just need to know the machines and languages used in the past. It’s part of you entity.

Thanks to places like that museum, we as XXI century engineers, do not forget our history. Our culture. Or Dennis Ritchie….

Contests & meals

There were several contests during the event. Quiz, contests after every session and table football competition. I’ve participated in first 2, but without success :P. Next time I demand a darts tournament!

Meals server during event also deserve separate paragraph. As a standard there was coffee and sweet rolls served during breaks. Surprisingly, there were also hot-dogs! Totally nerd’s stuff. Then there was typical lunch and at the end there was Asian and Italian cuisine server this way:

cuisine

Ofc. veggies version were available.

Community

I think this is the biggest value for the audience. We, as .NET developers, could meet similar people from different regions in Poland. I meet some who came from UK or Switzerland 馃檪 I had great time talking with all of you. Following pic shows what a mix of people from Poland we had:

community

Outro

Wroc# is over. I’m proud that this happened in Wroc艂aw. That we had opportunity to meet great speakers and dev-geeks from Poland. Thank you Objectivity for making this happen in Wroclaw, again!

ps.
The only bad thing was that I was home at 0:00 both after pre-Wroc# and WROC#…. But It was worth!

Debugging WPF Bindings

WPF + MVVM is very common way to make windows apps. It introduces concept of data binding. We create a view-model based on one or many models and bind it to the view. Usually it is easy….
But how do you debug bindings if something is not going right? For example you have Control Templates and styles and so on introduced in your app.

Since WPF 3.5 there is new diagnostics featured that you can turn on and it will output detailed binding messages to the Output window. Immensely helpful when you are trying to figure out why your binding does not work or works incorrectly.

To set it up first add diagnostics to your namespace:

<Window x:Class=鈥漈ester.Window2鈥 
xmlns:diag=鈥漜lr-namespace:System.Diagnostics;assembly=WindowsBase鈥

Then enable it on per-binding instance as such:

ItemsSource=鈥漿Binding Path=PaneItems, 
diag:PresentationTraceSources.TraceLevel=High} 

Now when you run your app watch Output window for clues on why binding is failing.

Hope this helps save your sanity while debugging bindings as much as it does mine 馃檪