Monthly Archives: June 2020

PrimeHotel – passing parameters to actions – assignments

This is a post with assignments to do if you would like to check your knowledge about ASP.NET Core in .NET 5. This one is about passing parameters to controller actions, which is a crucial thing to master when developing micro-services.

You don’t need to start from scratch, you can base on a PrimeHotel project, created especially for learning purposes. You can download it on my GitHub page. Also, take a look at the post on how to run this project: PrimeHotel – how to run this project

Full article about passing parameters to actions in ASP.NET Core in .NET 5 can be found here: ASP.NET Core in .NET 5 – pass parameters to actions

Assignment 1

Difficulty: easy

Context

Learn how to write CRUD operations. Let’s say we would like to handle invoices – add all methods that will allow handling invoices.

What needs to be done

  • create a new class called Invoice
  • create Add, Get, Update and Delete methods to handle invoices
  • list of invoices can be hardcoded in the controller class
  • add optional filtering in Get with query string parameters

Hint

Have a look at the WeatherForecastController and how we handle weather forecasts there.

Assignment 2

Difficulty: medium

Context

Learn how to pass array in a query string. It can be useful when you would like to pass a collection of objects but use a query string for it

What needs to be done

  • create a GET method
  • this method needs to accept an array of integers from the query string
  • how you would invoke this method and pass parameters?

Where to post the answers?

Simply write a comment to this post, I’ll take a look.

Or, if you feel like it, make a pull request to PrimeHotel repo.

Good luck! 🙂

PrimeHotel – jak uruchomić projekt

W tym poście poprowadzę Cię przez proces pobierania i uruchamiania mojego projektu – PrimeHotel. Jest to projekt stworzony do celów edukacyjnych, dzięki czemu masz swobodę wprowadzania zmian, klonowania projektu i wykorzystywania go do wszelkich działań niekomercyjnych.

Jest to średniej wielkości serwis reprezentujący system do zarządzania hotelem. Przechowuje rezerwacje użytkowników, profile użytkowników i zapisuje je w bazie danych MS SQL. Może także połączyć się z zewnętrzną usługą pogodową, aby pobrać bieżącą pogodę. Z czasem pojawi się jeszcze więcej funkcji, które pokażą więcej integracji i możliwości platformy .NET, dobre praktyki i niesamowite możliwości.

Jeżeli dopiero zaczynasz swoją przygodę z .NET, zerknij proszę na ten post: .NET 5 – Jak zacząć. Pomoże Ci w skonfigurowaniu twojego środowiska pracy i pokrótce opowie jakie są możliwości .NET.

Pobieranie projektu

PrimeHotel to projekt .NET 5, który wykorzystuje ASP.NET Core i Entity Framework Core 5. Jest on hostowany na GitHub, dzięki czemu możesz przejść do tego linku: https://github.com/mikuam/PrimeHotel

Upewnij się, że masz zainstalowany Git na swoim komputerze. Następnie możesz sklonować projekt za pomocą polecenia w terminalu konsoli.

git clone https://github.com/mikuam/PrimeHotel.git

Teraz otwórz projekt w swoim ulubionym IDE, takim jak Visual Studio lub Visual Studio Code.

Korzystam z programu Visual Studio 2019 i na moim komputerze wygląda to tak.

Rzućmy teraz okiem na strukturę projektu:

  • Clients – tutaj są klasy komunikujące się z innymi usługami za pomocą HttpClient
  • Controllers – tutaj są wszystkie klasy kontrolerów zawierające wszystkie punkty końcowe w tej usłudze
  • Data – klasy repozytoriów, które zawierają polecenia SQL – obecnie Dapper
  • Migrations – migracje Entity Framework Core 5, które utrzymują zmiany schematu bazy danych
  • Models – klasy Entity Framework Core 5, które reprezentują tabele w bazie danych

Konfiguracja bazy danych

Do celów edukacyjnych najlepiej skonfigurować SQL Server na komputerze. Właśnie to robię. Jeśli jednak chcesz ustawić go jako obraz dokera, możesz przeczytać o nim mój post: Set up a SQL Server in a docker container.

