Você está na página 1de 13

Microsoft Virtual Labs

Creating a Distributed
Application with C#
2 Creating a Distributed Application with C#

Table of Contents

Creating a distributed application with C#............................................................................................... 3


Exercise 1 Creating the middle-tier business object............................................................................................4
Exercise 2 Creating a Windows Forms User Interface........................................................................................7
Exercise 3 Creating a Web Forms User Interface .............................................................................................10
Creating a distributed application with C# 3

Creating a distributed application with


C#

Objectives After completing this lab, you will know about:


„ Creating the Middle-Tier Business Object.
„ Creating a Windows Forms User Interface Create custom shaped Windows
Forms.
„ Creating a Web Forms User Interface.

Scenario The objective of this lab is to create a multi-tiered, distributed application. The
application will consist of three logical tiers: data, business object, and user
interface. The data tier is a database in SQL Server. The business-object tier
will handle accessing the data and distributing it to the clients. The user-
interface tier will consist of both a Web-based application and a traditional
Windows application.
The application you will build is a simple data application with lookup and edit.
You will build both a Windows and Web-based client to display the Authors
table from the SQL Server Pubs sample database. For the Web portion, you will
use the Web Forms Designer to create a Web page that is compatible with a
standard HTML 3.2 browser. On the server, the Web Forms code will call an
XML Web service to retrieve data that contains Authors information from the
database. For the Windows portion, you will build a Windows application that
will communicate with this same XML Web service to retrieve a dataset
containing the author information. Communication with the XML Web service
is handled using HTTP and XML.

Estimated time to
complete this lab: 45
minutes
4 Creating a Distributed Application with C#

Exercise 1
Creating the middle-tier business object

Scenario
In this exercise, you will create a business object as an XML Web Service that exposes two
methods: GetAuthors and UpdateAuthors.

Tasks Detailed steps

1. Create an ASP.NET Web a. Click Start | All Programs | Microsoft Visual Studio .NET 2003 |
Service Project. Microsoft Visual Studio .NET 2003.
b. Click File | New | Project.
c. Select Visual C# Projects.
d. Select ASP.NET Web Service in the Templates pane.
e. In the Location box, type http://localhost/AuthorsWebService.
f. Click OK.
The AuthorsWebService project is added to the solution. Component
Designer for Service1.asmx.cs appears in the development environment.
g. In Solution Explorer, double-click Service1.asmx.
h. In the Properties window, change the Name property from Service1
to AuthorsService.
i. In Solution Explorer, right-click the Service1.asmx file, click
Rename and rename the file AuthorsService.asmx, to match the
service name.
2. Create and configure a a. In Server Explorer, right-click the Data Connections node and
database connection and choose Add Connection from the shortcut menu.
data adapter. b. In the Connection tab of the Data Link Properties dialog box, in the
Select or enter a server name drop down, type (local).
c. Select Use Windows NT Integrated security for the logon
information.
Info: If you do not have integrated security set up on your system, see your
network administrator.
d. Select the pubs database from the drop down below the Select the
database on the server radio button.
e. Click Test Connection to validate the information you provided.
f. Click OK.
g. Click OK to establish the connection.
h. A new node appears in the Data Connections node of Server
Explorer.
Info: If the database connection fails, see your database administrator.
i. In Server Explorer, expand the node for the new connection.
j. Expand the Tables node.
k. Expand the authors node to show the fields in the authors table.
Creating a distributed application with C# 5

l. Using the mouse (and the Ctrl key for multiple selection) select the
au_id, au_lname, au_fname, and city fields.
m. Drag these fields from Server Explorer onto the design surface on the
right.
A SqlConnection object paired with a SqlDataAdapter object appear in the
designer. A connection has now been created to the database, with the
transfer of information to be handled by the SqlDataAdapter object. These
components are configured to move a dataset with the authors table in and
out of the database.
3. Create a DataSet class n. Click Data | Generate Dataset.
definition. o. In the Generate Dataset dialog box, select New and name the dataset
authors1. Do not check Add this dataset to the designer.
p. Click OK.
Note: A dataset schema file, authors1.xsd, is created and added to the
project. This schema file contains a class definition for authors1. This
class, which inherits from the DataSet class, contains a typed dataset
definition for the authors table.
Caution: If you are planning on coding in C#, this name is case sensitive.
q. Click File | Save All.
4. Adding methods that will be r. Click View | Code (or press F7).
exposed by the XML Web A window with pre-populated code should appear.
Service.
s. Scroll through that window till you find a commented out block of
code showing how to define a HelloWorld function.
t. Replace this code with a new method named GetAuthors to deliver a
dataset to the client (Snippet1):
Note: The snippets in this lab can be found in the file C:\Microsoft Hands-
on-Lab\DEV-HOL22\HOL022_Snippets_CS.txt
// C#
[WebMethod]
public authors1 GetAuthors()
{
authors1 authors = new authors1();
sqlDataAdapter1.Fill(authors);
return authors;
}
u. Insert the following code fragment (Snippet2) to define another method
named UpdateAuthors to propagate changes from the client back to
the database.
// C#
[WebMethod]
public authors1 UpdateAuthors(authors1
authorChanges)
{
if (authorChanges != null)
{
sqlDataAdapter1.Update(authorChanges);
return authorChanges;
}
else
{
return null;
}
}
6 Creating a Distributed Application with C#

