Skip to content

Tutorial_Automatic_Screen_Generation(TableMaintenance)

daisuke nishino edited this page Oct 17, 2018 · 2 revisions

Open Touryo Tutorial (Table maintenance screen automatic generator edition)

September 15th, 2016

Introduction

Objective of this document

This tutorial describes the followings.

  • The development flow using Open Touryo table maintenance screen automatic generator. (Open Touryo table maintenance screen automatic generator is abbreviated as screen generator.)
  • How to create classes.
  • How to create configuration files.
  • How to use the tool.
  • How to check operation.

Table maintenance screen is the screen to perform crud program for a single table, that is create (insert), read (select), update, and delete.

Scope of this document

This tutorial targets SE and developers who are considering generating table maintenance screen for single table in ASP.NET application development with Open Touryo.

Overview of this document

This tutorial describes the generation flow for table maintenance screen for joined table. The sample program attached to Open Touryo Visual Studio 2015 template base is used as the material of this tutorial.

As we are pressed for time, some images are only displayed in Japanese.

Use of copyrights and trademarks of other companies

The company names and product names used in this document are the trademarks or registered trademarks of the respective companies.

License

This document can use Creative commons CC BY 2.1 JP license.

Table of Contents

1. Overview of Open Touryo framework

2. Set up the environment

3. Exercises in this tutorial

4. Exercise 1: Basic usage of screen generator

5. Exercise 2: Customize primary key and timestamp column

6. Exercise 3: Implement relation check and automatic numbering program

7. Appendix: Customize generated screen

1. Overview of Open Touryo framework

Open Touryo framework is an application framework for .NET. Open Touryo framework targets .NET Framework 4.6 or above and can be used in various applications like C/S (Windows Forms, WPF), Web (ASP.NET) and RIA (Silverlight).

Figure 1-1 shows the class configuration of Open Touryo framework.

Figure 1-1 Class diagram of Open Touryo framework

This tutorial describes how to use screen generator to generate table maintenance screen. The following figure shows the overview of the feature of screen generator.

2. Set up the environment

The followings are the prerequisites for this tutorial.

  • Development environment
    • IDE
      • Visual Studio 2015 (Express Edition is also available)
    • Application framework
      • Open Touryo Template Base for Visual Studio 2015
  • Runtime environment
    • Runtime
      • .NET Framework 4.6
    • Web Server
      • IIS Express
    • DB
      • SQL Server Express 2008 R2
  • Others
    • OS
      • Windows 7

Install Visual Studio referring to Microsoft homepage beforehand.

Next, set up Open Touryo Template Base and database.

  1. Click [Download ZIP] button on GitHub and obtain OpenTouryoTemplates.zip. Unzip this zip file and obtain Open Touryo Template Base for Visual Studio 2015.

  2. Set up Open Touryo Template Base and database according to Readme.md in root_VS2015 folder.

  3. Run the following command to create test table.

    "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S localhost\SQLExpress -E -d Northwind -i "C:\root\files\resource\Sql\sqlserver\ScreenAutoGen\CreateTable.sql"

3. Exercises in this tutorial

Users of this tutorial can practice by adding screen and logic, generated with screen generator, to the sample program that bundled with Open Touryo template base. Figure 3-1 shows the configuration of sample program and Figure 3-2 shows the Screen transition diagram of the tutorial.

Figure 3-1 Configuration of sample program

Figure 3-2 Screen transition diagram of tutorial

4. Exercise 1: Basic usage of screen generator

First, this chapter describes the basic usage of screen generator.

4.1 Generate table maintenance screen for Products table

4.1.1 Create D layer definition file

  1. Run C:\root\programs\C#\Frameworks\DaoGen_Tool\bin\Debug\DaoGen_Tool.exe to launch DaoGen_Tool.

  2. In the STEP1 screen, set database information as follows and click acquisition.

    • Data provider: SQL Server Client
    • Connection string: Data Source=localhost\SQLExpress;Initial Catalog=Northwind;Integrated Security=true;
    • Schema Info: Summary Information
  3. If database information, such as connection string, are correct, Display (Summary Information) dialog of schema information of DBMS screen is shown.

    Click Close to close the dialog box.

  4. Click Get Table List.

    In the Note? (prerequisites) dialog box, click OK.

  5. Tables and views in Northwind database are shown in list box. Since Products table, Categories table, and Supplier table will be used in this tutorial, select all tables and views except Products table, Categories table, and Supplier table, and click Delete.

  6. Confirm whether Table List contains only Products table, Categories table, and Supplier table, and click Load.

  7. The Generate D layer definition file button is activated. Select utf-8 as file encoding and click Generate D layer definition file.

    Save as C:\root\Info.csv.

  8. Click OK in the dialog box displaying the message Completion of generation of the D-layer definition information!.

