SlideShare uma empresa Scribd logo
1 de 27
(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.


The Class described below is the Business Access Layer
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Ms.Library.Entities;
using Marcelo_Library;
/*******************************************************************
 * Description: This class is utilized to gather all the data from
 *               the desired library database from methods of the
 *               LibraryDataAccess.cs
 * *****************************************************************
                                      * Author: Marcelo D. Salvador*
                                      * Create Date: 11/24/2008    *
                                      * Modified Date: 11/28/2007 *
                                      * Modification: 12/13/2008 *
 *******************************************************************/
namespace Marcelo_Library
{
    /// <summary>
    /// Class created to access methods of the LibraryDataAccess
    /// </summary>
    public class LibraryBusiness
    {
        Marcelo_Library.LibraryDataAccess myDAL = new
Marcelo_Library.LibraryDataAccess();
        /// <summary>
        /// Gets a member based on ID
        /// </summary>
        /// <param name="MemberID"></param>
        /// <returns></returns>
        public Member getMember(int MemberID)
        {
            Member mymember = myDAL.getMember(MemberID);
            return mymember;
        }
        /// <summary>
        /// Method utilized to add a new member to the Library
        /// </summary>
        /// <param name="newMember"></param>

        public void AddNewMember(Member newMember)
        {
            if (newMember is AdultMember)
                 myDAL.AddMember((AdultMember)newMember);
            else
                 myDAL.AddMember((JuvenileMember)newMember);
        }

        /// <summary>
        /// Method utilized to check in a book
        /// </summary>
        /// <param name="copyNumber"></param>
        /// <param name="isbnNumber"></param>
        public void CheckIn(short copyNumber, int isbnNumber)
        {
            myDAL.CheckInItem(copyNumber, isbnNumber);
        }
        /// <summary>
        /// Method utilized to check out a book
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="copyNumber"></param>
        /// <param name="isbnNumber"></param>
        public void CheckOutBook(int memberId, short copyNumber, int
isbnNumber)
        {
            myDAL.CheckOutItem(memberId, copyNumber, isbnNumber);
        }

        ///   <summary>
        ///   Returns the books a member has on loan
        ///   </summary>
        ///   <param name="memberId"></param>
        ///   <returns></returns>
public DataSet GetBooks(short memberId)
        {
            // create the library data access

            // call the GetItems method

            // return the dataset

            LibraryDataAccess dataAccess = new LibraryDataAccess();

            DataSet books = dataAccess.GetItems(memberId);

            return books;
        }
        /// <summary>
        /// Method utilizid to get book information
        /// </summary>
        /// <param name="isbnNumber"></param>
        /// <param name="copyNumber"></param>
        /// <returns></returns>
        public Item GetBook(int isbnNumber, short copyNumber)
        {
            Item myItem = myDAL.GetItem(isbnNumber, copyNumber);
            return myItem;
        }
        /// <summary>
        /// Method utilized to renew membership
        /// </summary>
        /// <param name="memberNumber"></param>
        public void RenewMembership(int memberNumber)
        {
            myDAL.RenewMembership(memberNumber);
        }
        /// <summary>
        /// Method utilized to convert a juvenile to an adult
        /// </summary>
        /// <param name="memberNumber"></param>
        public void KidtoMan(int memberNumber)
        {
            myDAL.adolescentToAdult(memberNumber);
        }
        /// <summary>
        /// Method utilized to insert a new book to the 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 InsertNewBook(string title, string author, string
synopsis, int isbn, string translation, string cover, char loanable)
        {
            myDAL.AddNewBook(title, author, synopsis, isbn,
translation, cover, loanable);
        }
}
}




The Class described below is the Data Access Layer
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);
            }
        }

    }

}



Exception Class Created To Handle Errors
using   System;
using   System.Collections.Generic;
using   System.Runtime.Serialization;
using   System.Security.Permissions;
using   System.Text;

/*
 *   Description: The exception that is thrown when a non-fatal
application
 *   error occurs in the Library application.
 *   For a list of all members of this type, see LibraryException
Members.
 *   LibraryException*/

 /*
 * Author: Marcelo D. Salvador
 * Create Date: 11/24/2008
 * Modified Date: 11/28/2007
 * Modification: 12/01/2008
 ********************************************************************/

namespace Ms.Library.Entities
{
    [Serializable]
    public class LibraryException : System.Exception, ISerializable
    {

