Rio Oktora Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.
Rio Oktora Forum


 
IndeksPortalLatest imagesPencarianPendaftaranLogin

 

 Windows Communication Framework Dengan Microsoft Visual Studio

Go down 
PengirimMessage
Administrator
Admininstrator
Admininstrator
Administrator


Jumlah posting : 321
Join date : 09.05.09
Lokasi : Bandar Lampung

Windows Communication Framework Dengan Microsoft Visual Studio Empty
PostSubyek: Windows Communication Framework Dengan Microsoft Visual Studio   Windows Communication Framework Dengan Microsoft Visual Studio Icon_minitimeThu May 19, 2011 11:20 pm

One of the talks I'm giving at the upcoming DevConnections conference in Las Vegas the week of November 6th covers moving from Web Services to Service Oriented Architectures (SOAs). Part of the talk will discuss how well Windows Communication Framework (WCF) satisfies SOA principles so I thought I'd put together a step by step tutorial on building a simple WCF service and client. To run the examples you'll need the .NET 3.0 components from Microsoft as well as the VS.NET 2005 "Orcas" additions (optional). At the time this blog was written .NET 3.0 wasn't available in a production release but that will change very soon.

WCF services can be exposed in several different ways such as HTTP and TCP. For this example I'll demonstrate how to build a simple HTTP WCF service that is hosted using Internet Information Services (IIS).

Step 1: Defining the Data Contract

A data contract defines the data that will be passed between a service and a client. To create a data contract using WCF there are different attributes that can be used. For this example I'll use the DataContract and DataMember attributes. The DataContract attribute applies to a class whereas the DataMember attribute applies to a field or property (although I'd highly recommend using public properties as opposed to public fields). An example of creating a simple contract to exchange data between a service and a client using a Customer class is shown next:
[DataContract]
public class Customer {
string _FirstName;
string _LastName;

[DataMember]
public string FirstName {
get { return _FirstName; }
set { _FirstName = value; }
}

[DataMember]
public string LastName {
get { return _LastName; }
set { _LastName = value; }
}
}

I typically prefer to model my data contracts using XML schemas (.xsd files). This way I know that messages exchanged between the client and service are based upon global standards which helps to eliminate interop issues across different platforms. With .NET you can use the xsd.exe tool (with the /classes switch) to generate classes. In WCF you can use the new svcutil.exe tool. For example, to automatically generate a data contract class from an existing schema the following can be run at the command prompt:

svcutil.exe /dconly schemaName.xsd

The /dconly switch says to create the data contract class from the types defined in the schema.

Step 2: Defining the Service Interface

Once the data that will be passed between the service and client is defined (the data contract) you can create the service interface. This is also done using WCF attributes. In this example I'll use the ServiceContract and OperationContract attributes. An example of using them in an interface named ICustomerService is shown next:
[ServiceContract()]
public interface ICustomerService
{
[OperationContract]
Model.Customer[] GetCustomers();
[OperationContract]
Model.Customer GetCustomer(string custID);
}

This interface defines two members named GetCustomers and GetCustomer. With .NET 1.1, attributes defined on interfaces wouldn't carry over to the class that implements the interface. Fortunately, in .NET 2.0 this has been changed and the attributes will follow the interface wherever it is implemented.
Step 3: Defining the Service

A WCF service is easy to create whether you have the VS.NET 2005 .NET 3.0 tools installed or not. Services exposed using IIS has a .svc file extension rather than the .asmx extension used with ASP.NET Web Services. The .svc file contains a ServiceHost attribute that points to a code-behind file that contains the actual service code.

<% @ServiceHost Language=C# Service="CustomerService"
CodeBehind="~/App_Code/Service.cs" %>

Since the data contract and service interface have already been defined, creating a service is straightforward and only requires that the ICustomerService interface be implemented:
public class CustomerService : ICustomerService
{
public Model.Customer[] GetCustomers()
{
return Biz.BAL.GetCustomers();
}
public Model.Customer GetCustomer(string custID)
{
return Biz.BAL.GetCustomer(custID);
}
}

