Export (0) Print
Expand All

Walkthrough: Creating a Web Application Using a Third-Party Business Object

Visual Studio .NET 2003

In this walkthrough, you are going to write the Web Forms application in Visual C# or Visual Basic and then integrate a business-object component that gives you a 10% discount for purchases.

To explore multiple-language interoperability, you will create the business object as a separate DLL project using Visual C++ (.NET). Then you will consume the DLL in the Web application project. This simulates the common situation in which you consume an executable component written by a third party.

Creating a Third-Party Business Object

In this section, you are going to create a business object that gives a 10% discount for book purchases. Later in the walkthrough, you will create a Web Form application that consumes this business object.

To create the business object

  1. On the File menu, click New, and then click Project.

    The New Project dialog box appears.

  2. In the Project Types pane, click the Visual C++ Projects folder, and in the Templates pane, click the Class Library (.NET) project icon.
  3. Name the project McPaymentRules. When you click OK, the source and header files will be created for you.
  4. In Class View, expand the McPaymentRules project node, and right-click the Class1 node underneath.
  5. On the shortcut menu, click Add, and then click Add Function.

    Add Function

    The Add Member Function Wizard appears.

  6. In the Add Member Function Wizard, completed the boxes with the following information:
    • Function name: CalcDiscount
    • Return type: double
    • Parameter type: double
    • Parameter name: price.
  7. Click Add to add the member function.
  8. Click Finish to create the function.

    The function code will appear in the code editor as part of the file McPaymentRules.h.

    Add Member Function Wizard

  9. If you do not see the function code, expand the McPaymentRules class in Class View until you see the CalcDiscount(double price) function node. Right-click the function node and select Go To Definition. The following code appears in the editor:
    double CalcDiscount(double price)
    {
       return 0;
    }
    
  10. Replace the return statement with:
       return price * 0.9;
    
  11. Save the project by clicking Save All in the File menu.
  12. On the Build menu, click Build Solution to generate the file McPaymentRules.dll.

You will consume this component later in the walkthrough.

Creating the Web Application Project

In this section, you create a Visual C# or Visual Basic Web Application project that represents the application's user interface. On the Web Forms page, you are going to place a DataSet, DataGrid, and a DataView to view a specific table in the database.

You are also going to add a component where you create the data-access object that contains your data source.