         protected ErrorCode errorCodeMessage;
//This enumeration defines the error codes that can be returned
in a LibraryException.
        /// <summary>
        /// Enumeration listing the error codes according to the return
values from the sqlserver
        /// database.
        /// </summary>
        public enum ErrorCode
        {
            None, //No error code has been provided.
            GenericException, //A generic exception was thrown. Check
the exception message and the inner exception for details.
            ItemNotFound, //No Item with the specified ISBN and copy
number was found.
            NoSuchMember, //No member with the specified member number
was found.
            ItemNotOnLoan, //Item with the specified ISBN and copy
number is not on loan currently.
            CheckInFailed, //Failed to check in specified item.
            ItemAlreadyOnLoan, //Item with the specified ISBN and copy
number is already on loan to another member. Check the OtherMemberID
property of the LibraryException to obtain the member ID of the member
to whom the item is on loan currently.
            CheckOutFailed, //Failed to check out specified item.
            AddAdultFailed, //Failed to add new adult member.
            MissingAdultMember, //No sponsoring adult member record
could be found while trying to add a new juvenile member.
            AddJuvenileFailed, //Failed to add new juvenile member.
            IsbnIsNull,
              CopyNoIsNull,
                MemberNoIsNull,
                BookDoesNotExist,
                CopyDoesNotExist,
            BookAlreadyCheckedOut,
            MemberHasfourBooksAlready,
            InsertFailed,
            OutOfRangeMemberValue,
            DeleteFailed,
            UpdateFailed,
            FirstnameIsNull,
            LastNameIsNull,
            StreetIsNull,
            CityIsNull,
            StateIsNull,
            ZipIsNull,
            BirthdateNull,
            NullValue,
            titleIsNull,
            AuthorIsNull,
            SynopsisIsNull,
            TranslationIsNull,
            CoverIsNull,
            LoanableIsNull,
            IsbnExistInItemTable,
            IsbnExistInCopyTable,
            TitleInsertFailed,
            ItemInsertFailed,
CopyInsertFailed
}
/// <summary>
/// Default Constructor
/// </summary>
public LibraryException() { }
/// <summary>
/// Constructor to pass messages accordingly
/// </summary>
/// <param name="message"></param>
public LibraryException(string message)
    : base(message)
{}
/// <summary>
/// Constructor utilized to reference the values
/// </summary>
/// <param name="message"></param>
/// <param name="error"></param>
public LibraryException(string message, ErrorCode error)
    : base(message)
{
    // sets the property value to be referenced
    errorCodeMessage = error;
}

/// <summary>
/// Property utilized to carry on the enum's functionlity
/// </summary>
public ErrorCode LibraryErrorCode
{
    get
    {
        return errorCodeMessage;
    }
    set { errorCodeMessage = value; }
}

/*Parameter SerializationInfo
 * The object that holds the serialized object data.
 * StreamingContext The contextual information about
 * the source or destination.
 * Remarks: Used by the serialization mechanism to rehydrate
 * an instance of this exception.*/

/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public override void GetObjectData(SerializationInfo info,
    StreamingContext context)
{
    base.GetObjectData(info, context);

    if (info != null)
    {
        info.AddValue("ErrorCode", this.errorCodeMessage);
}
        }
        [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags =
SecurityPermissionFlag.SerializationFormatter)]
        void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context)
        {
            if (info == null) throw new ArgumentNullException("info");
            GetObjectData(info, context);
        }

    }

}

Mais conteúdo relacionado

Mais procurados

JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivityMouli Chandira
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erickokelloerick
 
Blocks In Drupal
Blocks In DrupalBlocks In Drupal
Blocks In Drupalguest6fb0ef
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaionglslarmenta
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 ModuleSammy Fung
 
Goodbye hook_menu() - Routing and Menus in Drupal 8
Goodbye hook_menu() - Routing and Menus in Drupal 8Goodbye hook_menu() - Routing and Menus in Drupal 8
Goodbye hook_menu() - Routing and Menus in Drupal 8Exove
 
Data20161007
Data20161007Data20161007
Data20161007capegmail
 
Full compile invalid obje pl/sql
Full compile invalid obje pl/sqlFull compile invalid obje pl/sql
Full compile invalid obje pl/sqlAnar Godjaev
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysqljbersosa
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumnameEmanuele Quinto
 

Mais procurados (16)

Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Drupal 8 Routing
Drupal 8 RoutingDrupal 8 Routing
Drupal 8 Routing
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
Blocks In Drupal
Blocks In DrupalBlocks In Drupal
Blocks In Drupal
 
Growing jQuery
Growing jQueryGrowing jQuery
Growing jQuery
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 Module
 
Goodbye hook_menu() - Routing and Menus in Drupal 8
Goodbye hook_menu() - Routing and Menus in Drupal 8Goodbye hook_menu() - Routing and Menus in Drupal 8
Goodbye hook_menu() - Routing and Menus in Drupal 8
 
