oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Creating an Application from Scratch, Part 3
Pages: 1, 2, 3, 4, 5


There are two generic collections used throughout this program: myBooks, which is a type-safe List of Book objects, and AllReviewers which is a type-safe Dictionary of Reviewer objects keyed on the ReviewerID, as shown in listing 1.

 private List<Book> myBooks = new List<Book>();
 private Dictionary<string, Reviewer> allReviewers = 
    new Dictionary<string, Reviewer>();

Listing 1

The Book class holds an ASIN (ISBN) and my rating for that book. The Reviewer object holds the ID of the reviewer and that reviewer's score (how well that reviewer matches my taste). The reviewer's score is updated as the program runs, as described below. These two classes are incredibly simple, and are defined in the files Book.cs and Reviewer.cs respectively, as shown in listing 2.

public class Book
   private string asin;
   public string ASIN //... 
   private string myRating;
   public string MyRating //...
   public Book( string asin, string myRating )
      this.asin = asin; this.myRating = myRating;
public class Reviewer
   private string reviewerID = string.Empty;
   public string ReviewerID //...
   private int score = 0;
   public int Score //...
   private int numReviews = 1;
   public int NumReviews //....

    public Reviewer(string reviewerID, int score)
      this.reviewerID = reviewerID;  this.score = score; 
    Listing 2 (Compressed)

Database Interactions

The key to interacting with the database is to open the Data Sources window and create a DataSet for the tables, as shown in figure 2.

Figure 2
Figure 2.

With this in place, each table can be dragged onto the form. Delete the resulting data grid and the binding source and leave just the TableAdapters as shown in figure 3.

Figure 3
Figure 3.

Click on an adapter and use the smart tag to choose Edit Queries in DataSet, as shown in figure 4.

Figure 4
Figure 4.

For each of the TableAdapters you'll want to add queries (right-click on the adapter and choose Add Query). You'll need queries to add entries, to delete a set of reviews (by ReviewerID), and to query for how many reviews a given reviewer as entered, as shown in figure 5.

Figure 5
Figure 5.

These queries are implemented in code by passing in the appropriate parameters, as shown for example in listing 3.

 private void InsertBook(
    string asin,
    string title,
    string url,
    string author )
       this.booksTableAdapter.InsertBook( asin, title, url, author );
Listing 3 (partial)

They key here is that you call the InsertBook method that corresponds to the query you created on the booksTableAdapter (see red box in figure 5), passing in the parameters specified for the query. The elided code updates the User Interface and handles exceptions (e.g., duplicate entry).

Pages: 1, 2, 3, 4, 5

Next Pagearrow