Weird message getting with serialization and c# - c#

I tried to send it from one client to another, and the source, destination and the data receive fine, but the string and the double become null. This is the code of the TcpObject:
[Serializable]
public class TcpObject
{
public Command Command { set; get; }
public Object Data { set; get; }
public int Source { set; get; }
public int Destination { set; get; }
public string IDString { set; get; }
public double exactTime { set; get; }
public TcpObject()
{
Command = Command.Null;
Data = null;
}
This is where I send the data:
TcpObject tcpObject = new TcpObject();
tcpObject.Command = Command.Msg;
tcpObject.Source = 1;
tcpObject.Destination = 2;
byte[] junkMsg = new byte[1000];
tcpObject.Data = junkMsg;
tcpObject.IDString = randomString();
tcpObject.exactTime = exactTime.ExactTime();
WorkClient.Send(tcpObject);
hread.Sleep(20);
And this is where I receive:
public void Listen()
{
try
{
while (Connected)
{
TcpObject tcpObject = new TcpObject();
IFormatter formatter = new BinaryFormatter();
tcpObject = (TcpObject)formatter.Deserialize(ServerSocket);
MessageBox.Show(tcpObject.IDString);
//TcpObject succeedTcpObject = new TcpObject();
//get the remainder of the time that the message got send and when the message got accepted.
}
}
catch (Exception) { }
}
This is the send function:
public static void Send(TcpObject tcpObject)
{
try
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ServerSocket, tcpObject);
}
catch (Exception) { }
}
The MessageBox that pops up is empty. I checked before I sent the msg and the string was present.
Thanks.

Obviously, you send garbage that is never initialized:
byte[] junkMsg = new byte[1000];
tcpObject.Data = junkMsg;
--SNIP--
WorkClient.Send(tcpObject);

Related

Avro serialization deserializate a datastructure to base type

I wonder if with Avro serialization can I serialize a type and deserializate to the base type?
For example if I run the following test I get an arithmeticOperationOverflow exception:
[DataContract(Name = "BaseMessage")]
public class BaseMessage
{
[DataMember(Name = "Id")]
public Guid Id { get; set; }
[DataMember(Name = "Topic")]
public string Topic { get; set; }
}
[DataContract(Name = "MyMessage")]
public class MyMessage : BaseMessage
{
[DataMember(Name = "Aggregate", IsRequired=false)]
public byte[] Aggregate { get; set; }
}
public class AvroSPec
{
[Fact]
public void I_class_can_be_serializated_an_then_deserializated_to_its_base_type()
{
BaseMessage actual = null;
var expected = new MyMessage
{
Id = Guid.NewGuid(),
Topic = StringExtensions.RandomString(),
Aggregate = Encoding.UTF8.GetBytes(StringExtensions.RandomString())//random
};
byte[] SerilizedStream = null;
using (MemoryStream stream = new MemoryStream())
{
AvroSerializer.Create<MyMessage>().Serialize(stream, expected);
SerilizedStream = stream.GetBuffer();
}
using (MemoryStream stream = new MemoryStream(SerilizedStream))
{
actual = AvroSerializer.Create<BaseMessage>().Deserialize(stream);
}
Assert.Equal(actual.Id, expected.Id);
Assert.Equal(actual.Topic, expected.Topic);
}
}
}
Thanks in advance

protobuf does not deserialize object corrctly

I have three classes:
[ProtoContract]
public class Message
{
[ProtoMember(1)]
public int MethodId { set; get; }
[ProtoMember(2)]
public CustomArgs Arguments { set; get; }
}
[ProtoContract]
public class CustomArgs
{
[ProtoMember(1)]
public int IntVal { set; get; }
[ProtoMember(2)]
public string StrVal { set; get; }
[ProtoMember(3)]
public CycleData Cd { set; get; }
}
[ProtoContract]
public class CycleData
{
[ProtoMember(1)]
public int Id { set; get; }
[ProtoMember(2, AsReference = true)]
public CycleData Owner { set; get; }}
So when I create objects then serialize and deserialize it the Arguments property stay null but orignal object have a value. The sample code is:
static void Main(string[] args)
{
CycleData cd = new CycleData()
{
Id = 5
};
cd.Owner = cd;
CustomArgs a = new CustomArgs()
{
IntVal = 5,
StrVal = "string",
Cd = cd
};
Message oldMsg = new Message()
{
MethodId = 3,
Arguments = a
};
Stream st = new MemoryStream();
ProtoBuf.Serializer.Serialize(st, oldMsg);
var newMsg = ProtoBuf.Serializer.Deserialize<Message>(st);
}
So newMsg.Arguments is null after deserialize. What i do wrong?
You have a simple error. Once you serialize/write to the memstream, the .Pointer remain at the end of the stream. Deserializing immediately after using on the same stream fails because there is nothing to read after that point. Just reset it:
using (Stream st = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(st, oldMsg);
st.Position = 0; // point to start of stream
var newMsg = ProtoBuf.Serializer.Deserialize<Message>(st);
}
I also put the stream in a using block to dispose of it.

How to read this JSON on Windows Phone?

I have to read this JSON :
[
{"id":"2","code":"jne","name":"JNE"},
{"id":"5","code":"pcp","name":"PCP"},
{"id":"1","code":"pos","name":"Pos Indonesia"},
{"id":"6","code":"wahana","name":"Wahana"}
]
I have tried this :
[DataContract]
public class Ekspedisi
{
[DataMember]
public int id { get; set; }
[DataMember]
public String code { get; set; }
[DataMember]
public String name { get; set; }
}
and this:
public static Ekspedisi[] res;
string link5 = "http://www.ongkoskirim.com/api/0.2/?id=OAL66afd139a386fee6dc5a5597abd7daba&q=expedition"
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(link5), UriKind.Absolute);
and this :
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
var ser = new DataContractJsonSerializer(typeof(Ekspedisi));
res = (Ekspedisi[])ser.ReadObject(e.Result);
for (int i = 0; i < length; i++)
{
Debug.WriteLine(res[i].id+","+res[i].name);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}
}
But it always showing invalidCastException. Can anyone help me?
When you are deserialising the JSON, you are using the type of Ekspedisi even though you are returning a collection. If you change this line of code:
var ser = new DataContractJsonSerializer(typeof(Ekspedisi));
to
var ser = new DataContractJsonSerializer(typeof(IEnumerable<Ekspedisi>));
which is a collection of your type; you will find you no longer receive the exception.

How to save/load an ObservableCollection of custom class type in WP7

