Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 03-12-2006
aprendiz2 aprendiz2 is offline
Miembro
 
Registrado: dic 2006
Posts: 70
Poder: 18
aprendiz2 Va por buen camino
Ayuda! ObjectBinaryToText+WriteComponent+DefineProperties

Código Delphi [-]
{---------------------------------------------------------}
{ Delphi 5                                                }
{                                                         }
{ Descripcion del problema:                               }
{ 1)  ObjectBinaryToText reporta problemas al intentar    }
{    convertir un TComponent que contiene otro TComponent }
{    como miembro interno.                                }
{ El programa tiene 2 Botones:
{ TButton1 - Aparentemente funciona bien.. ( estara bien realmente ? ) }
{ TButton2 - Ahi hay problemas... por que ?               }
{---------------------------------------------------------}

unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;
type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  {----------------------------------}
  {   TMiembro pasa a ser un miembro }
  {   dentro de TPrincipal           }
  {----------------------------------}
  TMiembro = class( TComponent)
     private
         FAlgo2 : string;
     published
         property Algo2  : string read FAlgo2 write FAlgo2;
  end;
  {------------------------------------------------------}
  {  TPrincipal                                          }
  {                                                      }
  {  Se intenta :                                        }
  {   1) Pasar a un TMemoryStream un objeto de           }
  {      tipo TPrincipal - aparentemente se logra bien   }
  {                                                      }
  {   2) Convertir ese TMemoryStream a representacion en }
  {      texto - con el ObjectBinaryToText -- ahi sale   }
  {      el problema                                     }
  {------------------------------------------------------}
  TPrincipal = class( TComponent )
     private
         FAlgo1  : string;
         FMiembro : TMiembro;
     protected
         procedure DefineProperties( Filer : TFiler ) ; override;
         procedure LeeMiembro( Reader : TReader );
         procedure EscribeMiembro( Writer : TWriter );
     public
         constructor Create( aOwner : TComponent ); override;
         destructor  Destroy; override;
         property    Miembro : TMiembro read FMiembro write FMiembro;
     published
         property Algo1  : string read FAlgo1 write FAlgo1;
     end;
var
  Form1: TForm1;
implementation

{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
  var P1, P2 : TPrincipal ;
      MS     : TMemoryStream;
begin
   {-----------------------------------------------}
   {   Escribir el objeto P1 a un Stream           }
   {   y despues crear P2 a partir de ese stream   }
   {   ( Aparentemente funciona bien   )           }
   {-----------------------------------------------}
   P1 := TPrincipal.Create( nil );
   with P1 do
   begin
       Algo1 := 'JUAN';
       Miembro.Algo2 := 'PEDRO';
   end;
   MS := TMemoryStream.Create;
   MS.WriteComponent( P1 ) ;
   {--------------------------}
   { Crear P2 desde el Stream }
   {--------------------------}
   MS.Position := 0;
   P2 := MS.readComponent( nil ) as TPrincipal ;
   {--------------------------}
   {   Mostrar que hay en P2  }
   {--------------------------}
   ShowMessage( P2.Algo1 + '   ' + P2.Miembro.Algo2 );
   { Aparentemente todo salio bien aqui.... }
   P1.Free;
   P2.Free;
   MS.Free;
end;
{ TPrincipal }
constructor TPrincipal.Create(aOwner: TComponent);
begin
  inherited;
  FMiembro := TMiembro.Create( Self );
end;
procedure TPrincipal.DefineProperties(Filer: TFiler);
begin
  inherited;
 {-----------------------------------------------------------------------------------------}
 { Favor probar el programa "eliminando" la siguiente instruccion -ponerla como comentario }
 {-----------------------------------------------------------------------------------------}
  Filer.DefineProperty( 'Miembro', LeeMiembro, EscribeMiembro, FMiembro <> nil );
end;
destructor TPrincipal.Destroy;
begin
  FMiembro.Free;
  FMiembro := nil;
  inherited;
end;
procedure TPrincipal.EscribeMiembro(Writer: TWriter);
begin
   { En la Ayuda dice "Nunca llamar a Writer.WriteComponent",      }
   { pero no se otra forma de provocar la escritura de FMiembro,   }
   { aparentemente funciona bien con el WriteComponent....         }
   { Claro, se podria hacer FMiembro.writeString( Algo2 ),         }
   { pero esa no es la gracia,                                     }
   { cada objeto deberia escribir lo suyo...                       }
   Writer.writeComponent( FMiembro );
end;
procedure TPrincipal.LeeMiembro(Reader: TReader);
begin
   Reader.ReadComponent( FMiembro );
end;
procedure TForm1.Button2Click(Sender: TObject);
  var P1,P2 : TPrincipal;
      MS : TMemoryStream;
      SS : TStringStream;
begin
     {---------------------------------------------------}
     {   AYUDA !   AYUDA !   AYUDA !                     }
     { Se intenta convertir la representacion            }
     { de un objeto de clase TPrincipal a                }
     { texto con el ObjectBinaryToText,  pero falla      }
     { en la conversion.                                 }
     { Ojo: TPrincipal contienen un miembro.             }
     { los problemas                                     }
     {---------------------------------------------------}
     P1 := TPrincipal.Create( nil );
     P1.Algo1 := 'JUAN';
     P1.FMiembro.Algo2 := 'PEDRO';

     MS := TMemoryStream.Create;
     SS := TStringStream.Create('');
     { Escribimos P1 al MemoryStream MS }
     MS.WriteComponent( P1 );
     MS.Position := 0;
     {--------------------------------------------}
     { Comprobamos el contedido de MS, creando P2 }
     {--------------------------------------------}
     P2 := MS.ReadComponent( nil ) as TPrincipal;

     ShowMessage('Antes del ObjectBinaryToText' + #13 + ' P2 contiene:' + #13+#13+
                 P2.Algo1 + '   ' + P2.FMiembro.FAlgo2 );
     {---------------------------------------------}
     {        Aqui se nota el problema             }
     {---------------------------------------------}
     MS.Position := 0;
     ObjectBinaryToText( MS, SS );  { <------- AQUI SE REVIENTA   }
     ShowMessage('Despues del ObjectBinaryToText... pase bien !');

     SS.Position := 0;
     ShowMessage('Resultado en texto es: ' + #13 + SS.DataString );
     MS.Free;
     SS.Free;
     P1.Free;
     P2.Free;
end;
initialization
   RegisterClasses( [TPrincipal, TMiembro] );
end.

Última edición por dec fecha: 03-12-2006 a las 06:31:13.
Responder Con Cita
  #2  
Antiguo 03-12-2006
rounin rounin is offline
Miembro
 
Registrado: sep 2005
Posts: 43
Poder: 0
rounin Va por buen camino
Text Format de DFM no soporta este combinacion.

Hay tres casos (como yo se) de guardar los componentes en DFM
y ningun de ellos puede usarse con DefineProperties:

1) Referencia.
Se guarda como el nombre.
Código Delphi [-]
----------------------
  object Panel1: TPanel
  ..
    PopupMenu = PopupMenu1       {TOtherForm.PopupMenu1}
  ..
  end
----------------------
2) Componente filial (solo TControl)
Se guarda como
Código Delphi [-]
 