Looking through the service code you'll notice that the methods delegate all work to a business layer class named BAL that is in the Biz namespace. The BAL object in turn calls a data layer object named DAL which handles all database calls. This layered architecture is a good practice to follow for many reasons one of which is code re-use across different types of applications. For example, a local ASP.NET application could call the business layer code directly rather than having to serialize/deserialize messages by calling the WCF service (although in cases where you want all applications to call the service (following SOA principles) it's very efficient now if .NET 3.0 components are available to use by the applications). For those that need to add additional behaviors to services such as transaction support, the ServiceBehavior attribute can be applied to the service itself and related attributes can be applied to methods.

Step 4: Creating a Service Client

To create a service client that can consume the service created in steps 1 - 3 you can use the svcutil.exe tool and run the following at the command-prompt:

svcutil.exe http://www.site.com/service.svc?wsdl

The utility will generate a proxy class (C# or VB.NET can be choosen using switches) based upon the types and operations defined in the Web Service Description Language (WSDL) file that can be used to call the service. It will also generate configuration data for the client application to use. An example of the default configuration data generated by the tool that can be used to call the customer service is shown next:





closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00"
sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
inactivityTimeout="00:10:00"
enabled="false" />

proxyCredentialType="None" realm="" />
negotiateServiceCredential="true"
algorithmSuite="Default"
establishSecurityContext="true" />





binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ICustomerService"
contract="ICustomerService"
name="WSHttpBinding_ICustomerService">








An example of calling the service using the WCF client proxy is shown next:
protected void Page_Load(object sender, EventArgs e)
{
CustomerServiceClient proxy = new CustomerServiceClient();
lblOutput.Text = proxy.GetCustomer("ALFKI").ContactName;
}

Conclusion

That's all of the steps required to create a simple WCF service. While it could be argued that ASMX services are easier to create (slap a WebMethod attribute on a method and you're basically done), I really like the fact that creating WCF services encourages developers to follow contract-first design principles (designing the data contract, service interface and then the service). This should help with Web Service interoperability issues between different platforms and languages. There is of course much more to WCF than has been covered in this article. Read more about it at http://msdn.microsoft.com/webservices.

The code for this example can be downloaded at the following URL:
Kembali Ke Atas Go down
http://riooktora.nstars.org
Administrator
Admininstrator
Admininstrator
Administrator


Jumlah posting : 321
Join date : 09.05.09
Lokasi : Bandar Lampung

Windows Communication Framework Dengan Microsoft Visual Studio Empty
PostSubyek: Re: Windows Communication Framework Dengan Microsoft Visual Studio   Windows Communication Framework Dengan Microsoft Visual Studio Icon_minitimeThu May 19, 2011 11:20 pm

Translate :


Salah satu pembicaraan saya memberikan pada konferensi DevConnections mendatang di Las Vegas pada minggu 6 November mencakup bergerak dari Web Services untuk Service Oriented Arsitektur (SOA). Bagian dari pembicaraan akan membahas seberapa baik Windows Communication Framework (WCF) memenuhi prinsip SOA jadi saya pikir saya akan menyusun langkah demi langkah tutorial tentang membangun layanan WCF sederhana dan klien. Untuk menjalankan contoh Anda akan memerlukan NET 3.0. Komponen dari Microsoft serta VS.NET 2005 "Orcas" tambahan (opsional). Pada saat blog ini ditulis NET 3.0 tidak tersedia dalam siaran produksi tapi itu akan berubah sangat segera..

layanan WCF bisa terkena beberapa cara berbeda seperti HTTP dan TCP. Untuk contoh ini saya akan menunjukkan bagaimana membangun layanan HTTP sederhana WCF yang di-host menggunakan Internet Information Services (IIS).

Langkah 1: Mendefinisikan Data Kontrak

