Storing something other than a string in SuspensionManager.SessionState - windows-8

The sample apps include a Suspension Manager class that stores session state in a Dictionary, but never attempt to store anything except a string in it.
Whenever I store anything else but a string, then trigger the serialization, I get the following error
Type 'System.RuntimeType' with data contract name 'RuntimeType:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Do I have to do something else to be able to store other types in SessionState?

You will need to do two things:
Firstly, ensure the type you are (de)serializing is decorated with the DataContract attribute from System.Runtime.Serialization and ensure it's members are decorated appropriately. For example in c#:
[DataContract]
public struct Product
{
[DataMember]
public Guid Id { get; set; }
[DataMember]
public DateTime ManufactureDate { get; set; }
[DataMember]
public decimal Cost { get; set; }
}
Secondly you will need to call SessionManager's AddKnownType<T>() (with T being the type you need) before attempting to (de)serialize it.

looking at the SessionManager code it is only string types, guess you will have to 'roll your own'
http://code.msdn.microsoft.com/windowsapps/ApplicationData-sample-fb043eb2/sourcecode?fileId=43552&pathId=6033729

Related

Passing an inherited "Data Contract" through WCF call?

One of my WCF endpoints has this method:
GetData(DataTable dt)
I tried to create a class on the client that inherits from the DataTable class
public class ExtendedDataTable : DataTable{
//...implementation
}
and pass it along with the endpoint call:
GetData(new ExtendedDataTable());
Then I got the SerializationException. Accordingly to the error, it suggests that I use either DataContractResolver or the KnownType attribute.
I don't want to use the KnownType, because I shouldn't have to update the endpoint every time someone decides to inherit my DataContract. I can't write any DataContractResolver, because I didn't extend the exact structure of the DataTable class. Is it possible to to extend a DataContract from the client?
If so, what's the best practice?
Thanks!
I don't recommend using the Datatable, which makes it easy for WCF to have problems with client and server serialization, such as the need to specify a table name. It is best to use a custom data type, we can use the inheritance type with the KnownType attribute.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types
On my side, I can't use the inherited Datatable, while I could use an arbitrary custom class by using Knowntype attribute.
Please refer to my code segments.
[DataContract]
[KnownType(typeof(Product))]
public class MyData
{
[DataMember]
public ProductBase Product { get; set; }
}
[DataContract]
public class ProductBase
{
[DataMember]
public int ID { get; set; }
}
[DataContract]
public class Product : ProductBase
{
[DataMember]
public string Name { get; set; }
}
You can try to inherit DataTable and explicitly use DataContract attribute to declare it's name as "DataTable".
But I'm not sure about purpose of this replacement. Server side will see only what is related to original data contract. Even when new properties gets serialized, deserializatin will only work for server side properties. Unless some custom deserialization will be provided.
In all scenarios, using DataTable is not good idea at all as Abraham Qian already pointed out.

how to serialize Microsoft.AspNet.Identity.UserLoginInfo class?

I am using Microsoft.AspNet.Identity.UserLoginInfo class in my WCF service.
However, I am getting following error -
Type 'Microsoft.AspNet.Identity.UserLoginInfo' cannot be serialized.
Consider marking it with the DataContractAttribute attribute, and
marking all of its members you want serialized with the
DataMemberAttribute attribute. If the type is a collection, consider
marking it with the CollectionDataContractAttribute. See the
Microsoft .NET Framework documentation for other supported types
As the class is in-build provided in Microsoft.Aspnet.Identity library, and also marked as Sealed, I am not getting much help on extending that to make it accessible within my WCF service.
Any help on this will be much appreciated.
Thanks
As it says... you can't. The "Consider marking it with the DataContractAttribute attribute..." is misleading since you CAN'T do this unless you have the source code. I'm assuming that your just want to send some serialized object with a couple properties back to your client. I'd try to just map the current identity to a serializable object and send it back.
[DataContract]
public class MyUserLoginInfo
{
[DataMember]
public string LoginProvider { get; set; }
[DataMember]
public string ProviderKey { get; set; }
}
The later on...
//Return me to client
var loginInfo = new MyUserLoginInfo { LoginProvider = myIdentity.LoginProvider, ProviderKey = myIdentity.ProviderKey };

WCF DataContract Attribute

