Search
Search titles only
By:
Search titles only
By:
Log in
Register
Search
Search titles only
By:
Search titles only
By:
Menu
Install the app
Install
Forums
New posts
All threads
Latest threads
New posts
Trending threads
Trending
Search forums
What's new
New posts
New ads
New profile posts
Latest activity
Free Ads
Latest reviews
Search ads
Members
Current visitors
New profile posts
Search profile posts
Contact us
Latest ads
Premium Land with House for Sale
anil1961
Updated:
Friday at 10:15 AM
AWS Certified Solutions Architect-Associate + AWS Certified Cloud Practitioner
Sanjeewani95
Updated:
Aug 19, 2026
🚀 එක පැකේජ් එකයි - මාසෙටම Unlimited Internet! 🌐
sayuru bandara
Updated:
Aug 18, 2026
🎬 CapCut Pro 1 Month Access! LKR 600
sayuru bandara
Updated:
Aug 18, 2026
🚀 Google One AI PRO Plan (Gemini Pro Activation) – 18 Months Access! LKR 2200
sayuru bandara
Updated:
Aug 18, 2026
Electronics
Vehicles
Property
Search
Reply to thread
Forums
General
ElaKiri Talk!
WCF ගැන දන්න අය පොඩ්ඩක් එන්ඩෝ....
Get the App
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Message
<blockquote data-quote="ZoomLine" data-source="post: 21338307" data-attributes="member: 561907"><p><strong>Introduction</strong></p><p></p><p> This article discusses the simplest way to write, configure and consume Windows Communication Foundation (WCF) service, using Visual Studio 2010. This would help gain a better understanding to WCF services which is slightly different from ASP.NET web services.</p><p> <strong>Background</strong></p><p></p><p> We would look into writing and consuming a simple service using VS2010. </p><p><strong>Scenario</strong>: Book store service that would fetch the book information. </p><p> At the end of the article, you would know: </p><p> </p><ul> <li data-xf-list-type="ul">How to build a WCF service</li> <li data-xf-list-type="ul">How to consume WCF service in Windows Forms</li> <li data-xf-list-type="ul">How to bind custom object with DataGridView</li> <li data-xf-list-type="ul">How to configure WCF Service while publishing</li> <li data-xf-list-type="ul">How to convert XElement to custom object using LINQ</li> </ul><p> Also, you might be interested in <a href="http://izlooite.blogspot.com/2010/01/wcf-why-use-messagecontract-when.html" target="_blank">Why use MessageContract when DataContract is there?</a>; an article that I wrote some time back. BTW, we will use both in this example.</p><p> <strong>Steps to Follow </strong></p><p></p><p> Let's create a WCF Service Library project. Visual Studio 2010 <em>stubs-in</em> a default service which it calls Service1. Let's ignore this existing service for a while now. We would create a separate service that would return the list of books requested by the client end. </p><p> <strong>Note</strong> that to just to keep things simple, we would use XML file as our data store; taken from <a href="http://msdn.microsoft.com/en-us/library/ms762271%28VS.85%29.aspx" target="_blank">MSDN</a>.</p><p> The XML has columns: Author, Title, Genre, Price, Publish Date, Description, and Book ID. </p><p> The Book ID, which is a string shall be used as primary key to identify the book. </p><p> We would add a book interface that shall define what this service provides as book service. So, we want to provide a service that returns the list of books found based upon user criteria. </p><p> Add a new item as interface called IBookService under namespace Store. Add the directive, using System.ServiceModel; </p><p>Decorate the interface with service contract attribute as [ServiceContract]. </p><p> We want the following functionality as a scope of this sample: </p><p> </p><ul> <li data-xf-list-type="ul">List of all books</li> <li data-xf-list-type="ul">Filter functionality; return a book or a list of books given its ID or Title or Genre or Author</li> </ul><p> <strong>Note</strong> that we will also look into the <a href="http://msdn.microsoft.com/en-us/library/dd264739.aspx" target="_blank">.NET default/optional arguments functionality</a> that is provided in C# v4.0, as a part of this sample while we implement the above methods.</p><p> The interface shall contain the methods. </p><p> Let’s define the operations for IBookService interface: </p><p> Hide Copy Code</p><p>namespace Store { [ServiceContract] interface IBookService { [OperationContract] List GetAllBooks();//Get all books; returns list of books [OperationContract] List GetBookByID(string BookID);//Gets a(single) book by ID [OperationContract] List Filter(string Author, string Genre, string Title); //Returns list of //books by specified filter } } Let's add a Book type and define the attributes of the book that we want for the client to have. For now, it's all those attributes that are there in the XML data. </p><p> Right click on the Book return type, and select Generate Class for Book. This shall generate the class of type Book. Note that you also write the attributes where it is to be used and VS shall add those attributes in the class automatically.</p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig1.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p><p> FIG 1: Book service interface </p><p> If you select the generate new type, it will show the following window and provide you with the options about class. Its Access specifier, Kind (class, struct, etc.), and either to create a new file and stub the code in the current file. We would select a separate file.</p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig2.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p><p> FIG 2: Add Book data type</p><p> Right click on the Book return type and select Goto Definition.</p><p> Add the directive using ServiceModel, and using System.Runtime.Serialization;. And DataContract attribute on Book class; it would look like the following:</p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig3.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p><p> FIG 3: List of book attributes, similar to XML element attributes.</p><p> In figure 3, note that the ID is of type string, ideally IDs should be of integer type, when using as primary keys, integers keys work faster than the string keys. The reason we are using the string type primary key is that we have string data in the XML data store. </p><p> Let's decorate theBook class with DataContract attribute. </p><p> A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged. </p><p> Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. </p><p> Let's add the types that are required ID, Title, Author, Description, Genre, Price, and Publish Date and tag all members with[DataMember] attribute. </p><p> Now, we will add a class BookService that implements the IBookService interface; </p><p> The book service shall contain the definition. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig4.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p><p> FIG 4: Implement book service interface</p><p> <strong>Note</strong>, in case if you plan on using the database (and not the XML which is a part of this example), you can use <strong>Enterprise Library, Data Application Block</strong> for your data transactions; you will need to add a reference to the <em>Data.dll</em> file, generally available in the <em>DRIVE:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin</em>.</p><p> Now let's add the implementation of the methods. First, there this is a small GetDb() method, that loads the data from given XML and into the XDocument object. </p><p> Then, since we interested in the book nodes, therefore we select all the books. </p><p> The select new Book() creates a new object and copies the data from book attribute into our defined book object attribute. So by the end of the book structure "}" is complete, we have our book object ready to be inserted into the List object. </p><p> Implementing both the methods using XDocument and LINQ, answers the question, how to convert XElement to custom object using LINQ.</p><p> Hide Copy Code</p><p>public List GetAllBooks() { XDocument db = GetDb(); List lstBooks = (from book in db.Descendants("book") select new Book() { ID = book.Attribute("id").Value //Get attribute from XML and //set into the Book object attribute. , Author = book.Element("author").Value , Genre = book.Element("genre").Value , Price = Convert.ToDecimal(book.Element("price").Value) , Description = book.Element("description").Value , PublishDate = Convert.ToDateTime(book.Element("publish_date").Value) , Title = book.Element("title").Value }).ToList(); //Cast it into the list return lstBooks; } The above is the method that gets all of the books in the datastore. Now, let's add the definition for GetBookByID(). The method is the same as get all books, except for the where clause. Note that this shall be only one book in this case, so the list shall contain only one item. </p><p> Hide Copy Code</p><p>public List GetBookByID(string BookID) { XDocument db = GetDb(); //Howto: Convert XElements to Custom Object List lstBooks = (from book in db.Descendants("book") where book.Attribute("id").Value.Equals(BookID) select new Book() //Instantiate a new object { ID = book.Attribute("id").Value , Author = book.Element("author").Value , Genre = book.Element("genre").Value , Price = Convert.ToDecimal(book.Element("price").Value) , Description = book.Element("description").Value , PublishDate = Convert.ToDateTime(book.Element("publish_date").Value) , Title = book.Element("title").Value }).ToList(); return lstBooks; } The above code gets a book given its ID using LINQ. </p><p> <strong>Configuration and Deployment</strong></p><p></p><p> Add the service definition in <em>app.config</em> file under system.serviceModel/services tag.</p><p> The system.serviceModel/services tag contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications. </p><p> Hide Copy Code</p><p><service name="Store.BookService"> <endpoint binding="basicHttpBinding" contract="Store.IBookService"></endpoint> </service> basicHttpBinding represents a binding that a service can use to configure and expose endpoints that are able to communicate with ASMX-based Web services and clients and other services that conform to the <a href="http://msdn.microsoft.com/en-us/library/ms733080.aspx" target="_blank">WS-I Basic Profile 1.1</a> [<a href="http://msdn.microsoft.com/en-us/library/ms733080.aspx" target="_blank">^</a>] . Contract is the name of the interface that we expose. </p><p> Note that a WCF service requires an <em>application host</em>, in order to run and be accessible to clients. </p><p> We have a couple of options here, for instance: </p><p> </p><ul> <li data-xf-list-type="ul">Create a custom host application</li> <li data-xf-list-type="ul">Build a Windows service application</li> <li data-xf-list-type="ul">Using IIS</li> </ul><p> In our case, we would use IIS to simply publish the service. </p><p> Right click on the project and select Publish, would generate the following directory structure in IIS. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig5.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 5: Configure WCF Service in IIS</p><p> Just for your interest, if you are using a version prior to VS2010 to configure a WCF service, following is the manual process: </p><p> </p><ul> <li data-xf-list-type="ul">Ensure that you have the binary files being built inside the <em>\bin</em> folder, rather than <em>\debug</em> or <em>\release</em> folder.</li> <li data-xf-list-type="ul">Add a service definition file, a file having <em>.svc</em> extension.</li> <li data-xf-list-type="ul">Add a new item, select the Text File template; rename the file to <em>BookService.Svc</em>. This shall contain the service definitions.</li> </ul><p> Fortunately, Visual Studio 2010 does that for us. </p><p> We also need to tell the IIS that our service is going to use the .NET Framework version 4.0, so that it does not use its default .NET framwork. </p><p> Fig 6 shows how to change the framework that IIS is going to use for our app. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig6.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 6: Change app's framework in IIS</p><p> <strong>Publish in IIS</strong></p><p></p><p> In order to be able to be accessible to the outside world, we need to allow access. You can open the URL in IE and see it works. In my case, for instance, I have it under WCF folder <em><a href="http://localhost/WCF/Store.BookService.svc" target="_blank">http://localhost/WCF/Store.BookService.svc</a></em>. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig7_small.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p><p> FIG 7: Open service URL in the browser</p><p> <strong>Note</strong> the highlighted text in the above image. This requires a service behavior to be added in the <em>config</em> file, which Visual Studio 2010 <em>stubs</em> in for us automatically.</p><p> You will need to set the httpGetEnabled attribute to true, in order to publish your service metadata. It's a Boolean value that specifies whether to publish service metadata for retrieval using an HTTP/Get request. The default is false. </p><p> To save and publish the service into IIS, click on Save, Publish. </p><p> Now you can open the URL again in Internet Explorer, and you should be able to see your service's meta. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig8_small.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 8: Book service in Internet Explorer </p><p> Quick way to see the wsdl, type ?wsdl in the address bar to see the wsdl, like: <a href="http://localhost/WCF/Store.BookService.svc?wsdl">http://localhost/WCF/Store.BookService.svc?wsdl</a>.</p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig9.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 9: Book service WSDL listing</p><p> <strong>How to Consume WCF Service?</strong></p><p></p><p> We would create a small forms based client app that would show a couple of filter options, and provide a search button that requests the service for books based upon the filter provided by the user. </p><p> Add a Windows Forms project and design the form. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig10.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 10: Client user interface (UI) </p><p> To be able to consume the service, we will need to add a reference to that service. So when you try to add the service reference, the IDE discovers all the services on your system. Alternatively, you can provide the path that you have of the service. </p><p> Note that web services, by nature, are of public type. Though, WCF adds the Service, Message, and Data level contracts; but the service itself is public. </p><p> So right click on the WCF Client project and add a service reference. In your client app, add the service reference. </p><p> Add following as the service reference URI: <a href="http://localhost/WCF/Store.BookService.svc?wsdl" target="_blank">http://localhost/WCF/Store.BookService.svc?wsdl</a>. I would rename the reference to SvcBookstore. </p><p> <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig12_small.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /> </p><p> Fig 11: Client user interface (UI)</p><p> Since, at this point, we have already added the service reference, therefore we can access it by adding the using directive in the forms class, and then declaring the object of the service; exactly similar to how we add/declare other .NET objects. Let's declare the service object in our form. And add using directives. </p><p> <strong>One important thing:</strong> What if you are in the middle of developing real world WCF Services, and now you want to test it. And while testing using a demo client app, your service is throwing exception that you have hell no idea of. So in that case, a "<strong>natural</strong>" scenario a developer wants is that you should able to "step into (F11)" the service code and see if for yourself. That is going be to a great help. So, if this is the case, you can always go back to your service configuration file and add a serviceDebug within behavior element. </p><p> Hide Copy Code</p><p><servicedebug includeexceptiondetailinfaults="True" /> serviceDebug allows the client app to receive exception details in faults for debugging purposes, when set to true. DO NOT forget to set to false before deployment to avoid disclosing exception information. </p><p> So, if you want to get the service related exception here at the client end, add a tag in service. Because, at this point, you might want to<em> step into</em> it. </p><p> <strong>Client Code</strong></p><p></p><p> So, let's add the final code that collects the filter specified by the user, and call the service. When the data is retrieved, you can simply just assign object array to .DataSource property to show on Grid. Following the output of the client. </p><p> Hide Copy Code</p><p>private void button1_Click(object sender, EventArgs e) { //Get the combo choice, if there is any. string strGenre = cbxGenre.SelectedIndex > -1 ? cbxGenre.SelectedItem.ToString() : string.Empty; //Declare the books array; though the actual return type is List<books />, //it actually gets casted into //Book[] array. Book[] lstBooks = null; //Discard other filters, if user has entered a book id if (!string.IsNullOrEmpty(txtID.Text)) { lstBooks = bookService.GetBookByID(txtID.Text); } else { //Lets get books by filter. lstBooks = bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); } //Set datasource, custom object. dataGridView1.DataSource = lstBooks; } Did you notice bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); line in the code above? </p><p> That's what the named arguments are. Named arguments <em>free you</em> from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. Named arguments can follow positional arguments. </p><p> As an example, if at some point, for this client app, user only provides the Author to look for, you can provide only the author to this method. Like: bookService.Filter(Author: "Paulo Coelho"); </p><p> <strong>Note</strong> that you will have to update the Service's .Filter() method and provide the default arguments; for instance, like the following: </p><p> Hide Copy Code</p><p>public List<book> Filter(string Author = "N/A", string Genre = "N/A", string Title = "N/A") <img src="https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig14.jpg" alt="" class="fr-fic fr-dii fr-draggable " style="" /></p></blockquote><p></p>
[QUOTE="ZoomLine, post: 21338307, member: 561907"] [B]Introduction[/B] This article discusses the simplest way to write, configure and consume Windows Communication Foundation (WCF) service, using Visual Studio 2010. This would help gain a better understanding to WCF services which is slightly different from ASP.NET web services. [B]Background[/B] We would look into writing and consuming a simple service using VS2010. [B]Scenario[/B]: Book store service that would fetch the book information. At the end of the article, you would know: [LIST] [*]How to build a WCF service [*]How to consume WCF service in Windows Forms [*]How to bind custom object with DataGridView [*]How to configure WCF Service while publishing [*]How to convert XElement to custom object using LINQ [/LIST] Also, you might be interested in [URL="http://izlooite.blogspot.com/2010/01/wcf-why-use-messagecontract-when.html"]Why use MessageContract when DataContract is there?[/URL]; an article that I wrote some time back. BTW, we will use both in this example. [B]Steps to Follow [/B] Let's create a WCF Service Library project. Visual Studio 2010 [I]stubs-in[/I] a default service which it calls Service1. Let's ignore this existing service for a while now. We would create a separate service that would return the list of books requested by the client end. [B]Note[/B] that to just to keep things simple, we would use XML file as our data store; taken from [URL="http://msdn.microsoft.com/en-us/library/ms762271%28VS.85%29.aspx"]MSDN[/URL]. The XML has columns: Author, Title, Genre, Price, Publish Date, Description, and Book ID. The Book ID, which is a string shall be used as primary key to identify the book. We would add a book interface that shall define what this service provides as book service. So, we want to provide a service that returns the list of books found based upon user criteria. Add a new item as interface called IBookService under namespace Store. Add the directive, using System.ServiceModel; Decorate the interface with service contract attribute as [ServiceContract]. We want the following functionality as a scope of this sample: [LIST] [*]List of all books [*]Filter functionality; return a book or a list of books given its ID or Title or Genre or Author [/LIST] [B]Note[/B] that we will also look into the [URL="http://msdn.microsoft.com/en-us/library/dd264739.aspx"].NET default/optional arguments functionality[/URL] that is provided in C# v4.0, as a part of this sample while we implement the above methods. The interface shall contain the methods. Let’s define the operations for IBookService interface: Hide Copy Code namespace Store { [ServiceContract] interface IBookService { [OperationContract] List GetAllBooks();//Get all books; returns list of books [OperationContract] List GetBookByID(string BookID);//Gets a(single) book by ID [OperationContract] List Filter(string Author, string Genre, string Title); //Returns list of //books by specified filter } } Let's add a Book type and define the attributes of the book that we want for the client to have. For now, it's all those attributes that are there in the XML data. Right click on the Book return type, and select Generate Class for Book. This shall generate the class of type Book. Note that you also write the attributes where it is to be used and VS shall add those attributes in the class automatically. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig1.jpg[/IMG] FIG 1: Book service interface If you select the generate new type, it will show the following window and provide you with the options about class. Its Access specifier, Kind (class, struct, etc.), and either to create a new file and stub the code in the current file. We would select a separate file. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig2.jpg[/IMG] FIG 2: Add Book data type Right click on the Book return type and select Goto Definition. Add the directive using ServiceModel, and using System.Runtime.Serialization;. And DataContract attribute on Book class; it would look like the following: [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig3.jpg[/IMG] FIG 3: List of book attributes, similar to XML element attributes. In figure 3, note that the ID is of type string, ideally IDs should be of integer type, when using as primary keys, integers keys work faster than the string keys. The reason we are using the string type primary key is that we have string data in the XML data store. Let's decorate theBook class with DataContract attribute. A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged. Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Let's add the types that are required ID, Title, Author, Description, Genre, Price, and Publish Date and tag all members with[DataMember] attribute. Now, we will add a class BookService that implements the IBookService interface; The book service shall contain the definition. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig4.jpg[/IMG] FIG 4: Implement book service interface [B]Note[/B], in case if you plan on using the database (and not the XML which is a part of this example), you can use [B]Enterprise Library, Data Application Block[/B] for your data transactions; you will need to add a reference to the [I]Data.dll[/I] file, generally available in the [I]DRIVE:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin[/I]. Now let's add the implementation of the methods. First, there this is a small GetDb() method, that loads the data from given XML and into the XDocument object. Then, since we interested in the book nodes, therefore we select all the books. The select new Book() creates a new object and copies the data from book attribute into our defined book object attribute. So by the end of the book structure "}" is complete, we have our book object ready to be inserted into the List object. Implementing both the methods using XDocument and LINQ, answers the question, how to convert XElement to custom object using LINQ. Hide Copy Code public List GetAllBooks() { XDocument db = GetDb(); List lstBooks = (from book in db.Descendants("book") select new Book() { ID = book.Attribute("id").Value //Get attribute from XML and //set into the Book object attribute. , Author = book.Element("author").Value , Genre = book.Element("genre").Value , Price = Convert.ToDecimal(book.Element("price").Value) , Description = book.Element("description").Value , PublishDate = Convert.ToDateTime(book.Element("publish_date").Value) , Title = book.Element("title").Value }).ToList(); //Cast it into the list return lstBooks; } The above is the method that gets all of the books in the datastore. Now, let's add the definition for GetBookByID(). The method is the same as get all books, except for the where clause. Note that this shall be only one book in this case, so the list shall contain only one item. Hide Copy Code public List GetBookByID(string BookID) { XDocument db = GetDb(); //Howto: Convert XElements to Custom Object List lstBooks = (from book in db.Descendants("book") where book.Attribute("id").Value.Equals(BookID) select new Book() //Instantiate a new object { ID = book.Attribute("id").Value , Author = book.Element("author").Value , Genre = book.Element("genre").Value , Price = Convert.ToDecimal(book.Element("price").Value) , Description = book.Element("description").Value , PublishDate = Convert.ToDateTime(book.Element("publish_date").Value) , Title = book.Element("title").Value }).ToList(); return lstBooks; } The above code gets a book given its ID using LINQ. [B]Configuration and Deployment[/B] Add the service definition in [I]app.config[/I] file under system.serviceModel/services tag. The system.serviceModel/services tag contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications. Hide Copy Code <service name="Store.BookService"> <endpoint binding="basicHttpBinding" contract="Store.IBookService"></endpoint> </service> basicHttpBinding represents a binding that a service can use to configure and expose endpoints that are able to communicate with ASMX-based Web services and clients and other services that conform to the [URL="http://msdn.microsoft.com/en-us/library/ms733080.aspx"]WS-I Basic Profile 1.1[/URL] [[URL="http://msdn.microsoft.com/en-us/library/ms733080.aspx"]^[/URL]] . Contract is the name of the interface that we expose. Note that a WCF service requires an [I]application host[/I], in order to run and be accessible to clients. We have a couple of options here, for instance: [LIST] [*]Create a custom host application [*]Build a Windows service application [*]Using IIS [/LIST] In our case, we would use IIS to simply publish the service. Right click on the project and select Publish, would generate the following directory structure in IIS. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig5.jpg[/IMG] Fig 5: Configure WCF Service in IIS Just for your interest, if you are using a version prior to VS2010 to configure a WCF service, following is the manual process: [LIST] [*]Ensure that you have the binary files being built inside the [I]\bin[/I] folder, rather than [I]\debug[/I] or [I]\release[/I] folder. [*]Add a service definition file, a file having [I].svc[/I] extension. [*]Add a new item, select the Text File template; rename the file to [I]BookService.Svc[/I]. This shall contain the service definitions. [/LIST] Fortunately, Visual Studio 2010 does that for us. We also need to tell the IIS that our service is going to use the .NET Framework version 4.0, so that it does not use its default .NET framwork. Fig 6 shows how to change the framework that IIS is going to use for our app. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig6.jpg[/IMG] Fig 6: Change app's framework in IIS [B]Publish in IIS[/B] In order to be able to be accessible to the outside world, we need to allow access. You can open the URL in IE and see it works. In my case, for instance, I have it under WCF folder [I][url]http://localhost/WCF/Store.BookService.svc[/url][/I]. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig7_small.jpg[/IMG] FIG 7: Open service URL in the browser [B]Note[/B] the highlighted text in the above image. This requires a service behavior to be added in the [I]config[/I] file, which Visual Studio 2010 [I]stubs[/I] in for us automatically. You will need to set the httpGetEnabled attribute to true, in order to publish your service metadata. It's a Boolean value that specifies whether to publish service metadata for retrieval using an HTTP/Get request. The default is false. To save and publish the service into IIS, click on Save, Publish. Now you can open the URL again in Internet Explorer, and you should be able to see your service's meta. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig8_small.jpg[/IMG] Fig 8: Book service in Internet Explorer Quick way to see the wsdl, type ?wsdl in the address bar to see the wsdl, like: <a href="http://localhost/WCF/Store.BookService.svc?wsdl">http://localhost/WCF/Store.BookService.svc?wsdl</a>. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig9.jpg[/IMG] Fig 9: Book service WSDL listing [B]How to Consume WCF Service?[/B] We would create a small forms based client app that would show a couple of filter options, and provide a search button that requests the service for books based upon the filter provided by the user. Add a Windows Forms project and design the form. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig10.jpg[/IMG] Fig 10: Client user interface (UI) To be able to consume the service, we will need to add a reference to that service. So when you try to add the service reference, the IDE discovers all the services on your system. Alternatively, you can provide the path that you have of the service. Note that web services, by nature, are of public type. Though, WCF adds the Service, Message, and Data level contracts; but the service itself is public. So right click on the WCF Client project and add a service reference. In your client app, add the service reference. Add following as the service reference URI: [url]http://localhost/WCF/Store.BookService.svc?wsdl[/url]. I would rename the reference to SvcBookstore. [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig12_small.jpg[/IMG] Fig 11: Client user interface (UI) Since, at this point, we have already added the service reference, therefore we can access it by adding the using directive in the forms class, and then declaring the object of the service; exactly similar to how we add/declare other .NET objects. Let's declare the service object in our form. And add using directives. [B]One important thing:[/B] What if you are in the middle of developing real world WCF Services, and now you want to test it. And while testing using a demo client app, your service is throwing exception that you have hell no idea of. So in that case, a "[B]natural[/B]" scenario a developer wants is that you should able to "step into (F11)" the service code and see if for yourself. That is going be to a great help. So, if this is the case, you can always go back to your service configuration file and add a serviceDebug within behavior element. Hide Copy Code <servicedebug includeexceptiondetailinfaults="True" /> serviceDebug allows the client app to receive exception details in faults for debugging purposes, when set to true. DO NOT forget to set to false before deployment to avoid disclosing exception information. So, if you want to get the service related exception here at the client end, add a tag in service. Because, at this point, you might want to[I] step into[/I] it. [B]Client Code[/B] So, let's add the final code that collects the filter specified by the user, and call the service. When the data is retrieved, you can simply just assign object array to .DataSource property to show on Grid. Following the output of the client. Hide Copy Code private void button1_Click(object sender, EventArgs e) { //Get the combo choice, if there is any. string strGenre = cbxGenre.SelectedIndex > -1 ? cbxGenre.SelectedItem.ToString() : string.Empty; //Declare the books array; though the actual return type is List<books />, //it actually gets casted into //Book[] array. Book[] lstBooks = null; //Discard other filters, if user has entered a book id if (!string.IsNullOrEmpty(txtID.Text)) { lstBooks = bookService.GetBookByID(txtID.Text); } else { //Lets get books by filter. lstBooks = bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); } //Set datasource, custom object. dataGridView1.DataSource = lstBooks; } Did you notice bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); line in the code above? That's what the named arguments are. Named arguments [I]free you[/I] from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. Named arguments can follow positional arguments. As an example, if at some point, for this client app, user only provides the Author to look for, you can provide only the author to this method. Like: bookService.Filter(Author: "Paulo Coelho"); [B]Note[/B] that you will have to update the Service's .Filter() method and provide the default arguments; for instance, like the following: Hide Copy Code public List<book> Filter(string Author = "N/A", string Genre = "N/A", string Title = "N/A") [IMG]https://www.codeproject.com/KB/WCF/WCF-Service-Create-Config/fig14.jpg[/IMG] [/QUOTE]
Insert quotes…
Verification
Dahaya deken beduwama keeyada?
Post reply
Top
Bottom