Quick template for WCF services - Client/server code

When looking at a problem posted at the WCF forums (https://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=118&SiteID=1), I usually try to set up a local reproduction of the issue to understand what is going on. One thing that helps me the most is to have a few templates that I can use to get a head start in the investigation. This very small piece of code can come quite handy for most of the issues I've seen so far:

//Template for WCF services
public class PostXXXXXXX
{
[ServiceContract]
    public interface ITest
    {
[OperationContract]
        string Echo(string text);
}
    public class Service : ITest
    {
        public string Echo(string text)
{
            return text;
}
}
    static Binding GetBinding()
{
        BasicHttpBinding result = new BasicHttpBinding();
        //Change binding settings here
        return result;
}
    public static void Test()
{
        string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), GetBinding(), "");
host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();
        Console.WriteLine(proxy.Echo("Hello"));

((IClientChannel)proxy).Close();
factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
host.Close();
}
}

Hope this helps.

Comments