RestSharp - Serialization and "[XmlAttribute]" - restsharp

RestSharp - I have a class which contains nested classes.
public class Extension
{
public ID ID { get; set; }
public Extension()
{
ID = new ID();
}
}
public class ID
{
public string typeCode { get; set; }
public string Value { get; set; }
}
I'm trying to serialise an instance using RestSharp
XmlSerializer xmlSerializer = new XmlSerializer("HellThere");
string myXml = xmlSerializer.Serialize(getCatalog);
This work perfectly, and gives me (snippet)
<Extension>
<ID>
<typeCode>PriceListShortName</typeCode>
<Value>GLUS</Value>
</ID>
</Extension>
But what I want is
<Extension>
<ID typeCode="PriceListShortName">GLUS</ID>
</Extension>
I've based my class ID on the "public class Image" suggestion at
RestSharp Documentation
I've also tried using
public class ID
{
[System.Xml.Serialization.XmlAttribute("typeCode")]
public string typeCode { get; set; }
public string Value { get; set; }
}
But that doesn't fix it. Any suggestions please?

Solution found!
I changed
XmlSerializer xmlSerializer = new XmlSerializer("HelloThere");
to
DotNetXmlSerializer xmlSerialiser = new DotNetXmlSerializer("HelloThere");
And now it works!!

Related

WCF with abstract base class with implemented interfaces does not serialize properly?

On the service side I have an abstract base class like so:
[DataContract]
public abstract class EntityBase : IObjectState, IDatabaseMetaData
{
[NotMapped]
[DataMember]
public ObjectState ObjectState { get; set; }
#region IDatabaseMetaData Members
[DataMember] public DateTime InsertDatetime { get; set; }
[DataMember] public int InsertSystemUserId { get; set; }
[DataMember] public DateTime? UpdateDatetime { get; set; }
[DataMember] public int? UpdateSystemUserId { get; set; }
public virtual SystemUser InsertSystemUser { get; set; }
public virtual SystemUser UpdateSystemUser { get; set; }
#endregion
}
Here is an implementing class (data contract):
[DataContract(Namespace = Constants.MyNamespace)]
public class AccountClass : EntityBase
{
[DataMember] public int AccountClassId { get; set; }
[DataMember] public string AccountClassCode { get; set; }
[DataMember] public string AccountClassDesc { get; set; }
}
On the client side I have essentially duplicated contracts. Here is the Client.AccountClass:
public class AccountClass : ObjectBase
{
private int _accountClassId;
private string _accountClassCode;
private string _accountClassDesc;
public int AccountClassId
{
get { return _accountClassId;}
set
{
if (_accountClassId == value) return;
_accountClassId = value;
OnPropertyChanged(() => AccountClassId);
}
}
public string AccountClassCode
{
get { return _accountClassCode; }
set
{
if (_accountClassCode == value) return;
_accountClassCode = value;
OnPropertyChanged(() => AccountClassCode);
}
}
public string AccountClassDesc
{
get { return _accountClassDesc; }
set
{
if (_accountClassDesc == value) return;
_accountClassDesc = value;
OnPropertyChanged(() => AccountClassDesc);
}
}
}
..and here is the parts of ObjectBase that matter:
public abstract class ObjectBase : IObjectState, IDatabaseMetaData
{
public ObjectState ObjectState { get; set; }
#region IDatabaseMetaData Members
public DateTime InsertDatetime { get; set; }
public int InsertSystemUserId { get; set; }
public DateTime? UpdateDatetime { get; set; }
public int? UpdateSystemUserId { get; set; }
#endregion
}
When I debug the service in my WcfMessageInspector.BeforeSendReply, I can see the message correctly sending the IObjectState and IDatabaseMetaData values. However, on the client side, they are always null (or default values). I have tried using KnownTypes, applying the namespace to the abstract class. The only way I can serialize everything correctly is to get rid of the interfaces and base classes all together and put the properties directly on the Client/Server AccountClass object. What am I missing here? Thanks.
Update 1
This seems to be a namespace thing. If I move my EntityBase and ObjectBase into the same CLR Namespace, everything works (with no KnownType attributes). In my client contract's AssemblyInfo.cs file I have this:
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Project.Name.Client.Entities")]
I tried adding ContractNamespaces here to no avail. Like I said, unless the EntityBase and ObjectBase are in the same namespace, it won't work. However, this is a problem for me because it creates a circular reference, unless I move a lot of stuff around.
Any idea how I can see what the full data contract (namespaces, DataMembers, etc) looks like just before/after serialization on the client/server? I tried intercepting the OnSerializing event without much luck. Thanks again.
This was a namespace issue.
I explicitly add the correct namespace to all parties involved and everything works great. One thing I notice is that the ContractNamespace's ClrNamespace in your AssemblyInfo.cs file should match the AssemblyTitle. Also, putting more than one ContractNamespace in the AssemblyInfo.cs does nothing. For example, I was doing this:
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Company.Project.Client.Entities")]
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Company.Project.Client.Entities.Core")]
Any POCO in the Company.Project.Client.Entities.Core would not serialize correctly until I explicitly put the DataContract namespace on it like so
[DataContract(Namespace = Constants.MyNamespace)]
public class SomeObject
{
[DataMember] public string SomeProperty { get; set; }
//..etc
}
Alternatively, I could have restructured the project so SomeObject was in the Company.Project.Client.Entities namespace and that would have worked.
Finally, the most helpful thing to debugging this was looking at the WSDL, and then using a custom IDispatchMessageInspector to see the actual messages AfterReceiveRequest and BeforeSendReply. Hopefully this helps someone.