Możesz pobrać wersję SQL Server Express za darmo ze strony Microsoft. Po zainstalowaniu i skonfigurowaniu serwera będzie on prawdopodobnie dostępny z adresem localhost. Spróbuj połączyć się z serwerem SQL Server i sprawdź, czy masz bazę danych PrimeHotel. Do łączenia używam Azure Data Studio – niesamowite i szybkie narzędzie, idealne do prostych zadań.

Jeżeli nie masz bazy PrimeHotel, to po prostu ją stwórz i pozostaw pustą.

Ostatnią częścią jest zmiana connection stringa w projekcie. Aby to zrobić przejdź do edycji pliku appsettings.json. Wygląda on następująco:

Connection string może się nieco różnić, jednak mój wygląda tak:

Data Source=localhost;Initial Catalog=PrimeHotel;Integrated Security=True

Zamiast członu localhost możesz mieć coś podobnego do localhost\SQLEXPRESS, jednak jaki dokładnie będzie adres zależy od konfiguracji SQL Servera.

Uruchomienie projektu

Kiedy wszystko jest już gotowe, możesz już uruchomić projekt. Pamiętaj, że potrzebujesz także mieć zainstalowane środowisko uruchomieniowe .NET 5(.NET 5 runtime) oraz pakiet SDK.

W Visual Studio możesz po prostu nacisnąć F5. W Visual Studio Code otwórz okno terminala i wpisz dwie komendy: dotnet build oraz dotnet run. Następnie przejdź w przeglądarce do linku, który wyświetli się na konsoli. Powinieneś zobaczyć coś takiego:

Proste, prawda? Gratulacje, właśnie uruchomiłeś PrimeHotel. Teraz możesz zacząć kodować i ulepszać ten serwis.

Powodzenia!

PrimeHotel – how to run this project

In this post, I will guide you through the process of downloading and running my project – PrimeHotel. It is a project created for learning purposes so you are free to contribute, clone, and use it for any non-commercial activity.

It is a medium-sized service, that represents a hotel management system. Is holds user reservations, user profiles and saves them in the MS SQL database. It can also connect to a 3-rd party weather service to fetch current weather. More features are yet to come, which will show more .NET integrations and capabilities, good practices, and some awesome features.

If you are new to .NET, please take a look at this post first: .NET 5 – How to start. It will help you with making your first steps.

Download the project

PrimeHotel is a .NET 5 project that uses ASP.NET Core and Entity Framework Core 5. It is hosted on GitHub, so you can go ahead and navigate to this link: https://github.com/mikuam/PrimeHotel

Make sure you have Git installed on your machine. Then you can clone the project by using a command in a console terminal.

git clone https://github.com/mikuam/PrimeHotel.git

Now open the project with your favorite IDE like Visual Studio or Visual Studio Code.

I’m using Visual Studio 2019 and on my machine, it looks like this.

Let’s now have a quick look at the project structure:

  • Clients – this is where are classes that communicate with other services with HttpClient
  • Controllers – here are all controller classes containing all the endpoints in this service
  • Data – repository classes that encapsulate SQL commands – currently Dapper
  • Migrations – Entity Framework Core 5 migrations, that keeps the database schema changes
  • Models – Entity Framework Core 5 classes, that represent tables in the database 

Configure the database

For learning purposes, it will be best to set up a SQL Server on your machine. This is what I’m doing. However, if you would like to set it up as a docker image, you can read my post about it: Set up a SQL Server in a docker container.

You can download a SQL Server Express version for free from the Microsoft website. Once you install and set up a server, it would be available probably with the localhost address. Try to connect to your SQL Server and check if you have a PrimeHotel database created. For connecting I’m using Azure Data Studio – an awesome and fast tool, great for simple actions.

If you don’t have a PrimeHotel database, just create it and leave it empty.

The last part is to update a connection string in our project. Go ahead and edit appsettings.json file. It looks like this:

The connection string might differ slightly, mine is:

Data Source=localhost;Initial Catalog=PrimeHotel;Integrated Security=True

Instead of localhost you could also have something as localhost\SQLEXPRESS, but that is your individual configuration of SQL Server.

