Pages

Monday, March 6, 2017

Deshacerse de las 'Magic Strings' en C#

'Una magic string es un input que el programador cree que nunca vendra de una fuente externa y que activa funcionalidad que de otra manera estaria oculta.'


Basicamente el termino se usa para identificar a las cadenas existentes directamente en nuestro codigo (hard-codeadas). Testas cadenas sona  veces necesarias en una aplicacion o al menos a veces no pueden ser evitadas en algunas situaciones  (como cuando tenemos que lidiar con codigo antiguo).
El principal problema con las Cadenas Magicas es que son propensas al error, especialmente si son usadas en ams de un lugar de la aplicacion, porque podriamos aquivocarnos al teclarla y no tendriamos ningun error de compilacion o advertencia.

Por ejemplo:


Hay un par de maneras de resolver esto.

Thursday, February 9, 2017

Are you using class properties correctly ?

I am getting used to see properties implemented this way:




So you have your private members, and you created the properties for those, so you are happy and go on with your life. But I ask, Is there anything wrong in what we see here? Take a minute to think about it.


You see, the purpose of the properties is to protect the private members. But if there is absolutely no code in the properties getter or setter, then we are not really protecting anything, we just pass the values to the private member as they come.

This is a common mistake,  we create a class and immediately, almost unconsciously, we create the properties for our private fields. Because we were taught this way. It will not cause any exception and certainly you can use it  without problems is you have validations elsewhere, But then you are not taking advantage of one of the purpose of properties.

Now suppose our age variable has to have valid range, Or that for reporting purposes you have to see a 'Not Available' when a person does not have an address registered. You could do this:




See, now we are really using the properties for something meaningful. This is just a small example. What do you think about that ? It certainly got ME thinking.

And that, my friend, It's all!






Wednesday, January 14, 2015

DataAnnotations Cheat Sheet (esp)

He buscado por todo lado un Cheat Sheet como este para tener todas las opciones a mano pero no pude encontrar nada. Asi que arme uno propio, espero que les sirva de ayuda:


DataAnnotations Cheat Sheet v1.0


Nombre: AssociationAttribute

Descripcion: Especifica que un miembro de la entidad representa una relación, como una relacion de llave foranea.
Uso: [Association(Name, OtherKey, ThisKey)]
Ejemplo:
[Table(Name = "Clientes")]
public partial class Cliente
{
    [Column(IsPrimaryKey = true)]
    public string ClienteID;
    // ...
    private EntitySet<Pedido> _Pedidos;
    [Association(Storage = "_Pedidos", OtherKey = "ClienteID")]
    public EntitySet<Pedido> Pedidos

    {
        get { return this._Pedidos; }
        set { this._Pedidos.Assign(value); }
    }
}

Nombre: BindableTypeAttribute
Descripcion: Especifica si es que un tipo es tipicamente usado para hacer un   binding.
Uso: [BindableType(IsBindable = bool)]
Ejemplo:
  [BindableType(IsBindable = false)]
  public enum EstadoDeEntidad
  {
    Detached = 1,
    SinCambios = 2,
    Adicionado = 4,
    Borrado = 8,
    Modificado= 16,
  }


Copiar filas en la misma tabla solo cambiando el Id (TSQL) (esp)

Vamos a analizar diferentes escenarios en los cuales necesitamos copiar/clonar filas de una tabla a esa misma tabla, Solo cambiando el valor de un campo, Que en este caso sera el campo Id, Usando Microsoft SQL Server.

Supongamos que tenemos el AntId (Id original Id de el que queremos copiar las filas, en este caso este Id puede estar en varias filas o solo en una) y el NuevoId ( El Id nuevo que queremos poner en las filas que vamos a copiar/clonar)

Caso 1 - conocemos el nombre de la tabla y de todos sus campos:

El primer caso es de una tabla de la cual sabemos de antemano su nombre y su estructura, así que podemos escribir una consulta como la siguiente:

DECLARE @OldId int
DECLARE @NuevoId int
SET @AntId =13456 -- ejem.
SET @NuevoId =45687 -- ejem.

INSERT INTO MiTabla(Id,ColumnaA,ColumnaB,ColumnaC)
SELECT @NuevoId ,ColumnaA,ColumnaB,ColumnaC
FROM MyTable WHERE Id=@AntId 


Copying Rows On The Same Table and updating Only some fields (TSQL)

We will analyze different scenarios on which we need to copy or clone rows from one table to the same table, only changing the value of one know field, which in this case is the Id field, Using Microsoft SQL Server.

Supposing we are provided the OldId (original Id from were we want to copy the rows, in this case this Id can be on several rows or just one) and a NewId ( the Id we want to put on the row we are going to copy/clone)


If we know the columns and table names before hand:

The first scenario would be a table on which we know before hand the name of the table and all the fields involved, so we can easily write the following query.

DECLARE @OldId int
DECLARE @NewId int
SET @OldId =13456 -- i.e
SET @NewId =45687 -- i.e

INSERT INTO MyTable(Id,ColumnA,ColumnB,ColumnC)
SELECT @NewId,ColumnA,ColumnB,ColumnC
FROM MyTable WHERE Id=@OldId