I have created a custom class, named BrowserItem that I am using in my application, that contains a lot of values. I am using this class in an ObservableCollection to store a collection of items. For some reason, although this implementation works while my application is running, I cannot properly get these values to persist when the application closes and then reopens. I am not sure how to properly save and then reload the ObservableCollection of type BrowserItem.
BrowserItem.cs
[DataContract]
public class BrowserItem
{
[DataMember]
public FullWebBrowser Browser
{
get;
set;
}
[DataMember]
public string Url
{
get;
set;
}
[DataMember]
public BitmapImage ImageUri
{
get;
set;
}
[DataMember]
public string Title
{
get;
set;
}
[DataMember]
public string Notification
{
get;
set;
}
[DataMember]
public bool DisplayNotification
{
get
{
return !string.IsNullOrEmpty(this.Notification);
}
}
[DataMember]
public string Message
{
get;
set;
}
[DataMember]
public string GroupTag
{
get;
set;
}
[DataMember]
//for translation purposes (bound to HubTile Title on MainPage)
public string TileName
{
get;
set;
}
}
Setting.cs (my class that saves and loads from IsolatedStorage)
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
//Check for the cached value
if (!this.hasValue)
{
//Try to get the value from Isolated Storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
{
//It hasn't been set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
//Save the value to Isolated Storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
// Clear cached value
public void ForceRefresh()
{
this.hasValue = false;
}
}
Settings.cs (where the ObservableCollection is initialized)
public static Setting<ObservableCollection<BrowserItem>> BrowserList = new Setting<ObservableCollection<BrowserItem>>("Browsers", new ObservableCollection<BrowserItem>());
public static Setting<string> InitialUri = new Setting<string>("InitialUri", "http://www.bing.com");
In the above class, InitialUri works fine when new values are saved and then used later, but I believe the issue with the ObservableCollection is its type being BrowserItem. I do not know how to make it so BrowserItem will be able to be used in the ObservableCollection to save and retrieve items that are added to the ObservableCollection. An example of adding an item is below
TabsPage.xaml.cs
void addNew_Click(object sender, EventArgs e)
{
BitmapImage newTileImage = new BitmapImage();
var newItem = new BrowserItem() { Browser = new FullWebBrowser(), Url = "http://www.bing.com", ImageUri = newTileImage, Title = "new", /*Notification = "",*/ Message = "new browser", GroupTag = "TileGroup", TileName = "new" };
newItem.Browser.InitialUri = Settings.InitialUri.Value;
Settings.BrowserList.Value.Add(newItem);
}
Items in the ObservableCollection can be used while the application is active, but not once the application is activated once closed?
I had same kind of requirement in my earlier project
Create a class to save and read data from the ObservableCollection
public class SerializeHelper
{
public static void SaveData<T>(string fileName, T dataToSave)
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
if (store.FileExists(fileName))
{
store.DeleteFile(fileName);
}
using (IsolatedStorageFileStream stream = store.OpenFile(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, dataToSave);
}
}
catch (Exception e)
{
//MessageBox.Show(e.Message);
return;
}
}
}
public static T ReadData<T>(string fileName)
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
using (IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Read))
{
try
{
var serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
}
catch (Exception)
{
return default(T);
}
}
}
return default(T);
}
}
}
Saving Data in ISO Store
public ObservableCollection<CustomClass> AllEvents = new public ObservableCollection<CustomClass>();
//AllEvents.Add(customclassref1);
//AllEvents.Add(customclassref2);
//AllEvents.Add(customclassref3);
SerializeHelper.SaveData<ObservableCollection<CustomClass>>("AllEvents", AllEvents);
Retrieving Data from ISO store
AllEvents = (ObservableCollection<CustomClass>)SerializeHelper.ReadData<ObservableCollection<CustomClass>>("AllEvents");

How to connect to XML-RPC from c#

How to connect to XML-RPC Api from c# ,
A client can interact with a Pandorabot by POST'ing to:
http://www.pandorabots.com/pandora/talk-xml
The form variables the client needs to POST are:
botid - see H.1 above.
input - what you want said to the bot.
custid - an ID to track the conversation with a particular customer. This variable is optional. If you don't send a value Pandorabots will return a custid attribute value in the element of the returned XML. Use this in subsequent POST's to continue a conversation.
How to call?
This should get you going:
public void Talk()
{
string xmlResult = null;
Result result = null; // Result declared at the end
string botId = "c49b63239e34d1"; // enter your botid
string talk = "Am I a human?";
string custId = null; // (or a value )
using (var wc = new WebClient())
{
var col = new NameValueCollection();
col.Add("botid", botId);
col.Add("input", talk);
if (!String.IsNullOrEmpty(custId))
{
col.Add("custid", custId);
}
byte[] xmlResultBytes = wc.UploadValues(
#"http://www.pandorabots.com/pandora/talk-xml",
"POST",
col);
xmlResult = UTF8Encoding.UTF8.GetString(xmlResultBytes);
result = Result.GetInstance(xmlResultBytes);
}
//raw result
Console.WriteLine(xmlResult);
// use the Result class
if (result.status == 0) // no error
{
Console.WriteLine("{0} -> {1}",
result.input, result.that);
}
else // error
{
Console.WriteLine("Error: {0} : {1}",
result.input, result.message);
}
}
[XmlRoot(ElementName="result")]
public class Result
{
static XmlSerializer ser = new XmlSerializer(typeof(Result) , "");
public Result()
{
}
public static Result GetInstance(byte[] bytes)
{
return (Result)ser.Deserialize(new MemoryStream(bytes));
}
[XmlAttribute]
public int status { get; set; }
[XmlAttribute]
public string botid { get; set; }
[XmlAttribute]
public string custid { get; set; }
[XmlElement]
public string input { get; set; }
[XmlElement]
public string that { get; set; }
[XmlElement]
public string message { get; set; }
}

Categories

Resources