howto initialize a wcf class

Im trying to use a Class in a WCF service. When im calling the
u.attributeChanges.Add(a);
i get:
"Object reference not set to an instance of an object"
If create the classes in the client application it's working.
UpdateChanges Class
[DataContract]
public class UpdateChanges
{
private void Initialize()
{
this.attributeChanges = new List<AttributeChanges>();
}
public UpdateChanges()
{
this.Initialize();
}
[DataMember]
public string objectGuid { get; set; }
[DataMember]
public Utilities.ObjectTypes objectType { get; set; }
[DataMember]
public Utilities.ChangeType changeType{ get; set; }
[DataMember]
public List<AttributeChanges> attributeChanges { get; set; }
[OnDeserializing]
public void OnDeserializing(StreamingContext ctx)
{
this.Initialize();
}
}
AttributeChanges class
[DataContract]
public class AttributeChanges
{
[DataMember]
public string attributeName { get; set; }
[DataMember]
public string attributeValue { get; set; }
}
Client Code:
Service.DirsyncServiceClient proxyClient;
proxyClient = Utilities.GetProxy("http://192.168.1.45/vDir/Service.svc");
Service.UpdateChanges u = new Service.UpdateChanges();
Service.AttributeChanges a = new Service.AttributeChanges();
a.attributeName = "Attribute1";
a.attributeValue = "Value1";
u.attributeChanges.Add(a);
proxyClient.SaveObject(u);
Anyonw know how to solve this?
You're using a generated client code.
The problem is that the client generates this code on base of the WSDL xlm. The code in the CTOR doesn't generated in the client because the client can't be aware of this code.
You have a few options-
1. Use a shared DLL with the data contract instead of generating it via a web reference.
2. Implement it yourself in a 'partial' class.

ADO.NET Entity Framework on Vs2012 + WCF = Error

