WCF Message Contract namespace issue - wcf

I have following MessageContract
[MessageContract(IsWrapped = true, WrapperName = AuthorizationXmlElementNames.ElementNames.GetUserRightsResponse,
WrapperNamespace = AuthorizationXmlElementNames.Namespace)]
public class GetUserRightsResponseMessage
{
#region Properties
/// <summary>
/// Gets or sets GetUserRightsResponse.
/// </summary>
[MessageBodyMember(Namespace = AuthorizationXmlElementNames.Namespace)]
public GetUserRightsResponse GetUserRightsResponse { get; set; }
/// <summary>
/// Gets or sets ResponseHeader.
/// </summary>
[MessageHeader(
Name = XmlCoreElementNames.ElementNames.ResponseHeader,
Namespace = XmlCoreElementNames.Namespace,
ProtectionLevel = ProtectionLevel.None)]
public ResponseHeader ResponseHeader { get; set; }
#endregion
}
GetUserRightsResponse class looks like this
[XmlRoot(ElementName = AuthorizationXmlElementNames.ElementNames.GetUserRightsResponse,
Namespace = AuthorizationXmlElementNames.Namespace, IsNullable = false)]
[Serializable]
//[MessageContract(WrapperName = AuthorizationXmlElementNames.ElementNames.GetUserRightsResponse, WrapperNamespace = AuthorizationXmlElementNames.Namespace)]
public class GetUserRightsResponse
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="GetUserRightsResponse"/> class.
/// Initialize a new instance of the <see cref="GetUserRightsResponse"/> class.
/// </summary>
public GetUserRightsResponse()
{
this.UserServiceAccesses = new UserServiceAccesses();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the user rights for the current user.
/// </summary>
//[MessageBodyMember(Namespace = AuthorizationXmlElementNames.Namespace)]
public UserServiceAccesses UserServiceAccesses { get; set; }
#endregion
}
XmlCoreElementNames.Namespace is the constant string for namespace and it's value is urn:MyNamespace:Authorization
I return an instance of the GetUserRightsResponseMessage from my operation contract. But I always get wrong namespace for the GetUserRightsResponse instance contained in the returned object. The returned XML part looks like the following.
<s:Body u:Id="_0">
<GetUserRightsResponse xmlns="urn:MyNamespace:Authorization">
<GetUserRightsResponse i:nil="true"
xmlns:a="http://schemas.datacontract.org/2004/07/MyMessageContract.MessageContracts"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
</GetUserRightsResponse>
</s:Body>
Why do i always get the namespace xmlns:a="http://schemas.datacontract.org/2004/07 for the property in the returned object? What does xmlns:a mean?

Both GetUserRightsResponse elements are in namespace "urn:MyNamespace:Authorization", because the default namespace declaration on the outer one is inherited by the inner one.
xmlns:a="http://schemas.datacontract.org/2004/07/MyMessageContract.MessageContracts" is a namespace declaration which defines a namespace prefix ("a") which isn't actually used in your message. So it has no effect at all on the meaning of the XML message and could be omitted. Its presence is a quirk of the Microsoft implementation, perhaps triggered by the naming collision between your message wrapper element name and the data contract name (but I'm just guessing about this).
If your clients are fully XML compliant, this shouldn't be a problem for you at all. However, there are some non-compliant SOAP client toolsets around which are fussy about the treatment of namespace declarations. If you are very unlucky you might find you have one which is confused by an unused namespace prefix declaration.

You are not getting wrong namespace, as far as I can see.
All elements are set to "urn:MyNamespace:Authorization" which I imagine is the AuthorizationXmlElementNames.Namespace.
xmlns:a="http://schemas.datacontract.org/2004/07/MyMessageContract.MessageContracts" points to Microsoft's schema for message contracts. Now this does not seem to have been used in the snippet you published, so I am surprised it is there at all but this is an innocent namespace since you do not have any element or attribute in that namespace.

Related

Akka.net Hyperion IgnoringDataMember

