Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Service Reference for DateTimeOffset? not using FCL type

Tags:

c#

.net

wcf

I am using .NET 4.5.1 for my WCF service, and .NET 4.0 for a client windows service application.

In the Data Contract, there is a DataMember of type DateTimeOffset? (a nullable DataTimeOffset).

When I Add Service Reference to the WCF service, it thinks that DateTimeOffset? is a complex type. In other words, it doesn't think it's a System.DateTimeOffset?, it thinks it's a ServiceReference1.DateTimeOffset?

How do I fix this?

Here's what I've tried so far:

  1. Create the most simple example solution that demonstrates this. Unfortunately I couldn't recreate the issue, so it must be something unique to my configuration.

  2. Annotate the DataContract class with [KnownType(typeof(DateTimeOffset?))]. Unfortunately this didn't do anything.

  3. Check "Reuse types in referenced assemblies". This had the effect of the "ServiceReference1" object not being available at all in the Console Application.

Anyone have any other ideas on how to fix this?

Thank you.

like image 300
BlueSky Avatar asked Jun 11 '14 19:06

BlueSky


1 Answers

You're on the right track with KnownType.

In order to achieve your goal, you cannot use "Add Service Reference". Instead, your client application must have a reference to your [ServiceContract] class. Then, you can directly invoke the service using a ChannelFactory.

Server Code:

using System;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace Server
{
    public class Service : IService
    {
        public ReturnContract GetOffset()
        {
            return new ReturnContract { Offset = new DateTimeOffset(DateTime.Now) };
        }
    }

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        ReturnContract GetOffset();
    }

    [DataContract]
    [KnownType(typeof(DateTimeOffset))]
    public class ReturnContract
    {
        [DataMember]
        public DateTimeOffset? Offset { get; set; }
    }
}

Client Code

using Server;
using System;
using System.ServiceModel;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var cf = new ChannelFactory<Server.IService>("endpoint");
            var service = cf.CreateChannel();
            ReturnContract c = service.GetOffset();

            Console.WriteLine(c.Offset);
            Console.ReadLine();
        }
    }
}
like image 50
Dan Ling Avatar answered Oct 05 '22 22:10

Dan Ling