4.1.2 Generate data access class, sql files, and table maintenance screens

  1. Click Go to STEP 2.

  2. In the STEP2 screen, enter input / output settings as follows:

    • D layer definition file: C:\root\Info.csv
    • Source Template Folder: C:\root\files\tools\DGenTemplates
    • Output File: C:\root
    • Leave the other fields as default.
  3. Click Options.

  4. In the OPTIONS screen, set the properties as follows and click OK

    • Select Data Provider: SQL Server Client
    • Generate table maintenance screen: Set checked
  5. Click Generate Program.

  6. Click OK in the dialog box displaying the message Automatic Generation Completed!.

  7. Confirm that data access classes, sql files, and table maintenance screens are generated in C:\root folder.

    Note:
    In the Open Touryo framework, the files with extensions .sql and .xml are sql files. (For more details, refer to the Open Touryo framework user guide)

4.1.3 Deploy data access classes, sql files, and table maintenance screens

  1. Copy the generated sql files (.sql and .xml) to C:\root\files\resource\Sql.

  2. Copy the generated data access classes and table maintenance screen.

    1. Open C:\root\programs\C#\Samples\WebApp_sample\WebForms_Sample\WebForms_Sample.sln with Visual Studio.

    2. Copy the generated ProductsTableAdapter.cs to App_Code\sample\3TierTableAdapter in the Solution Explorer.

    3. Copy the generate data access classes, that is DaoCategories.cs and DaoSuppliers.cs, to App_Code\sample\Dao in the Solution Explorer.

    4. Copy the generated table maintenance screens, that is ProductsConditionalSearch.aspx, ProductsConditionalSearch.aspx.cs, ProductsDetail.aspx, ProductsDetail.aspx.cs, ProductsSearchAndUpdate.aspx, ProductsSearchAndUpdate.aspx.cs, to Aspx\sample\3Tier in the Solution Explorer.

4.2 Customize table maintenance screen for Products table

This section describes how to customize the generated table maintenance screen.

4.2.1 Add verification single item program

By default, table maintenance screen uses WebCustomTextBox, that is custom web textbox bundled in Open Touryo. WebCustomTextBox has the program to verify single item. This section describes how to add verification single item program.

  1. Open ProductConditionalSearch.aspx and ProductsSearchAndUpdate.aspx with Visual Studio.

  2. Select any textbox.

  3. Set properties in the Properties window. For example, if IsDate property is set to True, the check program to verify whether inputted value is date is executed.

  4. Implement the event handler to confirm the check result.

    // 一括チェック処理
    List<CheckResult> rets = new List<CheckResult>();
    if (CmnCheckFunction.HasErrors(this, rets))
    {
        foreach (CheckResult ret in rets)
        {
            this.TextBox1.Text += ret.CtrlName +"\r\n";
            foreach (string s in ret.CheckErrorInfo)
            {
                this.TextBox1.Text += "・" + s + "\r\n";
            }
        }
    }

4.2.2 Change control for foreign key column to dropdown list

