Can I deserialize an object in the Silverlight 3.0 runtime that was serialized using the full .NET 2.0 runtime using the BinaryFormatter? I am using the following code to serialize an object to a ByteArray which we write to a DB table:
MemoryStream serStream = new MemoryStream();
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(serStream, csMetric);
serStream.Position = 0;
return serStream.ToArray();
The Silverlight client then needs to retrieve this binary data from the DB (via a Web service call) and deserizlize the bytes back into an instance of the csMetric class.
Is this possible? If so, how is that done on the client given that the BinaryFormatter is not availble in the SL 3.0 runtime?
Thanks,
jon
Since you have to go through WCF, and thus the full .NET Framework, to get the data into Silverlight anyway I'd recommend deserializing the object on the server before sending it back to Silverlight. The Silverlight 3 WCF stack supports binary WCF encoding which should make the data transfer reasonably efficient.
Jon,
Have you tried to deserialize the object using the DataContractSerializer? I have not tested this exact scenario, but this is how I would approach it:
the following is an extension method off of a byte array (byte[]):
pubilc static T Deserialize<T>(this byte[] yourSerializedByteArray)
{
T deserializedObject;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using(MemoryStream ms = new MemoryStream(yourSerializedByteArray))
{
deserializedObject = (T)serializer.ReadObject(ms);
}
return deserializedObject;
}
Maybe one would like to try my SharpSerializer. It can serialize data to the both binary and xml format. It works on .NET Full, Compact und Silverlight.
DataContractSerializer has a whole bunch of problems, I've created a binary serializer that removes some of them (at least for me!) It uses reflection and produces reasonably compact representations that can be sent to WCF services.
More info here.
Related
I cannot find the System.Security.Cryptography.RNGCryptoServiceProvider class in .NetCore.
It is essential to the application I am trying to port from .Net Framework, as it is being used to generate an initialisation vector for encryption.
Does it exist under a different name, or is there another way of achieving this functionality?
System.Security.Cryptography.RandomNumberGenerator is the base class for Cryptographically-Secure Pseudo-Random Number Generator (CSPRNG) implementations. In .NET Framework RandomNumberGenerator.Create() returns an RNGCryptoServiceProvider instance (unless configured differently by CryptoConfig). In .NET Core RandomNumberGenerator.Create() returns an opaque type which is based on BCryptGenRandom (Windows) or OpenSSL's random number generator (!Windows).
RandomNumberGenerator.Create() is the only way to get an RNG instance on .NET Core, and since it works on both .NET Core and .NET Framework is the most portable.
Of course, if you're generating an IV, you can also just call the instance method SymmetricAlgorithm.GenerateIV() to have it use the CSPRNG internally; though as the documentation says, calling it is unnecessary as a random IV is created with the instance (GenerateIV can be used to force it to generate a new one before the next call to CreateEncryptor).
One of the solutions suggested is to use RandomNumberGenerator.Create()
https://github.com/dotnet/corefx/issues/2881
We can do it like this in .Net core. It worked for me.
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
var byteArray = new byte[4];
provider.GetBytes(byteArray);
//convert 4 bytes to an integer
var randomInteger = BitConverter.ToUInt32(byteArray, 0);
It is present under the namespace : System.Security.Cryptography
add this in your class to use the method :
using System.Security.Cryptography;
Hope it is Helpful.
Thanks
I have a WCF service which transport mode is set to Streamed. The service need to accept a stream.
My Client is Compact Framework 3.5. In the client I have n list object that carries large data. I want to serialize this object to stream and send it to WCF service where I will deserialize it.
This turn out to be a mission because of the limited serialization options in Compact Framework.
Currently I have the following for the serializing:
ServiceClient sc = new ServiceClient(CommonClient.MyDefaultBinding(), CommonClient.MyEndpointAddress);
MemoryStream s = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(ScannerService.AscAssetCaptureCollection));
serializer.Serialize(s, serverCollection);
OnComplete(sc.Send((Stream)s));
This is not working. The error I'm getting when trying to send is:
The type System.IO.MemoryStream was not expected. Use the XmlInclude or SoapInclude >attribute to specify types that are not known statically.
Does anyone know how can I achieve this?
There's no streaming from .NET CF. Because of memory limitations, the WCF version for .NET CF/WIN CE has a dramatically abbreviated tool set. The only option in your case for uploading files from a .NET CF device is buffering, though CF might be able to receive a stream (not sure. I've never tried it.) You're limited, too, in your binding options and encryption - SSL won't work, only message encryption.
Here's a link to the subset of features available in .NET 3.5 CF
http://blogs.msdn.com/b/andrewarnottms/archive/2007/08/21/the-wcf-subset-supported-by-netcf.aspx
Good luck ... I was able to get files uploading/downloading to CF, but it wasn't easy.
I've just switched to using the new web api for MVC 4, and I am having great difficulty in deserializing the response from my webservice.
This is my server code:
IEnumerable<Fish> myList = GetFish();
return Request.CreateResponse(HttpStatusCode.OK, myList,"application/xml");
This is serialised as:
<ArrayOfFish xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/MySolution.NameSpace.Resources\" />
As there are no results returned.
When I try to parse this using the XmlMediaTypeFormatter, I get an error saying it wasn't expecting what it got.
My code to deserialise it hasn't changed from before I started using web api, and is simply:
return content.ReadAsAsync<T>(formatters).Result;
formatters is a List of formatters, containing only the XmlMediaTypeFormatter
T is a generic list of Fish
If I omit the "application/xml" type then it appears to send in JSon (as the result is []) however the client expects xml, and will not use a JSon serialiser on it for some reason, even if I explicitly put the type as text/json.
It should be fairly simple to deserialise objects as it's exactly what I was doing before, I've just changed my server very slightly to use CreateResponse to make a HttpResponseMessage instead of using HttpResponseMessage<T> directly, because the generic version isn't supported anymore. I can't find a single client/server example online of someone decoding the result into objects which is frustrating.
Any ideas?
An XmlSerializer can't serialize an interface (IEnumerable). Convert to a List before returning.
return Request.CreateResponse(HttpStatusCode.OK, myList.ToList(),"application/xml");
simlar question with references here - XmlSerializer won't serialize IEnumerable
I ended up discovering that the serialization method web api uses is very slightly different to the former, standard way. I added this to my global.asax and it resolved the issue:
GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter() { UseXmlSerializer = true });
I have a WCF Restful Service that returns JSON objects that my iPhone and Android apps consume nicely. This is my first attempt at building something like this and I left WP7 till last as my background lies with C# and VS2010. But it seems it’s not going to be a simple as I had guessed.
So I guess I have three questions:
1, Can I consume JSON objects in WP7? If so does anyone know of a tutorial?
2, if not, can I use the existing service and build some new contracts for consumption in WP7? Or,
3, do I need to build a whole new service?
Option one is most desirable but either way, I need to develop for all three operating systems so does anyone know the best type of model to bring this all together???
Cheers,
Mike.
Yes, but not with the channel factory / proxy programming model which you may be used to with WCF. REST services are usually consumed by using some simpler classes such as WebClient. You can use the JSON libraries (DataContractJsonSerializer is in the WP7 profile) then to deserialize the data you receive. Even the untyped JSON (the System.Json classes from the System.Json.dll on Silverlight), while not officially in the profile, they kind of work on WP7 as well (I've seen a few people simply referencing the SL library on a WP7 project).
If you want proxy support, you can add a new endpoint to the service using BasicHttpBinding, which is supported in WP7; if you don't need it, see 1).
No. See 1) and 2).
Try this to deserialize a JSON object:
public static T Deserialize<T>(string strData) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
byte[] byteArray = Encoding.UTF8.GetBytes(strData);
MemoryStream memoryStream = new MemoryStream(byteArray);
T tRet = serializer.ReadObject(memoryStream) as T;
memoryStream.Dispose();
return tRet;
}
I find a totally wcf-based approach more interesting.
This is a good post that addresses this issue
http://blogs.msdn.com/b/carlosfigueira/archive/2010/04/29/consuming-rest-json-services-in-silverlight-4.aspx
So here's the problem - I have a DataTable I want WCF (.NET 3.5) to send out in a JSON store format commonly used in ExtJS, etc - basically "Rows[{"Field1":value,"Field2":value},{...}]" but I cannot find the right structure to feed back to the Operation contract to send it out in this format.
So any ideas, or any further info needed.
Thanks, in advance!
AndyPC, unfortunately, you're out of luck.
If you're dealing with an object whose type is an IXmlSerializable, the WCF JSON serializer delegates to IXmlSerializable methods first, gets the serialized XML out of them, wraps the XML in a JSON string, and just passes that on. This is one of the major weaknesses of the WCF JSON model in .NET 3.5. I think the entity framework (WCF Data Services) technologies try to handle this more elegantly, but not sure. I'd recommend manually using the JSON serializer and crafting up a string or a manual serialization mechanism that does what you want...