Webserivce [Create a distributed application]

Source: Internet
Author: User
Create a Distributed Application Program

In this walkthrough, you will create a multi-layer Distributed intranet application. The application consists of three logical layers: data layer, Business Object layer, and user interface layer. The data layer is a database in SQL Server. The Business Object layer processes how to access data and how to distribute data to clients. The user interface layer consists of web-based applications and traditional Windows applications. Describes the structure of the application.

Structure of the distributed application you will create

The application to be generated is a simple data application with the function of searching and editing. You will generate a windows and web-based client to display the authors table in the SQL Server pubs sample database. For the web section, you can use the web forms designer to create a web page compatible with the standard HTML 3.2 browser. On the server, web formsCodeXML Web Services is called to retrieve data containing the author information from the database. For Windows, you will generate a Windows application that communicates with the same XML Web Services to retrieve datasets containing the author information. Use http and XML to process the communication with XML Web Services.

You will create XML Web Services and client applications on the same server, even if the database resides on another server. The application server and database server must reside on the same intranet. This project structure allows you to use Windows authentication to access databases and test applications. At the same time, this structure removes a lot of detailed information about resource access, allowing you to see the interaction between XML Web Services and client applications. This structure may not be exactly the same as the structure required by your own application. More information about other security models and structures

System Requirements

To complete this drill, you must:

    • Access Permissions for servers with the pubs SQL Server Sample Database and with Windows Authentication integrated. Pubs database is one of the sample databases that can be installed with SQL Server.
    • Basic understanding of how data is processed in Visual Studio. NET.

Distributed Application creation process

One possible solution for developing distributed applications is to create a layer at a time, most of which starts from the data layer, move to the business rule object in the middle layer, and finally create the user interface layer. In this walkthrough, data has been generated and can be used in the pubs database in SQL Server. Therefore, this walkthrough starts from creating a business object, namely, XML Web Services, and then generates two user interfaces: web forms page and Windows form.

The drill process is as follows:

Create intermediate layer Business Objects

The business objects you create will run on the Web server to provide the performance and scalability required by distributed applications. In addition, you will implement the business object as XML Web Services, so that the client can use the standard Internet Protocol to communicate with your business objects from any platform.

In this walkthrough, the XML Web Services component saves data connections and dataset definitions. The XML Web Services method will be added to expose this dataset, which allows other applications to view and modify this dataset.

The ASP. NET Web Service Project template is a Web-based project designed to create an intermediate layer component that exposes its own interfaces as XML Web Services.

XML Web Services exposes two methods. First MethodGetauthorsThe dataset is returned from the database. Method 2UpdateauthorsThe database will be updated with user changes. Several private members are created to implement these methods. These include dataset definition, data adapter, data connection, and several command objects for retrieving data from the database and updating the database. The following diagram describes XML Web Services.

Intermediate Layer of distributed applications

Create an ASP. NET Web Service Project

    1. On the File menu, point to new, and click Project to display the new project dialog box.
    2. Select Visual Basic project or Visual C # project in the project type pane based on the language you want to use, and then select ASP.. NET web service ".
    3. In the "location" box, enter the name and Project Name of the Web server (on your development computer)Http ://Servername/AuthorswebserviceAnd then click OK ".

      PromptIf the Web server is on your computer, you can use the server name localhost.

      PromptIf it is difficult to create an ASP. NET Web Service Project

    4. ProjectAuthorswebserviceAdd it to the solution. The "component designer" of service1.asmx appears in the development environment.
    5. In Solution Explorer, double-clickService1.asmxTo select it.
    6. In the "properties" window, SetService1OfNameSet propertyAuthorsservice.
    7. In Solution Explorer, right-clickService1.asmxFile, select "RENAME", rename this fileAuthorsservice. asmxTo match the service name.

      In this component, you will create a connection to the data storage area and obtain data instances through datasets.

Create and configure database connections and dataset Architecture

You will add two objects to XML Web Services: One sqldataadapter object and one sqlconnection object. The connection object creates a new connection to the database, and the data adapter queries the database and sends the result to the DataSet object. The data adapter also updates the database with changes made to the dataset. By using this connection to the database, you can create an instance that stores the information that exists in the database. This dataset will be used later in this walkthrough to display data in Windows Forms and web forms pages.

