Quick Start Tutorial

Getting started with ODS

Introduction

This tutorial is intended as an introduction to ODS 2.2. In this tutorial we will demonstrate how easy it is to create a new ODS solution and a windows forms application that uses it. We will create a lightweight windows application that enables you to create, view, update and delete "Products".

Screenshot Instructions
Screenshot of the main screen

We will use ODS Design Studio to design our Data Access Layer. Then, we will use the ODS generated DAL from a windows application to create a database and store, retrieve and delete product objects from it. Our DAL will use a SQL Server database and as such assumes that SQL server is installed in the local machine and is configured to use integrated windows security.

The main application is located in the QuickStartTutorial folder and the DAL is located in the QuickStartTutorialDAL folder. The compiled application executable is located in the following folder:

QuickStartTutorial/QuickStartTutorial/bin/Debug/QuickStartTutorial.exe

Note that you will need to modify the QuickStartTutorial.exe.config file and provide a valid SQL Server connection string.

Although this is a simple demonstration, the tutorial goes through the process in a fair amount of detail and includes many screen shots. Note the green arrows on the screenshots which point to controls of interest. You can click each screenshot to view a larger version.

Part 1. Creating a new ODS solution

For the first part of this tutorial we will be using ODS Design Studio to create a new solution. Open ODS Design Studio.

Product Licensing

Screenshot Instructions
Screenshot of the ODS Design Studio licensing screen

If you have not yet purchased and installed a license then you should be greeted with the Product Licensing dialog. Select "Run the application without a license in evaluation mode" then click proceed.

The Start-up Dialog

Screenshot Instructions
Screenshot of the ODS Design Studio start-up screen

You should now see the ODS Start-up dialog. This is the main start-up dialog for ODS which allows you to open or create new solutions. Click the "New" button to create a new solution.

The New Solution Wizard - Step 1

Screenshot Instructions
Screenshot of the new solution wizard (step 1) screen

You should now see a dialog entitled "Step 1: Solution Name and Location". This dialog allows you to name your new solution and select where the solution files should be stored. Click the folder icon and a folder selection dialog will appear, prompting you to select a folder to place the new solution in. Create and select a new folder called "C:\ODS\Tutorials\QuickStartTutorial\". Each solution should have its own sub-folder. The "Create a sub-folder for the solution..." tick box is ticked by default.

Enter "QuickStartTutorialDAL" as the name of your solution. Later, ODS will create a "QuickStartTutorialDAL" folder to store the solution in under the "C:\ODS\Tutorials\QuickStartTutorial\" folder. Click the "Next Step" button.

The New Solution Wizard - Step 2

Screenshot Instructions
Screenshot of the new solution wizard (step 2) screen

You should now see a dialog entitled "Step 2: Supported Platform and Databases". This dialog allows you to select the platforms and databases types that you want your DAL to support. Check the box next to "SQL Server" then click the "Next Step" button.

The New Solution Wizard - Step 3

Screenshot Instructions
Screenshot of the new solution wizard (step 3) screen

You should now see a dialog entitled "Step 3: .NET Framework 2.0". You can enter anything you like as the namespace however for this tutorial we will use "HailstoneSoftware.QuickStartDAL". We will leave both the tick boxes checked so that ODS will generate VS2005 project and solution files for the source code and a batch file to compile the source code. Click the "Next Step" button.

The New Solution Wizard - Step 4

Screenshot Instructions
Screenshot of the new solution wizard (step 4) screen

You should now see a dialog entitled "Step 4: Finished". The new solution wizard only prompts us for a very small number of the total available solution settings. The rest are set to sensible defaults that will be fine for most situations. However, if you want to view or edit the remaining options before creating your new solution you can click the "View/Edit the solution properties" link. You can change these options at any time after the solution has been created. Click the "Finish" button.

Part 2. Designing the DAL

You should now see the main solution designer dialog. This is the main dialog you will use to edit the ODS solution.

Creating the Product class

Instructions Screenshot