I have a question about the [DataContract] attribute.
I have written my code like below: here I am not using [DataContract] attribute for my test class.
class test
{
[Datamember]
public string Strproperty
{
get;
set;
}
[Datamemer]
public string Strproperty2
{
get;
set;
}
}
class checktotal:Iservice
{
public string testmethod(test obj)
{
return obj.Strproperty+Strproperty2;
}
}
For that I am sending data from client I am getting the values correctly.
Here is it necessary to use [DataContract] attribute for that test class?
If I removed [Datamember] for test class property is getting error while sending from client. But I am not getting any errors even if I am not using the [DataContract] attribute.
Please give me a brief explanation with example so that I can understand when to give that attribute and when do not give that attribute.
Thanks,
Satya Pratap.
The DataContractSerializer can deal with classes that do not have the DataContract attribute if they provide a default constructor. See the MSDN documentation for more details.
As of .NET 3.5 Service Pack 1, you can omit (not use) the [DataContract] and [DataMember] attributes. If you do that, then the DataContractSerializer in WCF will behave just like the XML serializer - it will serialize all public properties only.
I prefer to use [DataContract] and [DataMember] explicitly anyway - it gives me the opportunity to specify options (like the data contract's XML namespace, the order of the [DataMember]) and it lets me e.g. also exclude certain properties from serialization.
As soon as you start using [DataMember] on one property, then only those properties decorated with a [DataMember] will be looked at for the WCF serialization.

Can't serialize nested nHibernate entity for WCF web service

I'm trying to use nHibernate, Spring and WCF together. I've got an Order object, and that contains a Customer object.
I can call a WCF method findOrder on my service, and providing the Order's Customer field does not have a DataMember annotation, the Web Service returns the Order I wanted. It does not contain the Customer details though, as expected.
But when I try to include the Customer as well, the WebService fails, and looking in the WCF trace logs, I can see this error:
System.Runtime.Serialization.SerializationException:
Type 'DecoratorAopProxy_95d4cb390f7a48b28eb6d7404306a23d' with data contract name
'DecoratorAopProxy_95d4cb390f7a48b28eb6d7404306a23d:http://schemas.datacontract.org/2004/07/'
is not expected. Consider using a DataContractResolver or add any types not known statically to
the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer
Pretty sure this is because the Customer contains extra nHibernate details, but I don't understand why WCF would be happy to send the Order, but not the Customer.
Can anyone help me understand?
Order object
[DataContract]
[KnownType(typeof(Customer))]
public class Order
{
// Standard properties
[DataMember]
public virtual int Id { get; set; }
public virtual Enums.OrderStatus Status { get; set; }
[DataMember]
[StringLength(20, ErrorMessage = "Order name must not be more than 20 characters long")]
public virtual string Name { get; set; }
[DataMember]
public virtual Customer Customer { get; set; }
[DataContract]
...
}
Customer object
public class Customer
{
public virtual int CustomerId { get; set; }
[DataMember]
private string name = "";
...
}
You should use a data transfer objects (DTO) to get your data over the wire. This is good practice anyway as you do not want to let your domain model leak into (and out of) the boundaries of your application.
Think about things like every change in your domain model results in a change of your data contract, resulting in a new wsdl, resulting in a change on the client. In addition you are telling the consumer of your service too many insights of your aplication.
Despite all this architectural bla bla. NHibernate uses proxies to enable lazy loading, those proxies are of another type than you serializer expects. You can disable lazy loading for your domain to get the application working. This is imho a bad idea.
<class name="Customer" table="tzCustomer" lazy="false" >

How do you send complex objects using WCF? Does it work? Is it good?

Can I have a data contract of this shape??
[DataContract]
public class YearlyStatistic{
[DataMember]
public string Year{get;set;}
[DataMember]
public string StatisticName {get;set;}
[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};
I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?
To use the same model for web services, mark your class as Serializable use the XmlRoot and XmlElement in the System.Xml.Serialization namespace. Here is a sample using your example:
[Serializable]
[XmlRoot("YearlyStatistic")]
public class YearlyStatistic
{
[XmlElement("Year")]
public string Year { get; set; }
[XmlElement("StatisticName")]
public string StatisticName { get; set; }
[XmlElement("MonthlyStats")]
public List<MonthlyStatistic> MonthlyStats { get; set; }
}
You will have to do the same thing for your complex object properties of the parent object.
Yep, thats standard WCF serialization right there. Are you trying to say the MonthlyStats collection has a property called WeeklyStats, or that each individual MonthlyStatistic has a WeeklyStat collection? If its the former, that doesnt work in WCF natively. You will have to do some fiddling in order to get it to work. If its the latter, its perfectly fine.
Yes, you can send the data contract you mentioned above back and forth from a WCF service. Like you said, MonthlyStatistic and all its members will have to be defined as data contracts themselves or be built in types (like strings).
You can even send and receive more complex types like when you have a base class but want to send or receive an object of a derived class (you would do that using the KnownType attribute). While receiving (de-serialization), from Javascript, there's a trick using which you have to specify the type for WCF. If you are interested, feel free to ask.