Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

To add a reference to the Web Service, right-click the project name in Solution Explorer and select Add Service Reference (see Figure 20-3).

Figure 203 In the Add Service Reference dialog enter the URL for the Web - фото 454

Figure 20-3

In the Add Service Reference dialog, enter the URL for the Web Service that you created earlier (see Figure 20-4). Because the Web Service is in the current solution, you can also click the Discover button to locate the Web Service.

Figure 204 In Visual Studio 2008 the Add Service Reference option replaces - фото 455

Figure 20-4

In Visual Studio 2008, the Add Service Reference option replaces the Add Web Reference option. That's because WCF is the preferred way to write your services in Visual Studio 2008. The exception to this is when developing Windows Mobile applications — for those, the Add Web Reference option is available, but the Add Service Reference item is not.

Give a name to the Web Service (say, StocksWebService), and click OK. A reference to the Web Service is added to the project (see Figure 20-5).

Figure 205 The StocksWebServiceis a proxy class generated by Visual Studio - фото 456

Figure 20-5

The StocksWebServiceis a proxy class generated by Visual Studio 2008 to handle all the work of mapping parameters to XML elements and then sending the SOAP messages over the network to the Web Service. Behind the scenes, Visual Studio has actually downloaded the WSDL (Web Services Description Language) document from the Web Service so that it knows exactly what the service offers and requires. You can view the WSDL document of the document by appending ?WSDLto the end of the Web Services URL, like this:

http://localhost:1044/Service1.asmx?WSDL

To access the services provided by the Web Service, you programmatically create an instance of the proxy class and then call the appropriate methods. Here's the code for the Check Price button:

private void btnCheckPrice_Click(object sender, EventArgs e) {

StocksWebService.Service1SoapClient ws =

new StocksPriceChecker.StocksWebService.Service1SoapClient();

MessageBox.Show("Price for " + txtSymbol.Text + " is " +

ws.GetStockPrice(txtSymbol.Text));

}

Set the StocksPriceCheckerproject as the startup project in Visual Studio 2008, and press F5 to debug the application. When you enter a stock symbol and click Check Price, the Web Service returns the price of the specified stock (see Figure 20-6).

Figure 206 From this very simple example you want to note the following - фото 457

Figure 20-6

From this very simple example, you want to note the following:

□ You need to host even a simple ASMX Web Service on a web server such as IIS.

□ To access the Web Service, clients use HTTP, a stateless protocol, which means that every request is treated like a new one. If you want to write an application that requires the Web Service to remember its previous state, you need to implement your own "stateful" mechanism.

□ The ASMX Web Service uses a request/response communication model. The Web Service only responds when requested by the client. In this example, if you need to monitor the price of a stock and want to be notified whenever a stock falls below a certain price, you must constantly poll the Web Service to retrieve the latest price. A better way would be to have a service that can automatically invoke the client when specific events happen on the service's end. You'll see how this can be done with WCF later in this chapter.

Comparing WCF with ASMX Web Services

Now that you've created a traditional ASMX Web Service, let's compare ASMX and WCF and see how they differ:

□ ASMX Web Services use web methods that are exposed to the world. Web methods use the request/response communication models. In WCF, these web methods are known as operations , and you can use any one of the three different types of communication models: one-way transaction, request/response, and full-duplex.

□ Web services use the Simple Object Access Protocol (SOAP) messaging transported over HTTP. WCF can utilize different protocols for messaging — SOAP, Plain Old XML (POX), and so on — transported over a wide variety of communication protocols, including TCP and HTTP.

□ Web services listen at a particular port number (such as port 80); WCF can have multiple endpoints listening at different port numbers.

□ Web services are hosted by web servers (such as IIS); WCF can be hosted in different forms, such as Windows services, Windows applications, or just processes.

Your First WCF Service

Developing a WCF service using Visual Studio 2008 will be helpful in comparing it with the traditional ASMX Web Services.

Using Visual Studio 2008, create a new WCF Service Library application, and name it WcfServiceLibraryTest(see Figure 20-7).

Figure 207 Notice the two files created in the project see Figure 208 - фото 458

Figure 20-7

Notice the two files created in the project (see Figure 20-8):

iService1.cscontains the service contract as well as the data contract.

Service1.cscontains the implementation of the contract defined in the IService1.csfile.

Figure 208 Heres the content of the IService1csfile using System using - фото 459

Figure 20-8

Here's the content of the IService1.csfile:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WcfServiceLibraryTest {

// NOTE: If you change the interface name "IService1" here, you must also

// update the reference to "IService1" in App.config.

[ServiceContract]

public interface IService1 {

[OperationContract]

string GetData(int value);

[OperationContract]

CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: Add your service operations here

}

// Use a data contract as illustrated in the sample below to add composite

// types to service operations

[DataContract]

public class CompositeType {

bool boolValue = true;

string stringValue = "Hello ";

[DataMember]

public bool BoolValue {

get { return boolValue; }

set { boolValue = value; }

}

[DataMember]

public string StringValue {

get { return stringValue; }

set { stringValue = value; }

}

}

}

Here, there is an interface ( IService1) and a class ( CompositeType) defined. The IService1interface is set with the [ServiceContract]attribute to indicate that this is a service contract and contains signatures of operations exposed by the service. Within this interface are signatures of methods that you will implement in the Service1.csfile. Each method is set with the [OperationContract]attribute to indicate that it is an operation. If you have additional operations to add, you can add them here.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x