예제 #1
0
 /// <summary>
 /// Populates a book BookDetails class with the data for a book.
 /// </summary>
 private XElement[] FormatBookData(BookDetails book)
 {
     XElement[] bookInfo =
     {
         new XElement("author",       book.Author),
         new XElement("title",        book.Title),
         new XElement("genre",        book.Genre),
         new XElement("price",        book.Price.ToString()),
         new XElement("publish_date", book.PublishDate.ToString()),
         new XElement("description",  book.Description)
     };
     return(bookInfo);
 }
예제 #2
0
 /// <summary>
 /// Method to add a new book to the catalog.
 /// Defines the implementation of the POST method.
 /// </summary>
 public BookDetails CreateBook(BookDetails book)
 {
     try
     {
         // Retrieve the book with the highest ID from the catalog.
         var highestBook = (
             from bookNode in xmlDocument.Elements("catalog").Elements("book")
             orderby bookNode.Attribute("id").Value descending
             select bookNode).Take(1);
         // Extract the ID from the book data.
         string highestId = highestBook.Attributes("id").First().Value;
         // Create an ID for the new book.
         string newId = "bk" + (Convert.ToInt32(highestId.Substring(2)) + 1).ToString();
         // Verify that this book ID does not currently exist.
         if (this.ReadBook(newId) == null)
         {
             // Retrieve the parent element for the book catalog.
             XElement bookCatalogRoot = xmlDocument.Elements("catalog").Single();
             // Create a new book element.
             XElement newBook = new XElement("book", new XAttribute("id", newId));
             // Create elements for each of the book's data items.
             XElement[] bookInfo = FormatBookData(book);
             // Add the element to the book element.
             newBook.ReplaceNodes(bookInfo);
             // Append the new book to the XML document.
             bookCatalogRoot.Add(newBook);
             // Save the XML document.
             xmlDocument.Save(xmlFilename);
             // Return an object for the newly-added book.
             return(this.ReadBook(newId));
         }
     }
     catch (Exception ex)
     {
         // Rethrow the exception.
         throw ex;
     }
     // Return null to signify failure.
     return(null);
 }