Creating a Service Reference Regardless of what type of application you’re building, you create a reference to a Web service, called a service reference, in the same way.. You’ll see the
Trang 1Normally, you don’t want to deploy the App_Data folder because it might hold a database file that is huge and would slow down your application considerably Of course, if you have SQL Server Express installed at the deployment location and need the database in App_Data to be deployed, check this box to include the database in the deployment Click Publish to deploy your service
When deployment is complete, you’ll see a message on the VS status bar stating either Publish Succeeded or Publish Failed If publishing fails, open the Output window, CTRL-W,
O, to see the reason why There are many reasons a deployment can fail, so look at the error message to see if it’s something that makes sense to you Verify that your Web site
is properly set up, as explained in the preceding section Other sources of information include the Microsoft Developer Network (MSDN), at http://msdn.microsoft.com, where you can search for Knowledge Base support articles Alternatively, you can copy the error message and paste it into your favorite search engine Many problems with deployment surround IIS setup, so it is worthwhile to learn more about how IIS works McGraw-Hill
offers Windows Server 2008: A Beginner’s Guide, by Marty Matthews (2008), which
does include IIS 7 information There’s also a Windows Server 2003 edition if you are deploying to IIS 6
Now that you know how to develop and deploy a WCF service, you’ll need to know how to write programs that use that service, which is covered next
Communicating with a WCF Service
Any NET application can communicate with a Web service In fact, one of the benefits of having a Web service is to expose functionality that can be used by multiple applications
In theory, any application on any platform can communicate via Web services because the underlying technology relies on open standards, such as HTTP and XML In practice, the goal of cross-platform communication is an advanced technique accomplished by architects and engineers with detailed knowledge of the inner workings of Web services For just getting started, it’s sufficient to know that you can communicate with Web services with any .NET technology The following sections show you how to make your applications, clients, communicate with Web services Let’s look at the task of generally creating a reference to a Web service first
Creating a Service Reference
Regardless of what type of application you’re building, you create a reference to a Web service, called a service reference, in the same way You start off with a project, any project type—Console, WPF, ASP.NET, or Silverlight will do Right-click the project
Trang 2and select Add Service Reference You’ll see the Add Service Reference window,
shown in Figure 11-11
As you may recall from previous discussion in this chapter, we spent some time on
setting up a Web service and configuring the Web service address Now the address comes into focus because it is where the Web service is deployed—you type it into the Address
box in the Add Service Reference window, shown in Figure 11-11 If you are using the
Web server built into VS to use a Web service project in the same solution, it is convenient
to click the Discover button, which will give you a list of Web services in the same
solution as the project you are adding the service reference to The address in Figure 11-11
is different from what you’ll see on your computer because the project name, port number, and service name will be different
If you need to use a deployed Web service, you would put the address of the deployed Web service in the Address box For example, earlier in this chapter you saw how we deployed
a Web service to the local IIS server and that to use that deployed Web service you would
Figure 11-11 The Add Service Reference window
Trang 3put http://localhost:8080/WcfDemo.CustomerService.svc into the Address box In the
deployed service, the service name might not be WcfDemo.CustomerService.svc as shown
in this demo To find out what the real service name file should be, navigate to the physical directory where the service was deployed to and use the file name of the *.svc file Sometimes, you’ll need to use Web services by third parties or another organization in your company In those cases, you’ll get the address to use from a person in the other organization or read their documentation to learn what address to use If you add your own address, click Go to get more information on the Web service
After either clicking Discover or adding an address and clicking Go, you’ll have one or more services in the Services list At this point, if you receive an error, it will be because the address is incorrect, the service is experiencing an outage, or (in the case
of referencing a service in your own project) the service won’t compile First check the address if you entered it yourself If you are referencing a project in your solution, go back and recompile the Web Service project to make sure it builds, fix any problems, and try
to create the service reference again Once you’ve ensured that you’ve corrected all the problems on your side of the wire, contact whoever owns the Web service to troubleshoot the problem
When a Web service can be communicated with successfully, you’ll see the list
of services You can drill down on each service until you find the interface for the
service you’re interested in In Figure 11-11, the ICustomerService is selected, which displays all available operations Looking back at the previous discussion of creating the CustomerService, you can see the interface that was created and the methods If you don’t see an interface or a method, check the attributes in the code to ensure the interface
has a ServiceContract attribute and that any methods that should be exposed have an
OperationContract attribute
The Web service will create a proxy, which is a class that communicates with the Web service, in your project, using the default namespace declared in the Properties for your project The namespace in the Add Service Reference defaults to Service1, and you’ll want
to change that to something meaningful, such as CustomerService, as shown in Figure 11-11
This will result in a proxy class created in MyProjectNamespace.CustomerService This is
important to know because you will need to create an instance of the proxy and must know the namespace that the proxy resides in Click OK to create the service reference such as the one shown in Figure 11-12
As you can see in Figure 11-12, the project has a new folder, named Service References The CustomerService reference under ServiceReferences is named after the namespace you specified in the Add Service Reference window
Trang 4Now that you have a service reference, you can use it in any NET application The
following section shows you how to write code to communicate with the Web service
Coding Web Service Calls
This section will explain how to write code that communicates with a Web service You’ll
see explanations of the individual statements required to call the Web service and then
you’ll see the entire listing of all of those statements together The program that calls
the Web service is a Console application You should create a new Console application
and add the code in this section inside of the Main method If you felt like skipping
ahead before reading the explanation, you can see the entire code listing of the Console
application that calls the Web service in Listing 11-7 However, we’ll begin at the first
statement and follow until you see all of the code that’s required to call and interact with
the CustomerService Web service created in the preceding sections
When creating a service reference, as explained in the preceding section, VS will
generate a new class, called a proxy The proxy looks just like your Web service class
but doesn’t contain any of the same code Instead, the proxy will translate calls from
the client and communicate with the Web service The proxy, created after adding the
service reference in the preceding section, is named CustomerServiceClient Remember
to add a using statement (Imports in VB) for the Web service proxy Since the default
Figure 11-12 A new service reference in a project
Trang 5namespace of the example code for this chapter is CustomerConsole, the namespace
of the Web service proxy is CustomerConsole.CustomerService Here’s code that
instantiates the proxy:
C#:
var svc = new CustomerServiceClient();
VB:
Dim svc = New CustomerServiceClient
The proxy is named after the service reference, with Client appended to the name As with any other class, you instantiate the proxy, resulting in a reference to the proxy, named svc Using the proxy makes your code feel like everything is in the same project, but really the proxy makes a call over HTTP, sending an XML package to the Web service The Web service translates the XML into a method call, executes the code for the method call, and translates the results back into XML Meanwhile, the proxy is waiting on the Web service and will receive the XML response, translate that response into a NET object, and pass the object back to your calling code If the method returns void instead of
a type, then there isn’t any value to return
With the service reference, you can begin communicating with the Web service The
following example creates a new customer record, calling the InsertCustomer method on
the Web service proxy:
C#:
var newCust = new Customer
{
Age = 36,
Birthday = new DateTime(1974, 8, 22),
Income = 56000m,
Name = "Venus"
};
var newCustID = svc.InsertCustomer(newCust);
VB:
Dim newCust = New Customer
With newCust
.Age = 36
.Birthday = New DateTime(1974, 8, 22)
.Income = 56000
Trang 6.Name = "Venus"
End With
Dim newCustID As Integer
newCustID = svc.InsertCustomer(newCust)
At this point, you might be wondering where the Customer type came from As you
may recall from the previous section of the chapter that discussed custom objects, the
Customer type is a proxy type for the Customer that was defined in LINQ to SQL Since
we set the Serialization Mode of the LINQ to SQL entity model to Unidirectional, the Web service was able to pass the definition of the Customer with the Web service interface,
resulting in a Customer proxy
To perform the insert operation, use the service proxy reference, svc, to pass the
instance of the Customer proxy The following example shows how to get a specified
customer from the Web service:
C#:
Customer cust = svc.GetCustomer(newCustID);
VB:
Dim cust As New Customer
cust = svc.GetCustomer(newCustID)
Here, the service proxy reference is used to call GetCustomer with an ID of the requested
customer, returning an instance of the Customer proxy The next example shows how to
update a Customer instance:
C#:
cust.Income = 49000m;
svc.UpdateCustomer(cust);
VB:
cust.Income = 49000
svc.UpdateCustomer(cust)
The cust reference in this example is the same reference that was created previously
In this example, we are only changing the Income property Next, we use the service
proxy to call the UpdateCustomer method, passing the Customer proxy reference If you
Trang 7wanted to see the changes that were made, you could call the GetCustomer method again, like this:
C#:
Customer updatedCust = svc.GetCustomer(cust.CustomerID);
VB:
Dim updatedCust As Customer
updatedCust = svc.GetCustomer(cust.CustomerID)
Similarly, you can delete a Customer, as follows:
C#:
svc.DeleteCustomer(updatedCust.CustomerID);
VB:
svc.DeleteCustomer(updatedCust.CustomerID)
As in the previous example, we use the service proxy reference to call the DeleteCustomer method, passing in an ID from the updated customer The updatedCust reference was from the previous call to GetCustomer If you wanted to get all of the Customer records from the Web service, you could call GetCustomers, like this:
C#:
Customer[] customers = svc.GetCustomers();
VB:
Dim customers As Customer()
customers = svc.GetCustomers()
While this is similar to other method calls in previous examples, you might notice that
the return value from GetCustomers here is an array of Customer, Customer[] (Customer()
in VB) However, the Web service defined GetCustomers as returning a List of Customer,
List<Customer> (List(Of Customer) in VB), as specified in the ICustomerService
interface in Listing 11-2 and implemented in the CustomerService class in Listing 11-5
As you may recall, the proxy is responsible for translating the XML return value from the Web service into an object, or collection of objects in this case By default, the proxy translates all collections into an array However, you can change the return collection type
by right-clicking the Service Reference in your project and selecting Configure Service Reference, showing the Service Reference Settings window in Figure 11-13
Trang 8Most of the items in the Service Reference Settings are advanced options, but focus
on the Collection Type setting in the Data Type section Switch the Collection Type from
System.Array to System.Collections.Generic.List and click OK to close Then change the
previous call to GetCustomers to the following:
C#:
List<Customer> customers = svc.GetCustomers();
VB:
Dim cust As New Customer
cust = svc.GetCustomer(newCustID)
Figure 11-13 The Service Reference Settings window
Trang 9This example shows that the proxy will translate the results into a List<Customer> (List(Of Customer) in VB) While I showed you how to make this setting after creating
the Web service, I chose this sequence because it shows the value of changing the collection return type However, you can make this setting when first creating the Web reference Looking at Figure 11-11, you can see an Advanced button at the bottom of the Add Service Reference window Clicking the Advanced button will show you the Service Reference Settings window, shown in Figure 11-13, allowing you to set the collection return type when first creating the service reference
Now, you’ve seen all five operations of the Web service Remember that exactly the same techniques are used here as in any other type of NET application For your convenience, Listing 11-7 shows you the entire example for using a Web service
Listing 11-7 An application using a Web service
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CustomerConsole.CustomerService;
namespace CustomerConsole
{
class Program
{
static void Main()
{
var svc = new CustomerServiceClient();
var newCust = new Customer
{
Age = 36,
Birthday = new DateTime(1974, 8, 22),
Income = 56000m,
Name = "Venus"
};
var newCustID = svc.InsertCustomer(newCust);
Console.WriteLine("New Customer ID: " + newCustID); Customer cust = svc.GetCustomer(newCustID);
Trang 10Console.WriteLine("New Customer: " + cust.Name);
cust.Income = 49000m;
svc.UpdateCustomer(cust);
Customer updatedCust = svc.GetCustomer(cust.CustomerID);
Console.WriteLine("Economic Adjustment: " + cust.Income);
svc.DeleteCustomer(updatedCust.CustomerID);
//Customer[] customers = svc.GetCustomers();
List<Customer> customers = svc.GetCustomers();
Console.WriteLine("\nAll Customers:\n");
foreach (var custItem in customers)
{
Console.WriteLine(custItem.Name);
}
Console.ReadKey();
}
}
}
VB:
Imports CustomerConsoleVB.CustomerService
Module Module1
Sub Main()
Dim svc = New CustomerServiceClient
Dim newCust = New Customer
With newCust
Age = 36
Birthday = New DateTime(1974, 8, 22)
Income = 56000
Name = "Venus"
End With
Dim newCustID As Integer