Becoming a software developer – episode VI

Becoming a software developer – episode VI

Welcome to the sixth episode of my course “Becoming a software developer”, which will show you how to deal with types via reflection, asynchronous operations, multithreading and other more advanced parts of the C#.

All of the materials including videos and sample projects can be downloaded from here.


 

Scope

This episode will focus on the different features of the language that will be very useful later on, once we start creating the application:

  • Reflection
  • Dynamic
  • Attributes
  • Async & Await
  • Parallelism

Abstract

Reflection

There’s a way to access the types defined in the Assembly and perform many different operations on them, starting from the very simple ones like filtering types by names or some specific properties and more sophisticated (yet still easy to achieve) like invoking the methods dynamically or setting values of the object instance properties. There’s much, much more that you can with types and everything thanks to the reflection mechanism which, as the name states, allows to “reflect” the objects and modify them while running the application.
Everything is available via GetType() and nested GetTypeInfo() methods. You can also use typeof to get the type info based on the type itself, without a need to user the instance of an existing object

Dynamic is a special type, that is not being checked by the compiler during compilation. Instead, you’re free to do whatever you want with dynamic, as it will be resolved during run time, which is both powerful and error-prone. It’s very while used along with reflection and e.g. mapping types from external data sources like databases or HTTP API, that can be directly transformed into dynamic objects and later on you can assign its properties into some strongly typed class. In order to make a dynamic object that can be extended without limits, make use of the special type called ExpandoObject.

Attributes are “decorators” that we can put on top of out classes, methods or properties in order to assign to them e.g. some special behavior that can be understood by a framework which provides particular attributes. For example, you use Required or EmailAddress attributes on top of your properties in order to validate them by the .NET framework itself. Attributes are related to the concept of Aspect Oriented Programming (AOP) as well as IL Weaving which is a part of this, very sophisticated and difficult mechanism. You can also easily create your own attributes and use them with the help of reflection>

Async & Await

Asynchronous programming is a very powerful concept that allows delegating the completion of some tasks that do not require computing resources of your computer at some point in the future. Think about the following – you’re asking a database or an HTTP API for some data. It might take some time and there’s no need to sit and wait until this synchronous request finishes. You’re blocking the threads which are limited in terms of capacity, quantity and of course computing resources. Instead, you can use Task along with async and await keywords to perform the asynchronous operation and greatly increase the available resources of your computing machine. You can join tasks, execute another one when the previous finishes and do much more cool things with them. Just remember not to use the void while running an async method. Always use Task or Task, otherwise you might run into serious issues e.g. with the proper handling the exceptions. Remember that asynchronous methods make the most sense for I/O (input/output) operations and the naming convention is to mark the ending of the method with the Async suffix.

Parallelism
For the high intensive computing operations that require a lot of CPU power, you can make use of the TPL library which, for example, contains Parallel.ForEach loop that will process the given collection using multiple threads. This might provide a very nice boost and saves quite some time for example while processing a big amount of words that should be counted by their presence.

And it was the last episode in which we are talking about specific features of the language. There are many more that were not covered like operators overloading, or ref and out (of which I’m not a fan, to be honest), yet I chose the most important ones (in my opinion at least), that we will be using very often while creating the application in the near future. In the next episode, we will talk in general about testing (unit & integration) and mention the Test Driven Development (TDD) topic.

Resources

Next

  • Unit testing
  • Integration testing
  • End-to-End testing

11 Comments Becoming a software developer – episode VI

  1. FoTeL

    Super seria – gratuluję!
    Jak za pomocą typy dynamic utworzyć obiekty w przykładzie z asynchronicznym pobraniem listy zdjęć z serwera.

    Reply
    1. Piotr Gankiewicz

      Dzięki!
      Odnośnie utworzenia obiektów, to najprościej jest zdeserializować otrzymane dane z serwera np. z wykorzystaniem biblioteki Newtonsoft.Json. Można deserializować dane bezpośrednio na własny typ lub typ dynamiczny. Zatem otrzymujesz content w postaci string z HttpClient i następnie za pomocą JsonConvert.DeserializeObject<IList<Photo>>(content) dostajesz silnie typowaną listę obiektów własnej klasy Photo.
      http://www.newtonsoft.com/json

      Reply
  2. Pingback: Dew Drop - March 3, 2017 (#2433) - Morning Dew

  3. Pingback: Becoming a software Developer – episode VI – Patryk Huzarski | Personal Blog

  4. Kamil

    Jak wygląda wywoływanie metod asynchronicznych w WPF? Wspomniałeś, ze to z Wait() na końcu jest złą praktyką. Czy możesz przybliżyć jak prawidłowo powinno się to wykonywać w aplikacjach desktopowych?

    Reply
    1. Piotr Gankiewicz

      Z WPF miałem ostatnio tylko krótki 3 miesięczny epizod na przestrzeni ostatnich lat, więc zbytnio w tym temacie już nie siedzę ale podejrzewam, że jeżeli chodzi np. o pobranie listy danych i uzupełnienie nimi jakiejś tabeli czy formularza, to wystarczy odpalić zapytanie asynchroniczne bez użycia await, natomiast jeżeli chcesz coś zapisać w sposób asynchroniczny to albo można użyć od biedy async void (typowa operacja fire & forget) albo kombinować coś z jakimś loaderem, który reaguje odpowiednio na wykonanie asynchronicznego zapytania i dopiero wtedy np. przekierowuje użytkownika do innego ekranu. Ogólnie nie jest to zbyt trywialne :).

      Reply
  5. Kuchi

    Cześć,
    Przede wszystkim świetny kurs, fajnie prowadzony super tłumaczysz aspekty języka z którymi początkujący mogą mieć problem. Oprócz pochwał przychodzę tutaj również z wyjątkiem:

    klient Http wywala mi błąd w runtimie (na OpenSuse):
    ….
    at System.Net.Http.CurlHandler.ThrowIfCURLEError(CURLcode error)
    at System.Net.Http.CurlHandler.MultiAgent.FinishRequest(StrongToWeakReference`1 easyWrapper, CURLcode messageResult)

    Nie wiem czy nie jest to spowodowane OpenSSL’em. Czy .net core wymaga jakieś specjalnej konfiguracji w tym zakresie? Z góry dzięki za odpowiedź i za wspaniałą robotę którą wykonujesz 🙂

    Reply
    1. Piotr Gankiewicz

      Cześć,
      Dzięki, niestety nie wiem za bardzo co to za problem, .NET Core nie wymaga żadnej konfiguracji, natomiast problem z HttpClient w tym przypadku może być specyficzny dla danego OS, najlepiej gdybyś przetestował ten sam kod na innym środowisku.

      Reply
      1. Kuchi

        Na elementary OS działa bez problemu 🙂 Dla OpenSuse istnieje problem z certyfikatami (nie byłem pierwszym osobnikiem z takim problemem). Mimo wszystko dzięki za pomoc.

        Reply

Leave a Reply to Mario Botero Cancel reply

Your email address will not be published. Required fields are marked *