I'm facing an annoying problem while providing a wcf service. I am familiar with wcf and its usage.
Service Implementation:
public class Service : IService
{
public SampleClass SampleMethod ( SampleClass sampleParameter )
{
return new SampleClass { MyProperty1 = Guid.NewGuid(), MyProperty2 = ObjectId.GenerateNewId() };
}
}
Service interface:
[ServiceContract]
public interface IService
{
[OperationContract]
SampleClass SampleMethod ( SampleClass sampleParameter );
}
And my contract class:
/// this class is in DataContracts dll - meantioned in the exception
[DataContract]
public class SampleClass
{
[DataMember]
public Guid MyProperty1 { get; set; }
[DataMember]
public ObjectId MyProperty2 { get; set; }
}
I keep the interface and the contracts in seperate library projects and use the dlls at the clients.
MVC Side calling of service:
static IService Service = new ChannelFactory<IService>(new BasicHttpBinding("regularBinding"), new EndpointAddress(BaseAddress + "Service.svc")).CreateChannel();
public ActionResult Index()
{
var xyz = Service.SampleMethod(new SampleClass());
return View();
}
I can call this service from my unit test project or from a desktop application. But when I call the service from an MVC application it throws ProtocolException:
An exception of type 'System.ServiceModel.ProtocolException' occurred in mscorlib.dll but was not handled in user code
Additional information: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:sampleParameter. The InnerException message was 'Error in line 1 position 451. 'EndElement' 'MyProperty2' from namespace 'http://schemas.datacontract.org/2004/07/DataContracts' is not expected. Expecting element '_increment'.'. Please see InnerException for more details.
I have a hunch that this is caused by some serializer related issue, but I don't really have deep understanding on those topics, so here I am.
What might be the cause of this behaviour? How can I overcome this without changing my data structures?
Update
Btw I realized that the exception occurs on return. When I throw an exception from within the service method, that exception propogates to the client. Therefore I can say my request with ObjectId can be received from the service but cannot return to the client.
We've found out the problem and the solution in the discussion with #jpgrassi, but since #jpgrassi is too humble to post the answer, here I am.
Following the answer of this question #jeff's answer was inspiring enough to make me check the MongoDB.Bson dll's versions. There it was, they were different on server and mvc client and causing this problem. Leveling them on a version solved the problem.
I have a WCF service and a client and I want both to share the same class library so they both have access to the same types. My issue is that one of the classes is a MessageContract because it is an object that is used to upload files to the server via streaming. The class is as follows:
[MessageContract]
public class RemoteFileInfo : IDisposable
{
private string fileName;
private long length;
private System.IO.Stream fileByteStream;
public string FileName
{
set { this.fileName = value; }
get { return this.fileName; }
}
public long Length
{
set { this.length = value; }
get { return this.length; }
}
[MessageBodyMember(Order = 1)]
public System.IO.Stream FileByteStream
{
set { this.fileByteStream = value; }
get { return this.fileByteStream; }
}
public void Dispose()
{
if (fileByteStream != null)
{
fileByteStream.Dispose();
fileByteStream = null;
}
}
}
This class is contained in a library that is shared between the server and the client. If I comment out the line that says [MessageContract] and then update the service reference, I am able to successfully share the type with the client and the service reference does not try to re-implement the type on its own. However, in order for streaming to work I need to make sure that this class is indeed a MessageContract so that the WCF service knows to only expect a single body member in the message and to deal with it appropriately.
If I uncomment the line that says [MessageContract] and update the service reference on the client side, it tries to re-implement RemoteFileInfo via the service reference instead of reusing the RemoteFileInfo that already exists in the library that both the service and the client are sharing. This means I end up with two of the same classes, MyClientProject.Shared.RemoteFileInfo and ServiceReference.RemoteFileInfo, which is ambiguous and causes the code to throw tons of errors.
I can get around it (sloppily) by commenting out the [MessageContract] line, updating the service reference, and then uncommenting the line on the service side before starting the service, so the client side thinks that it is just a normal class but the WCF service thinks its a MessageContract. This seems very silly to have to do and I am convinced theres a better way to do it. Any ideas?
Since you're already sharing all your data contracts, what's the point of not sharing your service contract interface as well, and simply avoid doing code generation at all? That would make far more sense.
I have a WCF service method that sends back a MembershipCreateStatus (System.Web.Security) to the calling method. When I look at the service definition it has recreated the enum as a type of MyProject.MyWebService.MembershipCreateStatus so it is essentially a completely different object.
Is there a way in which I can tell the service definition to use the System.Web.Security class instead, even though it is this within the WCF service?
You you can. You need to use the KnownTypeAttribute class to decorate the DataContract in your WCF Service to specify that the enum is of type System.Web.Security.MembershipCreateStatus I'm not aware of the details of your environment but in general unless you control both the WCF service and the consuming clients, I would carefully research the support requirements and the possibility of a future change to the enum causing backwards compatibility issues with clients that are consuming this enum. Also to consider is a scenario where a non .NET client could consume your WCF service. In that case you need to consider if using the System.Web.Security.MembershipCreateStatus enum is a good idea versus implementing your own statuses for Member creation. Here is another question on StackOverflow with a good discussion on this topic.
For example see the following code below
[ServiceContract]
public interface IMembershipService
{
[OperationContract]
CreateMemberResponse CreateMember(ApplicationUser userToCreate);
}
[DataContract]
[KnownType(typeof(System.Web.Security.MembershipCreateStatus))]
public class CreateMemberResponse
{
[DataMember]
public MembershipCreateStatus Status { get; set; }
}
[DataContract]
public class ApplicationUser
{
public bool ReturnSuccess { get; set; }
public ApplicationUser()
{
ReturnSuccess = true;
}
}
You can write a test against this service as follows and this test will succeed.
[TestClass]
public class MembershipStatusInvocationTests
{
[TestMethod]
public void CreateMemberShouldReturnMembershipCreateStatusEnum()
{
var client = new MembershipServiceClient();
var response = client.CreateMember(new ApplicationUser {ReturnSuccess = true});
Assert.IsInstanceOfType(response.Status, typeof(System.Web.Security.MembershipCreateStatus));
}
}
For more information on the KnownTypeAttribute class see here
I currently am running some WCF REST services in a Windows Service (not IIS), using the WebServiceHost. I have a separate interface and class defined for each service, but I'm having some issues understanding how WebServiceHost, ServiceEndpoint and ServiceContracts can be used together to create a selfhosted solution.
The way that I currently set things up is that I create a new WebServiceHost for each class which implements a service and use the name of the class as part of the URI but then define the rest of the URI in the interface.
[ServiceContract]
public interface IEventsService
{
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebGet(UriTemplate = "EventType", ResponseFormat=WebMessageFormat.Json)]
List<EventType> GetEventTypes();
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebGet(UriTemplate = "Event")]
System.IO.Stream GetEventsAsStream();
}
public class EventsService: IEventsService
{
public List<EventType> GetEventTypes() { //code in here }
public System.IO.Stream GetEventsAsStream() { // code in here }
}
The code to create the services looks like this:
Type t = typeof(EventService);
Type interface = typeof(IEventService);
Uri newUri = new Uri(baseUri, "Events");
WebServicesHost host = new WebServiceHost(t, newUri);
Binding binding = New WebHttpBinding();
ServiceEndpoint ep = host.AddServiceEndpoint(interface, binding, newUri);
This works well and the service endpoint for each service is created at an appropriate url.
http://XXX.YYY.ZZZ:portnum/Events/EventType
http://XXX.YYY.ZZZ:portnum/Events/Event
I then repeat for another service interface and service class. I would like to remove the Events in the Url though but if I do that and create multiple WebServiceHosts with the same base URL I get the error:
The ChannelDispatcher at 'http://localhost:8085/' with contract(s) '"IOtherService"' is unable to open its IChannelListener
with the internal Exception of:
"A registration already exists for URI 'http://localhost:8085/'."
I'm trying to understand how the WebServiceHost, ServiceEndpoint and ServiceContract work together to create the ChannelListener.
Do I need a separate WebServiceHost for each class which implements a service? I don't see a way to register multiple types with a single WebServiceHost
Secondly, I'm passing in the interface to the AddServceEndpoint method and I assume that method checks the object for all of the OperationContract members and adds them, the problem is how does the WebServiceHost know which class should map to which interface.
What I would love would be an example of creating a WCF self hosted service which runs multiple services while keeping the interface and the implementation classes separate.
Sounds to me like the problem that you are having is you are trying to register more than one service on the same service URI. This will not work, as you have noticed, each service must have a unique endpoint.
Unique By
IP
Domain
Port Number
Full URL
Examples
http://someserver/foo -> IFoo Service
http://someserver/bar -> IBar Service
http://somedomain -> IFoo Service
http://someotherdomain -> IBar Service
http://somedomain:1 -> IFoo Service
http://somedomain:2 -> IBar Service
You get the idea.
So to directly address your question, if you want more than once service to be at the root url for you site, you will have to put them on different ports. So you could modify your code to be something like
public class PortNumberAttribute : Attribute
{
public int PortNumber { get; set; }
public PortNumberAttribute(int port)
{
PortNumber = port;
}
}
[PortNumber(8085)]
public interface IEventsService
{
//service methods etc
}
string baseUri = "http://foo.com:{0}";
Type iface = typeof(IEventsService);
PortNumberAttribute pNumber = (PortNumberAttribute)iface.GetCustomAttribute(typeof(PortNumberAttribute));
Uri newUri = new Uri(string.Format(baseUri, pNumber.PortNumber));
//create host and all that
I think it might be useful for you to re-think about your URI approach. Uri is a unique resource identifier.
Each your endpoint says that you try to expose outside a different kind of resource it's "Events" and "OtherResource". Thus you need to change your UriTemplates a bit.
I would make it so:
[ServiceContract]
public interface IEventTypesService
{
[OperationContract]
[WebGet(UriTemplate = "", ResponseFormat=WebMessageFormat.Json)]
IList<EventType> GetEventTypes();
[OperationContract]
[WebGet(UriTemplate = "{id}")]
EventType GetEventType(string id);
}
[ServiceContract]
public interface IEventsService
{
[OperationContract]
[WebGet(UriTemplate = "")]
Stream GetEventsAsStream();
[OperationContract]
[WebGet(UriTemplate = "{id}")]
Event GetEvent(string id);
}
public class EventsService: IEventsService, IEventTypesService
{
public IList<EventType> GetEventTypes() { //code in here }
public EventType GetEventType(string id) { //code in here }
public Stream GetEventsAsStream() { // code in here }
public EventType GetEventType(string id) { // code in here }
}
Type t = typeof(EventService);
Type interface1 = typeof(IEventsService);
Type interface2 = typeof(IEventTypesService);
var baseUri = new Uri("http://localhost");
Uri eventsUri= new Uri(baseUri, "Events");
Uri eventTypesUri= new Uri(baseUri, "EventTypes");
WebServicesHost host = new WebServiceHost(t, baseUri);
Binding binding = New WebHttpBinding();
host.AddServiceEndpoint(interface1, binding, eventsUri);
host.AddServiceEndpoint(interface2, binding, eventTypesUri);
And yes, you are right - you have to have different addresses, but it's really different resources. To understand it better you can refer: RESTful API Design, best-practices-for-a-pragmatic-restful-api
To finish, there is a way to use the same address, but the approach a bit weird:
Using the same address
The following solution:
allows a single object to handle a specific endpoint
no part of the path is in the URI template
uses the same port for all of the services
It does requires more than one WebServiceHost - one per object that handles requests. Another difficulty is that adding deeper endpoints (like /events/2014) means they either need to have unique parameters or the URI template must include part of the path, if you go convention over configuration that shouldn't be a problem.
A WebServiceHost can only host one thing (class) but that object can have multiple interfaces to handle multiple different types of requests on different URLs. How can different WebServiceHosts bind to the same domain:port? They can't so I guess WebServiceHost wraps an underlying static object that routes requests to the right object. This doesn't technically answer your question but I think this implementation allows you to do what you want right?
A console app that hosts the web services.
public class Program
{
static void Main (string[] args)
{
var venueHost = new WebServiceHost (typeof (Venues));
venueHost.AddServiceEndpoint (typeof (IVenues), new WebHttpBinding (), "http://localhost:12345/venues");
venueHost.Open ();
var eventHost = new WebServiceHost (typeof (Events));
eventHost.AddServiceEndpoint (typeof (IEvents), new WebHttpBinding (), "http://localhost:12345/events");
eventHost.Open ();
while (true)
{
var k = Console.ReadKey ();
if (k.KeyChar == 'q' || k.KeyChar == 'Q')
break;
}
}
}
The Venues class implements IVenues and handles any requests to http://localhost:12345/venues/
[ServiceContract]
public interface IVenues
{
[WebInvoke (Method = "GET", UriTemplate = "?id={id}")]
string GetVenues (string id);
}
public class Venues : IVenues
{
public string GetVenues (string id)
{
return "This would contain venue data.";
}
}
The Events class implements IEvents and handles any requests to http://localhost:12345/events/
[ServiceContract]
public interface IEvents
{
[WebInvoke (Method = "GET", UriTemplate = "?venue={venue}")]
string GetEvents (string venue);
}
public class Events : IEvents
{
public string GetEvents (string venue)
{
return "This would contain event data.";
}
}
WCF self hosting can be done in many ways like Console application hosting, Windows service hosting, etc.
I had tried to host two services using a single console application. The structure of the services was similar to what you mentioned, that is, separate classes and interfaces for both the services.
You might want to have a look at this link:
Hosting two WCf services using one console app
I have the following WCF interface that is exposed via net.tcp:
[ServiceContract]
public interface IMyWCFService
{
[OperationContract]
Response ProcessRequest(Request request);
}
This is driven by the following classes (much simplified for the purposes of this question):
[Serializable]
public abstract class Message
{
[XmlAttribute]
public string Sender { get; set; }
[XmlAttribute]
public string Recevier { get; set; }
}
[Serializable]
public abstract class Response : Message
{
[XmlAttribute]
public int EventCode { get; set; }
}
[Serializable]
public abstract class Request : Message
{
[XmlAttribute]
public string SourceSystem { get; set; }
}
[XmlRoot(Namespace="http://blah.blah.com/blah/")]
public class StringRequest : Request
{
[XmlElement]
public string Payload { get; set; }
}
[XmlRoot(Namespace="http://blah.blah.com/blah/")]
public class StringResponse : Response
{
[XmlElement]
public string Payload { get; set; }
}
Note : We use XMLSerializer rather than DataContractSerializer as these classes have to be compatible with legacy systems that are .NET 2 based.
As the interface uses the abstract Request/Response classes in the ProcessRequest method we have to declare StringResponse / StringRequest as ServiceKnownType, for example:
[ServiceContract]
[ServiceKnownType(typeof(StringRequest))]
[ServiceKnownType(typeof(StringResponse))]
public interface IMyWCFService
{
[OperationContract]
ResponseMessage ProcessRequest(RequestMessage request);
}
This works perfectly and all is good in the world, however.....
The WCF listener is just one component of a much larger framework and the classes described above are used throughout. We have also designed the framework to allow us to add new types of Request/Response messages with relative ease. For example I might add:
public class CustomRequest : Request
{
public MyCustomXmlSerialisableRequestObject Payload { get; set; }
}
public class CustomResponse: Response
{
public MyCustomXmlSerialisableResponseObject Payload { get; set; }
}
Which also works fine until I get the the WCF service interface. When we add a new custom request/response pair we also need to update the ServiceKnownType on the interface to include them. Which then means I have to redeploy the service. So the question is - is there any way I can avoid having to update the interface?
As an example when we used remoting we could pass through any objects we liked as long as they were serialisable so I assume/hope that there is a similar solution in WCF.
EDIT : Update
Following the guidance found here:
http://ashgeek.blogspot.com/2011/02/wcf-serialization-dynamically-add.html
I seem to be on the right track. However when I update the client service reference it pulls in all the dynamically types into the service reference. Which is undesirable as not all clients need to, or should, know about all messages that derive from Request/Response
More importantly I seem to lose the the ServiceClient class that is used to push messages, e.g:
// Client proxy class goes AWOL after service reference update
var client = new MyServiceReference.Client();
var responseMessage = client.ProcessRequest(requestMessage)
At the beginning you are mentioning that you need compatibility with .NET 2.0 services but in the same time you are complaining that something which worked in .NET remoting doesn't work in WCF - you are limited by features possible with .NET 2.0 web services where both server and client must know about transferred types on the service layer = types must be in service description and WSDL. Moreover because you decided to use XmlSerializer you generally lost most of the ways how to achieve that:
ServiceKnowType can load known types from static method
KnownTypes defined in configuration (requires DataContractSerializer)
DataContractResolver (only WCF 4) and loading all derived types on startup (requires DataContractSerializer)
Passing .NET type information in messages (requires NetDataContractSerializer and custom behavior) = generally this is the same functionality as in remoting and it demands sharing types between service and client and both service and client must be .NET application using WCF stuff.
With XmlSerializer you have one option
Return XElement and receive XElement in your service operation and deal with XML by yourselves - doesn't work in .NET 2.0
Edit:
There is no dynamic behavior in service description. It is created only once when the host starts and after that doesn't change until you restart the host. If you need subset of WSDL per client you need separate endpoint for each client and you must define exactly which data contracts should be exposed on each endpoint.