Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How can a dictionary be sent to the client From Server ?

I want to do I send the following dictionary

C#
Dictionary rates = new Dictionary<string,>(); 
        rates.Add("usd", 47.5); 
        rates.Add("eur", 60.4);
        rates.Add("ukp", 78.8);


Codes do not work.Where is my problem? Whether this approach is wrong ?

Please show me the correct code

code in server :


C#
public void GetListn()
    {
        var dataToSend = new DataToSend { Rates = new Dictionary<string,>() };

        dataToSend.Rates.Add("asd", decimal.Parse("12.23"));
        dataToSend.Rates.Add("asd", decimal.Parse("41.11"));
        dataToSend.Rates.Add("asd", decimal.Parse("25.23"));

        var stream = new MemoryStream();
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, dataToSend.Rates);

        client.Send(stream.ToArray());
    }


public class DataToSend
{
    public Dictionary<string,> Rates { get; set; }
}


code in Client :

C#
private void WindowLoaded(object sender, RoutedEventArgs e)
    {
        try
        {
            _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _server.Connect(_ipep);

            _server.Send(Encoding.Unicode.GetBytes("GetList"));

            _data = new byte[BufferSize];

            _recv = _server.Receive(_data);

            var stream = new MemoryStream(_server.Receive(_data));
            var formatter = new BinaryFormatter();
            var dataToSend = (DataToSend)formatter.Deserialize(stream);

        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK,
                                MessageBoxImage.Error);
        }

    public class DataToSend
    {
        public Dictionary<string,> Rates { get; set; }
    }
Posted
Updated 10-Nov-11 8:43am
v2

your code should work, if you are sending using TCP protocol then dictionary object stream should work only thing is at receiver you have to return back to dictionary object. you can use TCP Serialization.

If its HTTP then you can use HTTP Serialization but only thing on receiver side you need to have same Class to marshal the stream back to Object.
In your case, with strings it should work without any problem.

Regards
Rushi
 
Share this answer
 
How about:
C#
var dataToSend = new DataToSend { Rates = new Dictionary<string,>() };
dataToSend.Rates = (DataToSend)formatter.Deserialize(stream);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900