By default, all columns are freely editable. However, foreign key column should not be freely editable, and should be selected from the list of the parent keys.

  1. Open ProductConditionalSearch.aspx and ProductsSearchAndUpdate.aspx with Visual Studio.

  2. Change the controls for SupplierID column and CategoryID column to dropdown list.

    1. Find the controls for SupplierID column and CategoryID column.

    The controls for SupplierID column and CategoryID column are implemented in four areas, that is AND = 条件 area, AND Like 条件 area, OR = 条件 area, and OR Like 条件 area. For example, in AND = 条件 area, the controls are implemented as follows.

     ```html
     <tr>
         <td>SupplierID</td>
         <td><cc1:WebCustomTextBox ID="txtSupplierID_And" runat="server"></cc1:WebCustomTextBox></td>
     </tr>
     <tr>
         <td>CategoryID</td>
         <td><cc1:WebCustomTextBox ID="txtCategoryID_And" runat="server"></cc1:WebCustomTextBox></td>
     </tr>
     ```
    
    1. Change WebCustomTextBox control to WebCustomDropDownList control.

      <tr>
          <td>SupplierID</td>
          <td><cc1:WebCustomDropDownList ID="ddlSupplierID_And" runat="server" AutoPostBack="false"/></td>
      </tr>
      <tr>
          <td>CategoryID</td>
          <td><cc1:WebCustomDropDownList ID="ddlCategoryID_And" runat="server" AutoPostBack="false"/></td>
      </tr>
    2. Same as the above, change the controls to WebCustomDropDownList in AND Like 条件 area, OR = 条件 area, and OR Like 条件 area.

  3. Next, implement the program to acquire master data.

    Note:
    The program to acquire data of Supplier table and Categories table already has been implemented in App_Code\sample\Business\GetMasterData.cs. This section shows the already implemented program. In actual development, developers should implement the program to acquire master data by referring this GetMasterData.cs.

    /// <summary>マスタデータ・ロード部品</summary>
    public class GetMasterData : MyFcBaseLogic
    {
        /// <summary>業務処理を実装</summary>
        /// <param name="parameterValue">引数クラス</param>
        private void UOC_Invoke(_3TierParameterValue parameterValue)
        { //メソッド引数にBaseParameterValueの派生の型を定義可能。
    
            // 戻り値クラスを生成して、事前に戻り値に設定しておく。
            _3TierReturnValue returnValue = new _3TierReturnValue();
            this.ReturnValue = returnValue;
    
            // ↓業務処理-----------------------------------------------------
         // データアクセス クラスを生成する
            DaoSuppliers daoSuppliers = new DaoSuppliers(this.GetDam());
            // 全件参照
            DataTable dt1 = new DataTable();
            daoSuppliers.D2_Select(dt1);
            // データアクセス クラスを生成する
            DaoCategories daoCategories = new DaoCategories(this.GetDam());
            // 実行
            DataTable dt2 = new DataTable();
            daoCategories.D2_Select(dt2);
            // 戻り値を戻す
            returnValue.Obj = new DataTable[] { dt1, dt2 };
            // ↑業務処理-----------------------------------------------------
        }
    }
  4. Create the following property, that returns the acquired master data, to ProductConditionalSearch.aspx.cs and ProductsSearchAndUpdate.aspx.cs.

    #region マスタ・データの設定用プロパティ
    /// <summary>DropDownList生成用のプロパティ</summary>
    public DataTable ddldsdt_Suppliers
    {
        set
        {
            Session["ddldsdt_SupplierID"] = value;
        }
        get
        {
            return (DataTable)Session["ddldsdt_SupplierID"];
        }
    }
    /// <summary>DropDownList生成用のプロパティ</summary>
    public DataTable ddldsdt_Categories
    {
        set
        {
            Session["ddldsdt_CategoryID"] = value;
        }
        get
        {
            return (DataTable)Session["ddldsdt_CategoryID"];
        }
    }
    #endregion
  5. Implement the program to acquire master data and bind the data to the dropdown list in UOC_FormInit in ProductConditionalSearch.aspx.cs and ProductsSearchAndUpdate.aspx.cs.

    #region マスタ・データのロードと設定
    
    // 引数クラスを生成
    // 下位(B・D層)は、テスト クラスを流用する
    _3TierParameterValue parameterValue = new _3TierParameterValue(this.ContentPageFileNoEx, "FormInit_PostBack", "Invoke", "SQL", this.UserInfo);
    
    // B層を生成
    GetMasterData getMasterData = new GetMasterData();
    
    // 業務処理を実行
    _3TierReturnValue returnValue = (_3TierReturnValue)getMasterData.DoBusinessLogic((BaseParameterValue)parameterValue, DbEnum.IsolationLevelEnum.ReadCommitted);
    DataTable[] dts = (DataTable[])returnValue.Obj;
    DataTable dt = null;
    DataRow dr = null;
    
    // daoSuppliers
    _3TierEngine.CreateDropDownListDataSourceDataTable(dts[0], "SupplierID", "CompanyName", out dt, "value", "text");
    
    // 空の値
    dr = dt.NewRow();
    dr["value"] = "";
    dr["text"] = "empty";
    dt.Rows.Add(dr);
    dt.AcceptChanges();
    
    this.ddlSupplierID_And.DataValueField = "value";
    this.ddlSupplierID_And.DataTextField = "text";
    this.ddlSupplierID_And.SelectedValue = "";
    this.ddlSupplierID_And.DataSource = dt;
    this.ddlSupplierID_And.DataBind();
    
    this.ddldsdt_Suppliers = dt;
    
    // daoCategories
    _3TierEngine.CreateDropDownListDataSourceDataTable(dts[1], "CategoryID", "CategoryName", out dt, "value", "text");
    
    // 空の値
    dr = dt.NewRow();
    dr["value"] = "";
    dr["text"] = "empty";
    dt.Rows.Add(dr);
    dt.AcceptChanges();
    
    this.ddlCategoryID_And.DataValueField = "value";
    this.ddlCategoryID_And.DataTextField = "text";
    this.ddlCategoryID_And.SelectedValue = "";
    this.ddlCategoryID_And.DataSource = dt;
    this.ddlCategoryID_And.DataBind();
    
    this.ddldsdt_Categories = dt;
    
    #endregion
  6. Open ProductConditionalSearch.aspx with Visual Studio.

  7. Change WebCustomTextBox controls for SupplierID and CategoryID to WebCustomDropDownList as follows.

    <asp:TemplateField SortExpression="SupplierID">
        <ItemTemplate>
            <cc1:WebCustomDropDownList ID="ddlSupplierID" runat="server" AutoPostBack="false" ReadOnly="true" DataSource="<%# this.ddldsdt_Suppliers %>" DataValueField="value" DataTextField="text" SelectedValue='<%# Bind(Container.DataItem, "SupplierID") %>'/>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField SortExpression="CategoryID">
        <ItemTemplate>
            <cc1:WebCustomDropDownList ID="ddlCategoryID" runat="server" AutoPostBack="false" ReadOnly="true" DataSource="<%# this.ddldsdt_Categories %>" DataValueField="value" DataTextField="text" SelectedValue='<%# Bind(Container.DataItem, "CategoryID") %>'/>
        </ItemTemplate>
    </asp:TemplateField>
  8. Same as the above, change WebCustomTextBox controls for SupplierID and CategoryID in ProductsSearchAndUpdate.aspx to WebCustomDropDownList as follows. (To enable batch update, set false to ReadOnly property.)

    <asp:TemplateField SortExpression="SupplierID">
        <ItemTemplate>
            <cc1:WebCustomDropDownList ID="ddlSupplierID" runat="server" AutoPostBack="false" ReadOnly="false" DataSource="<%# this.ddldsdt_Suppliers %>" DataValueField="value" DataTextField="text" SelectedValue='<%# Bind(Container.DataItem, "SupplierID") %>'/>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField SortExpression="CategoryID">
        <ItemTemplate>
            <cc1:WebCustomDropDownList ID="ddlCategoryID" runat="server" AutoPostBack="false" ReadOnly="false" DataSource="<%# this.ddldsdt_Categories %>" DataValueField="value" DataTextField="text" SelectedValue='<%# Bind(Container.DataItem, "CategoryID") %>'/>
        </ItemTemplate>
    </asp:TemplateField>
  9. Modify the event handler for btnSearch in ProductConditionalSearch.aspx and ProductsSearchAndUpdate.aspx.

    1. Find the code that refers txtSupplierID_XXX control and txtCategoryID_And control.

    2. Modify to make this code refer ddlSupplierID_XXX control and ddlCategoryID_XXX control. "XXX" is the string that indicates the search methods, that is AND = 条件, AND Like 条件, OR = 条件, and OR Like 条件. For example, modify the code for AND = 条件 as follows.

      // andEqualSearchConditions.Add("SupplierID", this.txtSupplierID_And.Text);
      // andEqualSearchConditions.Add("CategoryID", this.txtCategoryID_And.Text);
      andEqualSearchConditions.Add("SupplierID",this.ddlSupplierID_And.SelectedValue);  
      andEqualSearchConditions.Add("CategoryID", this.ddlCategoryID_And.SelectedValue);
    3. Same as the above, modify the codes for AND Like 条件, OR = 条件, and OR Like 条件.

