• Featured post

C# Task async programming (TAP) and parallel code

The core for asynchronous programming are the objects Task and Task<T>. Both of them are compatible with the keywords async and await.

First of all we need to identify if the code’s I/O-bound or CPU-bound.

  • the code’s limited for external operations and waits for something a lot of time. Examples of this are DDBB calls, or a server’s response. In this case we have to use async/await to free the thread while we wait
  • the code does a CPU-intensive operation. Then we move the work to another thread using Task.Run() so we don’t block the main thread.

async code vs parallel code

(!) Asynchronous code is not the same as parallel code (!)

  • In async code you are trying to make your threads do as little work as possible. This will keep your app responsibe, capable to serve many requests at once and scale well.
  • In parallel code you do the opposite. You use and keep a hold on a thread to do CPU-intensive calculations

async code

The importante of async programming is that you choose when to wait on a task. This way, you can start other tasks concurrently

In async code, one single thread can start the next task concurrently before the previous one completes.
(!) async code doesn’t cause additional threads to be created because an async method doesn’t run on its own thread. (!) It runs on the current synchronization context and uses time on the thread only when the method is active.

parallel code

For parallelism you need multiple threads where each thread executes a task, and all of those tasks are executed at the same time

Read More

C# Async await best practices

Don’t use async void

An async method may return Task, Task<T> and void. Natural return types are all but void.

Any sync method returning void becomes an async method returning Task. example:

// synchronous work
void MyMethod()
{
	Thread.sleep(1000);
}

// asynchronous work
async Task MyAsyncMethod()
{
	await Task.Delay(1000);
}

When an exception is thrown out of an async Task or async Task<T> method that exception is captured and placed on the Task object. For async void methods, exceptions aren’t caught.

Read More

C# Streams and Files

MemoryStream

Los streams en memoria se usan sobre todo para leer de ficheros, o para almacenar información que queremos guardar en ficheros.

Si se inicializa mediante el siguiente constructor no se puede cambiar su tamaño.

MemoryStream ms = new MemoryStream(150);
ms.Capacity;
ms.Length;
ms.Position;

// 0 bits from Begin
ms.Seek(0, SeekOrigin.Begin);
// 5 bits from current position
ms.Seek(5, SeekOrigin.Current);
// go back 10 bits from current position
ms.Seek(-10, SeekOrigin.Current);

Files

Ejemplo para leer y escribir un fichero.

write file

FileStream fsEscribir = new FileStream("miArchivo.txt", FileMode.Create);

string cadena = "this is an example";

fsEscribir.Write(ASCIIEncoding.ASCII.GetBytes(cadena), 0, cadena.Length);
fsEscribir.Close();

read file

byte[] infoArchivo = new byte[100];

FileStream fs = new FileStream("miArchivo.txt", FileMode.Open);
fs.Read(infoArchivo, 0, (int) fs.Length);

Console.WriteLine(ASCIIEncoding.ASCII.GetString(infoArchivo));
Console.ReadKey();

fs.Close();

Servicebus vs queue

ServiceBus

Sistema de mensajeria COMPLEJO que permite comunicacion entre MULTIPLES SERVICIOS usando patrones publication/subscription

Permite a un mensaje ser consumido por MULTIPLES CONSUMERS Ideal para flujos de trabajo complejos

Queue

Mecanismo mas simple y directo. Permite la transmision de mensajes de un punto a otro. Un mensaje enviado a la cola es recibido y procesado por un unico consumidor Se centra en GARANTIZAR LA ENTREGA del mensaje, pero es mas limitado.

C# Delegates

Un delegado es un placeholder para un método. Permite pasar una función como parámetro a un método.

Hay varios tipos de delegado:

  • Action<T> consume una clase, devuelve void Ejemplo Console.WriteLine();
  • Predicate<T> consume una clase, devuelve bool Por ejemplo para abstraer condiciones
  • Func<T, K> consume una clase y devuelve otra. Por ejemplo para abstraer mappings

Usaremos el struct Book para todos los ejemplos

public struct Book
{
	public string Title;        // Title of the book.
	public string Author;       // Author of the book.
	public decimal Price;       // Price of the book.
	public bool Paperback;      // Is it paperback?

	public Book(string title, string author, decimal price, bool paperBack)
	{
		Title = title;
		Author = author;
		Price = price;
		Paperback = paperBack;
	}
}

Action (Consumer)

Tenemos el ejemplo BookDBActionService

public class BookDBActionService
{
	// List of all books in the database
	List<Book> list = new List<Book>();

	// initialize test data on constructor
	public BookDBActionService()
	{
		list.Add(new Book("title1", "author1", 10, true));
		list.Add(new Book("title2", "author2", 20, false));
	}

	// Aqui tenemos el Action<Book> donde delegamos como se procesa cada libro
	public void ProcessPaperbackBooks(Action<Book> processBook)
	{
		foreach (Book b in list)
		{
			if (b.Paperback)
			{
				// delegate call
				processBook(b);
			}
		}
	}
}

Llamada donde ejecutamos el código y llamamos al Action<Book>

public static void Main(string[] args)
{
var bookDBAction = new BookDBActionService();
bookDBAction.ProcessPaperbackBooks(book => Console.WriteLine(book.Title));
}

Read More

Introduction to C#

Nullables

Check this post on c# nullables and how to use them

readonly

La palabra clave readonly hace que no se pueda asignar después de que el constructor acabe.

public class Age
{
	private readonly int _year;