----------------------
  object Panel1: TPanel
    ..
    object Button1: TButton    {object/inherited/inline}
      Left = 48
      Top = 56
      ..
    end
    ..
  end
----------------------
3) Subcomponente
Se guarda como serie de propiedades.
No puede tener componentes filial (no tiene mecanismo de guardarlos en DFM).

Código Delphi [-]
----------------------
  object LabeledEdit1: TLabeledEdit
    ..
    EditLabel.Width = 62
    EditLabel.Height = 13
    EditLabel.Caption = 'LabeledEdit1'
    ..
  end
----------------------


En tu caso hay suguientes posibilidades:

1) Crear TMiembro como Subcomponent de TPrincipal.
(Sin DefineProperties)

Código Delphi [-]
 
constructor TPrincipal.Create(aOwner: TComponent);
begin
  inherited;
  FMiembro := TMiembro.Create( Self );
  FMiembro.SetSubcomponent(True);
end;


2) Usar Filer.DefineBinaryProperty en lugar de Filer.DefineProperty.
Datas escribidas por Filer.DefineBinaryProperty no estan combertido en texto.
Responder Con Cita
  #3  
Antiguo 03-12-2006
aprendiz2 aprendiz2 is offline
Miembro
 
Registrado: dic 2006
Posts: 70
Poder: 18
aprendiz2 Va por buen camino
Muchas gracias, Rounin por su paciencia ! Necesito mas su ayuda !

Probe FMiembro.SetSubcomponent(True);pero no compila ( estoy en Delphi 5 ).

Que estoy haciendo mal ? ( por favor tenga paciencia !.. tengo mucho que aprender ).

Pregunta 1

Hay algun problema "escondido" al llamar a Writer.Writecomponent para forzar la escritura de FMiembro ? ( olvidandonos por el momento de ObjectBinayToText )

Pregunta 2

Cual es la forma correcta de escribir el objeto Principal en el stream, para poderlo recuperar despues con un ReadComponent ? ( olvidandonos por el momento de ObjectBinayToText )

Pregunta 3

Si Principal es el owner de FMiembro, como logro que el streaming system lo escriba automaticamente al stream ? ( writeComponent( xForm ) lo hace muy bien ! ).
( he probado de muchas formas y no lo logro sin el DefineProperties ).


Gracias otra vez por su ayuda y paciencia !

aprendiz2
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Instalar Ayuda (.HLP) en la Ayuda de Delphi? MasterXP Varios 6 12-04-2006 06:57:49
Ayuda para crear ayuda... Gabriel2 Varios 2 10-06-2005 00:15:18
Leer la ayuda... Ayuda! MaJeSTiC Varios 0 04-08-2004 21:24:42
ayuda con strtofloat, ayuda punto flotante TURING Varios 5 30-04-2004 08:03:59
Ayuda Con Instalacion De Archivos De Ayuda Legolas Varios 1 01-12-2003 14:48:03


La franja horaria es GMT +2. Ahora son las 19:39:24.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi