SlideShare une entreprise Scribd logo
1  sur  21
(Library         Project) by Marcelo Salvador
Introduction: The project was created in order to create a library database accessing a
SQL Server database and allowing data manipulation.

Audience:

                     Business Executives
                     Information Workers
                     IT Managers

Project Goals:

        The goal of this project was to allow data manipulation of a library database by
utilizing Windows Forms as a graphic user interface. Afterwards, the project was
migrated to ASP.NET.


Below I enclose examples of the classes utilizing N-Tier Architecture.

using System;
using System.Collections.Generic;
using System.Text;
using Ms.Library.Entities;
using Ms.Library.Entities.Properties;
using Ms.Library.Entities.ItemsDataSetTableAdapters;
using LibraryDataAccess;
using LibraryDataAccess.Properties;
using System.Data.SqlClient;
using System.Data;
/*********************************************************************
 * Description: This class is utilized to gather all the information
from
 *                 the database;also, deletes, updates,etc.   Every
single
 *                 methods contains a connection to the library database
and
 *                 returns an error number in case an error takes place.
 *
 * Author: Marcelo D. Salvador
 * Create Date: 11/24/2008
 * Modified Date: 11/28/2007
* Modification: 12/01/2008
 ********************************************************************/

namespace Marcelo_Library
{
    /// <summary>
    /// This class is utilized to access data in the library database
    /// </summary>
    public class LibraryDataAccess
    {
        /// <summary>
        /// default constructor
        /// </summary>
        public LibraryDataAccess()
        {
        }
        /// <summary>
        /// Gets the member based on member ID
        /// </summary>
        /// <param name="memberID"></param>
        /// <returns></returns>
        public Member getMember(int memberID)
        {
            Member mymember = new Member();
            int returnValue;
            try
            {
                // create connection
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    // create the command object
                    using (SqlCommand cmd = new SqlCommand("GetMember",
cnn))
                    {
                        // assign the connection above to your new
command object

                       cmd.Connection = cnn;
                       // name of the proc you are calling

                       // command object will use a stored procedure
                       cmd.CommandType = CommandType.StoredProcedure;

                       //add input paramater for memberID
                       cmd.Parameters.AddWithValue("@MemberID",
memberID);

                        //add return value parameter so we can access
the return value from the proc
                        SqlParameter returnParm = new SqlParameter();
                        returnParm.ParameterName = "@return";
                        returnParm.SqlDbType = SqlDbType.Int;
                        returnParm.Direction =
ParameterDirection.ReturnValue;
                        cmd.Parameters.Add(returnParm);
// open the connection
                        cnn.Open();

                        // create a SQLDAtaREader to use with the data
coming back from the proc
                        using (SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            // It will fall into the code
                            // block below if the proc
                            // executed successfully
                            // and returned a row.
                            while (reader.Read())
                            {//Column order on the table
                                /*     m.lastname,
                                       m.firstname,
                                       m.middleinitial,
                                       a.street,
                                       a.city,
                                       a.state,
                                       a.zip,
                                       a.phone_no,
                                       a.expr_date,
                                       j.adult_member_no,
                                       j.birth_date
                                */

                                /*    Checking if the column number 10
which is
                                 *       actually 9 because it is zero
based.*/

                                if (!(reader.IsDBNull(9)))
                                {
                                    //Juvenile member created...
                                    JuvenileMember juvMember = new
JuvenileMember();

                                     //using ordinal positions of columns

                                     juvMember.LastName =
reader[0].ToString();
                                     juvMember.FirstName =
reader[1].ToString();
                                     juvMember.MiddleInitial =
reader[2].ToString();
                                     juvMember.AdultMemberID =
short.Parse(reader[9].ToString());
                                     juvMember.BirthDate =
DateTime.Parse(reader[10].ToString());
                                     // juvenile member is built in
entity class can return it now
                                     return juvMember;
                                }
                                else
                                {
                                     //Adult member created
AdultMember myAdultMember = new
AdultMember();
                                       myAdultMember.LastName =
reader[0].ToString();
                                       myAdultMember.FirstName =
reader[1].ToString();
                                       myAdultMember.MiddleInitial =
reader[2].ToString();
                                       myAdultMember.Street =
reader[3].ToString();
                                       myAdultMember.City =
reader[4].ToString();
                                       myAdultMember.State =
reader[5].ToString();

                                       // zipcode needs to be trimmed

                                       string zip = reader[6].ToString();
                                       myAdultMember.ZipCode = zip.Trim();
                                       myAdultMember.PhoneNumber =
reader[7].ToString();
                                     myAdultMember.ExpirationDate =
DateTime.Parse(reader[8].ToString());
                                     return myAdultMember;
                                }
                            }
                        }
                        // Checking SQL stored procedures return values
and through exceptions based on them
                        returnValue =
int.Parse(cmd.Parameters["@return"].Value.ToString());

                        /*return   0    -- 'Return values successful from
the query*/
                        /*Return -1     -- 'MemberID is null'*/
                        /*Return -2     -- 'MemberID is < 1 OR MemberID >
32767*/
                        /*Return -3     -- 'No Member found or if length
is greater than 5*/

                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                case -1:
                                    throw new LibraryException("isbn is
null", LibraryException.ErrorCode.IsbnIsNull);
                                case -2:
                                    throw new LibraryException("copy_no
is null", LibraryException.ErrorCode.OutOfRangeMemberValue);
                                case -3:
                                    throw new
LibraryException("member_no is null",
LibraryException.ErrorCode.NoSuchMember);

                            }
                        }
}
               }

            }
            catch (InvalidCastException e)
            {
                string.Format("Invalid Cast", e.ToString());
            }
            catch (SqlException sql)
            {
                throw new LibraryException(sql.Message,
LibraryException.ErrorCode.GenericException);
            }

