(Library         Project) by Marcelo Salvador
Introduction: The project was created in order to create a library database ...
{
    /// <summary>
    /// Class created to access methods of the LibraryDataAccess
    /// </summary>
    public class L...
public DataSet GetBooks(short memberId)
        {
            // create the library data access

            // call the G...
}
}




The Class described below is the Data Access Layer
using System;
using System.Collections.Generic;
using System.Te...
{
                // create connection
                using (SqlConnection cnn = new
SqlConnection(Settings.Default.libra...
/*    Checking if the column number 10
which is
                                 *       actually 9 because it is zero
bas...
}
                        // Checking SQL stored procedures return values
and through exceptions based on them
           ...
ItemsDataSet.ItemsDataTable myTable = new
ItemsDataSet.ItemsDataTable();

            int returnValue = itemsTableAdapter....
cmd.Parameters.Add(returnParm);

                        // open the connection
                        cnn.Open();
      ...
returnValue =
int.Parse(cmd.Parameters["@return"].Value.ToString());
                        if (returnValue != 0)
       ...
using (SqlCommand cmd = new
SqlCommand("checkOutBookItem", cnn))
                    {
                        Item member...
case -4:
                                    throw new LibraryException("book
does not exist", LibraryException.ErrorCode....
prm.ParameterName = "@Return";
                        prm.Direction = ParameterDirection.ReturnValue;
                   ...
throw new LibraryException("copy
does not exist", LibraryException.ErrorCode.InsertFailed);
                              ...
cmd.Parameters.AddWithValue("@name",
member.FirstName);
                         cmd.Parameters.AddWithValue("@middleIniti...
throw new
LibraryException("Firstname is null",
LibraryException.ErrorCode.FirstnameIsNull);
                             ...
{
                         cmd.CommandType = CommandType.StoredProcedure;

                         // Set up the return v...
switch (returnValue)
                            {
                                case -1:
                              ...
using (SqlConnection cnn = new
SqlConnection(Settings.Default.libraryConnectionString))
                {
                ...
throw new LibraryException("Failed:
Member does not exist", LibraryException.ErrorCode.NoSuchMember);
                    ...
cmd.Parameters.AddWithValue("@title", title);
                        cmd.Parameters.AddWithValue("@author", author);
    ...
case -4:
                                    throw new LibraryException("The
translation is null", LibraryException.ErrorC...
//using (SqlConnection cnn = new
SqlConnection(connectionString))
                using (SqlConnection cnn = new
SqlConnec...
throw new LibraryException("Delete
from juvenile member table failed",
LibraryException.ErrorCode.DeleteFailed);
         ...
//This enumeration defines the error codes that can be returned
in a LibraryException.
        /// <summary>
        /// E...
CopyInsertFailed
}
/// <summary>
/// Default Constructor
/// </summary>
public LibraryException() { }
/// <summary>
/// Co...
}
        }
        [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags =
SecurityPermissionFlag.SerializationFo...
Upcoming SlideShare
Loading in …5
×

Library Project Marcelo Salvador

1,458 views

Published on

Project that allows users to insert, edit, update and delete library members.

Published in: Technology, Education
1 Comment
0 Likes
Statistics
Notes
  • i need source code of this project plz any one can send me this project code i am very thankfull to u. if u send me the project code
    on this email danish.awan99@yahoo.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Views
Total views
1,458
On SlideShare
0
From Embeds
0
Number of Embeds
19
Actions
Shares
0
Downloads
69
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

Library Project Marcelo Salvador

  1. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 27. } } [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); GetObjectData(info, context); } } }

×