Running the project

When you have everything in place, just go ahead and run the project. If everything is set-up and .NET 5 runtime and SDK are installed, you should be good.

In Visual Studio just press F5. In Visual Studio Code open the terminal and write two commands: dotnet build and dotnet run. Then when navigating to a given URL, you should see something like this:

Simple, right? Congratulation on running the project. Now you are good to go for coding and improving this service.

Good luck!

 

What I learned from $2500 Udi Dahan course

Around the beginning of April 2020 Udi Dahan, owner of Particular Software, released his course in a form of online videos, for free. The big deal is that Udi is one of the world’s foremost experts on Service-Oriented Architecture, Distributed Systems, and Domain-Driven Design. This was a trigger for me and my whole team to watch the course and have a weekly discussion session to talk through completed chapters. Here is what I learned.

Use messaging

In his course, Udi highlighted many times, that messaging can solve most of your service-to-service communication. It may be slower than traditional RPC calls, but it’s more reliable and stable. It also scales better, because it doesn’t really matter how many subscribers there are, but rather how easy we can change the existing architecture.

With RPCs, services are strongly bonded together and need to support the same contract. When the change is needed, we often need to change more than one service. With messaging we can use messages that are already sent and build a service that we need. 

It is also worth mentioning that messaging systems are in the business for a long time and there is a handful of solutions to choose from. It’s not a technology that is still changing quickly, but it’s been here for a while.

There’s no single best solution

This is something that was repeated dozens of times across the course. Udi showed the best available approaches and architectural styles available: RPCs, messaging, micro-services, CQRS, Sagas, and showed their good and bad usages. All those concepts are great, but it doesn’t mean that we should use one of them for everything. It’s actually better to combine a few approaches, technologies, database models and use whatever suits the problem best.

For example, if CQRS works great for one e-commerce solution, it doesn’t mean that now it is the formula for every e-commerce there is. Therefore we shouldn’t take unconsciously whatever worked for previous project without greater analysis.

Find your service boundaries

This was one of the most important chapters and an a-ha moment for me and my teammates. Udi explained how important it is to find the service boundaries – places where a business domain can be divided into smaller pieces. It also defines the best places where big codebase can be divided into smaller, independent services.

Let’s take a look at the example. Let’s say we are building a hospitality system, that a guest can interact with.

So we have nicely separated micro-services, each with separate front-end and DB. They are communicating via messages in Service Bus and save data they need in DB, in the form they need them. Every change done by the user is saved in DB and propagated via message.

So what’s wrong?

It may seem that it’s a perfect decoupled solution, that can be scaled according to needs. However, there are a few problems. The first one is that we have a lot on infrastructure to maintain: services and databases must have a deployment process and with this approach, we are going to have more and more small services.

The second one is scalability. They seem easy to scale because everything is separate, but in most cases, there will be no need to do so. We will end up using resources we do not need. The other thing is that it’s not easy to maintain many instances of a service, where you have the same database. Stateful services are hard to scale, where stateless services can be scaled easily. Scalable services need to be designed with this specific goal in mind.

The third and less obvious one is that those services are actually not decoupled. They are working on the same data: user basic data, reservation details, reservation suborders, and payments. We will end up having all those data in every database. Don’t get me wrong, data duplication isn’t a bad thing when it comes to reading. But when a change is necessary, it has to be synchronized with every service that uses this data. Now, let’s have a look at a different approach.

In this approach, we still have separate front-ends but we have a single API and DB. The deployment process is easier, applying a change of contract is also easier, because we can do it all at once and we need much less synchronization. Of course, this is only an example and it wouldn’t fit every scenario, but here it makes sense.

Micro-services approach doesn’t have to be better than the monolith

When looking at an example above, we clearly see that having slightly bigger services can bring certain advantages to our architecture. When building micro-service it is a common pattern, that it should do one thing only. It can lead to services, that would have a single method in their APIs. While it may make sense in some cases, it would result in creating many very small services, that contain more synchronization code, than the actual business logic.