First of all, thanks for reading my question.
I am developing a solution using VS 2012 using ADO.NET Entity Framework (5 i think, the latest version). All is working fine until I introduce a WCF service as a Business Layer (this is an assignment for school, I cannot scrap WCF from Business Layer).
The issue is that when I request data from the database. When I have a method that returns a string from the database, it works just fine (since its a primitive). But when it returns an Entity object (Such as Account), it all goes to hell.
Exception: (Yeah, its very vague).
An error occurred while receiving the HTTP response to http://localhost:8733/Services/AccountsManager. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
What I tried: I tried modifying the Entites.tt file to add the [DataContract] [DataMember] Attribute. This is because in the older versions of EF, it seemed to be doing it on its own. But I do not know if this is neccessary since it allows me to compile and does not complain that it is not serializable.
This is how it looks at first:
namespace CommonLayer
{
using System;
using System.Collections.Generic;
public partial class Account
{
public Account()
{
this.Transactions = new HashSet<Transaction>();
this.Transactions1 = new HashSet<Transaction>();
}
public System.Guid ID { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public int Currency { get; set; }
public decimal Balance { get; set; }
public System.DateTime DateOpened { get; set; }
public Nullable<int> Duration { get; set; }
public string UserName { get; set; }
public virtual AccountType AccountType { get; set; }
public virtual Currency Currency1 { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Transaction> Transactions1 { get; set; }
}
}
How it looks after modification:
namespace CommonLayer
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract] public partial class Account
{
public Account()
{
this.Transactions = new HashSet<Transaction>();
this.Transactions1 = new HashSet<Transaction>();
}
[DataMember] public System.Guid ID { get; set; }
[DataMember] public int Type { get; set; }
[DataMember] public string Name { get; set; }
[DataMember] public int Currency { get; set; }
[DataMember] public decimal Balance { get; set; }
[DataMember] public System.DateTime DateOpened { get; set; }
[DataMember] public Nullable<int> Duration { get; set; }
[DataMember] public string UserName { get; set; }
public virtual AccountType AccountType { get; set; }
public virtual Currency Currency1 { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Transaction> Transactions1 { get; set; }
}
}
Any pointers are greatly appreciated.
My WCF Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
[ServiceContract]
interface IAccountsManager
{
[OperationContract]
List<CommonLayer.Account> GetAccounts(String UserName);
[OperationContract]
String GetData();
[OperationContract]
CommonLayer.Account GetAccount(String UserName);
}
class AccountsManager: IAccountsManager, IDisposable
{
public List<CommonLayer.Account> GetAccounts(String UserName)
{
return DataLayer.AccountsRepository.Instance.GetAccountList(UserName).ToList();
}
public String GetData()
{
CommonLayer.Account acc = this.GetAccounts("test").FirstOrDefault();
return acc.DateOpened.ToString();
}
public CommonLayer.Account GetAccount(String UserName)
{
return this.GetAccounts(UserName).FirstOrDefault();
}
public void Dispose()
{
DataLayer.AccountsRepository.Reset();
}
}
}
You need to use a DTO (Data Transfer Object) and map from your EF object to your DTO.
So the service might accept an object called MyDto looking like:
[DataContract]
public class MyDto {
[DataMember]
public int Id {get;set;}
}
and a static mapping class with methods
public static MyEntity Map(MyDto dto) {
return new MyEntity { Id = dto.Id };
}
public static MyDto Map(MyEntity entity) {
return new MyDto { Id = entity.Id };
}
You can then map as required so that the service can use the DTO and Entity Framework can use the Entity.
It seems that when the EF class has Navigation properties (like ICollection<Transaction> Transactions in your class) it will fails when being transferred over WCF.
After many searches I could not find any solution except mapping an EF class into equivalent DTO class that is exactly the same as the EF class except the Navigation propertis and the constructor (i.e. I have stripped all virtual propertis (like ICollection ones) and the ctor from the EF class and have created from that a new class called the same as my EF class plus Dto suffix (e.g. CustomerDto).
I've used AutoMapper to automatically map an EF object into Dto-equivalent one. E.g:
var customer = getCustomer(cid);
var customerDto = Mapper.Map<CustomerDto>(customer);
return customerDto;
My WCF contract includes
[OperationContract]
CustomerDto getCustomerData(int cid);
In addition I needed to do one time initialization of the Mapper. I've done it within Global.asax as follows:
Mapper.CreateMap<Customer, CustomerDto>();
What I have done is changed my Entities.Edmx file. Firstly, I deleted all (2) ".tt" files. Then i changed Code Generation Strategy from None to Default. This seemed to solve all my problems.

How to setup a DataContract to match the complex XML input in WCF 4.0 REST Service

I have a XML structure like this:
<Message>
<Messagehead>
<OSType>Android</OSType>
<RouteDest>SiteServerName</RouteDest>
<ActionType>Enroll</ActionType>
</Messagehead>
<MessageBody>
<Raw>
<![CDATA[OrienginalMessageContent]]>
</Raw>
</MessageBody>
</Message>
and I want upload this XML to WCF 4.0 my rest service:
public string Enroll(Message instance)
{
// TODO: Add the new instance of SampleItem to the collection
return "success";
}
the Message is a DataContract type, I setup it like below:
[DataContract(Namespace = "")]
public class Message
{
[DataMember]
public MessageHead MessageHead { get; set; }
[DataMember]
public MessageBody MessageBody { get; set; }
}
public class MessageHead
{
public OSType OSType { get; set; }
public string RouteDest { get; set; }
public Action Action { get; set; }
}
public class MessageBody
{
public string RawRequestContent { get; set; }
}
but when I get the Message instance from the server side, all the property is null, except the OSType, can anybody tell me why? How could I solve this problem?
Besides being a really bad name for a class (since it's already used in the WCF runtime), your Message class also has some flaws:
<Message>
<Messagehead>
....
</Messagehead>
Your <Messagehead> has a lower-case h in the middle - yet your class defines it to be upper case:
[DataContract(Namespace = "")]
public class Message
{
[DataMember]
public MessageHead MessageHead { get; set; }
This will not work - case is important and relevant in a WCF message! If your XML has a lower-case h, so must your DataContract class!
Your XML also requires a <Raw> tag inside your <MessageBody>
<MessageBody>
<Raw>
<![CDATA[OriginalMessageContent]]>
</Raw>
</MessageBody>
yet your data contract doesn't respect that:
public class MessageBody
{
public string RawRequestContent { get; set; }
}
Again - those don't line up! Names are important - and they must match between your XML representation of the message, and the C# class representing that message.....

WCF DataContractSerialzer xml to object incomplete results

I'm creating a wcf wrapper service that returns xml from another web service.
What I'm noticing is that not all the xml from the source is being serialized to my object.
Here's the source xml:
<?xml version="1.0" standalone="yes"?>
<methodResponse>
<requestId>234843080</requestId>
<errorCode>0</errorCode>
<errorText></errorText>
<processingTime>00:00:00.234</processingTime>
<results>
<resultCode>0</resultCode>
<resultText></resultText>
<resultCount>1</resultCount>
<totalResultCount>1</totalResultCount>
<result>
<contactId>123</contactId>
<sourceFolderId>3443</sourceFolderId>
<contactState>4</contactState>
<contactStateSortOrder>3</contactStateSortOrder>
<contactType>person</contactType>
<displayName>Bond, James</displayName>
<office>unknown</office>
<department></department>
<changeDate></changeDate>
<firstName>James</firstName>
<middleName></middleName>
<lastName>Bond</lastName>
<jobTitle>Spy</jobTitle>
<ape>
<address type='Street' typeId='1' relationship='Business' relationshipId='1'>
<addressLine></addressLine>
<city></city>
<state></state>
<postalCode></postalCode>
</address>
<phone type='Phone' typeId='1' relationship='Business' relationshipId='1'>
<phoneNumber></phoneNumber>
<description/>
<formattedPhone></formattedPhone>
</phone>
</ape>
</result>
</results>
</methodResponse>
The wcf wrapper service:
[DataContract(Name="methodResponse", Namespace = "")]
public partial class methodResponse {
[DataMember]
public int errorCode {
get;
set;
}
[DataMember]
public string errorText {
get;
set;
}
[DataMember]
public string requestId
{
get;
set;
}
[DataMember]
public methodResponseResults[] results
{
get;
set;
}
}
[DataContract(Namespace = "")]
public partial class methodResponseResults
{
[DataMember]
public string resultCode {
get;
set;
}
[DataMember]
public string resultText {
get;
set;
}
[DataMember]
public string resultCount {
get;
set;
}
[DataMember]
public string totalResultCount {
get;
set;
}
[DataMember]
public methodResponseResultsResult[] result {
get;
set;
}
}
[DataContract(Namespace="")]
public partial class methodResponseResultsResult {
public string contactId
{
get;
set;
}
public string displayName
{
get;
set;
}
}
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class WcfWrapperService
{
public Response GetXml()
{
string uri = ""; // uri to source web service
var dataContractSerializer = new DataContractSerializer(typeof(methodResponse));
using (XmlReader reader = XmlReader.Create(uri))
{
var result = (methodResponse)dataContractSerializer.ReadObject(reader);
//result object looks like:
//result.errorCode = 0;
//result.errorText = null;
//result.requestId = 234843080;
//result.results = methodResponseResults[0];
}
// return Response object
}
}
The errorCode, errorText, requestId values are there but no results.
The first thing that jumps out is that you are trying to de/serialize a contract which contains attributes. DataContractSerializer has a few restrictions, one of which is that it can only serialize/deserialize elements. In order to properly handle this Schema, you will need to use an XmlSerializer.
Your not setting any values for the Order property on your DataMember attributes. This means that the elements will be processed in alphabetical order which is most likely NOT what you want. You must explicitly set Order to ensure it matches the schema of the documents you will process. You may also need to set IsRequired = false if there are any elements that may or not be in the instance document.