4.2.3 Delete and add the search criteria

Developers can delete and add the search criteria.

The first is how to delete the search criteria.

  1. Open ProductConditionalSearch.aspx and ProductsSearchAndUpdate.aspx with Visual Studio.

  2. Delete the corresponding control. For example, if you want to delete the search criteria for UnitPrice column, delete the following code. In the following code, XX is the string that indicates the search method, that is And, AndLike, Or, and OrLike.

    <tr>
        <td>UnitPrice</td>
        <td>
            <cc1:WebCustomTextBox ID="txtUnitPrice_XX" runat="server"></cc1:WebCustomTextBox>
        </td>
    </tr>
  3. Open ProductConditionalSearch.aspx.cs and ProductsSearchAndUpdate.aspx.cs with Visual Studio.

  4. Delete the program that is related with UnitPrice.

    andEqualSearchConditions.Add("UnitPrice", this.txtUnitPrice_And.Text);

The next is how to add the search criteria.

  1. Open ProductConditionalSearch.aspx and ProductsSearchAndUpdate.aspx with Visual Studio.

  2. Add the corresponding control. For example, if you want to add the search criteria for UnitPrice column, add the following code. In the following code, XX is the string that indicates the search method, that is And, AndLike, Or, and OrLike.

    <tr>
        <td>UnitPrice</td>
        <td>
            <cc1:WebCustomTextBox ID="txtUnitPrice_XX" runat="server"></cc1:WebCustomTextBox>
        </td>
    </tr>
  3. Open ProductConditionalSearch.aspx.cs and ProductsSearchAndUpdate.aspx.cs with Visual Studio.

  4. Add the program that is related with UnitPrice.

    andEqualSearchConditions.Add("UnitPrice", this.txtUnitPrice_And.Text);

Furthermore, the arbitrary search criteria can be added by referring the following sample code that is described in the template base.