On the other hand, a monolith does not need to be a bad idea. If we can make it performant enough and the codebase isn’t that bad, then it actually has some advantages. For example, introducing a change is far easier and quicker than in many micro-services. Also, we have all business logic and contracts in front of our eyes, where we can easily see it. It’s also easier to write unit tests in the monolith than integration tests with a micro-service approach.

Don’t try to model reality – it doesn’t exist

A very powerful sentence, that Udi said when talking about domain modeling. Although it is said that Object-Oriented Programming should mimic the real world, it doesn’t seem to be the right approach. Let me bring the example that Udi mentioned.

We need to count the amount for transactions that were done this week and the last week. When reflecting that as a real-life model, we would end up having a table of transactions with dates and amounts. Like this:

Then when we need the sum, we would calculate it on the fly. This, of course, would work, but calculating the sum of transactions every time is just a bad idea. If we shift our thinking, we could just have a structure like this:

It doesn’t remind a transaction list from the real-world, but in this case, we simply don’t need it. It will require some maintenance when the week is over, but it will be far less than calculating the sum on every read. 

The summary

Learn Advanced Distributed Systems Design course changed the way I’m thinking about distributed architecture and micro-services. Udi is an amazing speaker, that used his experience from many real-life projects and was able to explain the most complicated concepts in a way that child would understand. 

Although it wasn’t easy to go through 30+ hours of the course, it was a huge dose of knowledge and I would recommend it to anyone.

BTW, here is the link: https://particular.net/adsd

.NET 5 – How to start

Would you like to learn how to write programs in .NET and find out what the platform from Microsoft can do? What tools to use and where to start? You’ve come to the right place! I will explain everything step by step.

What is .NET?

.NET is a programming platform created by Microsoft. Here are the most important features:

  • You can write in many languages: C #, F # and VB.NET
  • libraries written in different languages ​​in .NET can work together because they are compiled into IL intermediate code
  • .NET 5 and associated technologies are open and their sources are available on the GitHub platform
  • in .NET 5 you can build console applications, websites, APIs, games, mobile applications and desktop computers
  • .NET is extremely popular, therefore it has many ready integrations with Amazon or Google technologies, but the easiest way will be to work with Microsoft products and the Azure cloud
  • the program written in .NET 5 can be easily run on Windows, Linux and MacOS

Of course, these few points in no way exhaust the topic, because you could easily write a few books what .NET is capable of, but at the beginning it’s a quick summary is enough.

What do I need to install?

To build applications you need to install the development tools package, i.e. the SDK. To run them – the development package.

You’ll find both here: https://dotnet.microsoft.com/download/dotnet/5.0

When choosing the Runtime, choose the one that you need:

  • ASP.NET Core – for building a web application
  • Desktop – for building Windows-based desktop applications
  • .NET Runtime – for building console applications

One of the above is enough to start with. I would recommend ASP.NET Core.

What to write programs with?

Apparently, a good programmer will cope with a notepad, but I think this era is long over. There are actually two good options to choose from.

Visual Studio

A huge and very popular code editor. It is a real multi-tool, it is perfectly integrated with all Microsoft technologies, especially the older ones. I use it for many years and I can’t imagine working without it.

The most important features:

  • convenient editor, where many things can be done from UI
  • support for older Microsoft technologies
  • available on Windows and MacOS
  • paid, however, there is a free, stripped-down version – Community

Visual Studio Code

Simple, cross-platform code editor, developed open-source. It does not have as many integrations as Visual Studio, but it is lightweight and thanks to free extensions, it can be easily adapted to your needs. Certainly, however, it works comfortably with smaller projects and with websites. I use it when I’m working with React.js, for example.

The most important features:

  • is fast and light
  • it’s free and it’s easy to customize
  • works under Windows, Linux and MacOS
  • integration with older Microsoft technologies is not the best, but with .NET Core and .NET 5 it works great 

And any other actually

Because .NET 5 comes with CLI we can create, build and run the project, and also execute tests with simple console commands. For writing code, any editor will do and some of my peers choose to use JetBrain Rider. It is a great, cross-platform IDE, that has a built-in Resharper. It’s also fast and intuitive, so the choice is yours. 

