DAL Product
Home

DAL Product

DAL Product

De producten worden opgeslagen in de databank onder de tabel Product.

Probleem

Er dient in onze applicatie aldus een klasse voorzien te worden die het informatieverkeer van en naar de databank behandelt. De DAL klasse implementeert de IDal interface. Dat maakt het gemakkelijker onze applicatie te testen.

Design

Velden

Naam Bereik Type Opmerking
message protected string
rowCount protected int
connection protected SqlConnection
product protected Models.Product

Methoden

Naam Bereik Parameters Retourneert Opmerking
create public - Int Een nieuw product wordt in de database geïnserted. Retourneert 1 bij succes en -1 bij falen.
update public - Boolean Een bestaand product wordt in de database aangepast. Retourneert true bij succes en false bij falen.
delete public - Boolean Een bestaand product wordt uit de database verwijderd. Retourneert true bij succes en false bij falen.
readOne public - Boolean Het product wordt rechtstreeks in het model geplaatst en de methode geeft true of false terug naargelang het selecteren is gelukt of niet
readAll public - Collection Retourneert een collectie met alle producten of een lege bij falen.
readById public - Collection Retourneert een collectie met geselecteerd product of een lege bij falen.
readByName public - Collection Retourneert een collectie met geselecteerde producten of een lege bij falen.
readLikeName public - Collection Retourneert een collectie met geselecteerde producten of een lege bij falen.
readLikeXName public - Collection Retourneert een collectie met geselecteerde producten of een lege bij falen.

Oplossing

De klasse Product

