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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

The CompositeTypeclass is prefixed with the [DataContract]attribute. This class defines the various composite data types required by your service.

The Service1.csfile contains the implementation for the operations defined in the IService1interface in 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 class name "Service1" here, you must also update the

// reference to "Service1" in App.config.

public class Service1 : IService1 {

public string GetData(int value) {

return string.Format("You entered: {0}", value);

}

public CompositeType GetDataUsingDataContract(CompositeType composite) {

if (composite.BoolValue) {

composite.StringValue += "Suffix";

}

return composite;

}

}

}

For now, use the default implementation provided by Visual Studio 2008 and examine how the service works.

Press F5 to debug the service. A WCF Test Client window will be displayed (see Figure 20-9). This is a test client shipped with Visual Studio 2008 to help you test your WCF service.

Figure 209 Expand the IService1item and select the GetDatamethod In the - фото 460

Figure 20-9

Expand the IService1item, and select the GetData()method. In the right of the window, enter 5 for the value and click the Invoke button (see Figure 20-10).

Figure 2010 When you see a security warning dialog click OK The service - фото 461

Figure 20-10

When you see a security warning dialog, click OK. The service returns its result in the Response pane (see Figure 20-11).

Figure 2011 Also try the GetDataUsingDataContractoperation and enter some - фото 462

Figure 20-11

Also, try the GetDataUsingDataContract()operation and enter some values as shown in Figure 20-12. Click Invoke, and observe the results returned.

Figure 2012 You can also see the SOAP messages exchanged between the test - фото 463

Figure 20-12

You can also see the SOAP messages exchanged between the test client and the service by clicking on the XML tab (see Figure 20-13).

Figure 2013 Notice that the SOAP messages contain a lot more information than - фото 464

Figure 20-13

Notice that the SOAP messages contain a lot more information than a traditional ASMX Web Service SOAP packet. This is because WCF services, by default, use wsHttpBinding, which ensures that information exchanged between the client and the service is encrypted automatically.

You'll see more about wsHttpBindinglater in this chapter.

Close the WCF Test Client window. Back in Visual Studio 2008, edit the IService1.csfile, adding the getAge()function signature to the IService1interface:

[ServiceContract]

public interface IService1 {

[OperationContract]

string GetData(int value);

[OperationContract]

CompositeType GetDataUsingDataContract(CompositeType composite);

[OperationContract]

int getAge(Contact c);

}

By default, the [OperationContract]attribute specifies a request/response messaging pattern for the operation.

After the class definition for CompositeType, define the following data contract called Contact:

[DataContract]

public class CompositeType {

//...

}

[DataContract]

public class Contact {

[DataMember]

public string Name { get; set; }

[DataMember]

public int YearofBirth { get; set; }

}

In Service1.cs, define the getAge()function as follows:

public class Service1 : IService1 {

//...

//...

public int getAge(Contact c) {

return (DateTime.Now.Year - c.YearofBirth);

}

}

Press F5 to test the application again. This time, select the getAge()method, enter your name and year of birth, and then click Invoke (see Figure 20-14). Observe the result returned by the service.

Figure 2014 Consuming the WCF Service The example you just created is a WCF - фото 465

Figure 20-14

Consuming the WCF Service

The example you just created is a WCF Service Library. The useful aspect of the project is that it includes the WCF Test Client, which enables you to test your WCF easily without needing to build your own client. In this section, you build a Windows application to consume the service.

Add a Windows Forms Application project to the current solution, and name it ConsumeWCFService.

Add a service reference to the WCF service created in the previous section. Because the WCF Service is in the same solution as the Windows Forms application, you can simply click the Discover button in the Add Service Reference dialog to locate the service (see Figure 20-15).

Figure 2015 Use the default ServiceReference1name and click OK Visual Studio - фото 466

Figure 20-15

Use the default ServiceReference1name, and click OK. Visual Studio 2008 automatically adds the two libraries — System.Runtime.Serialization.dlland System.ServiceModel.dll— to your project (see Figure 20-16). The proxy class ServiceReference1is the reference to the WCF service.

Figure 2016 Doubleclick on Form1 and in the Form1Loadevent handler code - фото 467

Figure 20-16

Double-click on Form1, and in the Form1_Loadevent handler, code the following:

private void Form1_Load(object sender, EventArgs e) {

//---create an instance of the service---

ServiceReference1.Service1Client client =

new ConsumeWCFService.ServiceReference1.Service1Client();

//---create an instance of the Contact class---

ServiceReference1.Contact c =

new ConsumeWCFService.ServiceReference1.Contact() {

Name = "Wei-Meng Lee", YearofBirth = 1990

};

//---calls the service and display the result---

MessageBox.Show(client.getAge(c).ToString());

//---close the client---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x