Siguiendo con la serie de posts sobre Cooperator Framework, esta vez voy a mostrarles cómo codificar un ABM de lo más simple.
Seguramente van a encontrar muchas formas de mejorar el ejemplo. La idea es brindar un punto de partida.
Para los que todavía no conocen Cooperator Framework les recomiendo los posts anteriores sobre el tema:
Introducción a Cooperator Framework,
Cooperator, un ejemplo sencillo para comenzar y
Cooperator, modificando el modelo.
Supongamos que tenemos una entidad en nuestro dominio denominada Occupations, con un ID autonumérico y un campo Descripcion de tipo VARCHAR.
Vamos a tener un formulario Occupations que contiene una DataGridView, de nombre dgDatos, con la lista de Occupations y un formulario Occupation con el que veremos el detalle de la Occupation al agregar o modificar un registro.
En el formulario Occupations tendremos una botonera y/o menú con las opciones de Agregar, Eliminar y Modificar.
La grilla de Occupations la completo con el siguiente código:
C#
OccupationList mOccupationList = OccupationMapper.Instance().GetAll;
OccupationListView mOccupationListView = new OccupationListView(mOccupationList);
mOccupationListView.Sort(“Description”, true);
dgDatos.DataSource = mOccupationListView;
dgDatos.Columns[ColumnaGrilla.ID].Visible = false;
dgDatos.Columns[ColumnaGrilla.Description].HeaderText = “Ocupación”;
VB.NET
Dim mOccupationList As OccupationList = OccupationMapper.Instance().GetAll
Dim mOccupationListView As OccupationListView = New OccupationListView(mOccupationList)
mOccupationListView.Sort(“Description”, True)
dgDatos.DataSource = mOccupationListView
dgDatos.Columns(ColumnaGrilla.ID).Visible = False
dgDatos.Columns(ColumnaGrilla.Description).HeaderText = “Ocupación”
En la primera linea declaro una lista que completo con el método GetAll del Mapper de Occupation. Luego completo una ListView a partir de la lista que complete con el GetAll. En la tercera linea le practico un ordenamiento, en la cuarta linea le paso este ListView al DataSource de la DataGridView con lo que queda poblada. En la quinta linea hago invisible la columna del ID y en la última linea de código le doy un título a la columna Descripcion.
Veamos ahora el código correspondiente a Eliminar:
C#
if ((dgDatos.SelectedRows == null))
{
MsgBox(“No se seleccionó ninguna fila de la grilla.”, ((MsgBoxStyle)((MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly))));
}
else if ((MsgBox((“¿Está a punto de eliminar a la Ocupación “
+ (dgDatos.SelectedRows.Item[0].Cells[ColumnaGrilla.Description].Value.ToString.Trim + “?”)), ((MsgBoxStyle)((MsgBoxStyle.Exclamation + (MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2))))) == MsgBoxResult.Yes))
{
OccupationMapper.Instance.Delete(((int)(dgDatos.SelectedRows.Item[0].Cells[ColumnaGrilla.ID].Value)));
MsgBox((“La Ocupación ” + (dgDatos.SelectedRows.Item[0].Cells[ColumnaGrilla.Description].Value.ToString.Trim + ” se eliminó exitosamente.”)), ((MsgBoxStyle)((MsgBoxStyle.Information + MsgBoxStyle.OkOnly))));
CargarGrilla();
}
VB.NET
If dgDatos.SelectedRows Is Nothing Then
MsgBox(“No se seleccionó ninguna fila de la grilla.”, CType(MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, MsgBoxStyle))
Else
If MsgBox(“¿Está a punto de eliminar a la Ocupación “ + dgDatos.SelectedRows.Item(0).Cells(ColumnaGrilla.Description).Value.ToString.Trim + “?”, CType(MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, MsgBoxStyle)) = MsgBoxResult.Yes Then
OccupationMapper.Instance.Delete(CType(dgDatos.SelectedRows.Item(0).Cells(ColumnaGrilla.ID).Value, Integer))
MsgBox(“La Ocupación “ + dgDatos.SelectedRows.Item(0).Cells(ColumnaGrilla.Description).Value.ToString.Trim + ” se eliminó exitosamente.”, CType(MsgBoxStyle.Information + MsgBoxStyle.OkOnly, MsgBoxStyle))
CargarGrilla()
End If
End If
ColumnaGrilla es un Enum donde ColumnaGrilla.ID es igual a cero y ColumnaGrilla.Descripcion es igual a uno.
CargarGrilla es el primer bloque de código del post.
Ahora les muestro el código que corresponde a Agregar:
C#
Occupation miOccupation = new Occupation();
miOccupation.ShowDialog(this);
if (!miOccupation.Cancelo)
{
CargarGrilla();
}
miOccupation = null;
VB.NET
Dim miOccupation As New Occupation
miOccupation.ShowDialog(Me)
If Not miOccupation.Cancelo Then
CargarGrilla()
End If
miOccupation = Nothing
Y lo correspondiente a Modificar
C#
int intPivot;
if ((dgDatos.SelectedRows == null))
{
MsgBox(“No se seleccionó ninguna fila de la grilla.”, ((MsgBoxStyle)((MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly))));
}
else
{
CoopRules.Entities.Occupation mOccupation = new CoopRules.Entities.Occupation();
intPivot = ((int)(dgDatos.SelectedRows.Item[0].Index));
mOccupation = OccupationMapper.Instance.GetOne(((int)(dgDatos.SelectedRows.Item[0].Cells[ColumnaGrilla.ID].Value)));
Occupation miOccupation = new Occupation(mOccupation);
miOccupation.ShowDialog(this);
if (!miOccupation.Cancelo)
{
CargarGrilla();
dgDatos.Rows.Item[intPivot].Selected = true;
dgDatos.CurrentCell = dgDatos.Rows[intPivot].Cells[ColumnaGrilla.Description];
MsgBox(“La modificación se registró exitosamente.”, ((MsgBoxStyle)((MsgBoxStyle.Information + MsgBoxStyle.OkOnly))));
}
miOccupation = null;
}
VB.NET
Dim intPivot As Integer
If dgDatos.SelectedRows Is Nothing Then
MsgBox(“No se seleccionó ninguna fila de la grilla.”, CType(MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, MsgBoxStyle))
Else
Dim mOccupation As New CoopRules.Entities.Occupation
intPivot = CType(dgDatos.SelectedRows.Item(0).Index, Integer)
mOccupation = OccupationMapper.Instance.GetOne(CType(dgDatos.SelectedRows.Item(0).Cells(ColumnaGrilla.ID).Value, Integer))
Dim miOccupation As New Occupation(mOccupation)
miOccupation.ShowDialog(Me)
If Not miOccupation.Cancelo Then
CargarGrilla()
dgDatos.Rows.Item(intPivot).Selected = True
dgDatos.CurrentCell = dgDatos.Rows(intPivot).Cells(ColumnaGrilla.Description)
MsgBox(“La modificación se registró exitosamente.”, CType(MsgBoxStyle.Information + MsgBoxStyle.OkOnly, MsgBoxStyle))
End If
miOccupation = Nothing
End If
Acá llamo la atención especialmente en la diferencia en la invocación al constructor del formulario Occupation entre Agregar y Modificar
C#
Agregar
Occupation miOccupation = new Occupation();
Modificar
Occupation miOccupation = new Occupation(mOccupation);
VB.NET
Agregar
Dim miOccupation As New Occupation
Modificar
Dim miOccupation As New Occupation(mOccupation)
Podemos observar que en el caso de Modificar al constructor le pasamos un Objeto Entity de tipo Occupation y en Agregar no.
Esto es porque el constructor del formulario Occupation tiene un parámetro opcional de tipo Occupation.
Les muestro el código del formulario Occupation:
C#
using CoopRules.Entities;
using CoopRules.Objects;
using CoopRules.Mappers;
using CoopCore.Core;
public class Occupation {
private bool mCancelo = true;
private CoopRules.Objects.OccupationObject mOccupation = new CoopRules.Objects.OccupationObject();
private CoopCore.Core.Estado mEstadoActual;
public Occupation(CoopRules.Entities.Occupation pOccupation = Nothing) {
InitializeComponent();
if ((pOccupation == null)) {
this.EstadoActual = CoopCore.Core.Estado.Agregar;
}
else {
mOccupation = pOccupation;
txtDescription.Text = pOccupation.Description;
this.Text = pOccupation.Description;
this.EstadoActual = CoopCore.Core.Estado.Modificar;
}
txtDescription.Focus();
}
public CoopCore.Core.Estado EstadoActual {
get {
return mEstadoActual;
}
set {
mEstadoActual = value;
}
}
bool Cancelo {
get {
return mCancelo;
}
set {
mCancelo = value;
}
}
private void Occupation_Load(object sender, System.EventArgs e) {
}
private void btnCancelar_Click(object sender, System.EventArgs e) {
this.Close();
}
private void btnAceptar_Click(object sender, System.EventArgs e) {
try {
Validar();
Grabar();
}
catch (Exception ex) {
if (ex.Message.Contains(“Cannot insert duplicate key row”)) {
MsgBox(“Ya existe una Ocupación con ese nombre.”, MsgBoxStyle.OkOnly, NombreEmpresa);
}
else {
MsgBox(ex.Message.ToString, MsgBoxStyle.OkOnly, NombreEmpresa);
}
}
}
private void BlanquearControles() {
txtDescription.Text = “”;
}
private void Validar() {
mOccupation.Description = txtDescription.Text;
mOccupation.Validate();
}
private void Grabar() {
if ((this.EstadoActual == CoopCore.Core.Estado.Agregar)) {
CoopRules.Entities.Occupation eOccupation = new CoopRules.Entities.Occupation();
eOccupation.Description = mOccupation.Description;
OccupationMapper.Instance.Insert(eOccupation);
this.Cancelo = false;
MsgBox(“La Ocupación se agregó exitosamente.”, MsgBoxStyle.OkOnly);
BlanquearControles();
txtDescription.Focus();
}
else {
OccupationMapper.Instance.Save(mOccupation);
this.Cancelo = false;
this.Close();
}
}
}
VB.NET
Imports CoopRules.Entities
Imports CoopRules.Objects
Imports CoopRules.Mappers
Imports CoopCore.Core
Public Class Occupation
#Region “Declaraciones Privadas”
Private mCancelo As Boolean = True
Private mOccupation As New CoopRules.Objects.OccupationObject
Private mEstadoActual As CoopCore.Core.Estado
#End Region
#Region “Eventos”
Public Sub New(Optional ByVal pOccupation As CoopRules.Entities.Occupation = Nothing)
InitializeComponent()
If pOccupation Is Nothing Then
Me.EstadoActual = CoopCore.Core.Estado.Agregar
Else
mOccupation = pOccupation
txtDescription.Text = pOccupation.Description
Me.Text = pOccupation.Description
Me.EstadoActual = CoopCore.Core.Estado.Modificar
End If
txtDescription.Focus()
End Sub
Private Sub Occupation_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
Me.Close()
End Sub
Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
Try
Validar()
Grabar()
Catch ex As Exception
If ex.Message.Contains(“Cannot insert duplicate key row”) Then
MsgBox(“Ya existe una Ocupación con ese nombre.”, MsgBoxStyle.OkOnly, NombreEmpresa)
Else
MsgBox(ex.Message.ToString, MsgBoxStyle.OkOnly, NombreEmpresa)
End If
End Try
End Sub
#End Region
#Region “Propiedades”
Public Property EstadoActual() As CoopCore.Core.Estado
Get
Return mEstadoActual
End Get
Set(ByVal value As CoopCore.Core.Estado)
mEstadoActual = value
End Set
End Property
Property Cancelo() As Boolean
Get
Return mCancelo
End Get
Set(ByVal value As Boolean)
mCancelo = value
End Set
End Property
#End Region
#Region “Rutinas y Funciones Privadas”
Private Sub BlanquearControles()
txtDescription.Text = “”
End Sub
Private Sub Validar()
mOccupation.Description = txtDescription.Text
mOccupation.Validate()
End Sub
Private Sub Grabar()
If Me.EstadoActual = CoopCore.Core.Estado.Agregar Then
Dim eOccupation As New CoopRules.Entities.Occupation
eOccupation.Description = mOccupation.Description
OccupationMapper.Instance.Insert(eOccupation)
Me.Cancelo = False
MsgBox(“La Ocupación se agregó exitosamente.”, MsgBoxStyle.OkOnly)
BlanquearControles()
txtDescription.Focus()
Else
OccupationMapper.Instance.Save(mOccupation)
Me.Cancelo = False
Me.Close()
End If
End Sub
#End Region
End Class
Espero les sea útil.


