For this simple tutorial we just want to store details about products so we will need a single class called "Product". Notice that the list of classes down the left hand side of the dialog contains a single item called "NewClass". All solutions must have at least one class so the wizard has created a blank class to get us started. We are going to rename this class to "Product".

In the class properties section on the top right of the dialog is a property called "Class name (Singular)". Change the text "NewClass" to "Product". Below this is another property called "Class name (Multiple)". Change the text to "Products". To the right is a property called "Description". Change the text to "A product line.". We now have a Product class.

Screenshot of the solution designer screen

Adding properties to the Product class

Instructions Screenshot

There would probably be many properties that we would add to a product class. However, for the purposes of this demonstration we will keep it simple.

The class properties are listed below the class details. Every class has an ID property. This ID uniquely identifies each object. Above the property list containing the ID property is a toolbar containing five buttons to add, delete, re-order and copy the properties. Click the add property button four times to add four new properties.

Select the first new property from the property list. Down the right hand side are the properties properties. Go to the "Property Name" text box and change the text to "Name". Below this is the "Property Type" drop-down combo. Leave this as a String. Below the property type is the description text box. Change the description text to "The product name". Change the max characters to 255.

Select the second new property from the property list. Go to the "Property Name" text box and change the text to "Description". Below this is the "Property Type" drop-down combo. Leave this as a String. Below the property type is the description text box. Change the description text to "A description of the product". Change the max characters to 255.

Select the third new property from the property list. Go to the "Property Name" text box and change the text to "FullPrice". Below this is the "Property Type" drop-down combo. Change this to a "Single Float". Below the property type is the description text box. Change the description text to "The original price of the product before markdowns".

Select the forth new property from the property list. Go to the "Property Name" text box and change the text to "SalePrice". Below this is the "Property Type" drop-down combo. Change this to a "Single Float". Below the property type is the description text box. Change the description text to "The current price of the product including markdowns".

Screenshot of the solution designer screen

A quick look at methods

Instructions Screenshot

Although our product class is now finished it is worth taking a quick look at the Methods tabs in ODS Design Studio. Click the Standard Methods tab. You will see a list of standard Add, Get and Delete methods. By default when you create a new class these are all ticked. Our application will use some of these methods to store and retrieve objects in a database.

Screenshot of the solution designer screen

Generating Source Code

Instructions Screenshot

Now that we've designed our Product class we can generate the source code for the DAL. Click the "Generate Code" button on the main toolbar at the top of the dialog. The Build dialog will appear and go through the build process. When code generation is complete you should see only green lights down the left hand side of the dialog. When it's finished click the "OK" button.

Screenshot of the build screen

And that's all there is to it. You should now find the DAL source code in your solution folder.

Reviewing the generated DAL

We are done with ODS Design Studio for now so you can close it down if you wish. We will take a quick look at what ODS has generated.

Reviewing the solution folder

Screenshot Description
Screenshot of file explorer

Open windows file explorer and browse out to "C:\ODS\Tutorials\QuickStartTutorial\QuickStartTutorialDAL\". It should contain several files and folders. The files with "ODSClass", "ODSSolution" and "ODSSolutionOverrides" extensions are the solution files. The "Versions" and "LastBuilt" folders contain more solution data.

You will notice that there is a file named "QuickStartTutorialDAL.dll". This is a DLL compiled from the source code that ODS just generated. By default ODS creates a batch file that calls the .NET Framework C# compiler to compile the source code into a DLL. This batch file is executed at the end of the source code generation process that we just initiated in ODS Design Studio.

Screenshot of file explorer

The "Sourcecode" folder contains the source code that we just generated plus the batch file that can be used to compile it. There are also VS2005 project and solution files.

Part 3. Creating the application

Create a new application

For this part of the demonstration we will assume that you know your way around Visual Studio 2005.

Open up Visual Studio 2005. Create a new Windows Project. We've called our solution QuickStartTutorial. Save the VS2005 solution in a new folder under "C:\ODS\Tutorials\QuickStartTutorial\". There should now be two folders as follows:

  • "C:\ODS\Tutorials\QuickStartTutorial\QuickStartTutorialDAL" contains the ODS generated DAL
  • "C:\ODS\Tutorials\QuickStartTutorial\QuickStartTutorial" contains the new application