            return mymember;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="memberNumber"></param>
        /// <returns></returns>
        public ItemsDataSet GetItems(short memberNumber)
        {
            ItemsDataSet itemsDS = new ItemsDataSet();
            ItemsTableAdapter itemsTableAdapter = new
ItemsTableAdapter();

            ItemsDataSet.ItemsDataTable myTable = new
ItemsDataSet.ItemsDataTable();

            int returnValue = itemsTableAdapter.Fill(itemsDS.Items,
memberNumber);


           returnValue = (int)itemsTableAdapter.GetReturnValue(0);

           if (returnValue == 0)
                return itemsDS;
           else
                throw new Exception("Book not Found!!!");
        }
        /// <summary>
        /// Get book information
        /// </summary>
        /// <param name="isbnNumber"></param>
        /// <param name="copyNumber"></param>
        /// <returns></returns>
        public Item GetItem(int isbnNumber, short copyNumber)
        {
            Item myitem = new Item();
            int returnValue;
            try
            {
                // create connection
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
// create the command object
                   using (SqlCommand cmd = new SqlCommand("GetMyItem",
cnn))
                   {
                       // assign the connection above to your new
command object
                       cmd.Connection = cnn;
                       // name of the proc you are calling

                       // command object will use a stored procedure
                       cmd.CommandType = CommandType.StoredProcedure;

                       //add input paramater for memberID

                       cmd.Parameters.AddWithValue("@isbn",
isbnNumber);
                       cmd.Parameters.AddWithValue("@copy_no",
copyNumber);

                        //add return value parameter so we can access
the return value from the proc
                        SqlParameter returnParm = new SqlParameter();
                        returnParm.ParameterName = "@return";
                        returnParm.SqlDbType = SqlDbType.Int;
                        returnParm.Direction =
ParameterDirection.ReturnValue;
                        cmd.Parameters.Add(returnParm);

                        // open the connection
                        cnn.Open();
                        // create a SQLDataReader to use with the data
coming back from the proc
                        using (SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            // we will fall into the code block below
if the proc executed successfully
                            // and returned a row.
                            while (reader.Read())
                            {
                                /*
                                  * @isbn,
                                  * @copy_no,
                                  * @title,
                                  * @author,
                                  * @member_no,
                                  * @out_date,
                                  * @due_date

                                */
                                if (!(reader.IsDBNull(0)))
                                {
                                    //add stuff to juvenile class
                                    Item dItem = new Item();
                                    // Using ordinal positions of
columns
dItem.ISBN =
Convert.ToInt32(reader[0].ToString());
                                    dItem.CopyNo =
Convert.ToInt32(reader[1].ToString());
                                    dItem.Title = reader[2].ToString();
                                    dItem.Author = reader[3].ToString();
                                    dItem.MemberNO =
Convert.ToInt32(reader[4].ToString());
                                    dItem.OutDate =
Convert.ToDateTime(reader[5].ToString());
                                    dItem.DueDate =
Convert.ToDateTime(reader[6].ToString());

                                     return dItem;
                                }

                            }
                       }

                       //RETURN Codes:

                       //RETURN 0     --   Sucesss
                       //RETURN -1    --   ISBN is null
                       //RETURN -2    --   Copy number is null
                       //RETURN -3    --   Member does not exist


                        returnValue =
int.Parse(cmd.Parameters["@return"].Value.ToString());
                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                case -1:
                                    throw new LibraryException("isbn is
null", LibraryException.ErrorCode.IsbnIsNull);
                                case -2:
                                    throw new LibraryException("copy_no
is null", LibraryException.ErrorCode.OutOfRangeMemberValue);
                                case -3:
                                    throw new
LibraryException("member_no is null",
LibraryException.ErrorCode.NoSuchMember);
                            }
                        }
                    }
                }

           }
           catch (InvalidCastException e)
           {
               string.Format("Invalid Cast", e.ToString());

           }
           catch (SqlException ex)
           {
throw new LibraryException(ex.Message,
LibraryException.ErrorCode.GenericException);
            }
            return myitem;

        }