/* modernways.be
 * created by an orm apart
 * Entreprise de modes et de manières modernes
 * Dal for Webwinkel app
 * Created on Wednesday 14th of October 2015 11:19:43 AM
 * FileName: modernways/webwinkel/Product.cs
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Webwinkel.Dal
{
    class Product : DAL.IDal<Webwinkel.Models.Product>
    {
        protected string message;
        public string Message
        {
            get { return this.message; }
        }
        protected int rowCount;
        protected Models.Product product;

        public Product(Models.Product product)
        {
            this.product = product;
        }

        public Product()
        {
        }
    }
}

De Create methode

public int Create()
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.
        ConnectionStrings["WebwinkelWindowsAuthentication"].ToString();
    SqlCommand command = new SqlCommand();
    // in de CommandText eigenschap stoppen de naam
    // van de stored procedure
    string sqlString = "ProductInsert";
    //we use here a getter method to obtain the value to be saved,
    command.Parameters.Add(
        new SqlParameter("@Description", SqlDbType.NVarChar, 1024)).
        Value = product.Description;
    command.Parameters.Add(
        new SqlParameter("@Name", SqlDbType.NVarChar, 255)).
        Value = product.Name;
    command.Parameters.Add(
        new SqlParameter("@Price", SqlDbType.Float)).
        Value = product.Price;
    command.Parameters.Add(
        new SqlParameter("@Image", SqlDbType.VarChar, 255)).
        Value = product.Image;
    SqlParameter id = new SqlParameter("@Id", SqlDbType.Int);
    id.Direction = ParameterDirection.Output;
    command.Parameters.Add(id);
    // zeg aan het command object dat het een stored procedure
    // zal krijgen en geen SQL Statement
    command.CommandType = CommandType.StoredProcedure;
    // stop het sql statement in het command object
    command.CommandText = sqlString;
    // geeft het connection object door aan het command object
    command.Connection = connection;
    this.message = "Niets te melden";
    // we gaan ervan uit dat het mislukt
    int result = 0;
    using (connection)
    {
        try
        {
            connection.Open();
            //Verbinding geslaagd
            result = command.ExecuteNonQuery();
            // we moeten kijken naar de waarde van out parameter
            // van Insert stored procedure. Als de naam van de
            // category al bestaat, retourneert de out parameter van
            // de stored procedure
            // -1
            if ((int)id.Value == -100)
            {
                this.message = " Product bestaat al.";
                result = -100;
            }
            else if (result <= 0)
            {
                this.message = " Product is niet geïnserted.";
            }
            else
            {
                this.message = " Product is geïnserted.";
                result = (int)id.Value;
            }
        }
        catch (SqlException e)
        {
            this.message = e.Message;
        }
    }
    return result; // 0 of de Id van de nieuwe rij
}

De Update methode

public int Update()
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.
        ConnectionStrings["WebwinkelWindowsAuthentication"].ToString();
    SqlCommand command = new SqlCommand();
    // in de CommandText eigenschap stoppen de naam
    // van de stored procedure
    string sqlString = "ProductUpdate";
    //we use here a getter method to obtain the value to be saved,
    command.Parameters.Add(
        new SqlParameter("@Id", SqlDbType.Int)).
        Value = product.Id;
    command.Parameters.Add(
        new SqlParameter("@Description", SqlDbType.NVarChar, 1024)).
        Value = product.Description;
    command.Parameters.Add(
        new SqlParameter("@Name", SqlDbType.NVarChar, 255)).
        Value = product.Name;
    command.Parameters.Add(
        new SqlParameter("@Price", SqlDbType.Float)).
        Value = product.Price;
    command.Parameters.Add(
        new SqlParameter("@Image", SqlDbType.VarChar, 255)).
        Value = product.Image;
    // zeg aan het command object dat het een stored procedure
    // zal krijgen en geen SQL Statement
    command.CommandType = CommandType.StoredProcedure;
    // stop het sql statement in het command object
    command.CommandText = sqlString;
    // geeft het connection object door aan het command object
    command.Connection = connection;
    this.message = "Niets te melden";
    // we gaan ervan uit dat het mislukt
    int result = 0;
    using (connection)
    {
        try
        {
            connection.Open();
            //Verbinding geslaagd
            result = command.ExecuteNonQuery();
            // we moeten kijken naar de waarde van out parameter
            // van Insert stored procedure. Als de naam van de
            // category al bestaat, retourneert de out parameter van
            // de stored procedure
            // -1
            if (result == 0)
            {
                this.message = " Product is niet geüpdated.";
            }
            else
            {
                this.message = " Product is geüpdated.";
            }
        }
        catch (SqlException e)
        {
            this.message = e.Message;
        }
    }
    return result;
}

De Delete mehode

public int Delete()
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.
        ConnectionStrings["WebwinkelWindowsAuthentication"].ToString();
    SqlCommand command = new SqlCommand();
    // in de CommandText eigenschap stoppen de naam
    // van de stored procedure
    string sqlString = "ProductDelete";
    //we use here a getter method to obtain the value to be saved,
    command.Parameters.Add(
        new SqlParameter("@Id", SqlDbType.Int)).
        Value = product.Id;
    // zeg aan het command object dat het een stored procedure
    // zal krijgen en geen SQL Statement
    command.CommandType = CommandType.StoredProcedure;
    // stop het sql statement in het command object
    command.CommandText = sqlString;
    // geeft het connection object door aan het command object
    command.Connection = connection;
    this.message = "Niets te melden";
    // we gaan ervan uit dat het mislukt
    int result = 0;
    using (connection)
    {
        try
        {
            connection.Open();
            //Verbinding geslaagd
            result = command.ExecuteNonQuery();
            // we moeten kijken naar de waarde van out parameter
            // van Insert stored procedure. Als de naam van de
            // category al bestaat, retourneert de out parameter van
            // de stored procedure
            // -1
            if (result == 0)
            {
                this.message = " Product is niet gedeleted.";
            }
            else
            {
                this.message = " Product is gedeleted.";
            }
        }
        catch (SqlException e)
        {
            this.message = e.Message;
        }
    }
    return result;
}

De ReadOne methode

public Models.Product ReadOne()
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.
        ConnectionStrings["WebwinkelWindowsAuthentication"].ToString();
    SqlCommand command = new SqlCommand();
    // in de CommandText eigenschap stoppen de naam
    // van de stored procedure
    string sqlString = "ProductSelectOne";

    // zeg aan het command object dat het een tored procedure
    // zal krijgen en geen SQL Statement
    command.CommandType = CommandType.StoredProcedure;
    // stop het sql statement in het command object
    command.CommandText = sqlString;
    //we use here a getter method to obtain the value to be saved,
    command.Parameters.Add(
        new SqlParameter("@Id", SqlDbType.Int)).
        Value = product.Id;
    // geeft het connection object door aan het command object
    command.Connection = connection;
    this.message = "Niets te melden";
    // we gaan ervan uit dat het mislukt
    SqlDataReader result;
    using (connection)
    {
        try
        {
            connection.Open();
            {
                // retourneert het aantal rijen dat geïnserted werd
                this.message = "De database is klaar!";
                // voeg using toe om er voor te zorgen dat
                // de datareader gesloten wordt als we die niet
                // meer nodig hebben
                using (result = command.ExecuteReader())
                {
                    if (result.HasRows)
                    {
                        // lees de gevonden rij
                        result.Read();
                        product.Id = (int)result["Id"];
                        product.Name = result["Name"].ToString();
                        // IIF immediate if
                        // condition expression ? true : false
                        product.Price = (Convert.IsDBNull(result["Price"]) ?
                            0f : float.Parse(result["Price"].ToString()));
                        product.Description = Convert.IsDBNull(result["Description"]) ?
                            "" : result["Description"].ToString();
                        product.Image = Convert.IsDBNull(result["Image"]) ?
                            "" : result["Image"].ToString();

                    }
                }
            }
        }
        catch (SqlException e)
        {
            this.message = e.Message;
        }
    }
    return product;
}

De ReadAll methode

public List<Models.Product> ReadAll()
{
    List<Models.Product> list = new List<Models.Product>();

    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = ConfigurationManager.
        ConnectionStrings["WebwinkelWindowsAuthentication"].ToString();
    SqlCommand command = new SqlCommand();
    // in de CommandText eigenschap stoppen de naam
    // van de stored procedure
    string sqlString = "ProductSelectAll";

    // zeg aan het command object dat het een tored procedure
    // zal krijgen en geen SQL Statement
    command.CommandType = CommandType.StoredProcedure;
    // stop het sql statement in het command object
    command.CommandText = sqlString;
    // geeft het connection object door aan het command object
    command.Connection = connection;
    this.message = "Niets te melden";
    // we gaan ervan uit dat het mislukt
    SqlDataReader result;
    using (connection)
    {
        try
        {
            connection.Open();
            {
                // retourneert het aantal rijen dat geïnserted werd
                this.message = "De database is klaar!";
                // voeg using toe om er voor te zorgen dat
                // de datareader gesloten wordt als we die niet
                // meer nodig hebben
                using (result = command.ExecuteReader())
                {
                    if (result.HasRows)
                    {
                        // zolang dat er iets te lezen valt
                        // uit de tabel
                        while (result.Read())
                        {
                            Models.Product product = new Models.Product();
                            product.Id = (int)result["Id"];
                            product.Name = result["Name"].ToString();
                            // IIF immediate if
                            // condition expression ? true : false
                            product.Price = (Convert.IsDBNull(result["Price"]) ?
                                0f : float.Parse(result["Price"].ToString()));
                            list.Add(product);
                        }
                    }
                }
            }
        }
        catch (SqlException e)
        {
            this.message = e.Message;
        }
    }
    return list;
}

JI
2016-01-11 11:05:24