Data20161007
Data20161007Data20161007
Data20161007
 
Full compile invalid obje pl/sql
Full compile invalid obje pl/sqlFull compile invalid obje pl/sql
Full compile invalid obje pl/sql
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysql
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 

Destaque

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
 
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
 
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
 

Destaque (7)

Sprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown TxSprinkler Repair Georgetown Tx
Sprinkler Repair Georgetown Tx
 
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..
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
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
 
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
 

Semelhante a Library Project Marcelo Salvador

F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise7sharp9
 
Library Project
Library ProjectLibrary Project
Library ProjectMauro_Sist
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdfanokhijew
 
Library Project Phase 1
Library Project Phase 1Library Project Phase 1
Library Project Phase 1gholtron
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScripttaobao.com
 
My Portfolio
My PortfolioMy Portfolio
My Portfolioz02247
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evoltGIMT
 
Library Website
Library WebsiteLibrary Website
Library Websitegholtron
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreStephane Belkheraz
 
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docxSinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docxjennifer822
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
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
 
operating system Ubunut,Linux,Mac filename messageService.cpp.pdf
 operating system Ubunut,Linux,Mac filename messageService.cpp.pdf operating system Ubunut,Linux,Mac filename messageService.cpp.pdf
operating system Ubunut,Linux,Mac filename messageService.cpp.pdfannethafashion
 

Semelhante a Library Project Marcelo Salvador (20)

Library Project
Library ProjectLibrary Project
Library Project
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 
Library Project
Library ProjectLibrary Project
Library Project
 
Framework Project Portfolio
Framework Project PortfolioFramework Project Portfolio
Framework Project Portfolio
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Library Project Phase 1
Library Project Phase 1Library Project Phase 1
Library Project Phase 1
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
Doctrine in FLOW3
Doctrine in FLOW3Doctrine in FLOW3
Doctrine in FLOW3
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evolt
 
Library Website
Library WebsiteLibrary Website
Library Website
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docxSinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
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
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
operating system Ubunut,Linux,Mac filename messageService.cpp.pdf
 operating system Ubunut,Linux,Mac filename messageService.cpp.pdf operating system Ubunut,Linux,Mac filename messageService.cpp.pdf
operating system Ubunut,Linux,Mac filename messageService.cpp.pdf
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 