        /// <summary>
        /// Add item to loan table
        /// </summary>
        /// <param name="memberID"></param>
        /// <param name="copyNumber"></param>
        /// <param name="isbnNumber"></param>
        public void CheckOutItem(int memberID, short copyNumber, int
isbnNumber)
        {
            try
            {
                //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("checkOutBookItem", cnn))
                    {
                        Item member = new Item();
                        // Item member = new Item(isbnNumber,
copyNumber, memberID);
                        cmd.CommandType = CommandType.StoredProcedure;

                       // Set up the return value parameter
                       SqlParameter prm = new SqlParameter();
                       prm.ParameterName = "@Return";
                       prm.Direction = ParameterDirection.ReturnValue;
                       cmd.Parameters.Add(prm);

                       // Passes in the memberID, copyNumber and
isbnNumber passed in
                       // from the checkout screen.

                       cmd.Parameters.AddWithValue("@isbn",
isbnNumber);
                       cmd.Parameters.AddWithValue("@copy_no",
copyNumber);
                       cmd.Parameters.AddWithValue("@member_no",
memberID);

                       // Open connection and execute query
                       cnn.Open();
                       cmd.ExecuteNonQuery();

                       /* Error Codes From the CheckOut Book stored
procedure...
Return   -1 -- 'isbn is null'
                                Return   -2 -- 'copy_no is null'
                                Return   -3 -- 'member_no is null'
                                Return   -4 -- 'book does not exist'
                                Return   -5 -- 'member does not exist'
                                Return   -6 -- 'copy does not exist'
                            Return -7    -- 'book already checked out'
                            Return -8    -- 'member has 4 books already'
                            Return -9    -- 'insert failed'
                        */
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;
                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                case -1:
                                    throw new LibraryException("isbn is
null", LibraryException.ErrorCode.IsbnIsNull);
                                case -2:
                                    throw new LibraryException("copy_no
is null", LibraryException.ErrorCode.CopyNoIsNull);
                                case -3:
                                    throw new
LibraryException("member_no is null",
LibraryException.ErrorCode.MemberNoIsNull);
                                case -4:
                                    throw new LibraryException("book
does not exist", LibraryException.ErrorCode.BookDoesNotExist);
                                case -5:
                                    throw new LibraryException("member
does not exist", LibraryException.ErrorCode.NoSuchMember);
                                case -6:
                                    throw new LibraryException("copy
does not exist", LibraryException.ErrorCode.CopyDoesNotExist);
                                case -7:
                                    throw new LibraryException("book
already checked out", LibraryException.ErrorCode.BookAlreadyCheckedOut);
                                case -8:
                                    throw new LibraryException("member
has 4 books already",
LibraryException.ErrorCode.MemberHasfourBooksAlready);
                                case -9:
                                    throw new LibraryException("insert
failed", LibraryException.ErrorCode.InsertFailed);
                            }
                        }
                    }
                }
            }
            catch (SqlException sqlex)
            {
                throw new LibraryException(sqlex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }
/// <summary>
          ///
          /// </summary>
          /// <param name="copyNumber"></param>
          /// <param name="isbnNumber"></param>
          public void CheckInItem(short copyNumber, int isbnNumber)
          {
              try
              {
                  //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("CheckInBookItem", cnn))
                    {

                         cmd.CommandType = CommandType.StoredProcedure;

                         // Set up the return value parameter
                         SqlParameter prm = new SqlParameter();
                         prm.ParameterName = "@Return";
                         prm.Direction = ParameterDirection.ReturnValue;
                         cmd.Parameters.Add(prm);

                         // Passes the new member variables to the
stored proc

                         cmd.Parameters.AddWithValue("@isbn",
isbnNumber);
                         cmd.Parameters.AddWithValue("@copy_no",
copyNumber);


                         // Open connection and execute query
                         cnn.Open();
                         cmd.ExecuteNonQuery();

                        // Get Error Code
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;

                         /* Error codes:
                                 Return -1 -- 'isbn is null'
                                 Return -2 -- 'copy_no is null'
                                 Return -3 -- 'member_no is null'
                                 Return -4 -- 'book does not exist'
                                 Return -5 -- 'copy does not exist'
                                 Return -6 -- 'book is not checked out'
                             Return -7 -- 'delete from loan table
failed'
Return -8   -- 'Adding row to loan history
table failed'
                            Return -9   -- 'Update on copy table failed'

                                                            */
                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                case -1:
                                    throw new LibraryException("isbn is
null", LibraryException.ErrorCode.IsbnIsNull);
                                case -2:
                                    throw new LibraryException("copy_no
is null", LibraryException.ErrorCode.CopyNoIsNull);
                                case -3:
                                    throw new
LibraryException("member_no is null",
LibraryException.ErrorCode.MemberNoIsNull);
                                case -4:
                                    throw new LibraryException("book
does not exist", LibraryException.ErrorCode.BookDoesNotExist);
                                case -5:
                                    throw new LibraryException("member
does not exist", LibraryException.ErrorCode.DeleteFailed);
                                case -6:
                                    throw new LibraryException("copy
does not exist", LibraryException.ErrorCode.InsertFailed);
                                case -7:
                                    throw new LibraryException("book
already checked out", LibraryException.ErrorCode.BookAlreadyCheckedOut);
                                case -8:
                                    throw new LibraryException("member
has 4 books already",
LibraryException.ErrorCode.MemberHasfourBooksAlready);
                                case -9:
                                    throw new LibraryException("insert
failed", LibraryException.ErrorCode.UpdateFailed);
                            }

                       }
                   }
                }
            }
            catch (SqlException ex)
            {
                throw new LibraryException(ex.Message,
LibraryException.ErrorCode.GenericException);
            }

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="member"></param>
        public void AddMember(AdultMember member)
        {
try
              {
                    //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new SqlCommand("AddAdult",
cnn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                           // Set up the return value parameter
                           SqlParameter prm = new SqlParameter();
                           prm.ParameterName = "@Return";
                           prm.Direction = ParameterDirection.ReturnValue;
                           cmd.Parameters.Add(prm);

                           // Passes the new member variables to the
stored proc

                           cmd.Parameters.AddWithValue("@lastName",
member.LastName);
                           cmd.Parameters.AddWithValue("@name",
member.FirstName);
                           cmd.Parameters.AddWithValue("@middleInitial",
member.MiddleInitial);
                           cmd.Parameters.AddWithValue("@street",
member.Street);
                           cmd.Parameters.AddWithValue("@city",
member.City);
                           cmd.Parameters.AddWithValue("@state",
member.State);
                           cmd.Parameters.AddWithValue("@zipCode",
member.ZipCode);
                           cmd.Parameters.AddWithValue("@phoneNumber",
member.PhoneNumber);

                           // Add the output params
                           prm = new SqlParameter("@InsertMemberID",
SqlDbType.SmallInt);
                           prm.Direction = ParameterDirection.Output;
                           cmd.Parameters.Add(prm);

                           prm = new SqlParameter("@ExpirationDate",
SqlDbType.DateTime);
                           prm.Direction = ParameterDirection.Output;
                           cmd.Parameters.Add(prm);

                           // Open connection and execute query
                           cnn.Open();
                           cmd.ExecuteNonQuery();

                           //                        --RETURN Codes:
//--                      RETURN   0   --
Successful
                        //--                      RETURN -1
--'Firstname is null'
                        //--                      RETURN -2
--'LastName is null'
                        //--                            RETURN -3
--'Street is null'
                        //--                            RETURN -4
--'City is null'
                        //--                            RETURN -5
--'State is null'
                        //--                            RETURN -6
--'Zip is null'
                        //--                            RETURN -7
--'insert into member failed'
                        //--                      RETURN -8    --'insert
into adult failed'
                        // Get Error Code
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;
                        if (returnValue != 0)

                            switch (returnValue)
                            {
                                case -1:
                                     throw new
LibraryException("Firstname is null",
LibraryException.ErrorCode.FirstnameIsNull);
                                case -2:
                                     throw new
LibraryException("LastName is null",
LibraryException.ErrorCode.LastNameIsNull);
                                case -3:
                                     throw new LibraryException("Street
is null", LibraryException.ErrorCode.StreetIsNull);
                                case -4:
                                     throw new LibraryException("City is
null", LibraryException.ErrorCode.CityIsNull);
                                case -5:
                                     throw new LibraryException("State
is null", LibraryException.ErrorCode.StateIsNull);
                                case -6:
                                     throw new LibraryException("Zip is
null", LibraryException.ErrorCode.ZipIsNull);
                                case -7:
                                     throw new LibraryException("insert
into member failed", LibraryException.ErrorCode.InsertFailed);
                                case -8:
                                     throw new LibraryException("insert
into adult failed", LibraryException.ErrorCode.InsertFailed);

                            }
                        // Get return variables
                        member.ExpirationDate = (DateTime)
(cmd.Parameters["@ExpirationDate"].Value);
member.MemberID =
(short)cmd.Parameters["@InsertMemberID"].Value;
                    }
                }
            }
            catch (SqlException ex)
            {
                throw new LibraryException(ex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }


        /// <summary>
        /// Insert juvenile and member rows into Library data base
        /// </summary>
        /// <param name="member">JuvenileMember object</param>
        public void AddMember(JuvenileMember member)
        {
            try
            {//Open Library connection
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("AddJuvenile", cnn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                         // Set up the return value parameter
                         SqlParameter prm = new SqlParameter();
                         prm.ParameterName = "@Return";
                         prm.Direction = ParameterDirection.ReturnValue;
                         cmd.Parameters.Add(prm);

                         // Pass the new member variables to the stored
proc
                         cmd.Parameters.AddWithValue("@lastname",
member.LastName);
                         cmd.Parameters.AddWithValue("@name",
member.FirstName);
                         cmd.Parameters.AddWithValue("@middleInitial",
member.MiddleInitial);
                         cmd.Parameters.AddWithValue("@adultMemberID",
member.AdultMemberID);
                         cmd.Parameters.AddWithValue("@juvBirthDate",
member.BirthDate);

                         // Add the output params

                        SqlParameter memberIDParm = new SqlParameter();
                        memberIDParm.ParameterName = "@InsertMemberID";
                        memberIDParm.SqlDbType = SqlDbType.SmallInt;
                        memberIDParm.Direction =
ParameterDirection.Output;
                        cmd.Parameters.Add(memberIDParm);
// Open connection and execute query
                        cnn.Open();
                        cmd.ExecuteNonQuery();

                        // Get Error Code
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;

                        //                       RETURN   0   --
Successful
                        //--                     RETURN -1    --'name is
null'
                         //--                      RETURN -2
--'middleinitial is null'
                         //--                            RETURN -3
--'lastname is null'
                         //--                            RETURN -4
--'adultmemberid is null'
                         //--                            RETURN -5
--'juvbirthdate is null'
                         //--                            RETURN -6
--'insert into member failed'
                         //--                      RETURN -7   --'insert
into juvenile failed'
                         if (returnValue != 0)
                         {
                              switch (returnValue)
                              {
                                  case -1:
                                      throw new
LibraryException("Firstname is null",
LibraryException.ErrorCode.FirstnameIsNull);
                                  case -2:
                                      throw new
LibraryException("MiddleInitial is null",
LibraryException.ErrorCode.NullValue);
                                  case -3:
                                      throw new
LibraryException("lastname is null",
LibraryException.ErrorCode.LastNameIsNull);
                                  case -4:
                                      throw new
LibraryException("adultMemberId is null",
LibraryException.ErrorCode.AddAdultFailed);
                                  case -5:
                                      throw new
LibraryException("juvBirthDateis null",
LibraryException.ErrorCode.BirthdateNull);
                                  case -6:
                                      throw new LibraryException("Insert
Into Member Failed", LibraryException.ErrorCode.InsertFailed);
                                  case -7:
                                      throw new LibraryException("insert
Int Juvenile failed", LibraryException.ErrorCode.AddJuvenileFailed);
                              }
}

                        member.MemberID =
(short)cmd.Parameters["@InsertMemberID"].Value;
                    }
                }
            }
            catch (SqlException ex)
            {
                throw new LibraryException(ex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }

        /// <summary>
        /// Used to renew membership
        /// </summary>
        /// <param name="memberNumber"></param>
        public void RenewMembership(int memberNumber)
        {
            try
            {
                //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("RenewExpirationDate", cnn))
                    {
                        Item member = new Item();
                        // Item member = new Item(isbnNumber,
copyNumber, memberID);
                        cmd.CommandType = CommandType.StoredProcedure;

                       // Set up the return value parameter
                       SqlParameter prm = new SqlParameter();
                       prm.ParameterName = "@Return";
                       prm.Direction = ParameterDirection.ReturnValue;
                       cmd.Parameters.Add(prm);

                       // Passes in the memberID
                       // from the checkout screen.

                       cmd.Parameters.AddWithValue("@member_no",
memberNumber);

                       // Add the output params

                        SqlParameter memberExpDate = new SqlParameter();
                        memberExpDate.ParameterName = "@expr_date";
                        memberExpDate.SqlDbType = SqlDbType.DateTime;
                        memberExpDate.Direction =
ParameterDirection.Output;
cmd.Parameters.Add(memberExpDate);

                        // Open connection and execute query
                        cnn.Open();
                        cmd.ExecuteNonQuery();

                        /* Error Codes From the CheckOut Book stored
procedure...
                                Return -1   -- 'Failed: Member number is
null'
                                Return -2   -- 'Failed: Member does not
exist'
                                Return -3   -- 'Insert into adult member
table failed'

                        */
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;
                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                 case -1:
                                     throw new LibraryException("Failed:
Member number is null", LibraryException.ErrorCode.MemberNoIsNull);
                                 case -2:
                                     throw new LibraryException("Failed:
Member does not exist", LibraryException.ErrorCode.NoSuchMember);
                                 case -3:
                                     throw new LibraryException("Insert
into adult member table failed",
LibraryException.ErrorCode.InsertFailed);

                            }
                        }
                    }
                }
            }
            catch (SqlException sqlex)
            {
                throw new LibraryException(sqlex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }

        /// <summary>
        /// Method used to add a new book to the library database
        /// </summary>
        /// <param name="title"></param>
        /// <param name="author"></param>
        /// <param name="synopsis"></param>
        /// <param name="isbn"></param>
        /// <param name="translation"></param>
        /// <param name="cover"></param>
        /// <param name="loanable"></param>
        public void AddNewBook(string title, string author, string
synopsis, int isbn, string translation, string cover, char loanable)
{
             try
             {
                   //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("EnterNewBook", cnn))
                    {
                        Item member = new Item();

                          cmd.CommandType = CommandType.StoredProcedure;

                          // Set up the return value parameter
                          SqlParameter prm = new SqlParameter();
                          prm.ParameterName = "@Return";
                          prm.Direction = ParameterDirection.ReturnValue;
                          cmd.Parameters.Add(prm);

                          // Passes in the values
                          // from the checkout screen.


                          cmd.Parameters.AddWithValue("@title", title);
                          cmd.Parameters.AddWithValue("@author", author);
                          cmd.Parameters.AddWithValue("@synopsis",
synopsis);
                          cmd.Parameters.AddWithValue("@isbn", isbn);
                          cmd.Parameters.AddWithValue("@translation",
translation);
                          cmd.Parameters.AddWithValue("@cover", cover);
                          cmd.Parameters.AddWithValue("@loanable",
loanable);

                          // Open connection and execute query
                          cnn.Open();
                          cmd.ExecuteNonQuery();

                        /*
***********************************************************************
****
                         * RETURN Codes:
                                RETURN -0 -- Sucesss
                                RETURN -1 -- The title is null
                                RETURN -2 -- The author is null
                                RETURN -3 -- The synopsis is null is
null
                                RETURN -4 -- The translation is null
                                RETURN -5 -- The cover is null
                                RETURN -6 -- The loanable is null
                                RETURN -7 -- The isbn is null is null
RETURN -8   -- The ISBN exist in the
Item table
                                RETURN -9   -- The isbn exist in the
copy table
                                RETURN -10 -- INSERT for the title
table failed
                                RETURN -11 -- INSERT for the item table
failed
                                RETURN -12 -- INSERT for the copy table
failed
                          **********************************************
********************************/
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;
                        if (returnValue != 0)
                        {
                             switch (returnValue)
                             {
                                 case -1:
                                     throw new LibraryException("The
title is null", LibraryException.ErrorCode.titleIsNull);
                                 case -2:
                                     throw new LibraryException("The
author is null", LibraryException.ErrorCode.AuthorIsNull);
                                 case -3:
                                     throw new LibraryException("The
synopsis is null is null", LibraryException.ErrorCode.SynopsisIsNull);
                                 case -4:
                                     throw new LibraryException("The
translation is null", LibraryException.ErrorCode.TranslationIsNull);
                                 case -5:
                                     throw new LibraryException("The
cover is null", LibraryException.ErrorCode.CoverIsNull);
                                 case -6:
                                     throw new LibraryException("The
loanable is null", LibraryException.ErrorCode.LoanableIsNull);
                                 case -7:
                                     throw new LibraryException("The
isbn is null is null", LibraryException.ErrorCode.IsbnIsNull);
                                 case -8:
                                     throw new LibraryException("The
ISBN exist in the Item table",
LibraryException.ErrorCode.IsbnExistInItemTable);
                                 case -9:
                                     throw new LibraryException("The
isbn exist in the copy table",
LibraryException.ErrorCode.IsbnExistInCopyTable);
                                 case -10:
                                     throw new LibraryException("INSERT
for the title table failed",
LibraryException.ErrorCode.TitleInsertFailed);
                                 case -11:
                                     throw new LibraryException("INSERT
for the item table failed",
LibraryException.ErrorCode.ItemInsertFailed);
                                 case -12:
throw new LibraryException("INSERT
for the copy table failed",
LibraryException.ErrorCode.CopyInsertFailed);

                             }
                         }
                     }
                 }
            }
            catch (SqlException sqlex)
            {
                throw new LibraryException(sqlex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }

        /// <summary>
        /// Method created to convert a Juvenile member of less than 18
yrs of age to an adult member)
        /// </summary>
        /// <param name="memberNumber"></param>
        public void adolescentToAdult(int memberNumber)
        {
            try
            {
                //Open Library connection

                //using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                    //create the command within a using block
                    using (SqlCommand cmd = new
SqlCommand("KidToAdult", cnn))
                    {
                        Item member = new Item();

                         cmd.CommandType = CommandType.StoredProcedure;

                         // Set up the return value parameter
                         SqlParameter prm = new SqlParameter();
                         prm.ParameterName = "@Return";
                         prm.Direction = ParameterDirection.ReturnValue;
                         cmd.Parameters.Add(prm);

                         // Passes in the memberID
                         // from the checkout screen.

                         cmd.Parameters.AddWithValue("@member_no",
memberNumber);

                         // Open connection and execute query
                         cnn.Open();
                         cmd.ExecuteNonQuery();
/* Error Codes From the KitToAdult Book stored
procedure...
                                    Return -1   -- 'Juvenile member
number is null'
                                    Return -2   -- 'Juvenile member does
not exist'
                                    Return -3   -- 'Delete from juvenile
member table failed'
                                Return -4   -- ''Insert into adult
member table failed'
                        */
                        int returnValue =
(int)cmd.Parameters["@Return"].Value;
                        if (returnValue != 0)
                        {
                            switch (returnValue)
                            {
                                 case -1:
                                     throw new
LibraryException("Juvenile member number is null",
LibraryException.ErrorCode.MemberNoIsNull);
                                 case -2:
                                     throw new
LibraryException("Juvenile member does not exist",
LibraryException.ErrorCode.NoSuchMember);
                                 case -3:
                                     throw new LibraryException("Delete
from juvenile member table failed",
LibraryException.ErrorCode.DeleteFailed);
                                 case -4:
                                     throw new LibraryException("Insert
into adult member table failed",
LibraryException.ErrorCode.InsertFailed);
                            }
                        }
                    }
                }
            }
            catch (SqlException sqlex)
            {
                throw new LibraryException(sqlex.Message,
LibraryException.ErrorCode.GenericException);
            }
        }

    }

}

Contenu connexe

Tendances

Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-entechbed
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Building a Pluggable Plugin
Building a Pluggable PluginBuilding a Pluggable Plugin
Building a Pluggable PluginBrandon Dove
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfoliomichael_colon
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented ArchitectureLuiz Messias
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalFredric Mitchell
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Ryan Mauger
 

Tendances (19)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-en
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Building a Pluggable Plugin
Building a Pluggable PluginBuilding a Pluggable Plugin
Building a Pluggable Plugin
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfolio
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented Architecture
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
 

En vedette

How AND Why to Create Your Facebook Business Page
How AND Why to Create Your Facebook Business PageHow AND Why to Create Your Facebook Business Page
How AND Why to Create Your Facebook Business PageSocial Image
 
Sprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown TxSprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown Txgubaz3k3
 
Phat Salad Enterprises..
Phat Salad Enterprises..Phat Salad Enterprises..
Phat Salad Enterprises..guestbad915
 
Social media for sales
Social media for salesSocial media for sales
Social media for salesIan Greenleigh
 
Automata Service - Injection Moulding Machines
Automata Service - Injection Moulding MachinesAutomata Service - Injection Moulding Machines
Automata Service - Injection Moulding MachinesEduardo Marcelo Borges
 
Ficha sesión tipo
Ficha sesión tipoFicha sesión tipo
Ficha sesión tiposergio
 
MED316 - Introduction and Twitter signup
MED316 - Introduction and Twitter signupMED316 - Introduction and Twitter signup
MED316 - Introduction and Twitter signupguest0231f6
 
CMC Presentation 2012
CMC Presentation 2012CMC Presentation 2012
CMC Presentation 2012Social Image
 

En vedette (15)

Rocket content
Rocket contentRocket content
Rocket content
 
How AND Why to Create Your Facebook Business Page
How AND Why to Create Your Facebook Business PageHow AND Why to Create Your Facebook Business Page
How AND Why to Create Your Facebook Business Page
 
Sprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown TxSprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown Tx
 
Candle Cafe
Candle CafeCandle Cafe
Candle Cafe
 
mmo
mmommo
mmo
 
Framework Project Portfolio
Framework Project PortfolioFramework Project Portfolio
Framework Project Portfolio
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
Phat Salad Enterprises..
Phat Salad Enterprises..Phat Salad Enterprises..
Phat Salad Enterprises..
 
Social media for sales
Social media for salesSocial media for sales
Social media for sales
 
Automata Service - Injection Moulding Machines
Automata Service - Injection Moulding MachinesAutomata Service - Injection Moulding Machines
Automata Service - Injection Moulding Machines
 
Ficha sesión tipo
Ficha sesión tipoFicha sesión tipo
Ficha sesión tipo
 
MED316 - Introduction and Twitter signup
MED316 - Introduction and Twitter signupMED316 - Introduction and Twitter signup
MED316 - Introduction and Twitter signup
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
CMC Presentation 2012
CMC Presentation 2012CMC Presentation 2012
CMC Presentation 2012
 
Updated 2 Tourism Tour09
Updated 2 Tourism Tour09Updated 2 Tourism Tour09
Updated 2 Tourism Tour09
 

Similaire à Library Database Project Manages SQL Data

Code Samples &amp; Screenshots
Code Samples &amp; ScreenshotsCode Samples &amp; Screenshots
Code Samples &amp; ScreenshotsNii Amah Hesse
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScripttaobao.com
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdfanokhijew
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdffederaleyecare
 
Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!Julien Truffaut
 
My Portfolio
My PortfolioMy Portfolio
My Portfolioz02247
 
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdfannamalaiagencies
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013Phillip Trelford
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 
Create a class named Student that has the following member variables.pdf
Create a class named Student that has the following member variables.pdfCreate a class named Student that has the following member variables.pdf
Create a class named Student that has the following member variables.pdfarrowvisionoptics
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript CodeSuresh Balla
 

Similaire à Library Database Project Manages SQL Data (20)

Code Samples &amp; Screenshots
Code Samples &amp; ScreenshotsCode Samples &amp; Screenshots
Code Samples &amp; Screenshots
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
 
Martin Roy Portfolio
Martin Roy PortfolioMartin Roy Portfolio
Martin Roy Portfolio
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
 
Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!
 
Js objects
Js objectsJs objects
Js objects
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
Portfolio Martin Roy
Portfolio Martin RoyPortfolio Martin Roy
Portfolio Martin Roy
 
Portfolio Martin Roy
Portfolio Martin RoyPortfolio Martin Roy
Portfolio Martin Roy
 
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 
Create a class named Student that has the following member variables.pdf
Create a class named Student that has the following member variables.pdfCreate a class named Student that has the following member variables.pdf
Create a class named Student that has the following member variables.pdf
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
 

Dernier

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Dernier (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Library Database Project Manages SQL Data

  • 1. (Library Project) by Marcelo Salvador Introduction: The project was created in order to create a library database accessing a SQL Server database and allowing data manipulation. Audience:  Business Executives  Information Workers  IT Managers Project Goals: The goal of this project was to allow data manipulation of a library database by utilizing Windows Forms as a graphic user interface. Afterwards, the project was migrated to ASP.NET. Below I enclose examples of the classes utilizing N-Tier Architecture. using System; using System.Collections.Generic; using System.Text; using Ms.Library.Entities; using Ms.Library.Entities.Properties; using Ms.Library.Entities.ItemsDataSetTableAdapters; using LibraryDataAccess; using LibraryDataAccess.Properties; using System.Data.SqlClient; using System.Data; /********************************************************************* * Description: This class is utilized to gather all the information from * the database;also, deletes, updates,etc. Every single * methods contains a connection to the library database and * returns an error number in case an error takes place. * * Author: Marcelo D. Salvador * Create Date: 11/24/2008 * Modified Date: 11/28/2007
  • 2. * Modification: 12/01/2008 ********************************************************************/ namespace Marcelo_Library { /// <summary> /// This class is utilized to access data in the library database /// </summary> public class LibraryDataAccess { /// <summary> /// default constructor /// </summary> public LibraryDataAccess() { } /// <summary> /// Gets the member based on member ID /// </summary> /// <param name="memberID"></param> /// <returns></returns> public Member getMember(int memberID) { Member mymember = new Member(); int returnValue; try { // create connection using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { // create the command object using (SqlCommand cmd = new SqlCommand("GetMember", cnn)) { // assign the connection above to your new command object cmd.Connection = cnn; // name of the proc you are calling // command object will use a stored procedure cmd.CommandType = CommandType.StoredProcedure; //add input paramater for memberID cmd.Parameters.AddWithValue("@MemberID", memberID); //add return value parameter so we can access the return value from the proc SqlParameter returnParm = new SqlParameter(); returnParm.ParameterName = "@return"; returnParm.SqlDbType = SqlDbType.Int; returnParm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(returnParm);
  • 3. // open the connection cnn.Open(); // create a SQLDAtaREader to use with the data coming back from the proc using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { // It will fall into the code // block below if the proc // executed successfully // and returned a row. while (reader.Read()) {//Column order on the table /* m.lastname, m.firstname, m.middleinitial, a.street, a.city, a.state, a.zip, a.phone_no, a.expr_date, j.adult_member_no, j.birth_date */ /* Checking if the column number 10 which is * actually 9 because it is zero based.*/ if (!(reader.IsDBNull(9))) { //Juvenile member created... JuvenileMember juvMember = new JuvenileMember(); //using ordinal positions of columns juvMember.LastName = reader[0].ToString(); juvMember.FirstName = reader[1].ToString(); juvMember.MiddleInitial = reader[2].ToString(); juvMember.AdultMemberID = short.Parse(reader[9].ToString()); juvMember.BirthDate = DateTime.Parse(reader[10].ToString()); // juvenile member is built in entity class can return it now return juvMember; } else { //Adult member created
  • 4. AdultMember myAdultMember = new AdultMember(); myAdultMember.LastName = reader[0].ToString(); myAdultMember.FirstName = reader[1].ToString(); myAdultMember.MiddleInitial = reader[2].ToString(); myAdultMember.Street = reader[3].ToString(); myAdultMember.City = reader[4].ToString(); myAdultMember.State = reader[5].ToString(); // zipcode needs to be trimmed string zip = reader[6].ToString(); myAdultMember.ZipCode = zip.Trim(); myAdultMember.PhoneNumber = reader[7].ToString(); myAdultMember.ExpirationDate = DateTime.Parse(reader[8].ToString()); return myAdultMember; } } } // Checking SQL stored procedures return values and through exceptions based on them returnValue = int.Parse(cmd.Parameters["@return"].Value.ToString()); /*return 0 -- 'Return values successful from the query*/ /*Return -1 -- 'MemberID is null'*/ /*Return -2 -- 'MemberID is < 1 OR MemberID > 32767*/ /*Return -3 -- 'No Member found or if length is greater than 5*/ if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("isbn is null", LibraryException.ErrorCode.IsbnIsNull); case -2: throw new LibraryException("copy_no is null", LibraryException.ErrorCode.OutOfRangeMemberValue); case -3: throw new LibraryException("member_no is null", LibraryException.ErrorCode.NoSuchMember); } }
  • 5. } } } catch (InvalidCastException e) { string.Format("Invalid Cast", e.ToString()); } catch (SqlException sql) { throw new LibraryException(sql.Message, LibraryException.ErrorCode.GenericException); } return mymember; } /// <summary> /// /// </summary> /// <param name="memberNumber"></param> /// <returns></returns> public ItemsDataSet GetItems(short memberNumber) { ItemsDataSet itemsDS = new ItemsDataSet(); ItemsTableAdapter itemsTableAdapter = new ItemsTableAdapter(); ItemsDataSet.ItemsDataTable myTable = new ItemsDataSet.ItemsDataTable(); int returnValue = itemsTableAdapter.Fill(itemsDS.Items, memberNumber); returnValue = (int)itemsTableAdapter.GetReturnValue(0); if (returnValue == 0) return itemsDS; else throw new Exception("Book not Found!!!"); } /// <summary> /// Get book information /// </summary> /// <param name="isbnNumber"></param> /// <param name="copyNumber"></param> /// <returns></returns> public Item GetItem(int isbnNumber, short copyNumber) { Item myitem = new Item(); int returnValue; try { // create connection using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) {
  • 6. // create the command object using (SqlCommand cmd = new SqlCommand("GetMyItem", cnn)) { // assign the connection above to your new command object cmd.Connection = cnn; // name of the proc you are calling // command object will use a stored procedure cmd.CommandType = CommandType.StoredProcedure; //add input paramater for memberID cmd.Parameters.AddWithValue("@isbn", isbnNumber); cmd.Parameters.AddWithValue("@copy_no", copyNumber); //add return value parameter so we can access the return value from the proc SqlParameter returnParm = new SqlParameter(); returnParm.ParameterName = "@return"; returnParm.SqlDbType = SqlDbType.Int; returnParm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(returnParm); // open the connection cnn.Open(); // create a SQLDataReader to use with the data coming back from the proc using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { // we will fall into the code block below if the proc executed successfully // and returned a row. while (reader.Read()) { /* * @isbn, * @copy_no, * @title, * @author, * @member_no, * @out_date, * @due_date */ if (!(reader.IsDBNull(0))) { //add stuff to juvenile class Item dItem = new Item(); // Using ordinal positions of columns
  • 7. dItem.ISBN = Convert.ToInt32(reader[0].ToString()); dItem.CopyNo = Convert.ToInt32(reader[1].ToString()); dItem.Title = reader[2].ToString(); dItem.Author = reader[3].ToString(); dItem.MemberNO = Convert.ToInt32(reader[4].ToString()); dItem.OutDate = Convert.ToDateTime(reader[5].ToString()); dItem.DueDate = Convert.ToDateTime(reader[6].ToString()); return dItem; } } } //RETURN Codes: //RETURN 0 -- Sucesss //RETURN -1 -- ISBN is null //RETURN -2 -- Copy number is null //RETURN -3 -- Member does not exist returnValue = int.Parse(cmd.Parameters["@return"].Value.ToString()); if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("isbn is null", LibraryException.ErrorCode.IsbnIsNull); case -2: throw new LibraryException("copy_no is null", LibraryException.ErrorCode.OutOfRangeMemberValue); case -3: throw new LibraryException("member_no is null", LibraryException.ErrorCode.NoSuchMember); } } } } } catch (InvalidCastException e) { string.Format("Invalid Cast", e.ToString()); } catch (SqlException ex) {
  • 8. throw new LibraryException(ex.Message, LibraryException.ErrorCode.GenericException); } return myitem; } /// <summary> /// Add item to loan table /// </summary> /// <param name="memberID"></param> /// <param name="copyNumber"></param> /// <param name="isbnNumber"></param> public void CheckOutItem(int memberID, short copyNumber, int isbnNumber) { try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("checkOutBookItem", cnn)) { Item member = new Item(); // Item member = new Item(isbnNumber, copyNumber, memberID); cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes in the memberID, copyNumber and isbnNumber passed in // from the checkout screen. cmd.Parameters.AddWithValue("@isbn", isbnNumber); cmd.Parameters.AddWithValue("@copy_no", copyNumber); cmd.Parameters.AddWithValue("@member_no", memberID); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); /* Error Codes From the CheckOut Book stored procedure...
  • 9. Return -1 -- 'isbn is null' Return -2 -- 'copy_no is null' Return -3 -- 'member_no is null' Return -4 -- 'book does not exist' Return -5 -- 'member does not exist' Return -6 -- 'copy does not exist' Return -7 -- 'book already checked out' Return -8 -- 'member has 4 books already' Return -9 -- 'insert failed' */ int returnValue = (int)cmd.Parameters["@Return"].Value; if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("isbn is null", LibraryException.ErrorCode.IsbnIsNull); case -2: throw new LibraryException("copy_no is null", LibraryException.ErrorCode.CopyNoIsNull); case -3: throw new LibraryException("member_no is null", LibraryException.ErrorCode.MemberNoIsNull); case -4: throw new LibraryException("book does not exist", LibraryException.ErrorCode.BookDoesNotExist); case -5: throw new LibraryException("member does not exist", LibraryException.ErrorCode.NoSuchMember); case -6: throw new LibraryException("copy does not exist", LibraryException.ErrorCode.CopyDoesNotExist); case -7: throw new LibraryException("book already checked out", LibraryException.ErrorCode.BookAlreadyCheckedOut); case -8: throw new LibraryException("member has 4 books already", LibraryException.ErrorCode.MemberHasfourBooksAlready); case -9: throw new LibraryException("insert failed", LibraryException.ErrorCode.InsertFailed); } } } } } catch (SqlException sqlex) { throw new LibraryException(sqlex.Message, LibraryException.ErrorCode.GenericException); } }
  • 10. /// <summary> /// /// </summary> /// <param name="copyNumber"></param> /// <param name="isbnNumber"></param> public void CheckInItem(short copyNumber, int isbnNumber) { try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("CheckInBookItem", cnn)) { cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes the new member variables to the stored proc cmd.Parameters.AddWithValue("@isbn", isbnNumber); cmd.Parameters.AddWithValue("@copy_no", copyNumber); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); // Get Error Code int returnValue = (int)cmd.Parameters["@Return"].Value; /* Error codes: Return -1 -- 'isbn is null' Return -2 -- 'copy_no is null' Return -3 -- 'member_no is null' Return -4 -- 'book does not exist' Return -5 -- 'copy does not exist' Return -6 -- 'book is not checked out' Return -7 -- 'delete from loan table failed'
  • 11. Return -8 -- 'Adding row to loan history table failed' Return -9 -- 'Update on copy table failed' */ if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("isbn is null", LibraryException.ErrorCode.IsbnIsNull); case -2: throw new LibraryException("copy_no is null", LibraryException.ErrorCode.CopyNoIsNull); case -3: throw new LibraryException("member_no is null", LibraryException.ErrorCode.MemberNoIsNull); case -4: throw new LibraryException("book does not exist", LibraryException.ErrorCode.BookDoesNotExist); case -5: throw new LibraryException("member does not exist", LibraryException.ErrorCode.DeleteFailed); case -6: throw new LibraryException("copy does not exist", LibraryException.ErrorCode.InsertFailed); case -7: throw new LibraryException("book already checked out", LibraryException.ErrorCode.BookAlreadyCheckedOut); case -8: throw new LibraryException("member has 4 books already", LibraryException.ErrorCode.MemberHasfourBooksAlready); case -9: throw new LibraryException("insert failed", LibraryException.ErrorCode.UpdateFailed); } } } } } catch (SqlException ex) { throw new LibraryException(ex.Message, LibraryException.ErrorCode.GenericException); } } /// <summary> /// /// </summary> /// <param name="member"></param> public void AddMember(AdultMember member) {
  • 12. try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("AddAdult", cnn)) { cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes the new member variables to the stored proc cmd.Parameters.AddWithValue("@lastName", member.LastName); cmd.Parameters.AddWithValue("@name", member.FirstName); cmd.Parameters.AddWithValue("@middleInitial", member.MiddleInitial); cmd.Parameters.AddWithValue("@street", member.Street); cmd.Parameters.AddWithValue("@city", member.City); cmd.Parameters.AddWithValue("@state", member.State); cmd.Parameters.AddWithValue("@zipCode", member.ZipCode); cmd.Parameters.AddWithValue("@phoneNumber", member.PhoneNumber); // Add the output params prm = new SqlParameter("@InsertMemberID", SqlDbType.SmallInt); prm.Direction = ParameterDirection.Output; cmd.Parameters.Add(prm); prm = new SqlParameter("@ExpirationDate", SqlDbType.DateTime); prm.Direction = ParameterDirection.Output; cmd.Parameters.Add(prm); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); // --RETURN Codes:
  • 13. //-- RETURN 0 -- Successful //-- RETURN -1 --'Firstname is null' //-- RETURN -2 --'LastName is null' //-- RETURN -3 --'Street is null' //-- RETURN -4 --'City is null' //-- RETURN -5 --'State is null' //-- RETURN -6 --'Zip is null' //-- RETURN -7 --'insert into member failed' //-- RETURN -8 --'insert into adult failed' // Get Error Code int returnValue = (int)cmd.Parameters["@Return"].Value; if (returnValue != 0) switch (returnValue) { case -1: throw new LibraryException("Firstname is null", LibraryException.ErrorCode.FirstnameIsNull); case -2: throw new LibraryException("LastName is null", LibraryException.ErrorCode.LastNameIsNull); case -3: throw new LibraryException("Street is null", LibraryException.ErrorCode.StreetIsNull); case -4: throw new LibraryException("City is null", LibraryException.ErrorCode.CityIsNull); case -5: throw new LibraryException("State is null", LibraryException.ErrorCode.StateIsNull); case -6: throw new LibraryException("Zip is null", LibraryException.ErrorCode.ZipIsNull); case -7: throw new LibraryException("insert into member failed", LibraryException.ErrorCode.InsertFailed); case -8: throw new LibraryException("insert into adult failed", LibraryException.ErrorCode.InsertFailed); } // Get return variables member.ExpirationDate = (DateTime) (cmd.Parameters["@ExpirationDate"].Value);
  • 14. member.MemberID = (short)cmd.Parameters["@InsertMemberID"].Value; } } } catch (SqlException ex) { throw new LibraryException(ex.Message, LibraryException.ErrorCode.GenericException); } } /// <summary> /// Insert juvenile and member rows into Library data base /// </summary> /// <param name="member">JuvenileMember object</param> public void AddMember(JuvenileMember member) { try {//Open Library connection using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("AddJuvenile", cnn)) { cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Pass the new member variables to the stored proc cmd.Parameters.AddWithValue("@lastname", member.LastName); cmd.Parameters.AddWithValue("@name", member.FirstName); cmd.Parameters.AddWithValue("@middleInitial", member.MiddleInitial); cmd.Parameters.AddWithValue("@adultMemberID", member.AdultMemberID); cmd.Parameters.AddWithValue("@juvBirthDate", member.BirthDate); // Add the output params SqlParameter memberIDParm = new SqlParameter(); memberIDParm.ParameterName = "@InsertMemberID"; memberIDParm.SqlDbType = SqlDbType.SmallInt; memberIDParm.Direction = ParameterDirection.Output; cmd.Parameters.Add(memberIDParm);
  • 15. // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); // Get Error Code int returnValue = (int)cmd.Parameters["@Return"].Value; // RETURN 0 -- Successful //-- RETURN -1 --'name is null' //-- RETURN -2 --'middleinitial is null' //-- RETURN -3 --'lastname is null' //-- RETURN -4 --'adultmemberid is null' //-- RETURN -5 --'juvbirthdate is null' //-- RETURN -6 --'insert into member failed' //-- RETURN -7 --'insert into juvenile failed' if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("Firstname is null", LibraryException.ErrorCode.FirstnameIsNull); case -2: throw new LibraryException("MiddleInitial is null", LibraryException.ErrorCode.NullValue); case -3: throw new LibraryException("lastname is null", LibraryException.ErrorCode.LastNameIsNull); case -4: throw new LibraryException("adultMemberId is null", LibraryException.ErrorCode.AddAdultFailed); case -5: throw new LibraryException("juvBirthDateis null", LibraryException.ErrorCode.BirthdateNull); case -6: throw new LibraryException("Insert Into Member Failed", LibraryException.ErrorCode.InsertFailed); case -7: throw new LibraryException("insert Int Juvenile failed", LibraryException.ErrorCode.AddJuvenileFailed); }
  • 16. } member.MemberID = (short)cmd.Parameters["@InsertMemberID"].Value; } } } catch (SqlException ex) { throw new LibraryException(ex.Message, LibraryException.ErrorCode.GenericException); } } /// <summary> /// Used to renew membership /// </summary> /// <param name="memberNumber"></param> public void RenewMembership(int memberNumber) { try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("RenewExpirationDate", cnn)) { Item member = new Item(); // Item member = new Item(isbnNumber, copyNumber, memberID); cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes in the memberID // from the checkout screen. cmd.Parameters.AddWithValue("@member_no", memberNumber); // Add the output params SqlParameter memberExpDate = new SqlParameter(); memberExpDate.ParameterName = "@expr_date"; memberExpDate.SqlDbType = SqlDbType.DateTime; memberExpDate.Direction = ParameterDirection.Output;
  • 17. cmd.Parameters.Add(memberExpDate); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); /* Error Codes From the CheckOut Book stored procedure... Return -1 -- 'Failed: Member number is null' Return -2 -- 'Failed: Member does not exist' Return -3 -- 'Insert into adult member table failed' */ int returnValue = (int)cmd.Parameters["@Return"].Value; if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("Failed: Member number is null", LibraryException.ErrorCode.MemberNoIsNull); case -2: throw new LibraryException("Failed: Member does not exist", LibraryException.ErrorCode.NoSuchMember); case -3: throw new LibraryException("Insert into adult member table failed", LibraryException.ErrorCode.InsertFailed); } } } } } catch (SqlException sqlex) { throw new LibraryException(sqlex.Message, LibraryException.ErrorCode.GenericException); } } /// <summary> /// Method used to add a new book to the library database /// </summary> /// <param name="title"></param> /// <param name="author"></param> /// <param name="synopsis"></param> /// <param name="isbn"></param> /// <param name="translation"></param> /// <param name="cover"></param> /// <param name="loanable"></param> public void AddNewBook(string title, string author, string synopsis, int isbn, string translation, string cover, char loanable)
  • 18. { try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("EnterNewBook", cnn)) { Item member = new Item(); cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes in the values // from the checkout screen. cmd.Parameters.AddWithValue("@title", title); cmd.Parameters.AddWithValue("@author", author); cmd.Parameters.AddWithValue("@synopsis", synopsis); cmd.Parameters.AddWithValue("@isbn", isbn); cmd.Parameters.AddWithValue("@translation", translation); cmd.Parameters.AddWithValue("@cover", cover); cmd.Parameters.AddWithValue("@loanable", loanable); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery(); /* *********************************************************************** **** * RETURN Codes: RETURN -0 -- Sucesss RETURN -1 -- The title is null RETURN -2 -- The author is null RETURN -3 -- The synopsis is null is null RETURN -4 -- The translation is null RETURN -5 -- The cover is null RETURN -6 -- The loanable is null RETURN -7 -- The isbn is null is null
  • 19. RETURN -8 -- The ISBN exist in the Item table RETURN -9 -- The isbn exist in the copy table RETURN -10 -- INSERT for the title table failed RETURN -11 -- INSERT for the item table failed RETURN -12 -- INSERT for the copy table failed ********************************************** ********************************/ int returnValue = (int)cmd.Parameters["@Return"].Value; if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("The title is null", LibraryException.ErrorCode.titleIsNull); case -2: throw new LibraryException("The author is null", LibraryException.ErrorCode.AuthorIsNull); case -3: throw new LibraryException("The synopsis is null is null", LibraryException.ErrorCode.SynopsisIsNull); case -4: throw new LibraryException("The translation is null", LibraryException.ErrorCode.TranslationIsNull); case -5: throw new LibraryException("The cover is null", LibraryException.ErrorCode.CoverIsNull); case -6: throw new LibraryException("The loanable is null", LibraryException.ErrorCode.LoanableIsNull); case -7: throw new LibraryException("The isbn is null is null", LibraryException.ErrorCode.IsbnIsNull); case -8: throw new LibraryException("The ISBN exist in the Item table", LibraryException.ErrorCode.IsbnExistInItemTable); case -9: throw new LibraryException("The isbn exist in the copy table", LibraryException.ErrorCode.IsbnExistInCopyTable); case -10: throw new LibraryException("INSERT for the title table failed", LibraryException.ErrorCode.TitleInsertFailed); case -11: throw new LibraryException("INSERT for the item table failed", LibraryException.ErrorCode.ItemInsertFailed); case -12:
  • 20. throw new LibraryException("INSERT for the copy table failed", LibraryException.ErrorCode.CopyInsertFailed); } } } } } catch (SqlException sqlex) { throw new LibraryException(sqlex.Message, LibraryException.ErrorCode.GenericException); } } /// <summary> /// Method created to convert a Juvenile member of less than 18 yrs of age to an adult member) /// </summary> /// <param name="memberNumber"></param> public void adolescentToAdult(int memberNumber) { try { //Open Library connection //using (SqlConnection cnn = new SqlConnection(connectionString)) using (SqlConnection cnn = new SqlConnection(Settings.Default.libraryConnectionString)) { //create the command within a using block using (SqlCommand cmd = new SqlCommand("KidToAdult", cnn)) { Item member = new Item(); cmd.CommandType = CommandType.StoredProcedure; // Set up the return value parameter SqlParameter prm = new SqlParameter(); prm.ParameterName = "@Return"; prm.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(prm); // Passes in the memberID // from the checkout screen. cmd.Parameters.AddWithValue("@member_no", memberNumber); // Open connection and execute query cnn.Open(); cmd.ExecuteNonQuery();
  • 21. /* Error Codes From the KitToAdult Book stored procedure... Return -1 -- 'Juvenile member number is null' Return -2 -- 'Juvenile member does not exist' Return -3 -- 'Delete from juvenile member table failed' Return -4 -- ''Insert into adult member table failed' */ int returnValue = (int)cmd.Parameters["@Return"].Value; if (returnValue != 0) { switch (returnValue) { case -1: throw new LibraryException("Juvenile member number is null", LibraryException.ErrorCode.MemberNoIsNull); case -2: throw new LibraryException("Juvenile member does not exist", LibraryException.ErrorCode.NoSuchMember); case -3: throw new LibraryException("Delete from juvenile member table failed", LibraryException.ErrorCode.DeleteFailed); case -4: throw new LibraryException("Insert into adult member table failed", LibraryException.ErrorCode.InsertFailed); } } } } } catch (SqlException sqlex) { throw new LibraryException(sqlex.Message, LibraryException.ErrorCode.GenericException); } } } }