Saltar al contenido

CRUD con Patron MVP, C#, SQL y Windows Forms – Parte 3 (FINAL)

Continuemos con la tercera y última parte del tutorial. Ahora implementaremos las funciones de agregar, editar y eliminar.

Tutorial

PetView.cs

   public partial class PetView : Form, IPetView
    {
        //Fields
        private string message;
        private bool isSuccessful;
        private bool isEdit;

        //Constructor
        public PetView()
        {
            InitializeComponent();
            AssociateAndRaiseViewEvents();
            tabControl1.TabPages.Remove(tabPagePetDetail);
            btnClose.Click += delegate { this.Close(); };
        }

        private void AssociateAndRaiseViewEvents()
        {
            //Search
            btnSearch.Click += delegate { SearchEvent?.Invoke(this, EventArgs.Empty); };
            txtSearch.KeyDown += (s, e) =>
              {
                  if (e.KeyCode == Keys.Enter)
                      SearchEvent?.Invoke(this, EventArgs.Empty);
              };
            //Add new
            btnAddNew.Click += delegate
            {
                AddNewEvent?.Invoke(this, EventArgs.Empty);
                tabControl1.TabPages.Remove(tabPagePetList);
                tabControl1.TabPages.Add(tabPagePetDetail);
                tabPagePetDetail.Text = "Add new pet";
            };
            //Edit
            btnEdit.Click += delegate
            {
                EditEvent?.Invoke(this, EventArgs.Empty);
                tabControl1.TabPages.Remove(tabPagePetList);
                tabControl1.TabPages.Add(tabPagePetDetail);
                tabPagePetDetail.Text = "Edit pet";
            };
            //Save changes
            btnSave.Click += delegate
            {
                SaveEvent?.Invoke(this, EventArgs.Empty);
                if (isSuccessful)
                {
                    tabControl1.TabPages.Remove(tabPagePetDetail);
                    tabControl1.TabPages.Add(tabPagePetList);
                }
                MessageBox.Show(Message);
            };
            //Cancel
            btnCancel.Click += delegate
            {
                CancelEvent?.Invoke(this, EventArgs.Empty);
                tabControl1.TabPages.Remove(tabPagePetDetail);
                tabControl1.TabPages.Add(tabPagePetList);
            };
            //Delete
            btnDelete.Click += delegate
            {               
                var result = MessageBox.Show("Are you sure you want to delete the selected pet?", "Warning",
                      MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    DeleteEvent?.Invoke(this, EventArgs.Empty);
                    MessageBox.Show(Message);
                }
            };
        }

PetPresenter.cs

public class PetPresenter
{
    //Fields
    private IPetView view;
    private IPetRepository repository;
    private BindingSource petsBindingSource;
    private IEnumerable<PetModel> petList;

    //Constructor
    public PetPresenter(IPetView view, IPetRepository repository)
    {
        this.petsBindingSource = new BindingSource();
        this.view = view;
        this.repository = repository;
        //Subscribe event handler methods to view events
        this.view.SearchEvent += SearchPet;
        this.view.AddNewEvent += AddNewPet;
        this.view.EditEvent += LoadSelectedPetToEdit;
        this.view.DeleteEvent += DeleteSelectedPet;
        this.view.SaveEvent += SavePet;
        this.view.CancelEvent += CancelAction;
        //Set pets bindind source
        this.view.SetPetListBindingSource(petsBindingSource);
        //Load pet list view
        LoadAllPetList();
        //Show view
        this.view.Show();
    }

    //Methods
    private void LoadAllPetList()
    {
        petList = repository.GetAll();
        petsBindingSource.DataSource = petList;//Set data source.
    }
    private void SearchPet(object sender, EventArgs e)
    {
        bool emptyValue = string.IsNullOrWhiteSpace(this.view.SearchValue);
        if (emptyValue == false)
            petList = repository.GetByValue(this.view.SearchValue);
        else petList = repository.GetAll();
        petsBindingSource.DataSource = petList;
    }
    private void AddNewPet(object sender, EventArgs e)
    {
        view.IsEdit = false;          
    }
    private void LoadSelectedPetToEdit(object sender, EventArgs e)
    {
        var pet = (PetModel)petsBindingSource.Current;
        view.PetId = pet.Id.ToString();
        view.PetName = pet.Name;
        view.PetType = pet.Type;
        view.PetColour = pet.Colour;
        view.IsEdit = true;
    }
    private void SavePet(object sender, EventArgs e)
    {
        var model = new PetModel();
        model.Id = Convert.ToInt32(view.PetId);
        model.Name = view.PetName;
        model.Type = view.PetType;
        model.Colour = view.PetColour;
        try
        {
            new Common.ModelDataValidation().Validate(model);
            if(view.IsEdit)//Edit model
            {
                repository.Edit(model);
                view.Message = "Pet edited successfuly";
            }
            else //Add new model
            {
                repository.Add(model);
                view.Message = "Pet added sucessfully";
            }
            view.IsSuccessful = true;
            LoadAllPetList();
            CleanviewFields();
        }
        catch (Exception ex)
        {
            view.IsSuccessful = false;
            view.Message = ex.Message;
        }
    }

    private void CleanviewFields()
    {
        view.PetId = "0";
        view.PetName = "";
        view.PetType = "";
        view.PetColour = "";            
    }

    private void CancelAction(object sender, EventArgs e)
    {
        CleanviewFields();
    }
    private void DeleteSelectedPet(object sender, EventArgs e)
    {
        try
        {
            var pet = (PetModel)petsBindingSource.Current;
            repository.Delete(pet.Id);
            view.IsSuccessful = true;
            view.Message = "Pet deleted successfully";
            LoadAllPetList();
        }
        catch (Exception ex)
        {
            view.IsSuccessful = false;
            view.Message = "An error ocurred, could not delete pet";
        }
    }

}

ModelDataValidations.cs

public class ModelDataValidation
{
    public void Validate(object model)
    {
        string errorMessage = "";
        List<ValidationResult> results = new List<ValidationResult>();
        ValidationContext context = new ValidationContext(model);
        bool isValid = Validator.TryValidateObject(model,context,results,true);
        if(isValid==false)
        {
            foreach (var item in results)
                errorMessage += "- " + item.ErrorMessage + "\n";
            throw new Exception(errorMessage);
        }
    }
}

PetRepository.cs

public class PetRepository : BaseRepository, IPetRepository
{
    //Constructor
    public PetRepository(string connectionString)
    {
        this.connectionString = connectionString;
    }
    //Methods
    public void Add(PetModel petModel)
    {
        using (var connection = new SqlConnection(connectionString))
        using (var command = new SqlCommand())
        {
            connection.Open();
            command.Connection = connection;
            command.CommandText = "insert into Pet values (@name, @type, @colour)";
            command.Parameters.Add("@name", SqlDbType.NVarChar).Value = petModel.Name;
            command.Parameters.Add("@type", SqlDbType.NVarChar).Value = petModel.Type;
            command.Parameters.Add("@colour", SqlDbType.NVarChar).Value = petModel.Colour;
            command.ExecuteNonQuery();
        }
    }
    public void Delete(int id)
    {
        using (var connection = new SqlConnection(connectionString))
        using (var command = new SqlCommand())
        {
            connection.Open();
            command.Connection = connection;
            command.CommandText = "delete from Pet where Pet_Id=@id";
            command.Parameters.Add("@id", SqlDbType.Int).Value = id;           
            command.ExecuteNonQuery();
        }
    }
    public void Edit(PetModel petModel)
    {
        using (var connection = new SqlConnection(connectionString))
        using (var command = new SqlCommand())
        {
            connection.Open();
            command.Connection = connection;
            command.CommandText = @"update Pet 
                                    set Pet_Name=@name,Pet_Type= @type,Pet_Colour= @colour 
                                    where Pet_Id=@id";
            command.Parameters.Add("@name", SqlDbType.NVarChar).Value = petModel.Name;
            command.Parameters.Add("@type", SqlDbType.NVarChar).Value = petModel.Type;
            command.Parameters.Add("@colour", SqlDbType.NVarChar).Value = petModel.Colour;
            command.Parameters.Add("@id", SqlDbType.Int).Value = petModel.Id;
            command.ExecuteNonQuery();
        }
    }

Descargas

Video Tutoriales

English

Part 1, 2 and 3

Part 1
Part 2
Part 3 – Final

Español

Parte 1, 2 y 3

Parte 1
Parte 2
Parte 3 – Final