Create Database Connection and data adapter

  1. Click server resource manager.

    Note:By default, server resource manager is displayed as a vertical tab on the left side of the development environment. If you cannot see this tab, click the View menu and select server resource manager ".

  2. In server resource manager, right-click the "Data Connection" node and select "add connection" from the shortcut menu ".
  3. In the connection tab of the Data Link Properties dialog box, enter the name of the SQL server where the pubs database is installed. If you have SQL Server on your local computer, enter(Local).
  4. Select "use Windows NT Integrated Security Settings" for the logon information ".

    Note:If integration security is not set on your system, contact your network administrator.

  5. Select from ListPubsDatabase.
  6. Click test connection to verify your information, and then click OK to establish the connection.

    A new node appears in the "Data Connection" node of the server resource manager.

    Note:If the database connection fails, contact the database administrator.

  7. In the server resource manager, expand the node of the new connection node, and then expand the "table" node.
  8. FindAuthorsNode and expand it to displayAuthorsFields in the table.
  9. Use Ctrl + mouse to click and selectAu_id,Au_lname,Au_fnameAndCityField.
  10. Drag and Drop these fields from the server resource manager to the design surface.SqlconnectionObject andSqldataadapterObjects appear in the designer. Now you have established a connection to the database.SqldataadapterObject processing. These components are configured to includeAuthorsThe dataset of the table is moved into and out of the database.

    Note:Used in this WalkthroughSqldataadapterThis object has been optimized for SQL Server 7.0 or later. You can also useOledbdataadapterObject, because it is more common and provides access to any ado. NET data sources compatible with ole db. If the database to be connected is not an SQL Server database, the project system createsOledbdataadapterObject andOledbconnectionObject.

    Note:In this walkthroughAuthorsSome columns and all rows in the table are filled with datasets. In a finished application, data access is optimized by creating a query that only returns the required columns and rows.

  11. Security Settings for configuration items are required to use integrated security. Disable Anonymous Access and enable simulation to perform this operation.

  12. Configure integrated Windows Authentication

To configure integrated Windows authentication for a project, you must use the Internet information service tool to change the project file and configure the project.

    1. Start the "Internet Information Service" tool. You can run it from "Administrative Tools" on the "control panel. (For more information about starting this tool, see the Windows Help documentation .)
    2. Expand the server node.
    3. Expand the "Default web site" node.
    4. Right-clickAuthorswebserviceAnd select "properties" from the shortcut menu ".
    5. Click the "Directory Security" tab.
    6. Click the edit button in the "Anonymous Access and authentication control" section.
    7. Clear the "Anonymous Access" check box.
    8. Select the integrated Windows Authentication check box. The XML Web Services Directory has been configured.
    9. Return to the project in Visual Studio and double-click the Web. config file in Solution Explorer.
    10. In<System. Web>Add the following tag to the row after the tag to configure integration security for XML Web Services.
      <Identity impersonate = "true"/>

Create a dataset class definition

    1. In Solution Explorer, double-clickAuthorsserviceFile to open it in the designer.
    2. Select "generate dataset" from the "data" menu ". In the "generate dataset" dialog box, select "new" and name the dataset "authors1 ". Do not select the box marked as "add this dataset to designer.

      Note:Create the dataset schema file authors1.xsd and add it to the project. This architecture file containsAuthors1Class definition. This class (fromDatasetClass inheritance) containsAuthorsDefines a typed dataset of a table.

    3. Select "Save all" from the "file" menu ".
Publish the authors1 dataset from the Business Object

The next step of this walkthrough is to publish the newly created DataSet object from the business object. This operation enables the dataset to be used by windows or web applications.

Add methods to XML Web Services

  1. In Solution Explorer, if you have not enabledAuthorsserviceDouble-click it.
  2. Click "code" on the "View" menu ".
  3. Add a method named getauthors to pass a dataset to the client.

    as shown below, this method creates a authors1 dataset, fill in the dataset according to the authors table with the sqldataadapter object. Then this method returns the dataset.

     // C # [webmethod] public authors1 getauthors () {authors1 authors = new authors1 (); sqldataadapter1.fill (authors ); return authors ;}
  4. Add nameUpdateauthorsTo pass the changes from the client back to the database.

    As shown below, this method hasAuthors1Dataset parameters (Authorchanges).Sqldataadapter.UpdateMethod to update the database.UpdateMethod to accept changes in the dataset. The dataset is returned to the client. The client then updates its ownAuthors1Dataset instance. RelatedUpdateMethods and how to accept dataset changes

    // C # [webmethod] public authors1 updateauthors (authors1 authorchanges) {If (authorchanges! = NULL) {sqldataadapter1.update (authorchanges); Return authorchanges;} else {return NULL ;}}

    Note:In the finished application, the error check and exception handling functions are added to these methods.

  5. Select "Save all" from the "file" menu ".
  6. Select "generate solution" from the "generate" menu ".

