Search Results

Search found 228 results on 10 pages for 'datacontract'.

Page 2/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Using custom DataContractResolver in WCF, to transport inheritance trees involving generics

    - by Benson
    I've got a WCF service, in which there are operations which accept a non-generic base class as parameter. [DataContract] class Foo { ... } This base class is in turn inherited, by such generics classes as [DataContract] class Bar : Foo { ... } To get this to work, I'd previously have to register KnownTypes for the Foo class, and have these include all possible variations of Bar (such as Bar, Bar and even Bar). With the DataContractResolver in .NET 4, however, I should be able to build a resolver which properly stores (and restores) the classes. My questions: Are DataContractResolvers typically only used on the service side, and not by the client? If so, how would that be useful in this scenario? Am I wrong to write a DataContractResolver which serializes the fully qualified type name of a generic type, such as Bar1[List1[string, mscorlib], mscorlib] ? Couldn't the same DataContractResolver on the client side restore these types?

    Read the article

  • Adding WCF service reference adds DataContract types too

    - by Avi Shilon
    Hi everybody, I've used Visual Studio's Add Service Reference feature to add a service (actually it is a workflow service, created in WF4 RC1, but I don't think this makes any difference), and it also added the DataContracts that the service uses. At first this seemed fine, because All I've had in the DataContracts was simply properties, with no implementations. But now I've added code in the constructor of one data contracts that initializes creates an instance of one of the properties that exposes a list of other DCs, and when I've updated the service reference via VS (2010 RC1), the implementation was not updated. What should I do? Should I use my DCs instead of the ones created by VS or should I use the ones VS created? I've noticed that the properties in the VS-generated DCs contain some additional logic for checking equality in the setters and they also implement some interfaces too (like IExtensibleDataObject and INotifyPropertyChanged) which might get handy I guess in the future (I'm not knowledgeable at WCF). Thank you for your time folks, Avi

    Read the article

  • WCF Service returning 400 error: The body of the message cannot be read because it is empty

    - by Josh
    I have a WCF service that is causing a bit of a headache. I have tracing enabled, I have an object with a data contract being built and passed in, but I am seeing this error in the log: <TraceData> <DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier> <Description>Throwing an exception.</Description> <AppDomain>efb0d0d7-1-129315381593520544</AppDomain> <Exception> <ExceptionType>System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>There is a problem with the XML that was received from the network. See inner exception for more details.</Message> <StackTrace> at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback) at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state) at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString> System.ServiceModel.ProtocolException: There is a problem with the XML that was received from the network. See inner exception for more details. ---&amp;gt; System.Xml.XmlException: The body of the message cannot be read because it is empty. --- End of inner exception stack trace --- </ExceptionString> <InnerException> <ExceptionType>System.Xml.XmlException, System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>The body of the message cannot be read because it is empty.</Message> <StackTrace> at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback) at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state) at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace> <ExceptionString>System.Xml.XmlException: The body of the message cannot be read because it is empty.</ExceptionString> </InnerException> </Exception> </TraceRecord> </DataItem> </TraceData> So, here is my service interface: [ServiceContract] public interface IRDCService { [OperationContract] Response<Customer> GetCustomer(CustomerRequest request); [OperationContract] Response<Customer> GetSiteCustomers(CustomerRequest request); } And here is my service instance public class RDCService : IRDCService { ICustomerService customerService; public RDCService() { //We have to locate the instance from structuremap manually because web services *REQUIRE* a default constructor customerService = ServiceLocator.Locate<ICustomerService>(); } public Response<Customer> GetCustomer(CustomerRequest request) { return customerService.GetCustomer(request); } public Response<Customer> GetSiteCustomers(CustomerRequest request) { return customerService.GetSiteCustomers(request); } } The configuration for the web service (server side) looks like this: <system.serviceModel> <diagnostics> <messageLogging logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" /> </diagnostics> <services> <service behaviorConfiguration="MySite.Web.Services.RDCServiceBehavior" name="MySite.Web.Services.RDCService"> <endpoint address="http://localhost:27433" binding="wsHttpBinding" contract="MySite.Common.Services.Web.IRDCService"> <identity> <dns value="localhost:27433" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MySite.Web.Services.RDCServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> <dataContractSerializer maxItemsInObjectGraph="6553600" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Here is what my request object looks like [DataContract] public class CustomerRequest : RequestBase { [DataMember] public int Id { get; set; } [DataMember] public int SiteId { get; set; } } And the RequestBase: [DataContract] public abstract class RequestBase : IRequest { #region IRequest Members [DataMember] public int PageSize { get; set; } [DataMember] public int PageIndex { get; set; } #endregion } And my IRequest interface public interface IRequest { int PageSize { get; set; } int PageIndex { get; set; } } And I have a wrapper class around my service calls. Here is the class. public class MyService : IMyService { IRDCService service; public MyService() { //service = new MySite.RDCService.RDCServiceClient(); EndpointAddress address = new EndpointAddress(APISettings.Default.ServiceUrl); BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; binding.MaxBufferSize = 65536; binding.MaxReceivedMessageSize = 4194304; ChannelFactory<IRDCService> factory = new ChannelFactory<IRDCService>(binding, address); service = factory.CreateChannel(); } public Response<Customer> GetCustomer(CustomerRequest request) { return service.GetCustomer(request); } public Response<Customer> GetSiteCustomers(CustomerRequest request) { return service.GetSiteCustomers(request); } } and finally, the response object. [DataContract] public class Response<T> { [DataMember] public IEnumerable<T> Results { get; set; } [DataMember] public int TotalResults { get; set; } [DataMember] public int PageIndex { get; set; } [DataMember] public int PageSize { get; set; } [DataMember] public RulesException Exception { get; set; } } So, when I build my CustomerRequest object and pass it in, for some reason it's hitting the server as an empty request. Any ideas why? I've tried upping the object graph and the message size. When I debug it stops in the wrapper class with the 400 error. I'm not sure if there is a serialization error, but considering the object contract is 4 integer properties I can't imagine it causing an issue.

    Read the article

  • Creating WCF DataContracts dynamically from code

    - by Fredrik Tonn
    Given the fact that I have a fully dynamic object model, that is, I have no concrete classes defined anywhere in code, but I still want to be able to create WCF DataContracts for them so I can use them in operations. How can I achieve this? My concrete class "Entity" implements ICustomTypeDescriptor which is used to present the various properties to the outside world, but my expeimentation with WCF suggests that WCF does not care about ICustomTypeDescriptor. Is this correct or have I missed something? Is this possible? It cannot be so that the only way to create a DataContract is to actually have a concrete harcoded class, can it?

    Read the article

  • WCF - (Custom) binary serialisation.

    - by Barguast
    I want to be able to query my database over the web, and I am wanting to use a WCF service to handle the requests and results. The problem is that due to the amount of data that can potentially be returned from these queries, I'm worried about how these results will be serialised over the network. For example, I can imagine the XML serialisation looking like: <Results> <Person Name="Adam" DateOfBirth="01/02/1985" /> <Person Name="Bob" DateOfBirth="04/07/1986" /> </Results> And the binary serialisation containing types names and other (unnecessary) metadata. Perhaps even the type name for each element in a collection? o_o Ideally, I'd like to perform the serialisation of certain 'DataContract'-s myself so I can make it super-compact. Does anyone know if this is possible, or of any articles which explain how to do custom serialisation with WCF? Thanks in advance

    Read the article

  • How do I solve this error, "error while trying to deserialize parameter"

    - by Paul Rowland
    I have a web service that is working fine in one environment but not in another. The web service gets document meta data from SharePoint, it running on a server where I cant debug but with logging I confirmed that the method enters and exits successfully. What could be the reason for the errors? The error message is, The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse. The InnerException message was 'Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'.'. Please see InnerException for more details. The InnerException was System.ServiceModel.Dispatcher.NetDispatcherFaultException was caught Message="The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse. The InnerException message was 'Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'.'. Please see InnerException for more details." Source="mscorlib" Action="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault" StackTrace: Server stack trace: at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameter(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeReply(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.ProxyOperationRuntime.AfterReply(ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request) at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2141 at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2150 at CompanyName.ProjectName.Services.Shared.SharepointAdapter.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Shared\SharepointAdapter.cs:line 260 at CompanyName.ProjectName.Services.Project.ProjectDocumentService.SetSharepointDocumentData(List`1 sourceDocuments) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 1963 at CompanyName.ProjectName.Services.Project.ProjectDocumentService.GetProjectConversionDocumentsImplementation(Int32 projectId) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 3212 InnerException: System.Runtime.Serialization.SerializationException Message="Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'." Source="System.Runtime.Serialization" StackTrace: at System.Runtime.Serialization.XmlObjectSerializerReadContext.ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, Int32 memberIndex, Int32 requiredIndex, XmlDictionaryString[] memberNames) at System.Runtime.Serialization.XmlObjectSerializerReadContext.GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, Int32 memberIndex, Int32 requiredIndex, ExtensionDataObject extensionData) at ReadFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadArrayOfFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadMetaDataSearchResultsDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadGetDocumentMetaDataResponseBodyFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns) at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName) at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName) at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) InnerException:

    Read the article

  • WCF Proxy generation

    - by dragonfly
    Hi, I'm generating proxy using svcutil tool. My contract methods return objects of particular type. However generated proxy client interface has return value of type object. What is more I get exception with message: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail] : The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:name. The InnerException message was 'XML 'Element' 'http://tempuri.org/:name' does not contain expected attribute 'http://schemas.microsoft.com/2003/10/Serialization/:Type'. The deserializer has no knowledge of which type to deserialize. Check that the type being serialized has the same contract as the type being deserialized.'. Please see InnerException for more details. Any ideas what's going on?

    Read the article

  • DataContractJsonSerializer produces list of hashes instead of hash

    - by Jacques
    I would expect a Dictionary object of the form: Dictionary<string,string> dict = new Dictionary<string,string>() {["blah", "bob"], ["blahagain", "bob"]}; to serialize into JSON in the form of: { "blah": "bob", "blahagain": "bob" } NOT [ { "key": "blah", "value": "bob" }, { "key": "blahagain", "value": "bob"}] What is the reason for what appears to be a monstrosity of a generic attempt at serializing collections? The DataContractJsonSerializer uses the ISerializable interface to produce this thing. It seems to me as though somebody has taken the XML output from ISerializable and mangled this thing out of it. Is there a way to override the default serialization used by .Net here? Could I just derive from Dictionary and override the Serialization methods? Posting to hear of any caveats or suggestions people might have.

    Read the article

  • Datacontracts property getter running twice

    - by user321426
    I have a set of data contracts that act as wrappers to base classes that we wish to expose. A quick example is: [DataMember] public List<decimal> Points { get { return sourceObject.ListPoints(); } private set{} } We have some other properties that we have to massage the data first (we are converting object graphs and need to guard against circular references). The issue that we are seeing is that this getter will fire twice, once within the service operation, then again during serialization. This is causing two problems: We manually add to collections, since this is running twice the collections are filled with dupes. If an exception is thrown during the second run, it happens outside of the try/catch in the operation, and does not throw a fault. The service throws a cryptic timeout message, and the only way to see the error is via WCF trace logs.

    Read the article

  • WCF DataContractSerializer Behavior

    - by sbanwart
    I'm seeing some unusual behavior when using the DataContractSerializer. I have defined a message contract like so: namespace MyNamespace.DataContracts { [MessageContract(WrapperName = "order", WrapperNamespace = @"http://example.com/v1/order")] public class MyOrder { [MessageBodyMember(Namespace = @"http://http://example.com/v1/order", Order = 1)] public MyStore store; [MessageBodyMember(Namespace = @"http://http://example.com/v1/order", Order = 2)] public MyOrderHeader orderHeader; [MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 3)] public List<MyPayment> payments; [MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 4)] public List<MyShipment> shipments; } . . I'm sending it an XML message that looks like this: <?xml version="1.0" encoding="utf-8"?> <order xmlns="http://example.com/v1/order> <store> ... </store> <orderHeader> ... </orderHeader> <payments> <payment> ... </payment> </payments> <shipments> <shipment> ... </shipment> </shipments> </order> My service deserializes this XML as expected. Inside my service, I'm using the DataContractSerializer to create an XML string and that's where things get weird. I'm using the serializer like this: DataContractSerializer serializer = new DataContractSerializer(typeof(MyOrder)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, order); ms.Position = 0; StreamReader sr = new StreamReader(ms); string outputMessage = sr.ReadToEnd(); } Once this finishes, the outputMessage contains the following XML: <?xml version="1.0" encoding="utf-8"?> <MyOrder xmlns="http://example.com/v1/order" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <order> <store> ... </store> <orderHeader> ... </orderHeader> <payments> <payment> ... </payment> </payments> <shipments> <shipment> ... </shipment> </shipments> </order> </MyOrder> Needless to say, anything expecting to receive the original XML message will fail to parse this. So I guess I have two questions: Why is the DataContractSerializer adding the extra outer node to my XML output? Is there a way to stop it from doing this? Thanks.

    Read the article

  • confused about how to use JSON in C#

    - by Josh
    The answer to just about every single question about using C# with json seems to be "use JSON.NET" but that's not the answer I'm looking for. the reason I say that is, from everything I've been able to read in the documentation, JSON.NET is basically just a better performing version of the DataContractSerializer built into the .net framework... Which means if I want to deserialize a JSON string, I have to define the full, strongly-typed class for EVERY request I might have. so if I have a need to get categories, posts, authors, tags, etc, I have to define a new class for every one of these things. This is fine if I built the client and know exactly what the fields are, but I'm using someone else's api, so I have no idea what the contract is unless I download a sample response string and create the class manually from the JSON string. Is that the only way it's done? Is there not a way to have it create a kind of hashtable that can be read with json["propertyname"]? Finally, if I do have to build the classes myself, what happens when the API changes and they don't tell me (as twitter seems to be notorious for doing)? I'm guessing my entire project will break until I go in and update the object properties... So what exactly is the general workflow when working with JSON? And by general I mean library-agnostic. I want to know how it's done in general, not specifically to a target library... I hope that made sense, this has been a very confusing area to get into... thanks!

    Read the article

  • Clone LINQ To SQL object Extension Method throws object dispose exception....

    - by gtas
    Hello all, I have this extension method for cloning my LINQ To SQL objects: public static T CloneObjectGraph<T>(this T obj) where T : class { var serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null); using (var ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); ms.Position = 0; return (T)serializer.ReadObject(ms); } } But while i carry objects with not all references loaded, while qyuerying with DataLoadOptions, sometimes it throws the object disposed exception, but thing is I don't ask for references that is not loaded (null). e.g. I have Customer with many references and i just need to carry on memory the Address reference EntityRef< and i don't Load anything else. But while i clone the object this exception forces me to load all the EntitySet< references with the Customer object, which might be too much and slow down the application speed. Any suggestions?

    Read the article

  • Can I find out what WCF methods are supported on the endpoint before calling it?

    - by alord1689
    I have a versioning issue with a WCF service contract in which one of the many endpoints which are called for the operation is missing one method from the contract. My question is, how can I make sure the command is available on the client before attempting to call it? I tried: foreach (var od in proxy.Endpoint.Contract.Operations) { if (od.Name == "MyMethodName") { hasMethod = true; break; } } Unfortunately, this is using the contract from the calling app and does not actually describe the implementations on the endpoint itself. As a result, it returns true even though the endpoint has failed to implement the command.

    Read the article

  • web service data type (contract)

    - by cyberguest
    hi, i have a general design question. we have a fairly big data model that represents an clinical object, the object itself has 200+ child attributes in the hierarchy. and we have a SetObject operation, and a GetObject operation. my question is, best practice wise, would it make sense to use that single data model in both operations or different data model for each? Because the Get operation will return much more details than what's needed for Set. an example of what i mean: the data model has say ProviderId, and ProviderName attributes, in the Get operation, both the ProviderId, and ProviderName would need to be returned. However, in the Set operation, only the ProviderId is needed, and ProviderName is ignored by the service since system has that information already. In this case, if the Get and Set operations use the same data model, the ProviderName is exposed even for Set operation, does that confuse the consuming developer?

    Read the article

  • Put objects which are decorated with [DataContract] into a StateServer?

    - by Dave
    Is there anyway to stick objects which are decorated with DataContract attributes but not decorated with Serializable attributes in to a SqlServer StateServer? In other words, I would prefer not having to decorate these objects with the Serializable attribute as I will also have to implement IXmlSerizable on all of these objects because they do not have empty contstructors, and non-public setters for properties.

    Read the article

  • Do I have to worry about escaping XML reserved characters before I return a DataContract object from

    - by Brett Widmeier
    Hi, I am pretty inexperienced with WCF. I have a DataContract that implements the IExtensibleDataObject interface. Some of the members of this object are populated from freetext input and could contain XML reserved characters ('', for example). I imagine that I get escaping of these characters for free with WCF, but I have been looking around and could not find anything commenting on this one way or another. Is this the case? I have set my service to log the messages that it sends and receives for viewing in the Trace Viewer. Part of a message that my service returns looks like this: <sInstructions>"></sInstructions> Now, I have a couple questions about this. 1) Is it actually transmitting "&gt; and just showing it in a more readable form in the trace viewer? 2) If it is actually is transmitting ">, is this legal XML?

    Read the article

  • SvcUtil and /dconly generates XSD's for data types NOT marked with the DataContract attribute.

    - by Bellerephon
    Has anyone ever encountered a problem with Svcutil and the /dconly option where it generates metadata for EVERY data type in an Assembly, even if it is NOT marked with with the [DataContract()] attribute? It also appears to be generating metadata for types only referenced in the code, such as XmlDictionaryReaderQuotas even though these are not a part of the physical assembly that I generated metadata on. Some info: Using the .NET 4.0 version of SvcUtil. Does not matter if class is empty or not. No references are specified in the command line for SvcUtil. Command line: "C:\In Progress Work (Prospective)\Prospective Server\Prospective Server\Management\Prospective.Server.Server.NET40.Debug.AnyCPU.dll" /nologo /t:metadata /d:"C:\In Progress Work (Prospective)\Prospective Server\Prospective Server\Management" /dconly

    Read the article

  • Business enum to DatContract Enum conversion in WCF

    - by chugh97
    I have an enum namespace Business { public enum Color { Red,Green,Blue } } namespace DataContract { [DataContract] public enum Color { [EnumMember] Red, [EnumMember] Green, [EnumMember] Blue } } I have the same enum as a datacontract in WCF with same values. I need to convert the Business enum to the DataContract enum using a translator. Hoe can I achieve this?

    Read the article

  • Is there a way to create a WCF DataContract on a third party type?

    - by Michael Hedgpeth
    I am migrating to wcf and trying to figure out how I'm going to declare my Data Contracts properly. Some of the types I have been demoting are from a third party that I am unable to change. Are attributes the only way to explicitly declare data contracts in wcf? I know about the auto data contract functionality in 3.5, but the books I'm readin discourage that. And besides, that way assumes all state is publically available, which is oftentimes not the case.

    Read the article

  • FormatException with IsolatedStorageSettings

    - by Jurgen Camilleri
    I have a problem when serializing a Dictionary<string,Person> to IsolatedStorageSettings. I'm doing the following: public Dictionary<string, Person> Names = new Dictionary<string, Person>(); if (!IsolatedStorageSettings.ApplicationSettings.Contains("Names")) { //Add to dictionary Names.Add("key", new Person(false, new System.Device.Location.GeoCoordinate(0, 0), new List<GeoCoordinate>() { new GeoCoordinate(35.8974, 14.5099), new GeoCoordinate(35.8974, 14.5099), new GeoCoordinate(35.8973, 14.5100), new GeoCoordinate(35.8973, 14.5099) })); //Serialize dictionary to IsolatedStorage IsolatedStorageSettings.ApplicationSettings.Add("Names", Names); IsolatedStorageSettings.ApplicationSettings.Save(); } Here is my Person class: [DataContract] public class Person { [DataMember] public bool Unlocked { get; set; } [DataMember] public GeoCoordinate Location { get; set; } [DataMember] public List<GeoCoordinate> Bounds { get; set; } public Person(bool unlocked, GeoCoordinate location, List<GeoCoordinate> bounds) { this.Unlocked = unlocked; this.Location = location; this.Bounds = bounds; } } The code works the first time, however on the second run I get a System.FormatException at the if condition. Any help would be highly appreciated thanks. P.S.: I tried an IsolatedStorageSettings.ApplicationSettings.Clear() but the call to Clear also gives a FormatException. I have found something new...the exception occurs twenty-five times, or at least that's how many times it shows up in the Output window. However after that, the data is deserialized perfectly. Should I be worried about the exceptions if they do not stop the execution of the program? EDIT: Here's the call stack when the exception occurs: mscorlib.dll!double.Parse(string s, System.Globalization.NumberStyles style, System.IFormatProvider provider) + 0x17 bytes System.Xml.dll!System.Xml.XmlConvert.ToDouble(string s) + 0x4b bytes System.Xml.dll!System.Xml.XmlReader.ReadContentAsDouble() + 0x1f bytes System.Runtime.Serialization.dll!System.Xml.XmlDictionaryReader.XmlWrappedReader.ReadContentAsDouble() + 0xb bytes System.Runtime.Serialization.dll!System.Xml.XmlDictionaryReader.ReadElementContentAsDouble() + 0x35 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlReaderDelegator.ReadElementContentAsDouble() + 0x19 bytes mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo rtmi, object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object parameters, System.Globalization.CultureInfo culture, bool isBinderDefault, System.Reflection.Assembly caller, bool verifyAccess, ref System.Threading.StackCrawlMark stackMark) mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture, ref System.Threading.StackCrawlMark stackMark) + 0x168 bytes mscorlib.dll!System.Reflection.MethodBase.Invoke(object obj, object[] parameters) + 0xa bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadValue(System.Type type, string name, string ns, System.Runtime.Serialization.XmlObjectSerializerReadContext context, System.Runtime.Serialization.XmlReaderDelegator xmlReader) + 0x138 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadMemberAtMemberIndex(System.Runtime.Serialization.ClassDataContract classContract, ref object objectLocal, System.Runtime.Serialization.DeserializedObject desObj) + 0xc4 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadClass(System.Runtime.Serialization.DeserializedObject desObj, System.Runtime.Serialization.ClassDataContract classContract, int membersRead) + 0xf3 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.Deserialize(System.Runtime.Serialization.XmlObjectSerializerReadContext context) + 0x36 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.InitializeCallStack(System.Runtime.Serialization.DataContract clContract, System.Runtime.Serialization.XmlReaderDelegator xmlReaderDelegator, System.Runtime.Serialization.XmlObjectSerializerReadContext xmlObjContext, System.Xml.XmlDictionaryString[] memberNamesColl, System.Xml.XmlDictionaryString[] memberNamespacesColl) + 0x77 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(System.Runtime.Serialization.XmlReaderDelegator xmlReader, System.Runtime.Serialization.XmlObjectSerializerReadContext context) + 0x5d bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(System.Runtime.Serialization.DataContract dataContract, System.Runtime.Serialization.XmlReaderDelegator reader) + 0x3 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator reader, string name, string ns, ref System.Runtime.Serialization.DataContract dataContract) + 0x10e bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator xmlReader, System.Type declaredType, System.Runtime.Serialization.DataContract dataContract, string name, string ns) + 0xb bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.DataContractSerializer.InternalReadObject(System.Runtime.Serialization.XmlReaderDelegator xmlReader, bool verifyObjectName) + 0x124 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator reader, bool verifyObjectName) + 0xe bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.Xml.XmlDictionaryReader reader) + 0x7 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream stream) + 0x17 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.Reload() + 0xa3 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.IsolatedStorageSettings(bool useSiteSettings) + 0x20 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.get() + 0xd bytes

    Read the article

  • LLBLGen Pro and JSON serialization

    - by FransBouma
    I accidentally removed a reply from my previous blogpost, and as this blog-engine here at weblogs.asp.net is apparently falling apart, I can't re-add it as it thought it would be wise to disable comment controls on all posts, except new ones. So I'll post the reply here as a quote and reply on it. 'Steven' asks: What would the future be for LLBLGen Pro to support JSON for serialization? Would it be worth the effort for a LLBLGenPro user to bother creating some code templates to produce additional JSON serializable classes? Or just create some basic POCO classes which could be used for exchange of client/server data and use DTO to map these back to LLBGenPro ones? If I understand the work around, it is at the expense of losing xml serialization. Well, as described in the previous post, to enable JSON serialization, you can do that with a couple of lines and some attribute assignments. However, indeed, the attributes might make the XML serialization not working, as described in the previous blogpost. This is the case if the service you're using serializes objects using the DataContract serializer: this serializer will give up to serialize the entity objects to XML as the entity objects implement IXmlSerializable and this is a no-go area for the DataContract serializer. However, if your service doesn't use a DataContract serializer, or you serialize the objects manually to Xml using an xml serializer, you're fine. When you want to switch to Xml serializing again, instead of JSON in WebApi, and you have decorated the entity classes with the data-contract attributes, you can switch off the DataContract serializer, by setting a global configuration setting: var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true; This will make the WebApi use the XmlSerializer, and run the normal IXmlSerializable interface implementation.

    Read the article

  • Mutating the expression tree of a predicate to target another type

    - by Jon
    Intro In the application I 'm currently working on, there are two kinds of each business object: the "ActiveRecord" type, and the "DataContract" type. So for example, we have: namespace ActiveRecord { class Widget { public int Id { get; set; } } } namespace DataContracts { class Widget { public int Id { get; set; } } } The database access layer takes care of "translating" between hierarchies: you can tell it to update a DataContracts.Widget, and it will magically create an ActiveRecord.Widget with the same property values and save that. The problem I have surfaced when attempting to refactor this database access layer. The Problem I want to add methods like the following to the database access layer: // Widget is DataContract.Widget interface DbAccessLayer { IEnumerable<Widget> GetMany(Expression<Func<Widget, bool>> predicate); } The above is a simple general-use "get" method with custom predicate. The only point of interest is that I 'm not passing in an anonymous function but rather an expression tree. This is done because inside DbAccessLayer we have to query ActiveRecord.Widget efficiently (LINQ to SQL) and not have the database return all ActiveRecord.Widget instances and then filter the enumerable collection. We need to pass in an expression tree, so we ask for one as the parameter for GetMany. The snag: the parameter we have needs to be magically transformed from an Expression<Func<DataContract.Widget, bool>> to an Expression<Func<ActiveRecord.Widget, bool>>. This is where I haven't managed to pull it off... Attempted Solution What we 'd like to do inside GetMany is: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( predicate.Body, predicate.Parameters); // use lambda to query ActiveRecord.Widget and return some value } This won't work because in a typical scenario, for example if: predicate == w => w.Id == 0; ...the expression tree contains a MemberAccessExpression instance which has a MemberInfo property (named Member) that point to members of DataContract.Widget. There are also ParameterExpression instances both in the expression tree and in its parameter expression collection (predicate.Parameters); After searching a bit, I found System.Linq.Expressions.ExpressionVisitor (its source can be found here in the context of a how-to, very helpful) which is a convenient way to modify an expression tree. Armed with this, I implemented a visitor. This simple visitor only takes care of changing the types in member access and parameter expressions. It may not be complete, but it's fine for the expression w => w.Id == 0. internal class Visitor : ExpressionVisitor { private readonly Func<Type, Type> dataContractToActiveRecordTypeConverter; public Visitor(Func<Type, Type> dataContractToActiveRecordTypeConverter) { this.dataContractToActiveRecordTypeConverter = dataContractToActiveRecordTypeConverter; } protected override Expression VisitMember(MemberExpression node) { var dataContractType = node.Member.ReflectedType; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); var converted = Expression.MakeMemberAccess( base.Visit(node.Expression), activeRecordType.GetProperty(node.Member.Name)); return converted; } protected override Expression VisitParameter(ParameterExpression node) { var dataContractType = node.Type; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); return Expression.Parameter(activeRecordType, node.Name); } } With this visitor, GetMany becomes: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var visitor = new Visitor(...); var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( visitor.Visit(predicate.Body), predicate.Parameters.Select(p => visitor.Visit(p)); var widgets = ActiveRecord.Widget.Repository().Where(lambda); // This is just for reference, see below Expression<Func<ActiveRecord.Widget, bool>> referenceLambda = w => w.Id == 0; // Here we 'd convert the widgets to instances of DataContract.Widget and // return them -- this has nothing to do with the question though. } Results The good news is that lambda is constructed just fine. The bad news is that it isn't working; it's blowing up on me when I try to use it (the exception messages are really not helpful at all). I have examined the lambda my code produces and a hardcoded lambda with the same expression; they look exactly the same. I spent hours in the debugger trying to find some difference, but I can't. When predicate is w => w.Id == 0, lambda looks exactly like referenceLambda. But the latter works with e.g. IQueryable<T>.Where, while the former does not (I have tried this in the immediate window of the debugger). I should also mention that when predicate is w => true, it all works just fine. Therefore I am assuming that I 'm not doing enough work in Visitor, but I can't find any more leads to follow on. Can someone point me in the right direction? Thanks in advance for your help!

    Read the article

  • AppFabric serialization problem.

    - by jandark
    I am trying cache a class instance with AppFabric but it return class instance with empty members. The reason is DataContract Attribute. My class is marked with [Serializable] and [DataContract(Name = "TestClass", Namespace = "CustomNameSpace.TestClass")] attributes. Problem solving if I mark all properties with DataMember or remove DataContract attribute. But I do not want to remove DataContract attributte because of other serialization needs (such as json or something else) Or I do not want to add DataMember attribute to other classes. (a lot of) Do you have any idea to solve that problem ? Thanks.

    Read the article

  • DataContractAttribute with Shared Assembly

    - by Sanju
    Hi All, Is it necessary to decorate custom objects with [DataContract] and [DataMember] when using shared assemblies (as opposed to auto proxy generation)? The reason I ask is that I have encountered the following scenario: Suppose the following object is implemented in my service: public class baseClass { Guid _guid; public baseClass() { _guid = Guid.NewGuid() } public Guid ReturnGuid { get {return _guid;}} } public class newClass : baseClass { int _someValue; public newClass {} public int SomeValue { get {return _someValue;} set {_someValue = value;} } } [ServiceContract] public IService { [OperationContract] newClass SomeOperation(); } In my client (with shared assemblie) I can happily recieve and use a serialized newClass when SomeOperation is called - even though I have not marked it as a DataContract. However, as soon as I do mark it with DataContract and use DataMember then it complains that set is not implemented on ReturnGuid in the base class. Could somebody explain why it works fine when I do not decorate with DataContract and DataMember. Many thanks.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >