473,666 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Serialize

9 New Member
hi,

i am a newbe to c#, i'm trying to send en custom object from a client to a server, after reading a lot on the web ifound that i need to use:
BinaryFormatter , MemoryStream, and Serialize Function, and Deserialize Function,
but the thing is that when trying to Serialize and then Deserialize on the same project it's working perfectly, but when i send the message to the server and trying to Deserialize i get en exception "Unable to find assembly"...,
i read on the web that i need the two classes (both of the server and the client) need to be able to read the same assembly, telling the truth i don't know what they mean...!

my code is:

client:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.IO;
  8. using System.Runtime.InteropServices;
  9. using System.Runtime.Serialization;
  10. using System.Reflection;
  11.  
  12. namespace Client
  13. {
  14.     [Serializable]
  15.     class publicMessage
  16.     {
  17.         public publicMessage(string mTs,Color cTs)
  18.         {
  19.             this.MessageToSend = mTs;
  20.             this.ColorToSend = cTs;
  21.         }
  22.  
  23.         private string messageToSend;
  24.         private Color colorToSend;
  25.  
  26.         #region propertys
  27.         public string MessageToSend
  28.         {
  29.             get { return this.messageToSend; }
  30.             set { this.messageToSend = value; }
  31.         }
  32.         public Color ColorToSend
  33.         {
  34.             get { return this.colorToSend; }
  35.             set { this.colorToSend = value; }
  36.         } 
  37.         #endregion
  38.  
  39.         #region Serialize \ Deserialize
  40.         public static byte[] Serialize(publicMessage toSerialize)
  41.         {
  42.             BinaryFormatter bf = new BinaryFormatter();
  43.             bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
  44.  
  45.             //bf.Binder = new VersionConfigToNamespaceAssemblyObjectBinder();
  46.             MemoryStream ms = new MemoryStream();
  47.  
  48.             bf.Serialize(ms, toSerialize);
  49.             ms.Close();
  50.             return ms.GetBuffer();
  51.         }
  52.         public static publicMessage Deserialize(byte[] bytes)
  53.         {
  54.             BinaryFormatter bf = new BinaryFormatter();
  55.             bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
  56.             //bf.Binder=new VersionConfigToNamespaceAssemblyObjectBinder();
  57.             MemoryStream ms = new MemoryStream();
  58.  
  59.             ms.Write(bytes, 0, bytes.Count());
  60.             ms.Seek(0, 0);
  61.             return (publicMessage)(bf.Deserialize(ms));
  62.         } 
  63.         #endregion
  64.  
  65.         internal sealed class VersionConfigToNamespaceAssemblyObjectBinder : SerializationBinder
  66.         {
  67.             public override Type BindToType(string assemblyName, string typeName)
  68.             {
  69.                 Type typeToDeserialize = null;
  70.                 try
  71.                 {
  72.                     string ToAssemblyName = assemblyName.Split(',')[0];
  73.                     Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
  74.                     foreach (Assembly ass in Assemblies)
  75.                     {
  76.                         if (ass.FullName.Split(',')[0] == ToAssemblyName)
  77.                         {
  78.                             typeToDeserialize = ass.GetType(typeName);
  79.                             break;
  80.                         }
  81.                     }
  82.                 }
  83.                 catch (Exception e)
  84.                 {
  85.                     throw e;
  86.                 }
  87.                 return typeToDeserialize;
  88.             }
  89.         }
  90.     }
  91. }
as you can see i tried also to use a custom binder (i read it on other forum) but it didn't help, i have both on the server and both on the client the same code above, with a change in the namespace.
if someone can help me it will be great.

thank you
idan
Dec 6 '08 #1
4 2194
djidan
9 New Member
hi,
ok never mind, i figure it out my self.
and for the curious one the only thing that i needed to do is to add a reference to the other project of mine (server) in the client project and then make a object from the referenced class get the object from the socket and then convert it to the server class in the client project.
sound's easy hard to figure it out.

thank's anyway
Dec 6 '08 #2
mldisibio
190 Recognized Expert New Member
Hi djidan,

You found a legitimate workaround, but I just wanted to point out a few things.
1. What you are actually emulating is "Remoting." The Framework has some built in classes under System.Runtime. Remoting that can handle much of the client/server communication infrastructure and the serialization. You would only write your own serialization routines if they needed to be customized. Otherwise, it will serialize your objects for you out of the box.