Your first app

The wizard in Visual Studio

The easiest way to create your first program in .NET 5 is to use one of the ready-made programs in Visual Studio. This environment offers us many options to choose from:

The simplest project that you can choose to start with is the console application in C #. However, if you prefer to start with a web project, select ASP.NET Core application.

 

To make sure you’re using .NET 5, edit the project file and check what value is entered in the TargetFramework should be net5.0.

 

To start the project, simply press F5. At this point, the console application will start and a black window will appear saying Hello World!.

New project in Visual Studio Code

.NET Core and .NET 5 are released together with .NET CLI, a cross-platform set of commands that allows you to create, build, and publish .NET projects. Cross-platform is an important word here – it is thanks to CLI that we can build and run programs in .NET 5 not only on Windows but also on Linux and MacOS.

Let’s create a new project. When we open Visual Studio Code, open a new terminal and enter the dotnet new --list command to see what projects are currently available.

To create a console application called ConsoleApp2, type dotnet new console -n ConsoleApp2.

Great, we already have a console application with a single C# file called Program.cs. We need to know two more commands:

  • dotnet build–  to build the app
  • dotnet run – to run the app

After a few seconds, your eyes will see a black window with the program.

The summary

Programming in .NET 5 can start very quickly and after a while writing your own programs. In addition, they will work not only on Windows but also on Linux and MacOS. They can also operate in the cloud, e.g. in containers. The possibilities are really huge.

If you would like to learn more about programming in the console, take a look at the series of my articles: How to make you console app look cool

If you’re starting your adventure with .NET, you’ve come to the right place. Subscribe to my blog and get information about new posts – you will definitely learn something interesting from them.

Cheers and good luck 🙂

.NET 5 – jak zacząć

Chciałbyś nauczyć się programować w .NET i dowiedzieć się co potrafi platforma od Microsoft? Jakich narzędzi użyć i od czego zacząć? Dobrze trafiłeś! Wyjaśnię Ci wszystko krok po kroku.

Co to jest .NET?

.NET jest to platforma programistyczna stworzona przez Microsoft. A oto najważniejsze jej cechy:

  • można pisać w wielu językach: C#, F# oraz VB.NET
  • biblioteki napisane w różnych językach w .NET mogą ze sobą współpracować, ponieważ są kompilowane do kodu pośredniego IL
  • .NET 5 i technologie mu towarzyszące są otwarte, a ich źródła są dostępne na platformie GitHub 
  • w .NET 5 można budować aplikacje konsolowe, strony internetowe, API, gry, aplikacje na komórkę oraz na komputery stacjonarne
  • .NET jest ogromnie popularny, dlatego posiada wiele gotowych integracji z technologiami Amazon, czy Google, jednak najłatwiej będzie się nam pracowało z produktami Microsoft oraz chmurą Azure
  • program napisany w .NET 5 możemy bez problemu uruchomić na Windows, Linux oraz MacOS

Oczywiście te kilka punktów w żadnym stopniu nie wyczerpuje tematu, bo można by spokojnie napisać kilka książek do czego zdolny jest .NET, jednak na sam początek to szybkie podsumowanie wystarczy.

Co muszę zainstalować na początek?

Aby budować aplikacje musisz zainstalować pakiet narzędzi programistycznych, czyli SDK. Aby je uruchomić – pakiet uruchomieniowy.

Oba znajdziesz tutaj: https://dotnet.microsoft.com/download/dotnet/5.0

Jeżeli chodzi o Runtime, to wybierz to co potrzebujesz:

  • ASP.NET Core – jeżeli chcesz buować aplikacje webowe
  • Desktop – dla aplikacji desktopowych pod Windows
  • .NET Runtime – dla aplikacji konsolowych

Jeden z powyższych na początek zdecydowanie wystarczy. Ja polecałbym ASP.NET Core.

W czym pisać programy?

Podobno dobry programista i w notatniku sobie poradzi, ale myślę, że ta era już dawno się skończyła. Tutaj są tak naprawdę dwie opcje do wyboru.

Visual Studio