```cs
//// ElseSearchConditions
//Dictionary<string, object> ElseSearchConditions = new Dictionary<string, object>();
//ElseSearchConditions.Add("myp1", 1);
//ElseSearchConditions.Add("myp2", 40);
//Session["ElseSearchConditions"] = ElseSearchConditions;
//Session["ElseWhereSQL"] = "AND [ProductID] BETWEEN @myp1 AND @myp2";
```

4.2.4 Customize the behavior of the primary key and timestamp column

Screen generator assumes the following two conditions.

  • The value of primary key is automatic numbered.
  • The table does not have timestamp column for optimistic locking.

So, by default, the primary key does not contain in generated INSERT statement. And timestamp column does not contain in generated UPDATE and DELETE statements. If corresponding table does not fit these conditions, developers should customize the behavior of the primary key and timestamp column.

Here, Products table fits these conditions. So it is unnecessary to customize generated screens. For the necessity and contents of customize, refer chapter 7. This tutorial only describes how to customize the display of the primary key. For the details of customize, refer section 5.2.

  1. Open Aspx\sample\3Tier\ProductsSearchAndUpdate.aspx.cs with Visual Studio.

  2. Find SetControlReadOnly method and change the control for the primary key.

    /// <summary>編集可否の制御</summary>
    /// <param name="readOnly">読取専用プロパティ</param>
    private void SetControlReadOnly(bool readOnly)
    {
            // 編集可否
            // ReadOnly
            // 主キー
            this.txtProductID.ReadOnly = true;
            // 主キー以外
            this.txtProductName.ReadOnly = readOnly;
            this.txtSupplierID.ReadOnly = readOnly;
            this.txtCategoryID.ReadOnly = readOnly;
            this.txtQuantityPerUnit.ReadOnly = readOnly;
            ・・・
            // 背景色
            // BackColor
            System.Drawing.Color backColor;
            if (readOnly)
            {
                    backColor = System.Drawing.Color.LightGray;
            }
            else
            {
                    backColor = System.Drawing.Color.Empty;
            }
            // 主キー
            this.txtProductID.BackColor = System.Drawing.Color.LightGray;
            // 主キー以外
            this.txtProductName.BackColor = backColor;
            this.txtSupplierID.BackColor = backColor;
            this.txtCategoryID.BackColor = backColor;
            this.txtQuantityPerUnit.BackColor = backColor;
            ・・・
    }

4.2.5 Check operation

  1. Open web.config with Visual Studio.

  2. Check connectionStrings section, and confirm that the connection string is correct.

    <connectionStrings>
        <!-- SQL Server / SQL Client用 -->
        <add name="ConnectionString_SQL" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=Northwind;Integrated Security=True;"/>
    </connectionStrings>
  3. Run services.msc in the Search programs and files box on the start menu.

  4. In Services window, right-click ASP.NET state service and select Start.

  5. Confirm that the status of ASP.NET state services has been changed to Started.

  6. Right-click Aspx\start\menu.aspx and select Set as start page.

  7. Debug the application.

  8. Since the browser is launched and login form is shown, input the value as follows and click ログイン (Login in Japanese).

    • ユーザID (User Id in Japanese): Arbitrary string, NOT allowed empty string
    • パスワード (Password in Japanese): Arbitrary string, allowed empty string
  9. Show ProductsConditionSearch.aspx by clicking 一覧→更新 link.

  10. Confirm that the controls for SupplierID and CategoryID have been changed to dropdown list.

  11. Confirm that the dropdown list for SupplierID has the items of Suppliers table.

  12. Same as the above, confirm that the dropdown list for CategoryID has the items of Categories table.

4.3 Check operation for generated screen

4.3.1 Check operation for ProductsConditionalSearch screen

  1. By referring section 4.2.5, debug the application and show ProductsConditionalSearch.aspx.

  2. Input nothing and click 上記の条件で検索 and confirm that all records are shown.

  3. Input the search condition and click 上記の条件で検索. By default, inputted search conditions are combined in order.

    1. When searching using And equals search, input the search condition in textboxes in AND = 条件 area.

    2. When searching using And equals search and Or equals search, input the search condition in textboxes in AND = 条件 area and OR = 条件 area. Here, users can input the several search conditions by splitting with a space.

    3. When searching using Or like search, input the search condition in textboxes in OR Like 条件 area. Here, users can use wildcard.

4.3.2 Check operation for ProductsDetail screen

  1. By referring section 4.2.5, debug the application and show ProductsDetail.aspx.

  2. When inserting new record, click レコードを追加する。.

  3. When updating or deleting the existing record, click 上記の条件で検索 and click 選択. By default, all textboxes are read-only. When updating the record, click 編集を可能にする.

4.3.3 Check operation for ProductsSearchAndUpdate screen

  1. By referring section 4.2.5, debug the application and show ProductsSearchAndUpdate.aspx. In ProductsSearchAndUpdate.aspx, users can batch update for the several records.

  2. When updating the record, edit the value and click 更新 link. When deleting the record click 削除 link. By clicking 更新 link or 削除 link, 下記の結果セットをバッチ更新する button has been activated.

  3. Click 下記の結果セットをバッチ更新する to batch update.