Sebuah kontrak data mendefinisikan data yang akan dilalui antara layanan dan klien. Untuk membuat kontrak data menggunakan WCF ada atribut yang berbeda yang dapat digunakan. Untuk contoh ini saya akan menggunakan DataContract dan atribut DataMember. Atribut DataContract berlaku untuk kelas sedangkan atribut DataMember berlaku untuk bidang atau properti (walaupun saya akan sangat merekomendasikan menggunakan sifat umum sebagai lawan dari bidang umum). Contoh membuat kontrak sederhana untuk pertukaran data antara layanan dan klien menggunakan kelas Customer ditunjukkan berikut ini:
[DataContract]
public class Nasabah {
_FirstName string;
_LastName string;

[DataMember]
public string FirstName {
mendapatkan _FirstName {return;}
set {_FirstName = nilai;}
}

[DataMember]
public string LastName {
mendapatkan _LastName {return;}
set {_LastName = nilai;}
}
}

Saya biasanya lebih suka model data saya kontrak menggunakan skema XML (file xsd.). Dengan cara ini saya tahu bahwa pesan yang dipertukarkan antara klien dan pelayanan didasarkan pada standar global yang membantu untuk menghilangkan masalah Interop di platform yang berbeda. Dengan. NET Anda dapat menggunakan alat xsd.exe (dengan switch kelas /) untuk menghasilkan kelas. Dalam WCF Anda dapat menggunakan alat svcutil.exe baru. Misalnya, untuk secara otomatis menghasilkan data kontrak kelas dari skema yang ada berikut ini dapat dijalankan di command prompt:

svcutil.exe / dconly schemaName.xsd

Switch / dconly mengatakan untuk membuat kelas data kontrak dari jenis yang didefinisikan dalam skema.

Langkah 2: Mendefinisikan Layanan Interface

Setelah data yang akan dilalui antara layanan dan klien didefinisikan (kontrak data) Anda dapat membuat antarmuka layanan. Hal ini juga dilakukan dengan menggunakan atribut WCF. Dalam contoh ini saya akan menggunakan atribut ServiceContract dan OperationContract. Sebuah contoh penggunaan dalam interface bernama ICustomerService ditunjukkan berikut ini:
[ServiceContract ()]
antarmuka publik ICustomerService
{
[OperationContract]
Model.Customer [] GetCustomers ();
[OperationContract]
Model.Customer GetCustomer (string custID);
}

Interface ini mendefinisikan dua anggota bernama GetCustomers dan GetCustomer. Dengan. NET 1.1, atribut yang didefinisikan pada antarmuka tidak akan membawa ke kelas yang mengimplementasikan antarmuka. Untungnya, di NET 2.0. Ini telah berubah dan atribut akan mengikuti antarmuka mana pun itu akan diterapkan.
Langkah 3: Mendefinisikan Layanan

Sebuah layanan WCF mudah untuk menciptakan apakah Anda memiliki 3.0 VS.NET 2005. NET alat diinstal atau tidak. Layanan terkena menggunakan IIS memiliki ekstensi file. SVC daripada ekstensi asmx. Digunakan dengan ASP.NET Web Services. File. SVC berisi atribut ServiceHost yang menunjuk ke kode-balik file yang berisi kode layanan yang sebenarnya.

% CodeBehind = "~ / App_Code / Service.cs">%

Karena kontrak layanan data dan antarmuka telah didefinisikan, menciptakan layanan sangat mudah dan hanya mensyaratkan bahwa antarmuka ICustomerService dilaksanakan:
public class customerservice: ICustomerService
{
publik Model.Customer [] GetCustomers ()
{
kembali Biz.BAL.GetCustomers ();
}
publik Model.Customer GetCustomer (string custID)
{
kembali Biz.BAL.GetCustomer (custID);
}
}

Melihat melalui kode layanan yang Anda akan melihat bahwa metode mendelegasikan pekerjaan semua lapisan kelas bisnis bernama BAL yang ada di dalam namespace Biz. Objek UUPA pada gilirannya panggilan lapisan data nama obyek DAL yang menangani semua panggilan database. Arsitektur berlapis adalah praktik yang baik untuk diikuti untuk satu alasan banyak yang re-use code di berbagai jenis aplikasi. Sebagai contoh, sebuah aplikasi ASP.NET lokal bisa memanggil kode lapisan bisnis secara langsung daripada harus serialize / deserialize pesan dengan memanggil layanan WCF (meskipun dalam kasus-kasus di mana Anda ingin semua aplikasi untuk memanggil layanan (prinsip berikut SOA) itu sangat efisien sekarang jika. NET 3.0 komponen yang tersedia untuk digunakan oleh aplikasi). Bagi mereka yang perlu menambahkan perilaku tambahan untuk layanan seperti dukungan transaksi, atribut ServiceBehavior dapat diterapkan untuk servis itu sendiri dan atribut terkait dapat diterapkan untuk metode.