That said, it could well be that it won't work for you and you need to write your own communication infrastructure. ..there are several ways to do the same thing...just pointing out Remoting.

2. When you think about what you are trying to accomplish, have two seperate and distinct applications, a client and a server, it sort of diminishes that architecture by then publishing the server assembly to the client. It is a legitimate workaround, and is often the easiest setup for initial development. But imagine you were publishing your client to your customers, but you did not want them to have access to your server library?

The workaround is to create a third library with objects you don't mind having public. The client references this library, and thereby the serialization works, and the server references the same library. Often these objects would be interfaces or abstract classes. Just enough for the client to have what it needs to reference the server, but no actual server code that someone could accidentally start using outside your client.

There are a lot of aspects to Remoting, too many for a short forum response. If anything I have mentioned peaks your interest, I suggest a good book on remoting, such as "Microsoft .NET Remoting" by Scott McLean.

The issue you are dealing with, if you were to google it or read about it, is "Remoting" and "Metadata dependency."
Dec 7 '08 #3
djidan
9 New Member
Hi mldisibio,

Thank you for your reply, about the issue of to put the code of the server in the client project, i already thought about what you said, and i wasn't sure what i need to do, if i need to link the client.exe to the server or to link the server.exe to the client, or to build a new project (as you said) and write the code that are relevent to both sides, and to give reference to both sides, there is somthing about what you saing that if i will realse the program "Client" as a new program to a lot of users they will be able to see my code, so i will listen to your advise and create a new project.
I have just one question is there any other way to that, or it's hard to explain on a forum?

thank's anyway

idan
p.s: not djidan
Dec 7 '08 #4
mldisibio
190 Recognized Expert New Member
Besides Scott McLean, another good remoting author is Ingo Rammer. You can find his website at thinktecture and some specific articles and facts at thinktecture - Resources. In particular, the .Net Remoting Best Practices pdf. As he notes, the syntax is dated to the 1.1 Framework, but the principles still apply. Some of the examples use SOAP, but the same architecture applies to straight binary serialization, which is what your are using.
At this site, you will find some sample source code which accompanies his book: Advanced .NET Remoting book. In the Chapter 3 samples, you the "Singleton Objects" sample presents three very simple sample classes:

- the server class "MyRemoteObject "
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Runtime.Remoting;
  3. using General;
  4. using System.Runtime.Remoting.Channels.Http;
  5. using System.Runtime.Remoting.Channels;
  6.  
  7. namespace Server{
  8.   class MyRemoteObject: MarshalByRefObject, IMyRemoteObject
  9.   {
  10.     int myvalue;
  11.     public MyRemoteObject()   {
  12.       Console.WriteLine("MyRemoteObject.Constructor: New Object created");
  13.     }
  14.  
  15.     public MyRemoteObject(int startvalue)     {
  16.       Console.WriteLine("MyRemoteObject.Constructor: .ctor called with {0}",startvalue);
  17.       myvalue = startvalue;
  18.     }
  19.  
  20.     public void setValue(int newval)    {
  21.       Console.WriteLine("MyRemoteObject.setValue(): old {0} new {1}",myvalue,newval);
  22.       myvalue = newval;
  23.     }
  24.     public int getValue()     {
  25.       Console.WriteLine("MyRemoteObject.getValue(): current {0}",myvalue);
  26.       return myvalue;
  27.     }
  28.   }
  29.  
  30.   class ServerStartup {
  31.     static void Main(string[] args)   {
  32.       Console.WriteLine ("ServerStartup.Main(): Server started");
  33.  
  34.       HttpChannel chnl = new HttpChannel(1234);
  35.       ChannelServices.RegisterChannel(chnl);
  36.       RemotingConfiguration.RegisterWellKnownServiceType(
  37.           typeof(MyRemoteObject),
  38.           "MyRemoteObject.soap", 
  39.           WellKnownObjectMode.Singleton);
  40.  
  41.       // the server will keep running until keypress.
  42.       Console.ReadLine();
  43.     }
  44.   }
  45. }
- the go-between class "IRemoteObj ect" which both the client and server have a reference to:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. namespace General{
  3.   public interface IMyRemoteObject  {
  4.     void setValue(int newval);
  5.     int getValue();
  6.   }
  7. }
