• 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

Interact with your pods

This details various ways that you can interact with the code and data running inside your pod.

Access a Pod via Network

If you want access to a specific pod, even if it’s not serving traffic on the internet. To achieve this, Kubernetes has support built into it.

kubectl port-forward <pod-name> <localport>:<podport>
kubectl port-forward istio 5015:80

A secure tunnel is created from your local machine, though the K8s master, to the instance of the Pod running on one of the worker nodes.

Getting More Info with Logs

When you need to debug.

# downloads the current logs from the running instance
kubectl logs kuard

# continuously streams logs
kubectl logs -f kuard

# get logs from a previous instance of the container. Useful if your containers are continuously restarting at startup. 
kubectl logs kuard --previous
  • -c if you have multiple containers in your Pod, you can choose the one to view

Read More

RDF and SPARQL

RDF (Resource Description Framework) - modelo de datos para representar datos como grafos (datos interconectados). Está dirigido y etiquetado para representar la información en la web.

SPARQL - query language estandarizado para consulta de grafos RDF.

Cuando trabajan ambos juntos, RDF y SPARQL te permiten construir aplicaciones de grafos.

What’s an RDF Graph?

This just means data represented using the RDF data model. This is what an example of such graph may look like

rdf-1

An RDF grahp is a directed graph consisting of nodes which are connected together by crearly labelled relationships with directionality. These relationships are known as edges. These edges connect one node to another.

Read More

How to import from JSON to Excel

It’s possible to import directly from JSON to Excel. This allows us to easily filter by some JSON fields or execute Excel queries on top of our JSON data.

I have a json file with hundreds of items following this structure.

{
	"_id": "63371b0027484f4f9f00587d",
	"guid": "ab4059e7-6441-4593-8272-42c53e4742d2",
	"isActive": true,
	"balance": "$2,120.18"
}

Read More

Introduction to GraphQL

What’s GraphQL?

A query language to build & query APIs. Invented by facebook in 2012, to solve its complexity in REST APIs.

It’s a good fit for companies where there’re tons of data we’d need otherwise to access through REST APIs. It’s not a replacement for REST, it’s an alternative for projects with large data sets.

GraphQL vs REST APIs

REST API

underfetching

Let’s say we want to retrieve the posts for a user and then, the comments and likes for a user’s post. In a REST API we’d have the following:

api/users/{id}/posts
api/users/{id}/posts/{postId}/comments
api/users/{id}/posts/{postId}/likes

With a single endpoint we cannot retrieve all the data. We need to call multiple endpoints to have all data we need.

overfetching

Let’s say I want to iterate the PostDescription for one user posts history. If I call the following endpoint it will give to me way more data than I need:

api/users/{id}/posts

gives back:

PostDescription UserId UserImage PostId PostCreationTime PostLocation etc.

This is way more data than I need to iterate and useless to me.

Read More

Windows debug errores

Visor de eventos

Aqui se pueden ver logs de errores y warnings. Interesantes son las carpetas de Registros de Windows - Aplicacion y Sistema windows-debug-1

Administrador de dispositivos

Si hay fallos de red aqui se puede ver el estado de los Adaptadores de Red: windows-debug-2

Dependency injection w. multiple implementations

I have the class package with a type, plus more info not relevant to the question

public class Package
{
	public string Type { get; set; }
	// ... more package properties
}

I have the following interface service to mail packages

public interface IMailService
{
	public Task<string> SendPackage(Package package);
}

Then I have several implementations for this interface

public class MailNewPackageService : IMailService
{
	public async Task<string> SendPackage(Package package)
	{
		Console.WriteLine("send package through new service");
		// implementation ...
	}
}

public class MailOldPackageService : IMailService
{
	public async Task<string> SendPackage(Package package)
	{
		Console.WriteLine("send package through old service");
		// implementation ...
	}
}

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# Events

Permite a una clase notificar a otras cuando ocurre algo de interés.

public class Publicador
{
	// Declaracion de un evento
	public event EventHandler EventoSimple;

	// trigger
	public void DispararEvento()
	{
		// verificacion de subscripcion
		if(EventoSimple != null)
		{
			EventoSimple(this, EventArgs.Empty);
		}
	}
}
public class Suscriptor
{
	public void Suscribirse(Publicador publicador)
	{
		// suscripcion al evento
		publicador.EventoSimple += ManejadorEvento;
	}

	private void ManejadorEvento(object sender, EventArgs e)
	{
		// do whatever you need to do and/or send here
	}
}
// usage
var publicador = new Publicador();
var suscriptor = new Suscriptor();
suscriptor.Suscribirse(publicador);

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