Ogromny i bardzo popularny edytor kodu. Jest to prawdziwy kombajn, jest świetnie zintegrowany ze wszystkimi technologiami Microsoft, zwłaszcza z tymi starszymi. Używam go od wielu lat i nie wyobrażam sobie pracy bez niego.

Najważniejsze cechy:

  • wygodny edytor, gdzie wiele rzeczy możemy wyklikać
  • wsparcie dla starszych technologii Microsoft
  • dostępny na Windows oraz MacOS
  • płatny, jednak istnieje wersja darmowa, okrojona – Community

Visual Studio Code

Prosty, wieloplatformowy edytor kodu, rozwijany open-source. Nie posiada tak wielu integracji jak Visual Studio, jednak jest lekki i dzięki darmowym rozszerzeniom, można go łatwo dostosować pod swoje potrzeby. Z pewnością jednak pracuje się na nim wygodnie z mniejszymi projektami oraz ze stronami internetowymi. Używam go w momencie kiedy pracuję np. z React.js

Najważniejsze cechy:

  • jest szybki i lekki
  • jest darmowy i łatwo można go dostosować
  • działa pod Windows, Linux oraz MacOS
  • integracja ze starszymi technologiami Microsoft nie jest najlepsza, jednak z .NET Core i .NET 5 działa świetnie

Pierwszy program

Kreator w Visual Studio

Najprostszym sposobem, aby stworzyć swój pierwszy program w .NET 5 jest użycie jednego z gotowców w Visual Studio. To środowisko oferuje nam wiele opcji do wyboru:

Najprostszy projekt, który możesz wybrać na początek to aplikacja konsolowa w języku C#. Jeżeli natomiast wolisz zacząć od projektu webowego, wybierz ASP.NET Core application.

 

Aby upewnić się, że używasz .NET 5, edytuj plik projektu i sprawdź jaka wartość jest wpisana w TargetFramework, powinna mieć wartość net5.0.

 

Aby uruchomić projekt, naciśnij po prostu F5. W tym momencie aplikacja konsolowa zostanie uruchomiona i pojawi się czarne okienko z napisem Hello World!.

Nowy projekt w Visual Studio Code

.NET Core jak i .NET 5 jest wydawany razem z .NET CLI, czyli wieloplatformowym zbiorem poleceń, który pozwala na tworzenie, budowanie i publikowanie projektów .NET. Ważnym słowem jest tutaj wieloplatformowość – to właśnie dzięki CLI możemy budować i uruchamiać programy w .NET 5 nie tylko na Windows, ale także na Linux i MacOS.

Stwórzmy zatem nowy projekt. Kiedy otworzymy Visual Studio Code, należy otworzyć nowy terminal i wpisać polecenie dotnet new --list, dzięki któremu zobaczymy jakie są obecnie dostępne gotowce projektów.

 Aby stworzyć aplikację konsolową o nazwie ConsoleApp2 należy wpisać polecenie dotnet new console -n ConsoleApp2

Świetnie, mamy już aplikację konsolową z pojedynczym plikiem w języku C# o nazwie Program.cs. Potrzebna nam będzie znajomość jeszcze dwóch komend:

  • dotnet build–  aby zbudować projekt
  • dotnet run – aby go uruchomić

Po kilku sekundach Twoim oczom ukaże się czarne okienko z programem.

Podsumowanie

Programowanie w .NET 5 można zacząć bardzo szybko i już po chwili pisać własne programy. Dodatkowo zadziałają one nie tylko na Windows, ale także na Linux i MacOS. Mogą także działać w chmurze, np. w kontenerach. Możliwości są naprawdę ogromne.

Jeżeli chciałbyś dowiedzieć się czegoś więcej o programowaniu w konsoli, zerknij na serię moich artykułów: https://www.michalbialecki.com/2018/05/25/how-to-make-you-console-app-look-cool/

Jeżeli zaczynasz swoją przygodę z .NET, to dobrze trafiłeś. Zasubskrybuj mój blog i dostawaj informacje o nowych postach – na pewno dowiesz się z nich czegoś ciekawego.

Pozdrawiam i powodzenia 🙂