Info: In a production application, you would add error checking and


exception handling to these methods
v. Click File | Save All.
w. Click Build | Build Solution (or press CTRL+SHIFT+B).
x. You should see a message in the Output window saying that 1 build
succeeded.
Creating a distributed application with C# 7

Exercise 2
Creating a Windows Forms User Interface

Scenario
In this exercise, you will create two versions of the client interface that will consume the Web
Service. In this exercise you will build a traditional Windows Form. Exercise 3 will then show you
how to create a Web Forms interface.

Tasks Detailed steps

1. Create the Windows a. Click File | Add Project | New Project.


Application. b. Select Visual C# Projects in the Project Types pane.
c. Select Windows Application in the Templates pane.
d. Name the project AuthorsWinClient and click OK.
e. The AuthorsWinClient project is added to the solution.
Form1 is automatically added to the project and appears in the Windows
Forms Designer.
f. In the Solution Explorer, right-click the AuthorsWinClient project
and click Add Web Reference on the shortcut menu.
The Add Web Reference dialog should appear.
g. Click the Web services on the local machine link.
After a short pause a list of all web services defined on this machine should
appear.
h. Click the AuthorsService link.
i. Click Add Reference.
You can now call the AuthorsService web service from your windows
application.
2. Add controls to the form. a. Click View | Toolbox to open the windows with available UI
components.
b. Drag a DataGrid control from the Windows Forms tab of the
Toolbox onto the form.
c. Click and drag the lower right corner to resize it, filling the empty
space on the form. Leave enough room at the top to add two buttons.
d. Hover over the Toolbox tab on the left side of the screen to open it.
e. Drag a Button control from the Windows Forms tab of the Toolbox
onto the form.
f. Change the button Name property to LoadData and its Text property
to Load using the Properties pane at the bottom right of the IDE.
g. Drag another Button control from the Windows Forms tab of the
Toolbox onto the form.
h. Change the button Name property to SaveData and its Text property
to Save.
i. Drag a DataSet object from the Data tab of the Toolbox onto the form.
8 Creating a Distributed Application with C#

j. The Add DataSet dialog box appears.


k. Accept Typed dataset and AuthorsWinClient.localhost.authors1 in
the Name drop down.
l. Click OK.
m. This action creates a DataSet object in the component tray (below the
form design surface) that is based on the Authors1 dataset class
definition.
n. Select the DataSet object in the component tray.
o. Change the Name property (NOT the DataSetName property) to
AuthorData.
p. Select the DataGrid control and change the DataSource property by
selecting AuthorData from the drop down (under the (DataBindings)
node in the Properties pane).
q. Select authors from the DataMember property list.
r. The column headings of the DataGrid are set to the authors table
column names. You may need to expand Form1 and the DataGrid.
3. Adding code for the a. Double-click the LoadData button to create an empty event handler for
LoadData and SaveData the Click event.
buttons. b. Add the following code (Snippet3) to the method.
Info: If the XML Web service is not running on your local computer, you
will need to replace localhost in the code example with the name of the
server running the XML Web service.
// C#
AuthorsWinClient.localhost.AuthorsService ws =
new
AuthorsWinClient.localhost.AuthorsService();
ws.Credentials =
System.Net.CredentialCache.DefaultCredentials;
AuthorData.Merge(ws.GetAuthors());
c. Click View | Designer. (or press Shift+F7)
d. Double-click the Save button to create an empty event handler for the
Click event.
e. Add the following code (Snippet4) to the handler:
// C#
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);
}
4. Run the application. a. Click File | Save All.
b. Right-click the AuthorsWinClient project in the Solution Explorer,
Creating a distributed application with C# 9

and click Set as StartUp Project.


c. Click Debug | Start or press F5 to run the application.
A window is displayed that contains an empty table with headers from the
authors table in the pubs database.
d. Click Load to populate the table, make some changes
e. Click Save to save changes you make.
f. Close the Form.
10 Creating a Distributed Application with C#

Exercise 3
Creating a Web Forms User Interface

Scenario
In this exercise, you will learn how to create an alternative interface based using Web Forms.

Tasks Detailed steps