5. Exercise 2: Customize primary key and timestamp column

This chapter describes how to customize the behavior for the primary key and timestamp column by using my_table table. my_table table has the composite key and timestamp column.

5.1 Generate table maintenance screen for my_table

5.1.1 Create D layer definition file

By referring section 4.1.1, create D layer definition file for my_table table.

5.1.2 Generate data access class, sql files, and table maintenance screens

By referring section 4.1.2, generate data access class, sql files, and table maintenance screens. Here, it is necessary to set the property for timestamp column.

In this tutorial, input "Timestamp" in タイムスタンプ列名 textbox.

Note:
The type of timestamp column in my_table table is timestamp. Because timestamp column is updated automatically, it is unnecessary to input 更新方法 textbox. If the type of timestamp column is not updated automatically, set update method in 更新方法 textbox. For example, if the type of timestamp column is datetime, input SYSDATETIME() in 更新方法 textbox.

5.1.3 Deploy data access classes, sql files, and table maintenance screens

By referring section 4.1.3, deploy data access classes, sql files, and table maintenance screens.

5.2 Customize table maintenance screen for my_table table

5.2.1 Customize menu

  1. Open C:\root\programs\C#\Samples\WebApp_sample\WebForms_Sample\WebForms_Sample.sln with Visual Studio.

  2. In the Solution Explorer, open Aspx\start\menu.aspx and add the following code.

    ● my_tableサンプル(3層データバインド・テスト)<br /><a href="/WebForms_Sample/Aspx/sample/3Tier/my_tableConditionalSearch.aspx">一覧→更新</a><br /><a href="/WebForms_Sample/Aspx/sample/3Tier/my_tableSearchAndUpdate.aspx">一覧&更新</a><br /><br />

5.2.2 Customize the behavior for the primary key and timestamp column

  1. In the Solution Explorer, open Aspx\sample\3Tier\my_tableConditionalSearch.aspx.

  2. Delete the controls for timestamp column from search criteria.

    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_And" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_And_Like" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_OR" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_OR_Like" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
  3. Hide the timestamp column in grid.

    <ItemTemplate>
            <cc1:WebCustomTextBox ReadOnly="true" Visible="false" ID="txtTimestamp" runat="server" Text='<%# Bind("Timestamp") %>'></cc1:WebCustomTextBox>
    </ItemTemplate>

    Note:
    Do not delete this control because this control is used for optimistic locking.

  4. In the Solution Explorer, open my_tableConditionalSearch.aspx.cs.

  5. Confirm that the following code is generated in gvwGridView1_SelectedIndexChanging method.

    // タイムスタンプ列
    if(dt.Rows[e.NewSelectedIndex]["Timestamp"].GetType() != typeof(System.DBNull))
    {
        PrimaryKeyAndTimeStamp.Add("Timestamp", dt.Rows[e.NewSelectedIndex]["Timestamp"]);
    }
    Session["PrimaryKeyAndTimeStamp"] = PrimaryKeyAndTimeStamp;

Next, customize my_tableDetail.aspx.

  1. In the Solution Explorer, open my_tableDetail.aspx.

  2. Hide the timestamp column in table.

    <tr style="display:none">
            <td>Timestamp</td>
            <td><cc1:WebCustomTextBox ID="txtTimestamp" runat="server"></cc1:WebCustomTextBox></td>
    </tr>
  3. In the Solution Explorer, open my_tableDetail.aspx.cs.

  4. Customize UOC_btnInsert_Click method as follows.

    • Because the primary key is not Identity column (automatic numbering column), add the code for the primary key.
    • Because timestamp column is updated automatically, delete the code for timestamp column.
    // 追加値(TimeStamp列は外す。主キーは採番方法次第。
    parameterValue.InsertUpdateValues = new Dictionary<string, object>();
    parameterValue.InsertUpdateValues.Add("ID", this.txtID.Text);
    parameterValue.InsertUpdateValues.Add("ID2", this.txtID2.Text);
    parameterValue.InsertUpdateValues.Add("Val", this.txtVal.Text);
    //parameterValue.InsertUpdateValues.Add("Timestamp", this.txtTimestamp.Text);
  5. Same as the above, customize UOC_btnUpdate_Click method as follows.

    // 更新値(TimeStamp列は外す。主キーは採番方法次第。
    parameterValue.InsertUpdateValues = new Dictionary<string, object>();
    parameterValue.InsertUpdateValues.Add("Val", this.txtVal.Text);
    //parameterValue.InsertUpdateValues.Add("Timestamp", this.txtTimestamp.Text);
  6. If the primary key is Identity column (automatic numbering column), customize SetControlReadOnly method. In this tutorial, the primary key of my_table table is not Identity column, it is unnecessary to customize.

    /// <summary>編集可否の制御</summary>
    /// <param name="readOnly">読取専用プロパティ</param>
    private void SetControlReadOnly(bool readOnly)
    {
            // 編集可否
            // ReadOnly
            // 主キー
            this.txtID.ReadOnly = false; // true;
            this.txtID2.ReadOnly = false; // true;
            // 主キー以外
            this.txtVal.ReadOnly = readOnly;
            this.txtTimestamp.ReadOnly = readOnly;
            // 背景色
            // BackColor
            System.Drawing.Color backColor;
            if (readOnly)
            {
                    backColor = System.Drawing.Color.LightGray;
            }
            else
            {
                    backColor = System.Drawing.Color.Empty;
            }
            // 主キー
            this.txtID.BackColor = backColor; // System.Drawing.Color.LightGray;
            this.txtID2.BackColor = backColor; // System.Drawing.Color.LightGray;
            // 主キー以外
            this.txtVal.BackColor = backColor;
            this.txtTimestamp.BackColor = backColor;
    }