In the previous section, you created a middle-layer business object that contains a dataset bound to the SQL Server database. You sendAuthorswebserviceCode is added to XML Web Services to obtain data from the data source and update the data source with changes. The client passesGetauthorsAndUpdateauthorsUse the XML Web Services method to access these functions.

Create user interface

Create an intermediate layer business object for data access and publish it as XML Web Services. The next step is to create a client interface. This walkthrough has two solutions: traditional Windows Forms and web forms pages. The two schemes are created as different projects in the same solution in this example.

Windows User Interface Options

The Windows interface uses the client function to process some applications. Generally, Windows interfaces provide more comprehensive functions and richer user operations than web interfaces. Server load is less than Web Front-end load because the server does not have to execute all application logic. In addition, the Windows interface can use resources available through the operating system, including calling the file system and registry.

The following diagram highlights the client to be implemented.

Windows clients in distributed applications

A Windows application (composed of a Windows form) will contain a pairAuthorswebserviceWeb reference. When you click the Load button on the form, the data in the database is displayed inDataGridControl. This loading behavior is performed by calling the XML Web ServicesGetauthorsMethod.DataGridControls allow direct editing and pass data changes directly to the Basic Dataset. This form also has a "save" button. The code of this button will callUpdateauthorsTo save the changes back to the database.

