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 馃檪

Local IT communities – snowball effect

Meet with the best or die like the rest!

I like to meet people, discuss things related to programming, new technologies, ideas and so on. I was living in several cities and always wanted to stick to people sharing same interests. After moving to Wroc艂aw few years ago I immediately joined WrocNET. At the moment I’m one of the organizers and looking forward for next meeting 馃檪

We use Meetup to organize meetings. Meetup actually opened a pandora’s box for me…..

Snowball effect

Meetup provides a very interesting possibility to check what is organized in your neighbourhood. Recently I have attended following events: Atlassian User Group, wroc.py and WrocNET. I attending 3 next meetings this week!

It looks like Meetup started a snowball effect because all the time new events pops up 馃檪

I encourage all of you to leave save zones (aka caves) and meet other developers in real life.

Multilingual team communication

Communication is substantial skill for humans. That applies also to software projects.

According to this article (and many others) lack of communication is one of the reason of project failures. After some years in software development business I’m able to share my observations on how to improve communication.

Here is the list:

  • Establish a common vocabulary for the project and team.
  • Explicitly articulate what you mean if somebody look confused.
  • Ask person to repeat your sentence in his words when something is unclear.
  • Try to explain issue/solution etc. using other words if someone is still confused.
  • Ask for clarification/explanation if you don’t understand something.
  • Use pen+paper technique to visualize your thoughts.

In addition if you have multilingual team you should also take into account following:

  • Give the team some time to ‘learn’ each other. What words do they use to express them selves or describe emotions.
  • Take into account person’s culture. Some people may for example disagreeing by not saying a word.
  • Skip person’s language errors, except cases when you don’t understand whole sentence :).
  • Wikipedia may help sometimes. Find term in your language and switch to their language or something that they understand.

Above lists are perhaps not complete, but they can be starting point for further elaboration.