- and the client class "Client"
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Runtime.Remoting;
  3. using General;
  4. using System.Runtime.Remoting.Channels.Http;
  5. using System.Runtime.Remoting.Channels;
  6. namespace Client
  7. {
  8.   class Client
  9.   {
  10.     static void Main(string[] args)
  11.     {
  12.       HttpChannel channel = new HttpChannel();
  13.       ChannelServices.RegisterChannel(channel);     
  14.       IMyRemoteObject obj = 
  15.       (IMyRemoteObject) Activator.GetObject(typeof(IMyRemoteObject), "http://localhost:1234/MyRemoteObject.soap");
  16.       Console.WriteLine("Client.Main(): Reference to rem.obj. acquired");
  17.  
  18.       int tmp = obj.getValue();
  19.  
  20.       Console.WriteLine("Client.Main(): Original server side value: {0}",tmp);
  21.       Console.WriteLine("Client.Main(): Will set value to 42");
  22.       obj.setValue(42);
  23.       tmp = obj.getValue();
  24.       Console.WriteLine("Client.Main(): New server side value {0}", tmp);
  25.       Console.ReadLine();
  26.     } 
  27.   }
  28. }
Again, the syntax to register the channels needs to be updated for 2.0, you don't need to use SOAP, but you get the basic idea. Your "clients" would only have access to the IRemoteObject interface. They could not do anything with it - they could not create a new instance, nor even mistakenly use it to directly access the server. However, it contains all the metadata needed by for the client to understand and deserialize the server object.
Dec 7 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

7
5826
by: Ian Tompsett | last post by:
H I was wondering if it possible for an object to serialize/deserialize itself from XML. I'd be guessing that it would need to use the XmlSerializer class, but that seems to want to create a brand new object when deserializing. In my case I have an existing object that I'd like to pass some XML to for the object to repopulate its member variables. Similarly I'd like it to be able to populate an XML string from the values of its member...
5
24698
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream s); public void Deserialize(Stream s); Within the MyUserControl class, there is a field of type MyInnerClass
10
4148
by: Dan | last post by:
All I Am Attempting To Serialize An Object To An XML File. Here Is The Code For That public string SaveNewSurvey( MutualSurveyObject mso_TempObject, int i_JobID ) { string s_RootFileName; string s_FinalFileName; try
3
10381
by: MAY | last post by:
Hi, I have a problem about serialize the form controls. I wrote a test program to test serialize a from but fail (->An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll) . Thx in advance. Here is the part of the code: Regards MAY
2
8877
by: films | last post by:
I understand the concept. Serialization of a class will add all the sub-objects of the class to the stream if there are also serializible. So say I have: class Author {
1
1468
by: js | last post by:
Does anybody knows how to solve the problem? I added attribute to the following classes in Microsoft.Practices.EnterpriseLibrary.Data namespace, but I still get the error. Thanks. Database.cs DatabaseFactory.cs DatabaseProviderFactory.cs DBCommandWrapper.cs
8
5446
by: cd~ | last post by:
I can provide a test app, the news server won't allow me to post the files because they are too large (93KB and 1.2KB) I downloaded the ESRI ArcXml schema and generated the classes from the schema using xsd.exe, which took a while because xsd doesn't handle recursive elements very well (StackOverFlow exception during generation). Now that I have the classes I am trying to serialize them to an xml document to send to ArcIMS to generate...
1
39693
by: Tim | last post by:
Could anyone tell me what this means and how do I correct it. Any suggestions? Thanks! Tim Richardson IT Developer and Consultant www.paladin3d.com Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same
4
7122
by: =?Utf-8?B?Qnlyb24=?= | last post by:
When I try to serialize an instance of the LocationCell below (note Building field) I get an error in the reflection attempt. If I remove the _Building field it serializes fine. I tried renaming Building._Name to Building._BName in case the duplicate name was the issue, but that didn't help. Is there a native way to serialize nested objects, or will I have to write my own? public class LocationCell
9
1889
by: Gillard | last post by:
i get an exeption and i do not know what else to do to continue Dim sdf As New SaveFileDialog With sdf .AddExtension = True .DefaultExt = ".record" .FileName = Now.ToLongDateString .Filter = "recorder (*.record)|*.record" End With If sdf.ShowDialog = Windows.Forms.DialogResult.OK Then Dim Serializer As New
0
8360
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8876
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8784
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8556
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8642
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2774
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1777
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.