Create a Windows Application

    1. On the File menu, point to add project, and click New project to open the Add project dialog box.
    2. Select "Visual C # project" or "Visual Basic Project" in the "project type" pane based on the language to use ", in the template pane, select windows application ".
    3. Name the projectAuthorswinclientAnd select a location for the project.

      AuthorswinclientThe project is added to the solution. Form1 is automatically added to the project and appears in the Windows Form Designer.

    4. Add a web reference for the ASP. NET web service project created earlier:
      1. In Solution Explorer, right-clickAuthorswinclientProject, and then click "add web reference" on the shortcut menu ".
      2. In the "url" box at the top of the "add web reference" dialog box, enter the location of the XML Web Services Project (http ://Servername/Authorswebservice/authorsservice. asmx), and then press Enter. If it is difficult to add web references
      3. Click Add reference ".
      4. Now you can createAuthors1The instance of the dataset.

Add a widget to a form

    1. In the Windows Forms tab of the toolboxDataGridDrag the widget to the form.
    2. In the Windows Forms tab of the toolboxButtonDrag the widget to the form. ClickNameSet propertyLoaddata, Set itsTextSet propertyLoad.
    3. From the Windows Forms tab of the toolboxButtonDrag the widget to the form. ClickNameSet propertySavedata, Set itsTextSet propertySave.
    4. From the data tab of the toolboxDatasetDrag the object to the form. The "add dataset" dialog box appears. Select "typed dataset" and select "authorswinclient. servername. authors1" from the "name" list ". This operation createsAuthors1The dataset class definesDatasetObject.
    5. SelectDatasetControl andNameSet propertyAuthordata.
    6. SelectDataGridControl andDatasourceSelectAuthordata. SlaveDatamemberSelectAuthors.DataGridIs setAuthorsThe column name of the table.

Add code for the loaddata and savedata buttons

  1. click designer on the View menu ". Double-click loaddata to create an empty event handler for the click event. The method to call the XML Web Services method is to first create an instance of the service class and then call the service method. In this case, call the getauthors method. The returned dataset is merged with the authordata dataset, the credentials attribute of XML Web Services is used to pass your identity to XML Web Services, which then passes it to the database server. Add the Code as follows to the method.

    note If XML Web Services are not running on a local computer, replace localhost In the code example with the name of the server that runs XML Web Services.

    /C # private void loaddata_click (Object sender, system. eventargs e) {authorswinclient. localhost. authorsservice Ws = new authorswinclient. localhost. authorsservice (); ws. credentials = system. net. credentialcache. defaultcredentials; authordata. merge (WS. getauthors () ;}
  2. click designer on the View menu ". Double-click the savedata button to create an empty event handler for the click event.

    If the dataset is changed, a authors1 type new dataset is created to save only the changed data. The dataset is then passed to the updateauthors method of XML Web Services. This dataset is returned along with the accepted changes, and the authordata dataset is updated to reflect these new changes.

    note In a finished application, you must consider data concurrency in this step.

  3. Add the following code to the method:

    // C # private void savedata_click (Object sender, system. eventargs e) {If (authordata. haschanges () {authorswinclient. localhost. authorsservice Ws = new authorswinclient. localhost. authorsservice (); ws. credentials = system. net. credentialcache. defaultcredentials; authorswinclient. localhost. authors1 diffauthors = new authorswinclient. localhost. authors1 (); diffauthors. merge (authordata. getchanges (); diffauthors = ws. updateauthors (diffauthors); authordata. merge (diffauthors );}}

Run the application

    1. Select "Save all" from the "file" menu ".
    2. Select "authorswinclient" in Solution Explorer, right-click and select "set as startup project ".
    3. Press Ctrl + F5 to run the application.

      A window is displayed, which contains an empty table. The table header comes from the authors table in the pubs database.

    4. Click load to fill the table, make some changes, and then clickSaveSave the changes.

In the previous section, you added a Windows form project as the Windows interface in solution. Connect windows forms to the XML Web Services created in Section 1 and useDataGridAndButtonControls create a user interface for loading and updating data. In the next section, you will create a web-based user interface for the solution.

Web User Interface Options

The Web interface helps applications access different clients and browsers. All user interface processing is performed on the Web server rather than on the client. You will use the web forms page to create a web interface. Like the Windows interface created in the previous section, this interface accesses the business objects of the same intermediate layer. The following diagram highlights the client to be implemented.

Web clients in distributed applications

Create a web form application

    1. On the File menu, point to add project, and click New project ".
    2. In the Add new project dialog box, select Visual C # project or visual basic project in the project type pane ", in the template pane, click ASP. net web application ".
    3. In the "location" box, enter the name and Project Name of the Web server (on your development computer)Http ://Servername/AuthorswebclientAnd then click OK ".

      Add a new project to Solution Explorer. A web form page named webform1.aspx is added to the project and loaded to the designer.

    4. Add a web reference for the ASP. NET web service project created earlier:
      1. In Solution Explorer, right-clickAuthorswebclientProject, and then click "add web reference" on the shortcut menu ".
      2. In the "url" box at the top of the "add web reference" dialog box, enter the location of the XML Web Services Project (http ://Servername/Authorswebservice/authorsservice. asmx), and then press Enter.
      3. Click Add reference ".
      4. Now you can createAuthors1The instance of the dataset.

Add controls to web pages

    1. From the data tab of the toolboxDatasetDrag the object to the form. The Select dataset dialog box is displayed. Select "typeddataset" and select "authorswebclient" from the "name" list.Servername. Authors1 ". OneDatasetThe object is added to the component bar.
    2. SelectDatasetObject andNameSet propertyAuthordata.
    3. From the web forms tab of the toolboxDataGridDrag the widget to the form.
    4. InDataGridIn the Properties window of the control, SetDatasourceSet propertyAuthordata, SetDatamemberSet propertyAuthors. These settings appear in the drop-down list of these controls.DataGridIs setAuthorsThe column name of the table.
    5. To supportDataGridYou must add an "edit, update, cancel" column for local editing in the control. This column will contain an "edit" button. When you click the edit button, the content of the row is displayed in the text box, And the edit button is replaced by the update and cancel buttons. To add this column, follow these steps:
      1. Click the "Property generator" link at the bottom of the "properties" window and select the "column" tab in the dialog box.
      2. In the available columns pane, expand the button column item.
      3. Select edit, update, and cancel, and then click.
      4. Click OK ".

Add code for "edit", "Update", and "cancel" buttons

  1. right-click the form and select "view code ". Add the code for filling the DataGrid Control in the page_load event, as shown below. These codes create an XML Web Services instance and fill in the authordata dataset, bind the dataset to the DataGrid control. Each time a page returns to a user after a round-trip, the grid will contain a new copy of data from the database. The credentials attribute of XML Web Services is used to pass your identity to XML Web Services, which then passes it to the database server.

    note In this walkthrough, when the web form page is downloaded to the client browser, all new copies of the authors table are retrieved from the database. This may not provide optimal performance.

    // C #
    private void page_load (Object sender, system. eventargs e)
    {< br> authorswebclient. localhost. authorsservice Ws =
    New authorswebclient. localhost. authorsservice ();
    ws. credentials = system. net. credentialcache. defaultcredentials;
    authordata. merge (WS. getauthors ();
    If (! Page. ispostback)
    {< br> datagrid1.databind ();
    }< BR >}

  2. When you click the edit buttonDataGridControlEditcommandEvent. Use this event to changeDataGridControlEdititemindexAttribute.EdititemindexThe row specified by the attribute is displayed in the text box along with all data.
    1. IsEditcommandCreate an event handler for an event.

      In Visual Basic, right-click the page and select view code ". SelectDatagrid1. Select "editcommand" in the right drop-down box ".

      -Or-

      In Visual C #, clickDatagrid1Control. In the Properties window, click the event button to displayDataGridEvent list. Double-clickEditcommandEvent.

    2. Add the Code as follows.
      // C #
      Private void datagrid1_editcommand (Object source,
      System. Web. UI. webcontrols. datagridcommandeventargs E)
      {
      Datagrid1.edititemindex = E. Item. itemindex;
      Datagrid1.databind ();
      }
  3. IsCancelcommandCreate an event handler for an event. (For information about adding event handlers, see Step 1 .)

    When you click the cancel buttonDataGridControlCancelcommandEvent. Use this eventEdititemindexSet property to-1 to display the current row as text again. Add the Code as follows.

  4. // C #
    Private void maid cancelcommand (Object source,
    System. Web. UI. webcontrols. datagridcommandeventargs E)
    {
    Datagrid1.edititemindex =-1;
    Datagrid1.databind ();
    }

  5. When you click the "Update" buttonDataGridControlUpdatecommandEvent. This method is usedDataGridUpdate changes in the controlAuthordataDatasets, and pass these changes back to the database through XML Web Services. IsUpdatecommandCreate an event handler for an event. (For information about adding event handlers, see Step 1 .) Add the Code as follows.
  6. // C #
    Private void datagrid1_updatecommand (Object source,
    System. Web. UI. webcontrols. datagridcommandeventargs E)
    {
    // Change the data in the dataset.
    For (INT I = 1; I <= authordata. Authors. Columns. Count; I ++)
    {
    Textbox t = (textbox) (E. Item. cells [I]. controls [0]);
    Datarow ROW = authordata. Authors [E. Item. datasetindex];
    Row [authordata. Authors. Columns [I-1]. Caption] = T. text;
    }

    // Update the database.
    If (authordata. haschanges ())
    {
    Authorswebclient. localhost. authorsservice Ws =
    New authorswebclient. localhost. authorsservice ();
    WS. Credentials = system. net. credentialcache. defaultcredentials;
    Authorswebclient. localhost. authors1 diffauthors =
    New authorswebclient. localhost. authors1 ();
    Diffauthors. Merge (authordata. getchanges ());
    WS. updateauthors (diffauthors );
    Authordata. Merge (diffauthors );
    }
    Datagrid1.edititemindex =-1;
    Datagrid1.databind ();
    }

Security Settings for configuration items are required to use integrated security. Disable Anonymous Access and enable simulation to perform this operation.

Configure integrated Windows Authentication

To configure integrated Windows authentication for a project, you must use the Internet information service tool to change the project file and configure the project.

    1. Start the "Internet Information Service" tool. You can run it from "Administrative Tools" on the "control panel. (For more information about starting this tool, see the Windows Help documentation .) Expand the server node.
    2. Expand the "Default web site" node.
    3. Right-clickAuthorswebclientAnd select "properties" from the shortcut menu ".
    4. Click the "Directory Security" tab.
    5. Click the edit button in the "Anonymous Access and authentication control" section.
    6. Clear the "Anonymous Access" check box.
    7. Select the integrated Windows Authentication box. The XML Web Services Directory has been configured.
    8. Return to the project in Visual Studio and double-click the Web. config file in Solution Explorer.
    9. In<System. Web>Add the following tag to the row after the tag to configure integration security for XML Web Services.
      <Identity impersonate = "true"/>

Run the application

    1. Select "authorswebclient" in Solution Explorer, right-click it, and select "set as startup project ".
    2. Press Ctrl + F5 to run the application.

In this section, you add an ASP. NET web application project in the solution as the data browser interface. Connect the web forms page to the XML Web Services created in Section 1 and useDataGridControl to create a user interface for displaying and Editing data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.