• Featured post

C# Async ops

El nucleo de la programacion asincrona son los objetos Task y Task<T>. Son compatibles con las palabras clave async y await.

Primero hay que reconocer si el codigo se usa para trabajos enlazados a I/O o si son CPU intensivos.

  • Si el codigo “espera” algo como una BBDD o una response de un servidor, es codigo I/O. En este caso hay que usar async y await pero SIN usar Task.Run
  • Si el codigo realiza un calculo costoso, es CPU intensivo. Use async y await y genere otro subproceso con Task.run

Async / Await (Operaciones I/O)

La palabra clave importante aqui es await. Lo que hace es suspender la ejecucion del metodo actual y devolver el control hasta que está lista para seguir.

public Task Main()
{
	string contenido = await LeerPaginaWebAsync("http://example.com");
}

public async Task<string> LeerPaginaWebAsync(string url)
{
	using (HttpClient client = new HttpClient())
	{
		return await client.GetStringAsync(url);
	}
}

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

Introduction to C#

Hacer variables nullables

A las variables como int no se le puede asignar null. Hay que declararlas como int?.

int edad = null; // compilation error
int? edad = null; // OK

operadores nullables

x.y acceso a miembros x?.y acceso a miembros que pueden ser null. Devuelve null si el operando izquierdo es null. x?[y] lo mismo para acceder a indices cuyos contenedores pueden ser null.

Como castear

Como hacer un cast a una variable de un tipo a otro tipo.

double valor = 8.45;
int entero = Convert.ToInt32(valor);

readonly

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

class Age
{
	private readonly int _year;

	Age(int year)
	{
		_year = year;
	}

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

Read More

C# Methods

Paso por valor o por referencia

En C# se puede elegir si quieres pasar a un método el valor o la referencia de una variable.

// pasar por valor
int numero = 25;
CambiarPorValor(numero); 
Console.Write(numero); // prints 25

// pasar por ref
CambiarPorReferencia(ref numero);
Console.Write(numero); // prints 12
// this is the same as in Java
public static void CambiarPorValor(int numero)
{
	numero = 12;
}
// referencia(!)
public static void CambiarPorReferencia(ref int numero)
{
	numero = 12;
}

out vs ref

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

The difference is ref needs the variables to be initialized first, while out does not. This could confuse readers as it looks the initial values are relevant.

out example (remember it also has to be marked in the method)

string a,b;
person.GetBothNames(out a, out b);
string a = String.empty, b = String.empty;
person.GetBothNames(ref a, ref b);

Read More

C# Classes

Auto properties

set vs private set

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

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

C# Colecciones

Listas

Para acceder a una lista se puede usando un método, o con un indexer igual a las Arrays [].

using System.Linq;

List<string> myList = new List<string> { "Yes", "No" };

// possibility 1
var firstItem = myList.ElementAt(0);
// possibility 2
var firstItem = myList[0];

List vs ArrayList

Don’t use ArrayList. Use List<T> instead. ArrayList comes from times when C# didn’t have generics and it’s not the same ArrayList we have in Java.

Don’t do.

ArrayList array = new ArrayList();
array.Add(1);
array.Add("Pony"); // Later error at runtime if you try to operate with numbers.

How to

List<int> list = new List<int>();
list.Add(1);
list.Add("Pony"); // Compilation error. 

Read More

Visual Studio (Code)

Shortcuts

  • 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

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;

EFCore consultas solo lectura - gran volumen entidades

Cuando se van a realizar consultas de solo lectura, las cuales NO se van a usar para actualizar en la base de datos, se puede llamar al método .AsNoTracking() para mejorar la performance.
Sería recomendable utilizarla para manejar grandes volumenes de entidades.

Las entidades de las queries donde se use .AsNoTracking() no se podrán actualizar.

// operacion de solo lectura
var libros = context.Libros
	.AsNoTracking()
	.Where(l => l.Autor == "Something")
	.ToList();