Library Project Marcelo Salvador

  • 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. The Class described below is the Business Access Layer using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Data; using Ms.Library.Entities; using Marcelo_Library; /******************************************************************* * Description: This class is utilized to gather all the data from * the desired library database from methods of the * LibraryDataAccess.cs * ***************************************************************** * Author: Marcelo D. Salvador* * Create Date: 11/24/2008 * * Modified Date: 11/28/2007 * * Modification: 12/13/2008 * *******************************************************************/ namespace Marcelo_Library
  • 2. { /// <summary> /// Class created to access methods of the LibraryDataAccess /// </summary> public class LibraryBusiness { Marcelo_Library.LibraryDataAccess myDAL = new Marcelo_Library.LibraryDataAccess(); /// <summary> /// Gets a member based on ID /// </summary> /// <param name="MemberID"></param> /// <returns></returns> public Member getMember(int MemberID) { Member mymember = myDAL.getMember(MemberID); return mymember; } /// <summary> /// Method utilized to add a new member to the Library /// </summary> /// <param name="newMember"></param> public void AddNewMember(Member newMember) { if (newMember is AdultMember) myDAL.AddMember((AdultMember)newMember); else myDAL.AddMember((JuvenileMember)newMember); } /// <summary> /// Method utilized to check in a book /// </summary> /// <param name="copyNumber"></param> /// <param name="isbnNumber"></param> public void CheckIn(short copyNumber, int isbnNumber) { myDAL.CheckInItem(copyNumber, isbnNumber); } /// <summary> /// Method utilized to check out a book /// </summary> /// <param name="memberId"></param> /// <param name="copyNumber"></param> /// <param name="isbnNumber"></param> public void CheckOutBook(int memberId, short copyNumber, int isbnNumber) { myDAL.CheckOutItem(memberId, copyNumber, isbnNumber); } /// <summary> /// Returns the books a member has on loan /// </summary> /// <param name="memberId"></param> /// <returns></returns>
  • 3. public DataSet GetBooks(short memberId) { // create the library data access // call the GetItems method // return the dataset LibraryDataAccess dataAccess = new LibraryDataAccess(); DataSet books = dataAccess.GetItems(memberId); return books; } /// <summary> /// Method utilizid to get book information /// </summary> /// <param name="isbnNumber"></param> /// <param name="copyNumber"></param> /// <returns></returns> public Item GetBook(int isbnNumber, short copyNumber) { Item myItem = myDAL.GetItem(isbnNumber, copyNumber); return myItem; } /// <summary> /// Method utilized to renew membership /// </summary> /// <param name="memberNumber"></param> public void RenewMembership(int memberNumber) { myDAL.RenewMembership(memberNumber); } /// <summary> /// Method utilized to convert a juvenile to an adult /// </summary> /// <param name="memberNumber"></param> public void KidtoMan(int memberNumber) { myDAL.adolescentToAdult(memberNumber); } /// <summary> /// Method utilized to insert a new book to the 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 InsertNewBook(string title, string author, string synopsis, int isbn, string translation, string cover, char loanable) { myDAL.AddNewBook(title, author, synopsis, isbn, translation, cover, loanable); }
  • 4. } } The Class described below is the Data Access Layer 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
  • 5. { // 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 */
  • 6. /* 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; } }
  • 7. } // 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();
  • 8. 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;
  • 9. 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
  • 10. 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
  • 11. 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);
  • 12. 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();
  • 13. 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:
  • 14. 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);
  • 15. 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:
  • 16. 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))
  • 17. { 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) {
  • 18. 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))
  • 19. 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:
  • 20. 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.
  • 21. 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);
  • 22. 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
  • 23. //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:
  • 24. 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); } } } } Exception Class Created To Handle Errors using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; /* * Description: The exception that is thrown when a non-fatal application * error occurs in the Library application. * For a list of all members of this type, see LibraryException Members. * LibraryException*/ /* * Author: Marcelo D. Salvador * Create Date: 11/24/2008 * Modified Date: 11/28/2007 * Modification: 12/01/2008 ********************************************************************/ namespace Ms.Library.Entities { [Serializable] public class LibraryException : System.Exception, ISerializable { protected ErrorCode errorCodeMessage;
  • 25. //This enumeration defines the error codes that can be returned in a LibraryException. /// <summary> /// Enumeration listing the error codes according to the return values from the sqlserver /// database. /// </summary> public enum ErrorCode { None, //No error code has been provided. GenericException, //A generic exception was thrown. Check the exception message and the inner exception for details. ItemNotFound, //No Item with the specified ISBN and copy number was found. NoSuchMember, //No member with the specified member number was found. ItemNotOnLoan, //Item with the specified ISBN and copy number is not on loan currently. CheckInFailed, //Failed to check in specified item. ItemAlreadyOnLoan, //Item with the specified ISBN and copy number is already on loan to another member. Check the OtherMemberID property of the LibraryException to obtain the member ID of the member to whom the item is on loan currently. CheckOutFailed, //Failed to check out specified item. AddAdultFailed, //Failed to add new adult member. MissingAdultMember, //No sponsoring adult member record could be found while trying to add a new juvenile member. AddJuvenileFailed, //Failed to add new juvenile member. IsbnIsNull, CopyNoIsNull, MemberNoIsNull, BookDoesNotExist, CopyDoesNotExist, BookAlreadyCheckedOut, MemberHasfourBooksAlready, InsertFailed, OutOfRangeMemberValue, DeleteFailed, UpdateFailed, FirstnameIsNull, LastNameIsNull, StreetIsNull, CityIsNull, StateIsNull, ZipIsNull, BirthdateNull, NullValue, titleIsNull, AuthorIsNull, SynopsisIsNull, TranslationIsNull, CoverIsNull, LoanableIsNull, IsbnExistInItemTable, IsbnExistInCopyTable, TitleInsertFailed, ItemInsertFailed,
  • 26. CopyInsertFailed } /// <summary> /// Default Constructor /// </summary> public LibraryException() { } /// <summary> /// Constructor to pass messages accordingly /// </summary> /// <param name="message"></param> public LibraryException(string message) : base(message) {} /// <summary> /// Constructor utilized to reference the values /// </summary> /// <param name="message"></param> /// <param name="error"></param> public LibraryException(string message, ErrorCode error) : base(message) { // sets the property value to be referenced errorCodeMessage = error; } /// <summary> /// Property utilized to carry on the enum's functionlity /// </summary> public ErrorCode LibraryErrorCode { get { return errorCodeMessage; } set { errorCodeMessage = value; } } /*Parameter SerializationInfo * The object that holds the serialized object data. * StreamingContext The contextual information about * the source or destination. * Remarks: Used by the serialization mechanism to rehydrate * an instance of this exception.*/ /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); if (info != null) { info.AddValue("ErrorCode", this.errorCodeMessage);
  • 27. } } [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); GetObjectData(info, context); } } }