Reference the DAL

In your Visual Studio 2005 project, click "Add a reference" and browse out to the ODS Solution folder. Reference the "QuickStartTutorialDAL.dll" file that we were looking at a moment ago.

Reference System.Configuration

Instructions Screenshot

We will be using an application config file to hold the database connection string. To do this we will need to use the System.Configuration assembly. In your Visual Studio 2005 project, click "Add a reference" and select the System.Configuration from the .NET tab.

Screenshot of the add reference screen

Create the App.Config

Instructions Screenshot

The database connection string will be held in a configuration file which we need to create. Add a new item to your project and select Application Configuration File. Open the file in Visual Studio and add change the contents as follows. We are adding a single key to the config file called ConnectionString. You can replace the connection string with one that works for you.

Screenshot of the add new file screen
<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <appSettings>
      <add key="ConnectionString" value="data source=.;initial catalog=QuickStartTutorial;integrated security=true;" />
    </appSettings>
</configuration>

Create the forms

Instructions Screenshot

We've renamed Form1 to MainForm and added a number of controls. Firstly, there is a ListView control that we will use to list products in the database. Then there are a number of buttons: "New Product", "Edit Product", "Delete Product", "Delete All Products", "Refresh Products" and "Exit". We will add code to these buttons to demonstrate how to use the DAL.

Screenshot of the main form

Add a second form called AddEditProduct. We will use this as a simple data entry form to enter Product details either to add or edit products. Add label and textbox controls to the form that will allow the user to enter a product name, full price, sale price and description. We will also need to add Accept and Cancel buttons.

Screenshot of the AddEditProduct screen

Part 4. Connecting your Application to a database

Connecting to a database

Switch to code view for the main form and add the following using statement to the top of the page:

using System.Configuration;
using HailstoneSoftware.QuickStartDAL;

It's probably worth quickly building the solution to check that the reference is ok.

Add the following line of code to the start of the MainForm class. We need a global variable that represents our database.

// The products database
private SQLServerDataStoreProvider dataStore = null;

To connect to a database we'll need an initialisation string. In this case we will use a bog standard SQL Server connection string as our initialisation string. We have already placed the connection string in the App.Config. In our case, the initialisation string tells the ODS DAL to connect to a database called "QuickStartTutorial", to use the instance of SQL Server running on the local machine and to logon to SQL Server using your windows login credentials.

Add the following code to the form load event, below the "InitializeComponent();" line:

// A SQL Server connection string for the QuickStartTutorial database
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

// Create a data store provider object
this.dataStore = new SQLServerDataStoreProvider(connectionString);

The SQLServerDataStoreProvider object that we've created represents a connection to a specific database. We will use it throughout the code to tell the DAL which database we are using.

Creating or upgrading a database

Add the following code to the form load event, below the code we've already added:

// Does the database already exist?
if (this.dataStore.Exists)
{
    // The database already exists. Make sure the schema is upto-date
    this.dataStore.Upgrade();
}
else
{
    // The database does not exist. Create a new database
    this.dataStore.Create();
}

The code firstly checks to see if the database pointed to by the dataStore object already exists. If the database already exists we tell the DAL to upgrade it to the latest schema. Otherwise, we tell the DAL to create a new database.

To keep the database and DAL in sync, we recommend adding a line of code that calls Upgrade() to the start-up code of any application using an ODS generated DAL. You can safely run the upgrade method as often as you like against a database that is already up to date.

Note that for database creation to work the SQL Server user you've specified must have permission to access the Master database. In SQL server 2005 the user must also have the create database permission on the Master database.

Part 5. Retrieving products from the database

Getting Product objects from the database

We need to populate the listview control with Products from the database. Add a new method to the MainForm class as follows:

/// <summary>
/// Populates the Products listview with products
/// </summary>
private void RefreshProductsListView()
{
    // Remove all existing rows from the listview
    this.productsListView.Items.Clear();

    // Get a list of products
    List<DataProduct> products = Product.GetAll(this.dataStore);

    // Add each product to the listview
    foreach (DataProduct product in products)
    {
        // Create a new listview item from the product
        ListViewItem productListViewItem = new ListViewItem(product.Name);
        productListViewItem.SubItems.Add(product.FullPrice.ToString());
        productListViewItem.SubItems.Add(product.SalePrice.ToString());
        productListViewItem.SubItems.Add(product.Description);

        // Keep track of which product this listview item represents
        productListViewItem.Tag = product;

        // Add the new listview item to the listview
        this.productsListView.Items.Add(productListViewItem);
    }
}

We firstly clear the listview of existing items, retrieve a list of product objects from the database and then add a new listview item to the listview for each product object. For more information see the storing and retrieving objects page.

To populate the listview when the application starts, we need to add a line to the end of the form load event, below the code we've already added. We also need to add the same code to the Click event of the "Refresh Products" button:

// Populate the products listview
this.RefreshProductsListView();

Part 6. Adding and Editing products

The AddEditProduct form

The AddEditProduct form will be used to gather the data needed to create or update products. The form will work in either add or edit mode. Open the AddEditProduct form and switch to code view. Add the following using statement to the top of the page:

using HailstoneSoftware.QuickStartDAL;

Add the following line of code to the start of the AddEditProduct class. We need a global variable that represents the product that we are adding or editing.

// The product being added or edited
private Product currentProduct = null;

Next, we need to replace the AddEditProduct class constructor method with one that implements an add and edit mode:

public AddEditProduct(bool newProduct, Product product)
{
    InitializeComponent();

    // Keep hold of the product so we can update it if the user clicks Accept
    this.currentProduct = product;

    // Is this a new product?
    if (newProduct)
    {
        // We want to run in new product mode
        this.Text = "Add a new product";
        this.mainTitleLabel.Text = "Add a new product";
    }
    else
    {
        // We want to run in edit product mode
        this.Text = "Edit a product";
        this.mainTitleLabel.Text = "Edit a product";

        // Pre-populate the textboxes with the product values
        this.productNameTextBox.Text = this.currentProduct.Name;
        this.fullPriceTextBox.Text = this.currentProduct.FullPrice.ToString();
        this.salePriceTextBox.Text = this.currentProduct.SalePrice.ToString();
        this.descriptionTextBox.Text = this.currentProduct.Description;
    }
}

In the replacement constructor, we pass in a product object. This object is either a new object or an existing object. Either way, if the user clicks the accept button we will populate the object using the data that the user entered on the form. The other parameter is a simple boolean that tells us whether we are creating a new product or editing an existing one. If we are editing an existing product then the product object passed in is used to pre-populate the fields on the form.

The Accept button

To complete the AddEditProduct form we will add code that is called when the user clicks the Accept button. We will populate the product object from the data that the user entered in the form. Add the following code to the Click event of the Accept button:

float fullPrice, salePrice;

// Validate the data entered
if (!float.TryParse(this.fullPriceTextBox.Text, out fullPrice))
{
    // The user did not enter a float in the full price textbox
    MessageBox.Show(this, "Please enter a numeric full price");
    return;
}

if (!float.TryParse(this.salePriceTextBox.Text, out salePrice))
{
    // The user did not enter a float in the sale price textbox
    MessageBox.Show(this, "Please enter a numeric sale price");
    return;
}

// Populate the product object using the details entered on this form
this.currentProduct.Name = this.productNameTextBox.Text;
this.currentProduct.FullPrice = fullPrice;
this.currentProduct.SalePrice = salePrice;
this.currentProduct.Description = this.descriptionTextBox.Text;

// Close the form
this.DialogResult = DialogResult.OK;
this.Close();

The code firstly checks that the user entered currency values in the full price and sale price textboxes. We then populate the global product object from the data that the user entered in the form. Lastly, we close the form.

Adding products

Next, we want to get the New Product button on the main form to show the AddEditProduct form that we've just coded. Open the MainForm and switch to code view. Add the following code to the Click event of the New Product button:

// Create a new product object
Product newProduct = new Product();