Next, customize my_tableSearchAndUpdate.aspx.

  1. In the Solution Explorer, open my_tableSearchAndUpdate.aspx.

  2. Delete the controls for timestamp column from search criteria.

    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_And" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_And_Like" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_OR" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
    ・・・
    <!--<tr>
        <td>Timestamp</td>
        <td>
            <cc1:WebCustomTextBox ID="txtTimestamp_OR_Like" runat="server">
            </cc1:WebCustomTextBox>
        </td>
    </tr>-->
  3. Hide the timestamp column in grid.

    <ItemTemplate>
            <cc1:WebCustomTextBox ReadOnly="true" Visible="false" ID="txtTimestamp" runat="server" Text='<%# Bind("Timestamp") %>'></cc1:WebCustomTextBox>
    </ItemTemplate>

    Note:
    Do not delete this control because this control is used for optimistic locking.

  4. In the Solution Explorer, open my_tableSearchAndUpdate.aspx.cs.

  5. Customize UOC_btnBatUpd_Click method to add timestamp column.

    // 主キー列
    parameterValue.AndEqualSearchConditions.Add("ID", "");
    parameterValue.AndEqualSearchConditions.Add("ID2", "");
    
    // タイムスタンプ列
    parameterValue.AndEqualSearchConditions.Add("Timestamp", "");

5.3 Check operation

5.3.1 Check operation of my_tableDetail screen

  1. By referring section 4.2.5, debug the application and show my_tableDetail.aspx.

  2. Click レコードを追加する and add new record with the following values.

    • ID: 2
    • ID2: 3
    • Val: 4
  3. To check operation of optimistic locking, run the following command. (A case of updating the record by somebody else is supposed.)

    "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S localhost\SQLExpress -E -d Northwind -Q "UPDATE [my_table] SET [Val] = '6' WHERE [ID]=2 AND [ID2]=3;"
  4. Click 選択 in the record that you just added.

  5. Edit the value of Val and click 編集結果で更新する.

  6. Confirm that 0件更新しました message has been shown. In the previous step, somebody else updated the record. Because timestamp value has been updated, update processing fails. (Optimistic locking is working normally.)

5.3.2 Check operation of my_tableSearchAndUpdate screen

  1. By referring section 4.2.5, debug the application and show my_tableSearchAndUpdate.aspx.

  2. By referring section 5.3.1, check operation of optimistic locking.

6. Exercise 3: Implement relation check and automatic numbering program

