none
Datacontract Resolver of WCF RRS feed

  • Question

  • Hi ,

      I have been getting error in DataContractResolver  Sample project implementation that I basically followed from the following articles

    http://kellabyte.com/2010/11/13/building-extensible-wcf-service-interfaces-with-datacontractresolver/

    It is a nice article, but when I am following then I am getting error in ServiceClient project for the line which one those containing as following:

    ScheduledTask<OrderTask> task = new ScheduledTask<OrderTask>();
    task.Value = new OrderTask(2);
     
    // Submit a shipment.
    ScheduledTask<ShipmentTask> task2 = new ScheduledTask<ShipmentTask>();

    task2.Value=newShipmentTask("Parliament");

    I have been getting error ScheduledTask is not defined. So, kindly let me know why I have been getting this type of error

    Following are my code sample for the project ServiceLib within 2 classes 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Xml;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Channels;
    using System.Reflection;
    namespace ServiceLib
    {
        public class TaskValueAttribute : Attribute
        {
            public TaskValueAttribute()
            {
                this.TypeNamespace = "http://tempuri.org/";
            }

            public TaskValueAttribute(string typeNamespace)
            {
                this.TypeNamespace = typeNamespace;
            }

            public string TypeNamespace { get; set; }
        }
        public class TaskDataContractResolver : DataContractResolver
        {
            private Dictionary<string, Type> typesByNamespace = null;
            private Dictionary<Type, string> typesByType = null;

            public TaskDataContractResolver()
            {
                typesByNamespace = new Dictionary<string, Type>();
                typesByType = new Dictionary<Type, string>();
                ConstructTypeMap();
            }

            private void ConstructTypeMap()
            {
                Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (Assembly assembly in assemblies)
                {
                    var availableTypes = from t in assembly.GetTypes()
                                         where t.GetCustomAttributes(
                                             typeof(TaskValueAttribute),
                                             true).Count() > 0
                                         select t;

                    foreach (Type type in availableTypes)
                    {
                        object[] attributes = type.GetCustomAttributes(
                            typeof(TaskValueAttribute), true);

                        if (attributes.Length > 0)
                        {
                            TaskValueAttribute taskContent =
                                attributes[0] as TaskValueAttribute;

                            string ns = taskContent.TypeNamespace + type.Name;

                            typesByNamespace.Add(ns, type);
                            typesByType.Add(type, ns);
                        }
                    }
                }

            }
            // Serialization
            public override bool TryResolveType(Type type, Type declaredType,
                DataContractResolver knownTypeResolver,
                out System.Xml.XmlDictionaryString typeName,
                out System.Xml.XmlDictionaryString typeNamespace)
            {
                Type[] genericTypes = type.GetGenericArguments();

                string ns = string.Empty;
                Type genericType = null;

                foreach (Type genType in genericTypes)
                {
                    if (typesByType.ContainsKey(genType) == true)
                    {
                        typesByType.TryGetValue(genType, out ns);
                        genericType = genType;
                        break;
                    }
                }
                if (string.IsNullOrEmpty(ns) == false)
                {
                    XmlDictionary dictionary = new XmlDictionary();
                    typeName = dictionary.Add(genericType.Name);
                    typeNamespace = dictionary.Add(ns);

                    return true;
                }
                else
                {
                    return knownTypeResolver.TryResolveType(
                        type, declaredType, null, out typeName, out typeNamespace);
                }
            }
            public override Type ResolveName(string typeName, string typeNamespace,
            Type declaredType, DataContractResolver knownTypeResolver)
            {
                Type type = null;
                typesByNamespace.TryGetValue(typeNamespace, out type);

                if (type != null)
                {
                    Type genType = typeof(ScheduledTask<>);
                    Type genericType = genType.MakeGenericType(type);
                    return genericType;
                }
                else
                {
                    // Defer to the known type resolver
                    return knownTypeResolver.ResolveName(
                        typeName, typeNamespace, null, knownTypeResolver);
                }
            }
        }



        [ServiceContract(Namespace = "http://localhost:8732/Design_Time_Addresses/ServiceLib/ScheduledTaskService")]
        public interface IScheduledTaskService
        {
            [OperationContract(IsOneWay = true)]
            void Submit(IScheduledTask task);
        }

        // This is our actual service implementation.
         public interface IScheduledTask
        {
            [DataMember]
            Guid TaskId { get; set; }
        }

        [DataContract]
        public class ScheduledTask<T> : IScheduledTask
        {
            [DataMember]
            public Guid TaskId { get; set; }

            [DataMember]
            public T Value { get; set; }

            public static implicit operator T(ScheduledTask<T> that)
            {
                return that.Value;
            }
        }
     
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.Xml;
    using System.ServiceModel.Description;
    namespace ServiceLib
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ScheduledTaskService" in both code and config file together.
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
        public class ScheduledTaskService : IScheduledTaskService
        {
            public void Submit(IScheduledTask task)
            {
                Console.WriteLine("We got a task!");
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                using (ServiceHost serviceHost = new ServiceHost(typeof(ScheduledTask<>)))
                {
                    ContractDescription cd = serviceHost.Description.Endpoints[0].Contract;
                    OperationDescription myOperationDescription = cd.Operations.Find("Add");

                    DataContractSerializerOperationBehavior serializerBehavior = myOperationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
                    if (serializerBehavior == null)
                    {
                        serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
                        myOperationDescription.Behaviors.Add(serializerBehavior);
                    }

                    serializerBehavior.DataContractResolver = new TaskDataContractResolver();

                    // Open the ServiceHost to create listeners and start listening for messages.
                    serviceHost.Open();

                    // The service can now be accessed.
                    Console.WriteLine("The service is ready.");
                    Console.WriteLine("Press <ENTER> to terminate service.");
                    Console.WriteLine();
                    Console.ReadLine();

                }
            }
        }
        
    }

    another project for the serviceClient in which I am getting error for the ScheduledTask Type.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ServiceClient.ServiceReference1;
    using System.Runtime.Serialization;
    using System.Xml;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Channels;
    using System.Reflection;
    namespace ServiceClient
    {
        public class TaskValueAttribute : Attribute
        {
            public TaskValueAttribute()
            {
                this.TypeNamespace = "http://tempuri.org/";
            }

            public TaskValueAttribute(string typeNamespace)
            {
                this.TypeNamespace = typeNamespace;
            }

            public string TypeNamespace { get; set; }
        }
        [DataContract]
        [TaskValue("http://mynamespace.com")]
        public class OrderTask
        {
            public OrderTask(int taskPriority)
            {
                this.TaskPriority = taskPriority;
            }

            [DataMember]
            public int TaskPriority { get; set; }
        }

        [DataContract]
        [TaskValue("http://mynamespace.com")]
        public class ShipmentTask
        {
            public ShipmentTask(string address)
            {
                this.Address = address;
            }

            [DataMember]
            public string Address { get; set; }
        }

        public class TaskDataContractResolver : DataContractResolver
    {
        private Dictionary<string, Type> typesByNamespace = null;
        private Dictionary<Type, string> typesByType = null;
     
        public TaskDataContractResolver()
        {
            typesByNamespace = new Dictionary<string, Type>();
            typesByType = new Dictionary<Type, string>();
            ConstructTypeMap();
        }
     
        private void ConstructTypeMap()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                var availableTypes = from t in assembly.GetTypes()
                                     where t.GetCustomAttributes(
                                         typeof(TaskValueAttribute),
                                         true).Count() > 0
                                     select t;
     
                foreach (Type type in availableTypes)
                {
                    object[] attributes = type.GetCustomAttributes(
                        typeof(TaskValueAttribute), true);
     
                    if (attributes.Length > 0)
                    {
                        TaskValueAttribute taskContent =
                            attributes[0] as TaskValueAttribute;
     
                        string ns = taskContent.TypeNamespace + type.Name;
     
                        typesByNamespace.Add(ns, type);
                        typesByType.Add(type, ns);
                    }
                }
            }
     
        }
            // Serialization
        public override bool TryResolveType(Type type, Type declaredType,
            DataContractResolver knownTypeResolver,
            out System.Xml.XmlDictionaryString typeName,
            out System.Xml.XmlDictionaryString typeNamespace)
        {
            Type[] genericTypes = type.GetGenericArguments();
     
            string ns = string.Empty;
            Type genericType = null;
     
            foreach (Type genType in genericTypes)
            {
                if (typesByType.ContainsKey(genType) == true)
                {
                    typesByType.TryGetValue(genType, out ns);
                    genericType = genType;
                    break;
                }
            }
             if (string.IsNullOrEmpty(ns) == false)
            {
                XmlDictionary dictionary = new XmlDictionary();
                typeName = dictionary.Add(genericType.Name);
                typeNamespace = dictionary.Add(ns);
     
                return true;
            }
            else
            {
                return knownTypeResolver.TryResolveType(
                    type, declaredType, null, out typeName, out typeNamespace);
            }
        }
        public override Type ResolveName(string typeName, string typeNamespace,
        Type declaredType, DataContractResolver knownTypeResolver)
        {
            Type type = null;
            typesByNamespace.TryGetValue(typeNamespace, out type);

            if (type != null)
            {
                Type genType = typeof(ScheduledTask<>);
                Type genericType = genType.MakeGenericType(type);
                return genericType;
            }
            else
            {
                // Defer to the known type resolver
                return knownTypeResolver.ResolveName(
                    typeName, typeNamespace, null, knownTypeResolver);
            }
        }
    }
        class Program
        {
            static void Main(string[] args)
            {
                ScheduledTaskServiceClient service = new ScheduledTaskServiceClient();
            ServiceHost host = new ServiceHost(service);
            AttachDataContractResolver(host.Description.Endpoints[0]);
            host.Open();
     
            IScheduledTaskService client =
                CreateClient("net.tcp://localhost:1212");
     
            // Submit an order.
            ScheduledTask<OrderTask> task = new ScheduledTask<OrderTask>();
            task.Value = new OrderTask(2);
     
            // Submit a shipment.
            ScheduledTask<ShipmentTask> task2 = new ScheduledTask<ShipmentTask>();
            task2.Value = new ShipmentTask("Parliament");
     
            client.Submit(task);
            client.Submit(task2);
     
            Console.ReadKey();
        
            }

            private static IScheduledTaskService CreateClient(string endpointAddress)
            {
                EndpointAddress address = null;
                address = new EndpointAddress(endpointAddress);

                Binding binding = new NetTcpBinding(SecurityMode.None);

                ChannelFactory<IScheduledTaskService> factory =
                    new ChannelFactory<IScheduledTaskService>(binding, address);

                IScheduledTaskService service = factory.CreateChannel();

                AttachDataContractResolver(factory.Endpoint);

                return service;
            }

            private static void AttachDataContractResolver(ServiceEndpoint endpoint)
        {
            ContractDescription cd = endpoint.Contract;
     
            foreach (OperationDescription opdesc in cd.Operations)
            {
                DataContractSerializerOperationBehavior serializerBehavior =
                    opdesc.Behaviors.Find<DataContractSerializerOperationBehavior>();
     
                if (serializerBehavior == null)
                {
                    serializerBehavior =
                        new DataContractSerializerOperationBehavior(opdesc);
     
                    opdesc.Behaviors.Add(serializerBehavior);
                }
                serializerBehavior.DataContractResolver =new TaskDataContractResolver();
            }
        }
        }
    }


    Monday, July 1, 2013 12:04 PM

Answers

All replies