To create the Web Form

  1. On the File menu, click New, and then click Project.

    The New Project dialog box appears.

  2. In the Project Type pane, click Visual Basic Projects or Visual C# Projects, and in the Templates pane, select ASP.NET Web Application.
  3. Name your application MyWebForm by changing the default name in the Location box (such as http://localhost/WebApplication1 to http://localhost/MyWebForm).
  4. Click OK.

    The application wizard will create the necessary project files, including the following files:

    • WebForm1.aspx - Contains the visual representation of the Web Form.
    • WebForm1.aspx.cs or WebForm1.aspx.vb – The code-behind file that contains the code for event handling and other programmatic tasks. To see this file in Solution Explorer, click the Show All Files icon, and then expand the WebForm1.aspx node.

    Web Form Files

    Note   If Solution Explorer is not open, on the View menu, click Solution Explorer.

For more details on creating a Web Application project, see Creating Web Projects. For information on configuring the security settings of your project, see Using SQL Server in Web Applications.

To add the component

  1. In Solution Explorer, right-click the project name.
  2. On the shortcut menu, click Add, and then click Add Component.

    The Add New Item dialog box appears and the Component Class in the right pane will be selected by default.

  3. Accept the default name (Component1) and click Open.

    Unless you choose another name for the component, this creates a new file in your project named Component1.cs or Component1.vb depending on the application language. The Component Designer opens a design view on Component1.cs or Component1.vb.

Creating the Data-Access Component

A dataset can be used to bind data values into the HTML transmitted to the client. It can be created either on the Web Form itself or on the component. To simulate real-life situations, you will create it on the component. You will also write the necessary code to fill the dataset with data from the database.

To add and configure a data source

  1. On the View menu, click Toolbox.
  2. From the Data tab of the Toolbox, drag sqlDataAdapter onto the Component Designer surface.

    This will start the DataAdapter Configuration Wizard.

  3. Click Next to advance to the Choose Your Data Connection page, and then click New Connection.

    This opens the Data Link Properties dialog box.

  4. In the Connection tab of the Data Link Properties dialog box:
    1. Enter the name of the server where the pubs database is installed.
    2. Enter the logon information for the server.
    3. Select pubs from the database list.
    4. Test the data link by clicking the Test Connection button.
    5. Click OK to return to the wizard.

      The name of the data connection appears in the drop-down list.

Note   If you do not know the user name and password for the SQL Server pubs database, contact your database administrator.

Data Link Properties

  1. Click Next to advance to the Choose a Query Type page.
  2. Select Use SQL statements, and then click Next.
  3. In the Generate the SQL Statements page, click Query Builder.
  4. In the Tables tab of the Add Table dialog box, click titles, click Add, and then click Close.

    This adds the titles table to your SQL query.

  5. In the Query Builder dialog box, shown in the following figure, select the title_id, title, price, notes, and pubdate check boxes, and then click OK to generate the SQL statement and return to the DataAdapter Configuration Wizard.

    Query Builder

    The Generate the SQL Statements page displays the generated SQL statement.

  6. Click Finish to exit the DataAdapter Configuration Wizard and connect your data source to the titles table. The following objects are added to the Component Designer surface:
    • sqlDataAdapter1
    • sqlConnection1

    Alternately, you can create both the sqlDataAdapter1 and sqlConnection1 objects by using Server Explorer. To do that, expand the SQL Servers tree to display your server, the pubs database, and the titles table as shown in the following figure. Expand titles and select the required columns, and then drag them onto the Component Designer surface.

    Server Explorer

    You can view the generated code in the InitializeComponent method of the file Component1.cs (or the InitializeComponent subroutine of the file Component1.vb). To do that, switch to the code view by right-clicking Component1.cs (or Component1.vb) in Solution Explorer, and then click View Code from the shortcut menu.

  7. Save the project by clicking Save All on the File menu.

To generate and fill the dataset

  1. If the Component Designer is not visible, double-click the file Component1.cs (or Component1.vb) in Solution Explorer.
  2. From the Data menu, click Generate DataSet.

    The Generate DataSet dialog box appears.

  3. If it is not already selected, select the New radio button. In the corresponding text box, enter a name such as myDataSet.
  4. Make sure that the Add this dataset to the designer check box is not selected, and click OK.

    The file myDataSet.xsd appears in Solution Explorer.

    You can view the XML schema and code that describe myDataSet by double-clicking myDataSet.xsd in Solution Explorer. Note that the DataSet and XML tabs are located at the lower left corner of the XML Designer surface.

    Dataset Schema

Binding the DataGrid

In this section, you add a dataset to the Web Forms page, fill it with data, and bind it to the DataGrid.

To add a dataset to the form

  1. In Solution Explorer, double-click the WebForm1.aspx file to select the Web Forms page.
  2. On the View menu, click Toolbox.
  3. Drag a DataSet from the Data tab of the Toolbox onto the Web Forms Designer surface.

    The Add DataSet dialog box appears.

  4. If it is not already selected, select TypedDataSet.
  5. Select the name of the dataset (MyWebForm.myDataSet) from the drop-down list and click OK.

    This adds a dataset, myDataSet1, to the nonvisual part of the Web Forms Designer surface.

    Adding a Dataset

To fill the dataset with data

  1. In Solution Explorer, right-click Component1.cs (or Component1.vb) and select View Code from the shortcut menu to switch to the component code view.
  2. Add the following method (or subroutine) to the Component1 class as follows:
    // C#
    public class Component1 : System.ComponentModel.Component
    {
    ...
    ...
       // Add the following code:
       public void FillDataSet(myDataSet dSet)
       {
          sqlDataAdapter1.Fill(dSet);
       }
       // End of the new code.
    ...
    ...
    }
    'Visual Basic
    Public Class Component1
       Inherits System.ComponentModel.Component
    ...
    ...
       ' Add the following code:
       Public Sub FillDataSet(ByVal dSet As myDataSet)
          sqlDataAdapter1.Fill(dSet)
       End Sub
       ' End of the new code.
    ...
    ...
    End Class
    
  3. Switch to the Web Form code view by right-clicking the WebForm1.aspx file, in Solution Explorer, and selecting View Code from the shortcut menu.

    This will open the code-behind file, which is WebForm1.aspx.cs (or WebForm1.aspx.vb).

  4. Declare a component object at the top level inside the WebForm1 class as follows:
    // C#
    public class WebForm1 : System.Web.UI.Page
    {
       // Add the following line:
       protected Component1 myComponent = new Component1();
       ...
    ' Visual Basic
    Public Class WebForm1
       Inherits System.Web.UI.Page
       ' Add the following line:
       Protected myComponent As New Component1
    ...
    
  5. Modify the Page_Load method (or the Page_Load sub) to call FillDataSet()as follows:
    // C#
    private void Page_Load (object sender, System.EventArgs e)
    {   
       // Add the following code:
       if (! IsPostBack)
       {
          myComponent.FillDataSet(myDataSet1);
       }
       // End of the new code.
    }
    ' Visual Basic
    Private Sub Page_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
       ' Add the following code:
       If Not IsPostBack Then
          MyComponent.FillDataSet(myDataSet1)
       End If
       ' End of the new code.
    End Sub
    

    Note that the statement inside the conditional block evaluates true the first time the browser hits the page.

To add and configure the DataGrid

  1. In Solution Explorer, double-click WebForm1.aspx to switch to the Web Forms page design view.
  2. On the View menu, click Toolbox.
  3. Drag a DataGrid control from the Web Forms tab of the Toolbox onto the Web Forms Designer surface.
  4. Right-click the DataGrid and click Property Builder on the shortcut menu.

    The DataGrid1 Properties dialog box appears.

  5. In the General form, set the DataSource to myDataSet1, and the Data Key Field to title_id (the primary key of the database).
  6. In the Columns form:
    1. Clear the check box Create columns automatically at runtime.
    2. Scroll down in the Available Columns list to the Button Column node.
    3. Expand the Button Column node and add the Select button by selecting it and clicking the right arrow between the two lists.
    4. Type "Title" in the Header Text box. Set the Sort Expression to "title" and the Text Field to "title."
    5. Add the price column from the Available Columns list by selecting it and clicking the right arrow between the two lists.
    6. In the Header Text box, provide an appropriate header, such as "Price."
    7. In the Data formatting expression text box, type the currency format string "{0:C}".
    8. Click OK.

    DataGrid1 Properties

    Your DataGrid now shows only the Title and Price columns from the DataSet.

    The DataGrid on the Web Forms Designer Surface

  7. Switch to the Web Forms page code view. Bind the data to the columns of the DataGrid by adding a DataBind() call to the Page_Load method/sub. The method or the subroutine will look like this:
    // C#
    private void Page_Load(object sender, System.EventArgs e)
       {
          if (!IsPostBack)
          {
             myComponent.FillDataSet(myDataSet1);
             DataGrid1.DataBind();      // Add this line
          }
       }
    ' Visual Basic
    Private Sub Page_Load(ByVal sender As System.Object, _
             ByVal e As System.EventArgs) Handles MyBase.Load
       If Not IsPostBack Then
          myComponent.FillDataSet(myDataSet1)
          DataGrid1.DataBind()      ' Add this line
       End If
    End Sub
    

    For more details on binding controls, see Data Access in Web Forms Pages.

To test the project

  1. On the Build menu, click Build Solution.
  2. On the Debug menu, click Start Without Debugging.

    You can now display data from the database on a Web Forms page and view it in your browser. The Titles column consists of hyperlinks. Later in the walkthrough, you will be able to click one of those hyperlinks and display the details of a specific book.

    Viewing the Titles Table in the Browser

Adding a Details Panel to the Web Form

The details panel allows you to view additional information about the selected books without cluttering the DataGrid with extraneous material.

In this step, you are going to add a DataView, which allows you to filter the table so that only the currently selected row is displayed.

To add a DataView

  1. Switch to the Web Forms page design view.
  2. On the View menu, click Toolbox.
  3. Drag a DataView control from the Data tab onto the Web Forms Designer surface.

    A new object, dataView1, is added to the nonvisual part of the Web Forms Designer surface.

  4. Select the dataView1 object and display its Properties page by clicking Properties Window on the View menu.
  5. Expand the Data node and select the Table property. Link the table by clicking titles in the drop-down list as shown in the following figure.

    The name myDataSet1.titles appears next to the Table property.

    dataView1 Properties

In this step, you add Label controls that correspond to data columns and bind each Label to the DataView.

To add Label controls

  1. For each detail field that you are using (such as title-id, title, price, and pubdate), drag a Label control from the Web Forms tab of the Toolbox onto the Web Forms Designer surface.
  2. Select each label and bind it to a field as follows:
    1. Display the Properties page of the selected label by clicking Properties Window on the View menu.
    2. Expand the Data property.
    3. Select the DataBindings property page by clicking the ellipsis () button next to DataBindings.

      The Labeln DataBindings dialog box appears (where n is the label number). The following figure shows the dialog box for Label1.

    4. Select the Text property from Bindable Properties in the left pane and select the appropriate column from the dataView1 node in the right pane.

      Label Bindable Properties

    5. Select the proper format from the Format drop-down list. For example, you can use the Currency format for price and one of the available date formats for pubdate.
    6. Click OK.
  3. Add text to describe the labels by preceding each label with an HTML Label that contains the description text (for example, Title ID, Title, Pub. date, and Price). To do that, open the Toolbox and drag a Label from the HTML tab onto the Web Forms Designer surface. Place the label before the corresponding bound label and modify its text as appropriate. Repeat this process to create four labels.

    Your Web Forms Designer surface should now look something like the following figure.

    The Web Forms Designer Surface

In this step, you add the necessary code to activate the details when you click the DataGrid.

To activate the details

  1. Double-click the DataGrid1 object.

    This will add a DataGrid1_SelectedIndexChanged event handler to your code-behind file and switch you to the code view.

  2. In the DataGrid1_SelectedIndexChanged method, add the following code to set the dataView1.RowFilter so that it will select only the row you want to display:
    // C#
    myComponent.FillDataSet(myDataSet1);
    int index = DataGrid1.SelectedIndex;
    string key = DataGrid1.DataKeys[index].ToString();
    dataView1.RowFilter = DataGrid1.DataKeyField + "='" + key + "'";
    ' Visual Basic
    MyComponent.FillDataSet(myDataSet1)
    Dim index As Integer
    Dim key As String
    index = DataGrid1.SelectedIndex
    key = DataGrid1.DataKeys(index).ToString()
    dataView1.RowFilter = DataGrid1.DataKeyField & "='" & key & "'"
    

    Conceptually, you are doing something very similar to specifying the WHERE clause of a SQL query and using this to get only a single row from the table. The DataKeys property, which was specified when you created the DataGrid, is a means for uniquely identifying each row. You determine the value of the key for the selected row by mapping the item index to a matching key. This key, which is a valid title_id, can now be used to uniquely select the row you want to use. This is true because the title_id is the primary key of the database. You cannot necessarily guarantee these constraints with a different database or with a different data key; therefore, you should alter your code if you want to use this technique on tables without a primary key.

  3. Bind each label that you are using by calling DataBind() on that label in the DataGrid1_SelectedIndexChanged method. Place these calls after the row filter change has been set:
    // C#
    Label1.DataBind();
    Label2.DataBind();
    Label3.DataBind();
    Label4.DataBind();
    ' Visual Basic
    Label1.DataBind()
    Label2.DataBind()
    Label3.DataBind()
    Label4.DataBind()
    
  4. Build and start the project.
  5. Click a title to get detailed information.

Consuming the Third-Party Business Object

In this step, you are going to use the DLL written in Managed Extensions for C++ (McPaymentRules.dll) to calculate the discounted price for a specific book.

To consume the business object

  1. In Solution Explorer, right-click the MyWebForm project and click Add Reference on the shortcut menu.

    The Add Reference dialog box appears.

  2. Click Browse to open the Select Component dialog box.
  3. In the Select Component dialog box, click My Projects and locate the McPaymentRules project folder.
  4. Browse to the McPaymentRules.dll file in the \bin\debug folder, select it, and click Open.

    The McPaymentRules.dll file appears in the Selected Components pane of the Add Reference dialog box.

  5. Click OK.
  6. Drag a WebForms Label control from the Toolbox onto the Web Forms Designer surface (It takes the ID Label5).

    This label will display the discounted price.

  7. Bind the text property of Label5 to the price column of DataView1.

    You do not have to use a specific format because the format will be specified in the code.

  8. Drag an HTML Label control from the Toolbox onto the Web Forms Designer surface and place it before Label5.
  9. Change the label's text to "Your Price."
  10. View the file WebForm1.aspx.cs (or WebForm1.aspx.vb) and add the following code to the end of DataGrid1_SelectedIndexChanged method/sub:
    // C#
    // Declare an instance of the business object:
    McPaymentRules.Class1 pr = new McPaymentRules.Class1();
    // Invoke the CalcDiscount Method:
    try
    {
       decimal price = myDataSet1.titles[index].price;
       Label5.Text = String.Format("{0:C}",
             pr.CalcDiscount(Convert.ToDouble(price)));
    }
    catch 
    {
       // If the price is blank, display a message:
       Label1.Text = "Price is not available for this item.";
       Label5.Text = "Discount is not available for this item.";
    }
    ' Visual Basic
    ' Declare an instance of the business object
    Dim pr As New McPaymentRules.Class1()
    
    ' Invoke the CalcDicount Method:
    Try
       Dim price As decimal
       price = myDataSet1.titles(index).price
       Label5.Text = String.Format("{0:C}", _
             pr.CalcDiscount(Convert.ToDouble(price)))
    Catch
    ' If the price is blank, display a message:
    Label1.Text = "Price is not available for this item."
    Label5.Text = "Discount is not available for this item."
    End Try
    
  11. Save all, build, and run the application.

    When you click any title in the table, you get the details of that book including the discounted price (Your Price) as shown in the following figure.

    The Detailed Information of a Book

Deploying

In this step, you deploy the project on a specific production server. To do that, copy the project to the production server.

To copy the project to a production server

  1. Click Copy Project on the Project menu.

    The Copy Project dialog box appears.

  2. In the Destination project folder text box, enter the name of the server and the project folder, for example:

    http://ProductionServerName/MyWebForm/

  3. In the Copy section, select one of the following radio buttons:
    • Only files needed to run the application.
    • All project files.
    • All files in the source project folder.
  4. Click OK to start the copying process.

    The Copy Project Dialog Box

Note   To learn about the security issues associated with Web Forms, see Overview of Web Application Security Threats.

See Also

Managed Extensions for C++ | XML Web Services in Visual Studio | Walkthrough: Creating a Distributed Application | DataGrid Web Control | Web Walkthroughs

Show:
© 2014 Microsoft