Program NETSerializableDemo;

{$APPTYPE CONSOLE}

uses
  System.IO, System.Runtime.Serialization,
  System.Runtime.Serialization.Formatters.Binary,
  System.Runtime.Serialization.Formatters.Soap;

type
  [Serializable] 
  TMyClass = class(System.Object, ISerializable)
  private
    sName : String;
    iSize : Integer;
  public
    Constructor Create;
    Constructor Create(info : SerializationInfo; context : StreamingContext);
    procedure GetObjectData(info : SerializationInfo; context : StreamingContext);

    function GetName : String;
    function GetSize : Integer;
  end;


{ TMyClass }

constructor TMyClass.Create;
begin
  inherited;

  sName := Self.ClassName;
  iSize := sizeof(Self);
end;

constructor TMyClass.Create(info: SerializationInfo;
  context: StreamingContext);
begin
  inherited Create;
  
  iSize := Integer(info.GetValue('iSize', typeof(Integer)) );
  sName := String(info.GetValue('sName', typeof(String)) );
end;

function TMyClass.GetName: String;
begin
  Result := sName;
end;

procedure TMyClass.GetObjectData(info: SerializationInfo;
  context: StreamingContext);
begin
  info.AddValue('iSize', iSize);
  info.AddValue('sName', sName);
end;

function TMyClass.GetSize: Integer;
begin
  Result := iSize;
end;

const
  PERFILE = 'TMyClass.xml';
var
  myObject : TMyClass;
  sm : Stream;
  bformatter : BinaryFormatter;
  spFormatter : SoapFormatter;
begin
  myObject := TMyClass.Create;

  try
    sm := System.IO.File.Open(PERFILE, FileMode.Create);
//    bformatter := BinaryFormatter.Create;
//    bformatter.Serialize(sm, myObject);
    spFormatter := SoapFormatter.Create;
    spFormatter.Serialize(sm, myObject);
  finally
    sm.Close();
    myObject := nil;
  end;

  try
    sm := System.IO.File.Open(PERFILE, FileMode.Open);
//    bformatter := BinaryFormatter.Create;
//    myObject := TMyClass(bformatter.Deserialize(sm) );
    spFormatter := SoapFormatter.Create;
    myObject := TMyClass(spFormatter.Deserialize(sm) );

    Console.WriteLine(myObject.GetName);
    Console.WriteLine(myObject.GetSize);
  finally
    sm.Close();
  end;
end.