I use akka.net in a cluster schema. (n) processing nodes, with currently 1 lighthouse.
One of the package that navigate throught network expose langage information.
/// <summary>
/// Define scored a suite of token info
/// </summary>
/// <seealso cref="Hammer.Immutable.ImmutableObject" />
[DataContract]
public sealed class TokenSuite : ImmutableObject, IIdItem
{
#region Ctor
/// <summary>
/// Initializes a new instance of the <see cref="TokenSuite"/> class.
/// </summary>
public TokenSuite(Guid id, string langCode)
: base(id, langCode)
{
this.Id = id;
this.LangCode = langCode;
if (!string.IsNullOrEmpty(langCode))
LangInfo = CultureInfo.GetCultureInfoByIetfLanguageTag(langCode);
}
#endregion
#region Properties
/// <summary>
/// Gets the identifier.
/// </summary>
[DataMember]
public Guid Id { get; }
/// <summary>
/// Gets the main language code.
/// </summary>
[DataMember]
public string LangCode { get; }
/// <summary>
/// Gets the lang information.
/// </summary>
[IgnoreDataMember]
public CultureInfo LangInfo { get; }
#endregion
In local no problem but when it pass through the network (serialized) i got this issue on the lighthouse :
Reading the error it seems coming from the CultureInfo Object but it is flag to be ignored in the serializations.
I use Akka version 1.3.5, Hyperion 0.9.8, Akka.Serialization.Hyperion 1.3.2-beta54.
I try to serialize locally and it works :
var serializer = Context.System.Serialization.FindSerializerForType(typeof(TokenSuite));
var data = serializer.ToBinary(result);
var rtoObjectBack = serializer.FromBinary<TokenSuite>(data);
Any idea ?
Hyperion does not make any use of data contract attributes. This also means that [IgnoreDataMember] won't be taken into account.
Probably it fails when trying to deserialize a CultureInfo object, you've provided. You can always try to convert that to string, and resolve after deserialization.

WCF Serialization Long Namespace being repeated instead of prefix

We are using contract first approach for WCF services in our project, XSD(s) are converted to entities using WSCF Blue and default serialization is used. The default serializer serializes the packets in following way
<category xmlns="http://myportal.com/schema/category/v1.0">
<processingDate xmlns="http://myportal.com/schema/common/elements/v1.0">0001-01-01T00:00:00</processingDate>
<key **xmlns="http://myportal.com/schema/common/elements/v1.0"**>f9a8d542-72c8-4465-8d6b-aaeb94a72394</key>
<code>C511746379</code>
<name>category308277327</name>
<description>One Tow</description>
</category>
<region xmlns="http://myportal.com/schema/shared/region/v1.0">
<key **xmlns="http://myportal.com/schema/common/elements/v1.0"**>3</key>
<code>N35</code>
<name>North</name>
<panelCode>N98</panelCode>
</region>
<category xmlns="http://myportal.com/schema/category/v1.0">
<processingDate xmlns="http://myportal.com/schema/common/elements/v1.0">0001-01-01T00:00:00</processingDate>
<key **xmlns="http://myportal.com/schema/common/elements/v1.0"**>00121be8-968f-4dbf-9d5c-d7b81e127a36</key>
<name>Aplha</name>
<code>76542</code>
<createdDate **xmlns="http://myportal.com/schema/common/elements/v1.0"**>2014-03-26T16:36:52.794876</createdDate>
<stream>Online</stream>
</category>
The problem is highlighted in bold, why the default serializer puts the whole namespace there, why can't it declare it at the top and use prefix. The whole namespace inflates size of packet.
The category entity looks like following
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.18058")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://myportal.com/schema/category/v1.0", TypeName="category")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://myportal.com/schema/category/v1.0", IsNullable=false, ElementName="category")]
public partial class CategoryType : BaseType
{
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://myportal.com/schema/common/elements/v1.0", Order = 0, ElementName = "key")]
public string Key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1, ElementName = "code")]
public string Code
{
get
{
return this.codeField;
}
set
{
this.codeField = value;
}
}
How do I enforce the XmlElementAttribute to use prefix instead of complete namespace?
Thanks,
Avi
Finally I was able to resolve this one, all of my DTO (XSD) were an extension of same parent class by the name BaseType. I had to add a public field with XmlNamespaceDeclarations decoration, this field is consulted right before serialization.
#region Public Fields
/// <summary>
/// This is considered at the time of serialization for adding namespace prefixes,
/// The namespaces are built in the default constructor, it queries a Constant that in chance fetches the namespace(s) from configuration file
/// </summary>
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Prefixes;
#endregion
#region Public Constructors
/// <summary>
/// Builds namespace prefixes for serialization
/// </summary>
public BaseType()
{
Prefixes = new XmlSerializerNamespaces();
int index = 1;
Constants.NAMESPACES
.ForEach(tempNamespace =>
Prefixes.Add(Constants.PREFIX_LETTER + index++, tempNamespace)
);
}
#endregion
I hope this one helps somebody.
Cheers,
Avi