Langkah 4: Membuat Client Service

Untuk membuat klien layanan yang dapat mengkonsumsi layanan yang dibuat dalam langkah 1 - 3 Anda dapat menggunakan alat svcutil.exe dan menjalankan berikut pada command prompt:

svcutil.exe http://www.site.com/service.svc?wsdl

Utilitas yang akan menghasilkan kelas proxy (C # atau VB.NET dapat dipilih dengan menggunakan saklar) berdasarkan jenis dan operasi yang didefinisikan di file Web Service Description Language (WSDL) yang dapat digunakan untuk memanggil layanan tersebut. Hal ini juga akan menghasilkan data konfigurasi untuk aplikasi klien untuk menggunakan. Contoh dari data konfigurasi default yang dihasilkan oleh alat yang dapat digunakan untuk memanggil layanan pelanggan ditunjukkan berikut ini:





closeTimeout = "00:01:00"
openTimeout = "00:01:00" receiveTimeout = "00:10:00"
sendTimeout = "00:01:00"
bypassProxyOnLocal = "false" transactionFlow = "false"
hostNameComparisonMode = "StrongWildcard"
maxBufferPoolSize = "524288"
maxReceivedMessageSize = "65536"
messageEncoding = "Teks" textEncoding = "utf-8"
useDefaultWebProxy = "true"
allowCookies = "false">
maxArrayLength = "16384"
maxBytesPerRead = "4096"
maxNameTableCharCount = "16384" />
reliableSession inactivityTimeout = "00:10:00"
enabled = "false" />

proxyCredentialType = "Tidak ada" alam = "" />
negotiateServiceCredential = "true"
algorithmSuite = "Default"
establishSecurityContext = "true" />





mengikat = "wsHttpBinding"
bindingConfiguration = "WSHttpBinding_ICustomerService"
kontrak = "ICustomerService"
name = "WSHttpBinding_ICustomerService">








Contoh memanggil layanan menggunakan proxy WCF klien ditunjukkan berikut ini:
void dilindungi Page_Load (object sender, EventArgs e)
{
CustomerServiceClient proxy CustomerServiceClient = new ();
lblOutput.Text = proxy.GetCustomer ("ALFKI") ContactName.;
}

Kesimpulan

Itu semua langkah yang diperlukan untuk membuat layanan WCF sederhana. Sementara itu dapat dikatakan bahwa ASMX jasa lebih mudah untuk membuat (tamparan atribut WebMethod metode dan pada dasarnya Anda dilakukan), saya benar-benar menyukai fakta bahwa menciptakan layanan WCF mendorong pihak pengembang untuk mengikuti prinsip-prinsip desain kontrak-pertama (merancang data kontrak, antarmuka layanan dan kemudian servis). Hal ini akan membantu dengan isu-isu interoperabilitas Web Service antara platform dan bahasa yang berbeda. Ada tentu saja jauh lebih banyak untuk WCF dari telah tercakup dalam artikel ini. Baca lebih lanjut tentang itu di http://msdn.microsoft.com/webservices.

Kode untuk contoh ini dapat didownload di URL berikut:
Kembali Ke Atas Go down
http://riooktora.nstars.org
 
Windows Communication Framework Dengan Microsoft Visual Studio
Kembali Ke Atas 
Halaman 1 dari 1
 Similar topics
-
» Windows Communication Framework
» Windows Communication Foundation ( Yudi )
» Daftar Nilai Mahasiswa (Net. Framework) TI/SI 2009 (Update 3 Mei 2011)

Permissions in this forum:Anda tidak dapat menjawab topik
Rio Oktora Forum :: Universitas Bandar Lampung :: Fakultas Ilmu Komputer-
Navigasi: