Create Project based on WCF Service Library. This project will come with Service implementation by default as below
IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFSelfHostingService
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFSelfHostingService
{
// 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;
}
}
}
Create Console Application and replace code as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFSelfHostingService;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/MyService/Service1");
ServiceHost host = new ServiceHost(typeof(Service1), baseAddress);
host.AddServiceEndpoint(typeof(WCFSelfHostingService.IService1),
new WSHttpBinding(), baseAddress);
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
}
}
Create Windows Form Application and add code as below in form load event
private IService1 channel = null;
var endPoint = new EndpointAddress("http://localhost:8080/MyService/Service1");
channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
string temp = channel.GetData(10);
No comments:
Post a Comment