Create Image Server using WCF WEB HTTP Service

Last post I wrote on WCF Web HTTP Service: why and how. This post was for beginners in which I discussed how to get it started and write your fist WCF WEB HTTP Service. In this post we will go one step further and learn to work with streams or to be precisely images. Service will return image based on the input from client. We are going to create an image server. Image server will do following task

  • Read requested image from file system on server
  • Convert that to stream
  • Return stream to clients

We are going to create WCF WEB HTTP Service which will act as image server. So to start with let us create Service Contract.

 


using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Demo1
{    
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        Stream FetchImage(string imageName);      
       
    }
}


In above Service, there is one Operation Contract which returns a stream. Operation Contract can be accessed using baseurl/FetchImage?imageName={imagename with extension}. Client will pass image name in query parameter to fetch a particular image. If image is not present on image then null would be returned from service.

Service implementation is very simple. You need to do following steps to fetch image and return it as stream.

Step 1: First check for existence of the image. If it exists got to step 2 else go to step 4

Step 2: Read image as FileStream

Step 3: Set Outgoing Request Content Type as image/jpeg

Step 4: convert string Image does not exist as stream and return

Service is implemented as below,


public class Service1 : IService1
    {       

        public Stream FetchImage(string imageName)
        {
            string filePath = @"c:\\" + imageName;

            if (File.Exists(filePath))
            {
                FileStream fs = File.OpenRead(filePath);
                WebOperationContext.Current.OutgoingRequest.ContentType = "image/jpeg";
                return fs;
            }
            else
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(" Requested Image does not exist :(");
                MemoryStream strm = new MemoryStream(byteArray);
                return strm;
            }
        }        
    }


Service implementation is very simple but one line of code in which we are explicitly saying that outgoing response content type is image/jpeg

image

Already we have covered this in previous post about EndPoint configuration but for quick reference open markup of .svc file and add use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

This is what all you need to do to create an Image Server as WCF WEB HTTP Service. You can test server from IE browser.

image

And if requested image is not present then error message will be rendered as below,

image

Now you can go ahead and consume and work with this image server in any kind of client able to perform HTTP GET operation. In further post we will get into details of consuming this service from various kind of clients. I hope this post will help you.

About these ads

WCF Web HTTP Service: why and how

Very often I talk on WCF to user groups and find developers confused on various forms of WCF. For example some of the questions I get are as follows

  • How to create REST Service
  • Can we create REST and SOAP Service together
  • What is WCF Web HTTP Service
  • How Web HTTP Service and WCF REST Service are different to each other
  • Can I host HTTP Service and REST Service in a console application
  • Why we need REST and HTTP Services
  • What kind of security can be applied on REST and HTTP Services and many more questions of this kind

In this post I will answer few of the above questions regarding WCF Web HTTP Services.

By definition, WCF Web HTTP programming model allows services to be exposed on non-SOAP EndPoints and helps to create WEB HTTP Services. Now a question may arise that why we need HTTP Services and what are the advantages of using that.

Mainly HTTP Services are designed and created for wide range of clients. Any application capable of following can be potential clients

  • Understand HTTP protocols and verbs
  • Can process URI and URL Schemes
  • Can work with different types of message and data formats
  • Perform HTTP Get and HTTP Post operations

Web HTTP Services doesn’t work on SOAP message format however any serilizable type can be returned from Web HTTP Services. Since HTTP Service does not work with SOAP so all WCF Security features cannot be applied on this. However basic Transport level security can be applied to WCF Web HTTP Services.

Let us see how we can create a very basic WCF Web HTTP Service. Create WCF Service Application project from WCF tab to create Web HTTP Service

image

After creation of project we need to create Service Contract.


 [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebGet]
        string HelloGet(string   name);

        [OperationContract]
        [WebInvoke]
        string  HelloPost(string  name);
       
    }


Above I have created very basic service. Service contains only two methods. One method will work on HTTP GET and other will work on HTTP POST operation. There are restrictions on passing parameters in query string. For example string can be passed in query parameter.


public class Service1 : IService1
    {       

        public string HelloGet(string name)
        {
            return "Hello GET " + name; 
        }

        public string HelloPost(string name)
        {
            return "Hello POST" + name; 
        }
    }



Above Service Contract is implemented as below. It’s very simple implementation in which service is returning string with concatenating of input string parameters.

Now there are various ways WCF WEB HTTP Services can be hosted and its EndPoint can be configured. You can configure and host service

  • In IIS
  • In Windows Services Application
  • In Managed Application like Console Application
  • Windows Azure Services

In this post let us learn how EndPoint can be configured for Web Server hosting like IIS. It’s very simple to configure EndPoints for HTTP Services. You can use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

You can fetch service from browser by navigating to URL as below. Keep in mind that port number could be different in your scenario.

http://localhost:55400/Service1.svc/HelloGet?name=dj

You can notice that we are passing input dj as string in query parameter. Response from service will be as below,

image

Another way service can be configured and hosted in a console application. In Console Application first you need to add reference of System.ServiceModel and System.ServiceModel.Web in the project.


using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using Demo1;

namespace ConsoleAppHostingService
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service1), new Uri("http://localhost:8989/"));
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), new WebHttpBinding(), "");
            ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            sdb.HttpHelpPageEnabled = false;
            host.Open();
            Console.WriteLine("Service is running");
            Console.WriteLine("Press enter to quit...");
            Console.ReadLine();
            host.Close();

        }
    }
}


Few points about above hosting code are as follows

  • WEB HTTP Service should be hosted in a WebServiceHost instance.
  • WebHttpBinding is used to created HTTP Service
  • Help page is disabled

On running Console Application, service can be accessed on URL passed in WebServiceHost instance

image

In this way you can create WCF WEB HTTP Service. In further posts we will learn how to consume this service in various kind of clients and work with different kind of data format. I hope this post will help you.

Can we implement Inheritance in WCF ServiceContract : WCF Interview Series #2

Can we implement Inheritance in WCF ServiceContract?

YES we can have Contract Inheritance in WCF. In other words in WCF one ServiceContract can inherit other ServiceContract.

image

Let us take an example that you have a ServiceContract named IParentService as given below,


[ServiceContract]
 public interface IParentService
 {
 [OperationContract]
 string ParentMessage(string message);

}

Another ServiceContract named IChildService can inherit IParentService as following,


[ServiceContract]
 public interface IChildService : IParentService
 {
 [OperationContract]
 string ChildMessage(string message);
 }

Next you need to decide on implantation of Service. Single Service class can implement both contract by implementing bottom most ServiceContract in hierarchy. In this case bottom most ServiceContract is IChildService

image

Service can be implemented as following in a single service class.


public class Service1 : IChildService
 {
 public string ChildMessage(string message)
 {
 return "Hello " + message + "from Child Service";
 }

public string ParentMessage(string message)
 {
 return "Hello " + message + "from Parent Service";
 }
 }

Now you have choice that either you can expose whole hierarchy as single EndPoint or different EndPoints for different Service Contract. To expose contract hierarchy create EndPoint with bottom most ServiceContract. In this case we are creating EndPoint with Service Contract IChildService . At the client side operations from whole hierarchy could be invoked.

image

So at client side Service will be exposed as single class as given below,

image

In this way you can work with Inheritance in Service Contract. I hope you find this post useful. Thanks for reading.