This section describes how to implement relation check and automatic numbering program.

  1. Add new class named My3TierEngine.cs in App_Code\sample\Business with Visual Studio.

  2. Implement My3TierEngine.cs as follows.

    //**********************************************************************************
    //* クラス名                :My3TierEngine
    //* クラス日本語名    :三層データバインドの関連チェック・自動採番用の業務コードクラス
    //*
    //* 作成者                    :xxxx
    //* 更新履歴                :
    //*
    //*    日時                更新者                        内容
    //*    ----------    ----------------    -------------------------------------------------
    //*    201x/xx/xx    xxxx xxxx                新規作成
    //**********************************************************************************
    
    // System
    using System;
    using System.IO;
    using System.Data;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    
    // 業務フレームワーク
    using Touryo.Infrastructure.Business.Business;
    using Touryo.Infrastructure.Business.Common;
    using Touryo.Infrastructure.Business.Dao;
    using Touryo.Infrastructure.Business.Exceptions;
    using Touryo.Infrastructure.Business.Presentation;
    using Touryo.Infrastructure.Business.Util;
    
    // フレームワーク
    using Touryo.Infrastructure.Framework.Business;
    using Touryo.Infrastructure.Framework.Common;
    using Touryo.Infrastructure.Framework.Dao;
    using Touryo.Infrastructure.Framework.Exceptions;
    using Touryo.Infrastructure.Framework.Presentation;
    using Touryo.Infrastructure.Framework.Util;
    using Touryo.Infrastructure.Framework.Transmission;
    
    // 部品
    using Touryo.Infrastructure.Public.Db;
    using Touryo.Infrastructure.Public.IO;
    using Touryo.Infrastructure.Public.Log;
    using Touryo.Infrastructure.Public.Str;
    using Touryo.Infrastructure.Public.Util;
    
    /// <summary>
    /// My3TierEngineの概要の説明です
    /// </summary>
    public class My3TierEngine : _3TierEngine
    {
        /// <summary>コンストラクタ</summary>
        public My3TierEngine()
        {
            // TODO: コンストラクター ロジックをここに追加します
        }
    
        #region 固定の実装
        /// <summary>baseを呼ぶ</summary>
        /// <param name="parameterValue">引数クラス</param>
        protected override void UOC_SelectRecord(_3TierParameterValue parameterValue)
        {
            base.UOC_SelectRecord(parameterValue);
        }
        /// <summary>baseを呼ぶ</summary>
        /// <param name="parameterValue">引数クラス</param>
        protected override void UOC_UpdateRecord(_3TierParameterValue parameterValue)
        {
            base.UOC_UpdateRecord(parameterValue);
        }
        /// <summary>baseを呼ぶ</summary>
        /// <param name="parameterValue">引数クラス</param>
        protected override void UOC_DeleteRecord(_3TierParameterValue parameterValue)
        {
            base.UOC_DeleteRecord(parameterValue);
        }
        /// <summary>baseを呼ぶ</summary>
        /// <param name="parameterValue">引数クラス</param>
        protected override void UOC_BatchUpdate(_3TierParameterValue parameterValue)
        {
            base.UOC_BatchUpdate(parameterValue);
        }
        #endregion
    
        /// <summary>三層データバインドの関連チェック・自動採番</summary>
        /// <param name="parameterValue">引数クラス</param>
        protected override void UOC_RelatedCheck(_3TierParameterValue parameterValue)
        {
            // TODO: 関連チェック・自動採番 ロジックをここに追加します
        }
    }
  3. Implement relation check and automatic numbering program in UOC_RelatedCheck method. Here, the properties of _3TierParameterValue class are useful. (This tutorial describes the implementing position only, and does not describe how to implement relation check and automatic numbering program.)

  4. Set a breakpoint to UOC_RelatedCheck method.

  5. Open my_tableDetail.aspx.cs and search the code that refers _3TierEngine class in UOC_btnUpdate_Click method and UOC_btnDelete_Click method.

    // B layer Initialize
    _3TierEngine b = new _3TierEngine();
  6. Modify the above code as follows. (Change referred class to My3TierEngine.)

    // B layer Initialize
    My3TierEngine b = new My3TierEngine();
  7. Set my_tableDetail.aspx as start page and debug application.

  8. Confirm that the breakpoint, that is set at UOC_RelatedCheck method, is hit during update program.

7. Appendix: Customize generated screen

7.1 Customize the behavior of primary key and timestamp column

This chapter describes the customize contents of primary key and timestamp column

  • Primary key
    Generated screens are assuming that the primary key is automatically numbered by Identity column or Sequence.

    • In case of using Identity column or Sequence
      • By referring section 4.2.4, make the textbox for primary key read-only and gray out the textbox.
    • In case of not using Identity column or Sequence
      • By referring section 5.2.2, input the value of primary key or implement automatic numbering program.
  • Timestamp column

    • In case of not existing timestamp column for optimistic locking
      • Customization is unnecessary.
    • In case of existing timestamp column for optimistic locking
      • Screen (.aspx files)
        • By referring section 5.2.2, delete timestamp from search criteria and hide timestamp column.
      • Code behind (.aspx.cs files)
        • By referring section 5.2.2, add timestamp column.
        • In case of updating timestamp column automatically
          • Do not input the timestamp value when inserting or updating the record.
        • In case of updating timestamp column manually
          • Input the timestamp value when inserting or updating the record.

7.2 Other customize contents

Developer can also customize generated screen as follows.

  • In case of reducing the search criteria
    • Delete the textboxes in screen (.aspx file) and related program in code behind (.aspx.cs file).
  • In case of adding the search criteria
    • Add the arbitrary textboxes in screen (.aspx file) and related program in code behind (.aspx.cs file).
  • In case of add verification single item program
    • By referring section 4.2.1, set the check attributes in the property grid.
  • In case of changing textbox control for foreign key to drop-down list.
    • By referring section 4.2.2, change textbox control to drop-down list in screen (.aspx file) and modify related program in code behind (.aspx.cs file).
Clone this wiki locally