// Use the AddEditProduct dialog to populate the new product object
AddEditProduct addEditProduct = new AddEditProduct(true, newProduct);

// Show the AddEditProduct dialog
if (addEditProduct.ShowDialog(this) == DialogResult.OK)
{
    // The user clicked the Accept button on the AddEditProduct dialog
    // Add the new product to the data store
    Product.Add(newProduct, this.dataStore);
    
    // Populate the products listview
    this.RefreshProductsListView();
}

The first thing we do when the user clicks the New Product button is create a new product object. At this point the new product object is blank and exists only in memory. Next, we display the AddEditProduct dialog, passing in our new product object and instructing the AddEditProduct dialog to run in add mode. Then we wait until the user clicks the Accept or Cancel button on the dialog.

If the user clicks the Accept button on the AddEditProduct dialog, we add the new product to the database. The AddEditProduct dialog will have populated the product object from the data that the user entered on the form. Lastly, we refresh the listview since there is now a new product object in the database.

Editing products

We also want to get the Edit Product button to show the AddEditProduct form. Add the following code to the Click event of the Edit Product button:

// Make sure a listview item is selected
if (this.productsListView.SelectedItems.Count > 0)
{
    // Extract the product from the selected listview item
    Product editProduct = new
        Product((DataProduct)this.productsListView.SelectedItems[0].Tag);

    // Use the AddEditProduct dialog to populate the new product object
    AddEditProduct addEditProduct = new AddEditProduct(false, editProduct);

    // Show the AddEditProduct dialog
    if (addEditProduct.ShowDialog(this) == DialogResult.OK)
    {
        // The user clicked the Accept button on the AddEditProduct dialog
        // Update the product in the data store
        Product.Update(editProduct, this.dataStore);

        // Populate the products listview
        this.RefreshProductsListView();
    }
}

We start out with a guard condition to prevent the code being executed when no listview items are selected. We will only deal with the first selected listview item. When we originally populated the listview, we set the Tag property of each row to the DataProduct object returned from the database. We firstly extract the DataProduct object from the Tag property of the first selected listview item and use it to populate a Product object. For more details on Data objects see the working with data structures page.

Next, we display the AddEditProduct dialog, passing in the existing product object that we just extracted from the selected listview item. We instruct the AddEditProduct dialog to run in edit mode. Then we wait until the user clicks the Accept or Cancel button on the dialog.

If the user clicks the Accept button on the AddEditProduct dialog, we update the existing product object in the database. The AddEditProduct dialog will have populated the product object from the data that the user entered on the form. Lastly, we refresh the listview since the data in the database has changed.

Part 7. Deleting products

Delete Product

Add the following code to the Click event of the Delete Product button:

// Delete each item selected in the listview
foreach (ListViewItem listViewItem in this.productsListView.SelectedItems)
{
    // Extract the product from the selected listview item
    Product deleteProduct = new Product((DataProduct)listViewItem.Tag);

    // Delete the product
    Product.DeleteByID(deleteProduct.ID, this.dataStore);
}

// Populate the products listview
this.RefreshProductsListView();

The code processes each selected item in the products listview. It extracts the Product object from the Tag property of the selected listview item and then deletes it from the database. Lastly, the products listview is refreshed since products have been deleted.

Delete All Products

Add the following code to the Click event of the Delete All Products button:

// Delete all products from the database
Product.DeleteAll(this.dataStore);

// Populate the products listview
this.RefreshProductsListView();

The code here simply deletes all products from the database and them refreshes the products listview.

Part 8. Tidying up

The Exit button

Add the following code to the Click event of the Exit button to close the main form:

// Close the application
this.Close();

Cleanup

When the application is closed we need to tell the data store provider to release any resources it is holding. To do this we will subscribe to the FormClosing event. Add the following code to the event handler:

// Tell the data store provider that we are finished
this.dataStore.Cleanup();

Conclusions

That's it for this tutorial.

We've demonstrated just how quickly and easily a DAL can be created using ODS. More detailed information on ODS generated DALs can be found on the generated source code pages.