Saturday 27 July 2013

WINDOW COMMUNICATION FOUNDATION IN DOT NET BY ANIL KUMAR

WCF

WCF IS MICROSOFT DISTRIBUTED APPLICATION WHICH SUPPORT THE DISTRIBUTED ENVIRONMENT IN TO A SINGLE FRAMEWORK.
Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ.

IN WCF
 IN WCF SINGLE BUSINESS LOGIC COMMUNICATE WITH BOTH WINDOW OR WEB BASED APPLICATION AND CAN BE USED BY ANY LANGUAGE AND TECHNOLOGY IT CAN BE USED IN JAVA, ASP, AND PHP TECHNOLOGY, MEANS IT IS A STANDARD FORMAT WHICH IS SUPPORTABLE BY ANY TECHNOLOGY
        >>>> WCF IS SOFTWARE INDEPENDENT
CLIENT

BUSINESS LOGICS
     >>>>>> WCF IS PROTOCOL INDEPENDENT    


                                                                                          REQUEST


                                                                     RESPONSE
                               ANY TECHNOLOGY, WINDOW      ,WEB BASED AND ANY TYPE OF TECHNOLOGY 

IMP
  AND IF WE WANT TO IMPLEMENT A SERVICES WHICH CAN BE USED BY BOTH WINDOW BASE APPLICATION AND WEB BASED APPLICATION THAN WE WILL USE WCF TECHNIQUE TO IMPLEMENT THESE TYPE OF SERVICES
WEB BASED APPLICATION
 WINDOW BASE APPLICATION
 


                                                                            
 



TCP/IP                                                                                       HTTP

CONNECTION ORIENTED                                          CONNECTION LESS

>>> TO IMPLEMENT DISTRIBUTED APPLICATION IN WINDOW WE USED REMOTING
STANDARD OF REMOTING
1.       MARSHAL OBJECT
2.       TCP/IP
3.       CHANNEL
4.       .NET (BOTH APPLICATION ARE IN .NET)
5.       BINARY FORMAT
DEMERITS := BOTH SIDE AT CLIENT SIDE AND SERVER SIDE .NET SHOULD BE INSTALLED AND DISADVANTAGES OF WEB SERVICES IS THAT CAN WORK ONLY


SERVICE ORIENTED ARCHITECTRE( SOA):-

In software engineering, a Service-Oriented Architecture (SOA) is a set of principles and methodologies for designing and developing software in the form of interoperable services. These services are well-defined business functionalities that are built as software components (discrete pieces of code and/or data structures) that can be reused for different purposes,
Service-orientation requires loose coupling of services with operating systems and other technologies that underlie applications. 
CLIENT

BUSINESS LOGICS
                                           REQUEST
                                                               
 


                                                      RESPONSE
                                                                                                                                                       JSP
                        SERVER                                                                                                                             ASP
                                                                                                                   PHP
STANDARD OF WEB SERVICES

Web Services Overview

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

Soap Message

A SOAP message consists of several elements, most notably an envelope. The envelope encapsulates the data transmitted within the SOAP message. Below is a simple SOAP message complete with HTTP headers:

What are Web Services?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

How Does it Work?

The basic Web services platform is XML + HTTP.
XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.
The HTTP protocol is the most used Internet protocol.
Web services platform elements:
  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

What is SOAP?

SOAP is an XML-based protocol to let applications exchange information over HTTP.
SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format.
Or more simple: SOAP is a protocol for accessing a Web Service.
  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is a format for sending messages
  • SOAP is designed to communicate via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP is a W3C standard
Read more about SOAP on our Home page.

What is WSDL?

WSDL is an XML-based language for locating and describing Web services.
·         WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
·         WSDL contains every details regarding using web service
o    Method and Properties provided by web service
o    URLs from which those method can be accessed.
o    Data Types used.
o    Communication Protocol used.
·         What is Discovery or .Disco Files?
o    Discovery files are used to group common services together on a web server.
o    Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o    .Disco File (static)
§  .Disco File contains
§  URL for the WSDL
§  URL for the documentation
§  URL to which SOAP messages should be sent.
§  A static discovery file is an XML document that contains links to other resources that describe web services.
o    .VsDisco File (dynamic)
§  A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
·         What is difference between Disco and UDDI?
o    Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
·         What is Web Service Discovery Tool (disco.exe) ?
o    The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
·         What is Proxy Class?
o    A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of theapplication logic. Instead, the proxy class contains marshalling and transport logic.
o    A proxy class object allows a client to access a web service as if it were a local COM object.
o    The Proxy must be on the computer that has the web application.
·         What is Web Service Description Language Tool (wsdl.exe)?
o    This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o    Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o    Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
·         Testing a Web Service?
o    You can test web service without building an entire client application.
§  With Asp.net you can simply run the application and test the method by entering valid input paramters.
§  You can also use .Net Web Service Studio Tool comes from Microsoft.



  • WSDL stands for Web Services Description Language
  • WSDL is based on XML
  • WSDL is used to describe Web services
  • WSDL is used to locate Web services
  • WSDL is a W3C standard
Read more about WSDL on our Home page.

What is UDDI?

UDDI is a directory service where companies can register and search for Web services.
  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory for storing information about web services
  • UDDI is a directory of web service interfaces described by WSDL
  • UDDI communicates via SOAP
  • UDDI is built into the Microsoft .NET platform

1.     WEB METHOD
2.     XML
3.     HTTP PROTOCOL
4.     SOAP


TCP/IP
  TCP/IP STANDS FOR TRANSIMISSTION CONTROL PROTOCOL/ INTERNET PROTOCOL WHICH IS CONNECTION ORIENTED PROTOCOL, IT IS USED IN LAN,  AND IT IS MORE SECURE TECHNIQUE




NAMED PIPE
THIS IS A TECHNIQUE WHICH IS USED FOR INTERPROCESS COMMUNICATION IN UNIX FOR SAME SYSTEM

What is MSMQ(Microsoft Message Queuing)

MESSAGE QUEEN
IN SOCKET PROGRAMMING IF RECEIVER IS NOT AVAILABLE THAN MESSAGE WILL NOT DELIVER TO THE CLIENT WHERE AS IN MESSAGE QUEEN MESSAGE IS DELIVERED TO THE CLIENT IS AVAILABLE OR NOT
  IT CHECK THE RECEIVER IS AVAILABLE OR NOT CONTINEOUSLY AND WHEN RECEIVER IS AVAILABLE IT DELIVER THE MESSAGE TO IT
Microsoft Message Queuing, or MSMQ, is technology for asynchronous messaging. Whenever there's need for two or more applications (processes) to send messages to each other without having to immediately know results, MSMQ can be used. MSMQ can communicate between remote machines, even over internet. It's free and comes with Windows, but is not installed by default.

Typical usage

Typical example of MSMQ usage would be order processing application: orders are collected online using web forms and by sales team using some offline application. Order processing is slow, because third party payment provider is used. Third party resource can be unavailable at times and we don't want that failure to affect our application - we can delay processing of pending orders, but new orders must be collected.

Advantage
  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.

1.   Difference between WCF and Web service
2.       Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContraact] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ
Protocols
Security
Security, Reliable messaging, Transactions
.
WCF FUNDAMENTAL CONCEPTS

EndPoint

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components.
END POINT IS MAIN ENTRY POINT TO ENTER IN YOUR SERVICE ,
END POINT IS AN LOCATION ON NETWORK WHERE MESSAGE CAN BE SEND

SPECIAL FEATURES ADDED BY WCF THAT INCREASE TH PERFORMANCE OF EXECUTION, END POINT MEANS UNIQUE ADDRESS OF EACH FUCTIONALITY AND METHODS AND  IT SHOW ALL FORMATION IN XML FORMAT


EXAMPLE:-METHODS IN CLASS CALL FOR XYZ AND MEMORY FOR ALL METHODS WHERE AS PHONE CALL IN HOME FOR PARTICULAR PERSON

>>> WCF HAVE NO USER INTERFACE
>>> WCF MANAGES BUSINESS LOGICS
>>>> EXTENSION OF WCF IS S.V.C


>>> HERE A OTHER END POINT IS ALSO AVAILABE WHICH IS CREATED AUTOMATICALLY AND IT CREATED BY DEFAULT NAME IS METADATA EXCHANGE END POINT
AND OTHER END POINT WICH IS CREATED BY US IS USED TO ACCESS THE METHOD AND FUNCTIONALITY OF THE SERVICES


IN WCF WE FOLLOW A STANDARD
A|B|C
HERE A (ADDRESS)

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service.


HTTP://LOCAL HOST:9809/MYSERVICE
NET.TCP://LOCALHOST:9809/MYSERVICE
HERE HTTP IS AN PROTOCOL
LOCAL HOST IS DOMAIN NAME
9809 IS PORT NUMBER
MY SERVICE IS SERVICE NAME
HERE WE USE NET.TCP AT THE PLACE OF TCP/IP PROTOCOL IN WCF
NOTE :- BY DEFAULT PORT NUMBER OF IIS IS 80
THIS COMPLETE ADDRESS IS THE ADDRESS OF THE END POINT OF YOUR SERVICE

B (BINDING)
Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability

 INFORMATION ABOUT CHANNEL THAT IS USED BY CLIENT TCP/HTTP
CHANNELS
 CHANNELS ARE USED TO DO COMMUNICATION AND TO CONNECT THE CLIENT END POINT TO SERVICE END POINT
PROTOCOL GOVERNS THE CHANNELS MEANS CHANNELS ARE ACCORDING TO THE PROTOCOL TYPE
>> MICROSOFT PROVIDE THE PREBUILD PACKAGES(CHANNELS)

 TYPES OF BINDING
Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions
BasicHttpBinding
  • It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
  • This binding uses HTTP as the transport and text/XML as the default message encoding.
  • Security is disabled by default
  • This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
  • It is fairly weak on interoperability.
WSHttpBinding
  • Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
  • It offers lot more functionality in the area of interoperability.
  • It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
  • It uses HTTP and HTTPS transport for communication.
  • Reliable sessions are disabled by default.
WSDualHttpBinding
This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.
WSFederationHttpBinding
This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.
NetTcpBinding
This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.
NetNamedPipeBinding
This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.
NetMsmqBinding
  • This binding provides secure and reliable queued communication for cross-machine environment.
  • Queuing is provided by using MSMQ as transport.
  • It enables for disconnected operations, failure isolation and load leveling
NetPeerTcpBinding
  • This binding provides secure binding for peer-to-peer environment and network applications.
  • It uses TCP protocol for communication
  • It provides full support for SOAP security, transaction and reliability.

1.BASICHTTPBINDING
2.WSHTTPBINDING
1.BASIC HTTP BINDING
 IN BASIC HTTP WE CANNOT MANAGE THE STATE
2. WS HTTP BINDING
HERE WE CAN MANAGE THE STATE AT SERVICE SIDE AND IT REFLECT IT AT CLIENT SIDE

C FOR CONTRACT

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

>>>> CONTRACT IS PROVIDED BY THE SERVICE TO THE CLIENT
>>>> CONTRACT IS USED TO SET THE FORMAT AND STRUCTURE OF SERVICE
>>>IT CONSUME THE FACILITY OF SERVICES AND KNOWLEDGE OF FACILITY CONSUME BY THE CLIENT
TYPES OF CONTRACT
1.     SERVICE CONTRACT
2.     OPERATION CONTRACT
3.     DATA CONTRACT
4.     FAULT CONTRACT
5.       MESSAGE CONTRACT


1.      SERVICE CONTRACT
IT TELL US THAT WHAT IS THE PURPOSE OF THE SERVICE, WHAT IS PROVIDING BY THE SERVICE, THIS ATTRIBUTE SHOWS THE META DATA OF INTERFACE
Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

2.    OPERATION CONTRACT
HERE WE CAN SPECIFY SPECIAL FEATURES OF SERVICES, THIS ATTRIBUTE USED TO SHOW THE META DATA OF METHODS
               IN THIS CONTRACT WE CREATE THE INTERFACE. IT SHOW THE LIST OF ALL OPERATION NAME PROVIDED BY THE SERVICES
3.    DATA CONTRACT
TO KNOW THE STRUCTURE OF CONTRACT OF DATA EXCHANGE BETWEEN CLIENT AND SERVICES
Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

4.    FAULT CONTRACT
   IF AT SERVICE SIDE ANY EXCEPTION IS ARISE THAN IF YOU WANT TO TELL THE INFORMATION ABOUT THIS FAULT TO THE CLEINT THAN WE DO THIS IT IN FAULT CONTRACT. Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.


5.    MESSAGE CONTRACT
MESSAGE IS BIG TERM TO  KNOW THE STRUCTURE OF MESSAGE EXCHANGE BETWEEN CLIENT AND SERVICE SIDE

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achie



WCF Client
WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.
A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:
  1. Get the Proxy class and service end point information
Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.
svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
  1. Call operations.
Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.
//Creating the proxy on client side
MyCalculatorServiceProxy.MyServiceProxy proxy
= new MyCalculatorServiceProxy.MyServiceProxy();
 Console.WriteLine("Counter: " + proxy.MyMethod());
Metadata
Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
    <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

WCF Hosting



  • IIS
Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

 

 

 Service Host

Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.
In the below example you can find that WCF service is self hosted using console application.
//Creating uri for the hosting the service
Uri uri = new Uri("http://localhost/CategoryService");
//Creating the host object for MathService
  ServiceHost host = new ServiceHost(typeof(CategoryService), uri);
//Adding endpoint to the Host object
  host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);
  host.Open(); //Hosting the Service
  Console.WriteLine("Waiting for client invocations");
  Console.ReadLine();
  host.Close();
ved by using Message Contract attribute.


IN ISERVICE1.CS  HERE WE STORE THE INTERFACE , IT STORES THE SERVICE CONTRACT, HERE WE USE THE SERVICE ORIENTED ARCHITECTURE, HERE WE CONCENTRATE ONLY IN BUSINESS LOGICS

                             PRACTICAL
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
       OPEN WCF FILE >>>>NEW PROJECT >>>  WCF SERVICE APPLICATION

IN ISERVICE1.CS FILE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        double power(double x, double y);

        [OperationContract]

        bool leap(int y);

      
    }


  
    }

NOW OPEN SERVICE1.SVC.CS FILE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class Service1 : IService1
    {

        #region IService1 Members

        public double power(double x, double y)
        {
            return Math.Pow(x, y);
        }

        public bool leap(int y)
        {
            if ((y % 4 == 0) && ((y % 400 == 0) || (y % 100 != 0)))
                return true;
            else
                return false;
        }

        #endregion
    }
}

NOW OPEN WEB.CONFIG FILE TO SET END POINT
FISLY DELETE ALLREADY WRITTEN XML DATA AND WRITE THIS
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCFSevice2.Service">
        <endpoint address="" contract="WCFService2.IService" binding="basicHttpBinding"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
 
</configuration>

STEP 4.
NOW BUILD YOUR PROGRAM>>>>>>>>>> AND RUN YOUR PROGRAM
>>> COPY THE URL

USE IN WEB

NOW OPEN A WEB SITE TO USE THIS SERVICE

RIGHT CLICK ON WEBSITE AND THAN CLICK ON ADD A SERVICE REFERENCE
 AND PAST YOUR URL>>> IT WILL YOUR SERVICE AND THAN OK.

  protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient ob = new ServiceReference1.ServiceClient();
        Response.Write(ob.sum(34, 65).ToString());
    

    }

To use in window
NOW OPEN YOUR  FORM APPLICATION TO USE THIS SERVICE TO CREATE A CLIENT APPLICATION

>>>> FILE >>> NEW PROJCT >>>> THAN SELECT PROJECT>>> ADD A SERVICE REFERENCE >>>>> PAST THE URL HERE  THAN  >>>>> SELECT  GO>> IT WILL SHOW YOUR SERVICE NAME >>>>> THAN GIVE NAME OF YOUR SERVICE BELOW THE NAMESPACE TAG>>> OK.






private void button1_Click(object sender, EventArgs e)
        {
            ServiceReference1.Service1Client s1 = new WindowsFormsApplication7.ServiceReference1.Service1Client();

            bool result = s1.leap(int.Parse(textBox1.Text));
            MessageBox.Show(result.ToString());
        }


And FOLLOW THE SAME WAY TO ACCESS THIS WCF SERVICE IN WEB SITE ALSO

>>>> TO USE A WCF SERVICE IN WINDOW BY CREATING THE PROXY OWN SELF BY USING A TOOL SVCUTIL
    WHICH CREATE THE PROXY ON SELF OF THAT SERVICE.

IT WILL CREATE THESE TWO FILES

OPEN A WINDOW FORM APPLICATION>>>> A NEW PROJECT
>>> THAN RIGHT CLICK AND ADD EXISTING ITEMS>> AND ADD THESE TWO MYCLIENT AND APP.CONFIG FILE IN YOUR APPLICATION>>> THAN BUILD IT.
>>> AND ALSO DO A ADD REFERENCE OF USING SYTEM.SERVICEMODEL

private void button1_Click(object sender, EventArgs e)
        {
            ServiceClient ob = new ServiceClient();
            MessageBox.Show(ob.sum(87, 54).ToString());
        }

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>NOW SUPPOSE YOU WANT TO CREATE A NEW END POINT ON EXISTING WCF SERVICE THAN OPEN YOUR WCF SERVICE
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
>> basic httpBinding does not support binding session
By default instance creation is per call
>>> wsHttpBinding support binding session
 It means instance creation is per client

LET UNDERSTAND THIS BY PRACTICAL JUST CREATE A WCF SERVICE





>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>..>>>>
PRACTICAL EXAMPLE OF SELF HOSTING by console application
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
OPEN A CONSOLE APPLICATION>>>>>>> THAN DO ADD A REFERENCE
USING SYSTEM.SERVICEMODEL.DESCRIPTION
USING SYSTEM.SERVICEMODEL;
USING SYSTEM.RUNTIME.SERIALZATION;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace consoleservice
{
    [ServiceContract]
    public interface Imath
    {
        [OperationContract]
        double root(double x);
    }
    public class MathServi : Imath
     {
        public double root(double x)
        {
            return Math.Sqrt(x);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host;
            Uri uri = new Uri("http://localhost:9889/ConsoleService");
COPY THIS URL TO ACCESS THIS APPLICATION
            WSHttpBinding binding = new WSHttpBinding();
            host = new ServiceHost(typeof(MathServi), uri);
            ServiceMetadataBehavior b = new ServiceMetadataBehavior();
            b.HttpGetEnabled = true;
            host.Description.Behaviors.Add(b);
            host.AddServiceEndpoint(typeof(Imath), binding, uri);
            host.Open();
            Console.WriteLine("service is running");
            Console.ReadLine();
            Console.WriteLine("service is closed");
            host.Close();
            Console.Read();
        }
    }
}


>>>>>>BUILD THIS APPLICATION AND RUN THIS
 >>>>>TO USE THIS SERVICE THIS APPLICATION MUST BY IN RUNNING MODE

>>>>>NOW CREATE A CLIENT APPLICATION
NOW OPEN A WEB AND WINDOW APPLICATION
>>>> ADD SERCIVE REFERENCE >>>> PAST URL AND CLICK ON GO>>>>
GIVE A SERVICE REFERENCE NAME IF YOU WANT

THAN ON CLIENT APPLICATION BEHIND BUTTON CALL IT

protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.ImathClient ob = new ServiceReference1.ImathClient();
        Response.Write(ob.root(5).ToString());
    }










No comments:

Post a Comment