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.

16 comentarios
Feed de los comentarios de este artículo
Sábado 28 \28UTC junio \28UTC 2008 a 11:06:40
Horacio Velasco
Excelente ejemplo Carlos, gracias a personas como vos es que se pueden hacer grandes cosas en esta comunidad. voy a tratar de ver de llevarlo a un video tutorial. Gracias de nuevo, saludos desde CBA!
Sábado 05 \05UTC julio \05UTC 2008 a 8:07:58
Carlos Marcelo Santos
Muchas gracias Horacio, sos muy generoso conmigo.
Cuando ande por Córdoba lo celebramos con un buen asado.
Martes 11 \11UTC noviembre \11UTC 2008 a 8:11:20
Gabriel Arroyo
Hola Carlos, soy nuevo en el uso de cooperator y Vb.net, podrias decirme como utilizar la funcion GetSettings(), ya que no me la reconoce como funcion. Tenes los fuentes del ejemplo, creo que mirandolo sobre los fuentes, con los forms y todo seria mucho mas facil la comprension del mismo.
Saludos y desde ya gracias Gabriel
Martes 11 \11UTC noviembre \11UTC 2008 a 20:11:52
Carlos Marcelo Santos
Hola Gabriel. ¡Qué bueno tu comentario!
La función GetSettings es un error mio, me quedó esa linea en el medio.
Ya lo corregí gracias a tu observación. No tengas en cuenta ese GetSettings para nada.
Lamentablemente no conservo los fuentes. Además también estarías necesitando la base de datos y el .coop para poder generar las capas.
Te recomiendo que te armes el ejemplo vos, definiendo una tabla como la del ejemplo, un ID y una Descripción y arrancar desde ahí, entiendo que paso a paso, viendo que usar en cada caso, va a ser más provechoso que poner a andar código que escribió otro (GetSettings aparte…)
Creo que el GetSettings sumó confusión. Ahora pienso que no vas a tener dificultad para entender el ejemplo, que, como escribí al comienzo del post, “La idea es brindar un punto de partida”.
Si tenés algún inconveniente por favor contame y vemos como seguir.
¡Muchas Gracias por tu observación!
Miércoles 12 \12UTC noviembre \12UTC 2008 a 15:11:24
Gabriel Arroyo
Gracias Carlos, Cuando termine el ABM que esto haciendo voy ha tratar de subir los fuentes.
Espero poder termianrlo pronto, ya que me estaba dando un problema al querer insertar o modificar un nuevo objeto
Saludos
Jueves 13 \13UTC noviembre \13UTC 2008 a 14:11:27
Carlos Marcelo Santos
Buena idea la de publicar tus fuentes. Si necesitás ayuda con este problema al insertar o modificar escribime acá o a carlos@prognos.com.ar
Saludos.
Jueves 05 \05UTC noviembre \05UTC 2009 a 15:11:47
Juan Alvarez
Estimado Carlos,
Muy buen ejemplo, se me abrió el apetito, pero no encuentro mucha documentación, así que te prgunto, existe alguna forma de filtrar en el ListView, por ejemplo por el valor de un campo?.
Gracias
Viernes 06 \06UTC noviembre \06UTC 2009 a 14:11:03
Carlos Marcelo Santos
Qué bueno que te haya servido.
Si, existe una forma de filtrar ListViews, es usando Predicates. Lamentablemente no tengo ningún post sobre esto, pero si buscás en Google por “.net predicate listview” vas a encontrar varios ejemplos de como usarlos y no vas a tener problemas para llevarlo al caso del ejemplo o al que necesites.
Si no conocés Predicates y el tema te resulta extraño, te recomiendo que entiendas Delegates primero. Pero aún así, sin conocer lo que subyace, podrías armarte un ejemplo sin problemas.
Lunes 16 \16UTC agosto \16UTC 2010 a 19:08:41
Melisa
Gracias Carlos!
Domingo 26 \26UTC junio \26UTC 2011 a 19:06:21
Agustin
Hola Carlos te cuento que en una materia de la facultad me piden hacer un sistema en c# en capaz modelo vista controladora con entity framework,quisera saber si me podrias ayudar con algun ejemplo .slh o como sea, donde explique como crear distintas abms con lo que te mencione previamente.
Te lo agradeceria un muchisimo si me podrias ayudar para seguir adelante!
Muchas gracias por tomarte el tiempo en leer mi ayuda!
Lunes 27 \27UTC junio \27UTC 2011 a 10:06:05
Carlos Marcelo Santos
Hola Agustín:
Si bien tengo un proyecto con MVC, lo hice con NHibernate, no con Entity Framework. No tengo ningún ejemplo en este momento para publicar y no sé cuanto tiempo me llevaría publicar algo, ya que previamente necesito escribir varios posts que vayan sirviendo como introducción al tema.
Lunes 27 \27UTC junio \27UTC 2011 a 22:06:44
Agustin
OK, no hay ningun drama! muchas gracias de todos modos!
Si conoces algun manual bueno practico que me pueda ayudar o algun libro o curso o videotutorial etc te lo agradeceria demasiado!
Abrazo y gracias por la onda!
Martes 28 \28UTC junio \28UTC 2011 a 20:06:19
Carlos Marcelo Santos
Hola Agustín:
Hay muchísimo material en la web sobre estos temas, un buen punto de partida para MVC sería http://www.asp.net/mvc, allí además de MVC en Learning Resources, punto 5 tenés mucho sobre Entity Frameworks.
También te recomiendo que te veas los videos de las VANs de Alt.NET.Hispano, http://altnethispano.org, es un material muy valioso, tomate el tiempo de mirarlos, vas a ahorrar mucho esfuerzo.
MVC Introducción
http://altnethispano.org/wiki/van-2009-05-02-asp-net-mvc-introduccion.ashx?HL=mvc
MVC Avanzado
http://altnethispano.org/wiki/van-2009-05-09-asp-net-mvc-avanzado.ashx?HL=mvc
MVC Con estilo
http://altnethispano.org/wiki/2009-11-21-van-aspnet-mvc-2-con-estilo.ashx?HL=mvc
MVC 3 y Razor
http://altnethispano.org/wiki/van-2010-07-30-aspnet-mvc-3-y-razor.ashx?HL=mvc
Entity Framework:
http://altnethispano.org/wiki/van-2010-11-17-entity-framework.ashx?HL=entity,framework
Si querés escribime a carlos@prognos.com.ar y te puedo hacer llegar algo más.
Suerte en la facu.
Lunes 06 \06UTC febrero \06UTC 2012 a 17:02:54
galo
Agradecere si alguien me puede decir donde puedo descargar la version 1.3.4.0.
Lunes 06 \06UTC febrero \06UTC 2012 a 18:02:44
Carlos Marcelo Santos
Hola Galo:
Yo no administro el sitio de Cooperator. Sé que su repositorio está aquí http://www.assembla.com/spaces/cooperator/trac_subversion_tool
Lo mejor sería que consultes a la lista oficial que te van a poner al tanto de las novedades.
Lunes 06 \06UTC febrero \06UTC 2012 a 18:02:41
galo
Gracias amigo.