	public Age(int year)
	{
		_year = year;
	}

	public void OverwriteYear()
	{
		_year = 1967; // Compilation error
	}
}

readonly vs const

readonly values can be computed dynamically, (!) but need to be assigned before the constructor exits (!).

In the other hand const are implicitly static.

(More info on this subject)

public class ReadonlyVsConst
{
	public const int I_VALUE = 2; // HAS TO be assigned on declaration.
	public readonly int I_RO_VALUE; // Can be assigned on the constructor.

	public ReadonlyVsConst()
	{
		I_RO_VALUE = 3;
	}
}

Read More

C# Methods

Pass by value or pass by reference

In C# you may choose how you want to pass a method’s variable.

by value example (default)

// by value
int number = 25;
PassByValue(number); 
Console.Write(number); // prints 25
public static void PassByValue(int number)
{
	// this won't take effect
	number = 12;
}

by reference example (out)

// by reference
int number;
PassByOutReference(out number);
Console.Write(number); // prints 12
public static void PassByOutReference(out int number)
{
	number = 12;
}

by reference example (ref)

// by reference (ref)
int number = -1;
PassByReference(out number);
Console.Write(number); // prints 12
public static void PassByRefReference(ref int number)
{
	number = 12;
}

out vs ref

(!) You should use out unless you explicitly need ref (!)

  • out doesn’t need the variable to be initialized first
  • ref needs the variable to be initialized first. This could confuse readers as it looks as if the initial values were relevant, but they’re not.

Read More

C# Classes

Auto properties

set vs private set

  • La variable que está como public x { get; set; } se puede llamar de manera externa e interna.
  • Mientras que la variable public x { get; private set; } se puede hacer un get de manera externa pero no un set

ejemplo

public class Person
{
	public string Name { get; set; }
	public string Surname { get; private set; }

	public Person()
	{
		Name = "ctor name";
		Surname = "ctor surname";
	}

	public void SetInternalValues()
	{
		Name = "name internal value";
		// if we'd have public string Surname { get; } without set; 
		//  then we couldn't set Surname inside its own class either 
		Surname = "surname internal value";
	}
}
var person = new Person(); 
person.Name = "name external value";
// person.Surname = "this isn't possible"; // cannot be set as we use { private set; }

Read More

Visual Studio (Code)

Shortcuts and QoL features

  • ctrl + F12 - over a method call -> go directly to the method inside the interface’s implementation
  • ctrl + - - go back where you where after entering a method
  • ctrl + G - go to line number
  • ctrl + T - search for a class. If you want to search for UserController.cs you can type UCont and it will find it
  • ctrl + shift + P - search inside Visual Studio options
  • ctrl + D - duplicate actual line
  • alt + ↑ / ↓ - move code lines

Auto-complete placeholders

  • prop - creates a new property for a class
  • ctor - creates a new constructor
  • cw - creates a new Console.WriteLine() statement
  • try - creates a try-catch statement

To create a new property, type prop, hit twice tab and it creates a property template which you can navegate and override

vstudio 2

Multi-caret and multi-cursor editing

(check this for more details)

For lines that are aligned

  • alt + mouse click - selects a block to edit
  • alt + shift + arrow - same with keyboard

For multiple places that are not aligned

  • ctrl + alt + mouse click - click where you want to add a caret
  • (select the word you want to match) alt + shift + ; - vstudio selects all locations that match selected text in the current document and you may edit them

    Debug in VsCode

    Watch a variable

    En la pestaña watch se puede introducir el nombre de una variable y al hacer debug mostrará siempre el valor de esta variable.

vstudio-4

Read More

Teoria Entity Framework Core

En el Program tenemos código que depende del nugget y la implementación de la base de datos que vamos a integrar.
Este usa una cadena del appsettings.json para conectar a la BBDD

"server=localhost;database=postgres;uid=postgres;password=thisisSomepassword"

Para crear una nueva entidad en la base de datos:

  • Creamos el Model pertinente (por ej.) Coche
  • Lo añadimos al ApplicationDbContext como un DbSet<Coche>
  • Añadimos una migration add-migration addedCoche
  • Ejecutamos update-database

Migration

Mecanismo para aplicar cambios en el modelo de datos de la aplicacion a la BBDD de manera incremental y versionable. Cada migracion contiene los pasos necesarios para llevar a cabo las modificaciones en la BBDD como agregar nuevas tablas, cambiar columnas existentes o eliminar indices.

Esto permite tener:

  • Despliegues consistentes: aplica mismos cambios en diferentes entornos.
  • Control de versiones
  • Evolucionar la BBDD

Read More

Entity Framework Core Scaffolding

Go to Tools > Nuget Package Manager > Package Manager Console

Adapt and paste the following code. This includes:

  • db’s connection string
  • name for the context it’s going to create
  • Where it pastes the data classes to
Scaffold-DBContext "Host=host_here;Database=database_name;Username=username_here;Password=pwd_here" Npgsql.EntityFrameworkCore.PostgreSQL -DataAnnotations -Context ContextNameHereDbContext -ContextDir Data -o Models/DB -force -NoOnConfiguring -verbose

This creates:

  • DbContext.cs class
  • all Model/Data classes

Remember to modify Startup.cs to set the service classes as AddTransient for the services which use this DbContext

services.AddTransient<SomethingService, SomethingService>(); 

Add into the service, the context you’ve just created and set it at the constructor.

private readonly ApplicationDbContext _context;