Unable to deserialize CSLA request in soap message sent by WCF (C#)

I am learning WCF so my apologies if my terminology is off here and there.
I am trying to deserialize a soap message that was sent with WCF and captured by Fiddler and I keep getting this error message: "The data at the root level is invalid. Line 1, position 1."
The WCF service is setup with the following code:
// Set up WcfProxy DataPortal service url
Csla.DataPortalClient.WcfProxy.DefaultUrl = appRootUrl + "WcfSilverlightPortal.svc";
// Set up WcfProxy Binding
System.ServiceModel.BasicHttpBinding largeBinding = new System.ServiceModel.BasicHttpBinding();
largeBinding.MaxReceivedMessageSize = 20000000;
largeBinding.MaxBufferSize = 20000000;
largeBinding.OpenTimeout = new TimeSpan(0, 10, 0);
largeBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
largeBinding.CloseTimeout = new TimeSpan(0, 10, 0);
largeBinding.SendTimeout = new TimeSpan(0, 10, 0);
largeBinding.Name = "BasicHttpBinding_IWcfPortal";
Csla.DataPortalClient.WcfProxy.DefaultBinding = largeBinding;
The soap message captured in Fiddler is as follows:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Fetch xmlns="http://ws.lhotka.net/WcfDataPortal">
<request xmlns:d4p1="http://schemas.datacontract.org/2004/07/Csla.Server.Hosts.Silverlight" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:ClientContext>QBhBcnJheU9mU2VyaWFsaXphdGlvbkluZm8IQWh0dHA6Ly9zY2hlbWFzLmRhdGFjb250cmFjdC5vcmcvMjAwNC8wNy9Dc2xhLlNlcmlhbGl6YXRpb24uTW9iaWxlCQFpKWh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlQBFTZXJpYWxpemF0aW9uSW5mb0AIQ2hpbGRyZW4JAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS8yMDAzLzEwL1NlcmlhbGl6YXRpb24vQXJyYXlzAUALUmVmZXJlbmNlSWSDQAhUeXBlTmFtZZhlQ3NsYS5Db3JlLkNvbnRleHREaWN0aW9uYXJ5LCBDc2xhLCBWZXJzaW9uPTQuMy4xMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTkzYmU1ZmRjMDkzZTRjMzABQAZWYWx1ZXMJAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS8yMDAzLzEwL1NlcmlhbGl6YXRpb24vQXJyYXlzAQEB</d4p1:ClientContext>
<d4p1:ClientCulture>en-US</d4p1:ClientCulture>
<d4p1:ClientUICulture>en-US</d4p1:ClientUICulture>
<d4p1:CriteriaData i:nil="true" />
<d4p1:GlobalContext>QBhBcnJheU9mU2VyaWFsaXphdGlvbkluZm8IQWh0dHA6Ly9zY2hlbWFzLmRhdGFjb250cmFjdC5vcmcvMjAwNC8wNy9Dc2xhLlNlcmlhbGl6YXRpb24uTW9iaWxlCQFpKWh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlQBFTZXJpYWxpemF0aW9uSW5mb0AIQ2hpbGRyZW4JAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS8yMDAzLzEwL1NlcmlhbGl6YXRpb24vQXJyYXlzAUALUmVmZXJlbmNlSWSDQAhUeXBlTmFtZZhlQ3NsYS5Db3JlLkNvbnRleHREaWN0aW9uYXJ5LCBDc2xhLCBWZXJzaW9uPTQuMy4xMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTkzYmU1ZmRjMDkzZTRjMzABQAZWYWx1ZXMJAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS8yMDAzLzEwL1NlcmlhbGl6YXRpb24vQXJyYXlzAQEB</d4p1:GlobalContext>
<d4p1:Principal>QBhBcnJheU9mU2VyaWFsaXphdGlvbkluZm8IQWh0dHA6Ly9zY2hlbWFzLmRhdGFjb250cmFjdC5vcmcvMjAwNC8wNy9Dc2xhLlNlcmlhbGl6YXRpb24uTW9iaWxlCQFpKWh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlQBFTZXJpYWxpemF0aW9uSW5mb0AIQ2hpbGRyZW4JAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2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JhbCwgUHVibGljS2V5VG9rZW49N2NlYzg1ZDdiZWE3Nzk4ZV1dLCBDc2xhLCBWZXJzaW9uPTQuMy4xMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTkzYmU1ZmRjMDkzZTRjMzABQAZWYWx1ZXMJAWE5aHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS8yMDAzLzEwL1NlcmlhbGl6YXRpb24vQXJyYXlzXjNLZXlWYWx1ZU9mc3RyaW5nU2VyaWFsaXphdGlvbkluZm8uRmllbGREYXRhT3pvWnZMcm1eA0tleZkFJGxpc3ReBVZhbHVlQAxFbnVtVHlwZU5hbWUuA25pbIYBQAdJc0RpcnR5hUAFVmFsdWUuBHR5cGWYDmI6YmFzZTY0QmluYXJ5CQFiIGh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hnoc8QXJyYXlPZnN0cmluZyB4bWxuczppPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeG1sbnM9Imh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vMjAwMy8xMC9TZXJpYWxpemF0aW9uL0FycmF5cyIgLz4BAQEBAZ8BAQEBAQEB</d4p1:Principal>
<d4p1:TypeName>Competition.Domain.Entities.SchoolSummaryList, Competition.Domain.Csla, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</d4p1:TypeName>
</request>
</Fetch>
</s:Body>
</s:Envelope>
I am trying to deserialize this to an object of type Csla.Server.Hosts.Silverlight.CriteriaRequest
The code for this class looks like this:
//-----------------------------------------------------------------------
// <copyright file="CriteriaRequest.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Message sent to the Silverlight</summary>
//-----------------------------------------------------------------------
using System;
using System.Runtime.Serialization;
using System.Security.Principal;
using Csla.Core;
namespace Csla.Server.Hosts.Silverlight
{
/// <summary>
/// Message sent to the Silverlight
/// WCF data portal.
/// </summary>
[DataContract]
public class CriteriaRequest
{
/// <summary>
/// Assembly qualified name of the
/// business object type to create.
/// </summary>
[DataMember]
public string TypeName { get; set; }
/// <summary>
/// Serialized data for the criteria object.
/// </summary>
[DataMember]
public byte[] CriteriaData { get; set; }
/// <summary>
/// Serialized data for the principal object.
/// </summary>
[DataMember]
public byte[] Principal { get; set; }
/// <summary>
/// Serialized data for the global context object.
/// </summary>
[DataMember]
public byte[] GlobalContext { get; set; }
/// <summary>
/// Serialized data for the client context object.
/// </summary>
[DataMember]
public byte[] ClientContext { get; set; }
/// <summary>
/// Serialized client culture.
/// </summary>
/// <value>The client culture.</value>
[DataMember]
public string ClientCulture { get; set; }
/// <summary>
/// Serialized client UI culture.
/// </summary>
/// <value>The client UI culture.</value>
[DataMember]
public string ClientUICulture { get; set; }
}
}
I have tried grabbing each of the three xml elements 'Body', 'Fetch' and 'request' from the soap message and storing them as an XElement variable named 'element' and running the code below:
DataContractSerializer dcs = new DataContractSerializer(typeof(CriteriaRequest));
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(element.Value));
ms.Seek(0, SeekOrigin.Begin);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(ms, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
CriteriaRequest fr = (CriteriaRequest)dcs.ReadObject(reader);
In every case it has failed to deserialize the object and I am out of ideas.
I think I have provided all the relavent information but if anything else would help please let me know and I will provide it.
Thanks.
You can't use the more simplistic serializers to directly serialize a CSLA .NET object graph. Serializers such as XmlSerializer, JsonSerializer, and the various DataContractSerializer variations aren't sophisticated enough to completely clone and object graph, and so they aren't supported by CSLA.
Only the BinaryFormatter, NetDataContractSerializer, and MobileFormatter are supported.
Odds are you are trying to expose your business objects directly as a service interface. That's a poor architectural choice, and one I'd never choose to support or encourage anyone to do. You might find the XML Services FAQ page useful.

Silverlight is not liking my WCF MessageContract. Why?

I am attempting to upload a file through a Silverlight client using the following MessageContract:
[MessageContract]
public class CategoryClientFileTransferMC : IDisposable
{
/// <summary>
/// CategoryID - Category identity.
/// </summary>
[MessageHeader(MustUnderstand = true)]
public int CategoryID;
/// <summary>
/// ID - File identifier.
/// </summary>
[MessageHeader(MustUnderstand = true)]
public string ID;
/// <summary>
/// Length - File length in bytes.
/// </summary>
[MessageHeader(MustUnderstand = true)]
public long Length;
/// <summary>
/// FileByteStream - File stream.
/// </summary>
[MessageBodyMember(Order = 1)]
public Stream FileByteStream;
/// <summary>
/// Dispose the contract.
/// </summary>
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
My problem is that the generated operation method on the client only takes a single argument; a byte array called FileByteStream. In other (non-Silverlight) clients I've created it asks for the MemberHeader fields as well. Without specifying these headers, the server has no idea what to do with the file. How can I set these headers when I call the operation?
Also, is there a better way to upload a file from a Silverlight client? This has been a huge headache.
Thanks.
The Silverlight subset of the WCF client does not support the [MessageHeader] attribute. You can still set message headers, but it's not as straightforward as in other platforms. Basically, you'll need to set the headers using the operation context, prior to making the call, like in the example below:
var client = new SilverlightReference1.MyClient();
using (new OperationContextScope(client.InnerChannel))
{
string contractNamespace = "http://tempuri.org/";
OperationContext.Current.OutgoingMessageHeaders.Add(
MessageHeader.CreateHeader("CategoryId", contractNamespace, 1));
OperationContext.Current.OutgoingMessageHeaders.Add(
MessageHeader.CreateHeader("ID", contractNamespace, "abc123"));
OperationContext.Current.OutgoingMessageHeaders.Add(
MessageHeader.CreateHeader("Length", contractNamespace, 123456L));
client.UploadFile(myFileContents);
}
Where contractNamespace is the XML namespace for the message header fields (IIRC they default to the same as the service contract). You can use Fiddler and something like the WCF Test Client to see which namespace is used there.

Problem with DataContract and hierarchy on WCF

i have a problem with an object in my wcf project.
I have lets say this object:
[DataContract(Name="ClassA")]
public class Person{
//---attributes---
}
[DataContract(Name="ClassB")]
public class Men : Person{
//---attributes---
}
Where ClassB is child of ClassA on the other side.
Then i have a method that is post:
[OperationContract]
[WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")]
public string PostPerson(Person person) {
if(person is Men){
//code...
}
}
The thing is that i receive the person (in the other side, they sendme as a ClassB) but the person is Men returns false.. why?
You need to add the [ServiceKnownType(typeof(Men))] attribute to the PostPerson method.
As Ryan Gross mentions, you need Men to be a known type. Here's a similar question/answer here on SO. One option not mentioned in the linked article is the KnownType attribute. Here's an example of code I've used in the past. The prerequisite is that this class is the base class for all of your data contracts and all of your data contracts are in the same assembly:
/// <summary>
/// Base class for all data contracts.
/// </summary>
[DataContract(Name = "Base", Namespace = "your namespace")]
[KnownType("GetKnownTypes")]
public class BaseDC : IExtensibleDataObject
{
#region Constants and Fields
/// <summary>
/// Instance used to control access to the known types list.
/// </summary>
private static readonly object _knownTypesLock = new object();
/// <summary>
/// Classes derived from this class. Needed to ensure proper functioning of the WCF data
/// constract serializer.
/// </summary>
private static List<Type> _knownTypes;
#endregion
#region Properties
/// <summary>
/// Gets or sets an <c>ExtensionDataObject</c> that contains data that is not recognized as belonging to the
/// data contract.
/// </summary>
public ExtensionDataObject ExtensionData { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Enumerates the types in the assembly containing <c>BaseDC</c> that derive from <c>BaseDC</c>.
/// </summary>
/// <returns>List of <c>BaseDC</c>-derived types.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Not appropriate for a property.")]
public static IEnumerable<Type> GetKnownTypes()
{
lock (_knownTypesLock)
{
if (_knownTypes == null)
{
_knownTypes = new List<Type>();
Assembly contractsAssembly = Assembly.GetAssembly(typeof(BaseDC));
Type[] assemblyTypes = contractsAssembly.GetTypes();
foreach (Type assemblyType in assemblyTypes)
{
if (assemblyType.IsClass && !assemblyType.IsGenericType)
{
if (assemblyType.IsSubclassOf(typeof(BaseDC)))
{
_knownTypes.Add(assemblyType);
}
}
}
_knownTypes.Add(typeof(BaseDC));
}
return _knownTypes;
}
}
#endregion
}