1. Create the Web Forms a. Click File | Add Project | New Project.
application. b. In the Add New Project dialog box, select Visual C# Projects in the
Project Types pane.
c. Select ASP.NET Web Application in the Templates pane.
d. In the Location box, type http://localhost/AuthorsWebClient.
e. Click OK.
f. A new project is added to Solution Explorer.
A Web Forms page named WebForm1.aspx is added to the project and is
loaded into the designer.
g. In the Solution Explorer, right-click the AuthorsWebClient project
and click Add Web Reference.
The Add Web Reference dialog should appear.
h. Click the Web services on the local machine link.
i. Click the AuthorsService link.
j. Click Add Reference.
You can now create an instance of the authors1 dataset in your application.
2. Add controls to the Web a. If not in Design View click the Design tab under the Code Editor
page. window for WebForm1.aspx.
b. Right-click the Web Form in the Design view and click Properties.
c. In the Page Layout drop down select FlowLayout.
d. Click OK.
e. Drag a DataSet object from the Data tab of the Toolbox onto the form.
f. Accept Typed dataset and AuthorsWebClient.localhost.authors1 in
the Name list.
g. Click OK.
h. A DataSet object is added to the component tray.
i. Select the DataSet object in the component tray.
j. Change the Name property to AuthorData.
k. Drag a DataGrid control from the Web Forms tab of the Toolbox
onto the form.
l. In the Properties pane for the DataGrid control, change the
DataSource property to AuthorData.
m. Change the DataMember property to authors.
n. The column headings of the DataGrid are set to the authors table
Creating a distributed application with C# 11

column names.
Info: To support in-place editing in the DataGrid control, you need to add
an Edit, Update, Cancel column, which will contain an Edit button. When
the user clicks the Edit button, the contents of the row will be displayed in
text boxes, and the Edit button will be replaced by Update and Cancel
buttons.
o. Click the Property Builder link at the bottom of the Properties pane.
p. Select the Columns tab in the left pane.
q. Expand the Button Column node in the Available Columns pane.
r. Select Edit, Update, Cancel.
s. Click the add > button.
t. Click OK.
3. Add code for the Edit, a. Right-click the Web Form and select View Code. (Or, press F7)
Update, and Cancel b. Add the following code (Snippet5) to the existing Page_Load event
buttons. handler to fill the DataGrid control, replacing the comment:
// C#
AuthorsWebClient.localhost.AuthorsService ws =
new
AuthorsWebClient.localhost.AuthorsService();
ws.Credentials =
System.Net.CredentialCache.DefaultCredentials;
AuthorData.Merge(ws.GetAuthors());
if (! Page.IsPostBack)
{
DataGrid1.DataBind();
}
Note: Now we need to create an event handler for the EditCommand event
raised when the user clicks the Edit button.
c. Press SHIFT+F7 to switch to design view.
d. Select the DataGrid1 control.
e. In the Properties window, click the Events (yellow thunderbolt
button) button to display the list of DataGrid events.
f. Double-click the EditCommand event.
g. Add the following code (Snippet6) to the DataGrid1_EditCommand
event handler:
// C#
DataGrid1.EditItemIndex = e.Item.ItemIndex;
DataGrid1.DataBind();
Note: Now we need to create an event handler for the CancelCommand
event raised when the user clicks the Cancel button.
h. Press SHIFT+F7 to switch to design view.
i. Select the DataGrid1 control.
j. In the Properties window, click the Events (yellow thunderbolt
button) button to display the list of DataGrid events.
k. Double-click the CancelCommand event.
l. Add the following code (Snippet7) to the
DataGrid1_CancelCommand event handler in order to set the
EditItemIndex property to -1 so that the current row is displayed as
text again.
// C#
12 Creating a Distributed Application with C#

DataGrid1.EditItemIndex = -1;
DataGrid1.DataBind();
Note: Now we need to create an event handler for the UpdateCommand
event raised when the user clicks the Update button.
m. Press SHIFT+F7 to switch to design view.
n. Select the DataGrid1 control.
o. In the Properties window, click the Events (yellow thunderbolt
button) button to display the list of DataGrid events.
p. Double-click the UpdateCommand event.
q. Add the following code (Snippet8) to the
DataGrid1_UpdateCommand event handler:
// C#
// 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();
r. Click File | Save all.
4. Configure Integrated a. Click Start | Administrative Tools | Internet Information Services.
Windows authentication. Info: In order to allow your web client to access the database, you will
need to change the IIS properties to pass your Windows credentials to
ASP.NET, as per the following instructions.
b. Expand CLIENT1 (local computer).
c. Expand Web Sites.
d. Expand Default Web Site.
e. Right-click AuthorsWebClient and click Properties.
f. Click the Directory Security tab.
g. Click the Edit button in the Anonymous access and authentication
control section.
Creating a distributed application with C# 13

h. Clear the Anonymous Access check box.


i. Ensure that the Integrated Windows authentication checkbox is
selected.
j. Click OK.
k. Click OK.
l. Close Internet Information Services.
You have now configured your web application directory.
m. Return to the project in Visual Studio, double-click the Web.config
under AuthorsWebClient in the Solution Explorer.
n. Add the following tag on the line after the <system.web> tag to
configure integrated security for your XML Web service:
<identity impersonate="true"/>
5. Test the Web Page. a. Right-click AuthorsWebClient in the Solution Explorer and click Set
as StartUp Project.
b. Click Debug | Start (or press F5) to run the application.
c. When the page loads, click Edit for any of the rows and change some
data.
Note that because of column constraints in the Database, and error will
occur if you attempt to edit the au_id.
d. Click Update to save the changes.
e. Close the browser.

Você também pode gostar