Ir al contenido


Foto

Hola, amigos necesito ayuda con programación orientada a objetos?


  • Por favor identifícate para responder
6 respuestas en este tema

#1 Master23

Master23

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 230 mensajes
  • LocationSanto Domingo

Escrito 03 diciembre 2010 - 05:04

Hola amigos , ¿cómo estás?,espero que bien. He estado tratando de aprender el concepto de programación orientada a objetos en Delphi o mas bien el manejo de este he leído bastante, sin embargo no logro asimilarlo si alguno de ustedes puede darme una pequeña explicación o por lo menos hacer una aplicación normal para ver el código y ver como se usa porque en verdad no entiendo el uso de este paradigma ya que en el curso que hice hace tiempo solo aprendí en programación modular y estructurada,espero me puedan ayudar gracias de antemano.
  • 0

#2 adriano_servitec

adriano_servitec

    Advanced Member

  • Miembros
  • PipPipPip
  • 91 mensajes
  • LocationCuritiba-Pr - Brasil

Escrito 03 diciembre 2010 - 07:04

Hola amigo, me gustaría poder ayudar a más ...

Pero programación orientada a objetos implica muchas cosas, herencia, polimorfismo, encapsulación, etc ..

Por  lo que he leído, usted desea aprender programación orientada a objetos,  muestro mi clase de la persistencia de la creación de selección,  inserción, eliminación y actualización genérica, en este ejemplo estoy  usando la tecnología con dbExpress SQLDataSet, ClientDataSet  DataSetProvider. Yo solía ir DELPHI XE este ejemplo.



delphi
  1. unit IPersist;
  2.  
  3. interface
  4.  
  5. uses variants, classes, db, dbtables, sysutils, SqlExpr, uConexao, uDMBase,
  6.   DBClient, Provider, midaslib;
  7.  
  8. type
  9.   TTableEvent = procedure(Sender: TObject; var CanExecute: Boolean) of object;
  10.  
  11.   TMyFieldType = (ftString, ftMemo, ftFloat, ftInteger, ftDate, ftUnknown);
  12.  
  13.   TPk = Array of string;
  14.  
  15.   IField = interface
  16.   ['{B0E0C59D-0857-473A-9D93-1EEA0D00B128}']
  17.     function get_Name: string;
  18.     procedure set_Name(Value: string);
  19.  
  20.     function get_FieldType: TMyFieldType;
  21.     procedure set_FieldType(Value: TMyFieldType);
  22.  
  23.     function get_IsPk: Boolean;
  24.     procedure set_IsPk(Value: Boolean);
  25.  
  26.     function get_String: string;
  27.     procedure set_String(Value: String);
  28.  
  29.     function get_Float: Double;
  30.     procedure set_Float(Value: Double);
  31.  
  32.     function get_Integer: Integer;
  33.     procedure set_Integer(Value: Integer);
  34.  
  35.     function get_Date: TDateTime;
  36.     procedure set_Date(Value: TDateTime);
  37.  
  38.     function get_Value: Variant;
  39.     procedure set_Value(Value: Variant);
  40.  
  41.     function get_IsModified: boolean;
  42.  
  43.     property Name: string read get_Name write set_Name;
  44.     property FieldType: TMyFieldType read get_FieldType write set_FieldType;
  45.     property IsPk: Boolean read get_IsPk write set_IsPk;
  46.     property IsModified: Boolean read get_IsModified;
  47.  
  48.     property AsString: String read get_String write set_String;
  49.     property AsFloat: Double read get_Float write set_Float;
  50.     property AsInteger: Integer read get_Integer write set_Integer;
  51.     property AsDate: TDateTime read get_Date write set_Date;
  52.     property AsValue: Variant read get_Value write set_Value;
  53.   end;
  54.  
  55.   ITable = interface
  56.   ['{7D561737-BD28-4AA4-9D52-AE18FCB2E395}']
  57.     function get_TableName: String;
  58.  
  59.     function get_IFields(Index: Integer): IField;
  60.  
  61.     function FieldCount: Integer;
  62.  
  63.     function FieldByName(lcField: String): IField;
  64.  
  65.     procedure AssignByIndex(loSource: ITable);
  66.     procedure AssignByName(loSource: ITable);
  67.  
  68.     function get_Log: Boolean;
  69.     procedure set_Log(Value: Boolean);
  70.  
  71.     function get_FileLog: String;
  72.     procedure set_FileLog(Value: String);
  73.  
  74.     function getBeforeInsert: TTableEvent;
  75.     procedure setBeforeInsert(Value: TTableEvent);
  76.  
  77.     function getBeforeUpdate: TTableEvent;
  78.     procedure setBeforeUpdate(Value: TTableEvent);
  79.  
  80.     function getBeforeDelete: TTableEvent;
  81.     procedure setBeforeDelete(Value: TTableEvent);
  82.  
  83.     function get_cdsDataSet: TClientDataSet;
  84.     procedure set_cdsDataSet(Value: TClientDataSet);
  85.  
  86.     function Insert: Integer;
  87.     function Update: Integer;
  88.     function Delete: Integer;
  89.     function Select(lcFields: String): Boolean;
  90.  
  91.     procedure AtualizarDataSet;
  92.  
  93.     property TableName: string read get_TableName;
  94.     property Fields[Index: Integer]: IField read get_IFields;
  95.     property UseLog: Boolean read get_Log write set_Log;
  96.     property FileLog: String read get_FileLog write set_FileLog;
  97.     property TcdsDataSet: TClientDataSet read get_cdsDataSet write set_cdsDataSet;
  98.     //Eventos
  99.     property OnBeforeInsert: TTableEvent read getBeforeInsert write setBeforeInsert;
  100.     property OnBeforeUpdate: TTableEvent read getBeforeUpdate write setBeforeUpdate;
  101.     property OnBeforeDelete: TTableEvent read getBeforeDelete write setBeforeDelete;
  102.  
  103.   end;
  104.  
  105.   // **************** class auxiliar *******************************************
  106.  
  107.   TUtil = class
  108.     class function VarToDateTime(Value: Variant): TDateTime;
  109.     class function VarToInteger(Value: Variant): Integer;
  110.     class function VarToDouble(Value: Variant): Integer;
  111.     class function FieldTypeToMyFieldType(Value: TFieldType): TMyFieldType;
  112.     class function MyFieldTypeToString(Value: TMyFieldType): String;
  113.  
  114.     class function GetInterfaceByPointer(I: IUnknown): Pointer;
  115.     class procedure ReleaseInterfaceByPointer(P: Pointer);
  116.   end;
  117.  
  118.   // **************** classes **************************************************
  119.  
  120.   TField = class(TInterfacedObject, IField)
  121.   private
  122.     FName: string;
  123.     FFieldType: TMyFieldType;
  124.     FIsPk: Boolean;
  125.     FValue: Variant;
  126.     FIsModified: Boolean;
  127.  
  128.   protected
  129.     function get_Name: string; virtual;
  130.     procedure set_Name(Value: string); virtual;
  131.  
  132.     function get_FieldType: TMyFieldType; virtual;
  133.     procedure set_FieldType(Value: TMyFieldType); virtual;
  134.  
  135.     function get_IsPk: Boolean; virtual;
  136.     procedure set_IsPk(Value: Boolean); virtual;
  137.  
  138.     function get_String: string; virtual;
  139.     procedure set_String(Value: String); virtual;
  140.  
  141.     function get_Float: Double; virtual;
  142.     procedure set_Float(Value: Double); virtual;
  143.  
  144.     function get_Integer: Integer; virtual;
  145.     procedure set_Integer(Value: Integer); virtual;
  146.  
  147.     function get_Date: TDateTime; virtual;
  148.     procedure set_Date(Value: TDateTime); virtual;
  149.  
  150.     function get_Value: Variant; virtual;
  151.     procedure set_Value(Value: Variant); virtual;
  152.  
  153.     function get_IsModified: Boolean; virtual;
  154.  
  155.   public
  156.     constructor Create(lcName: String; lTMyFieldType: TMyFieldType; llPK: Boolean);
  157.   end;
  158.  
  159.   TTable = class(TInterfacedObject, ITable)
  160.   private
  161.     //Autor: Adriano - Para usar com DBX chamando a uses do DM aonde esta�
  162.     FConection: TdmBase;
  163.     loQuery: TSQLDataSet; //Compoente DBX
  164.     pProvider: TDataSetProvider;
  165.     loCDSLocal: TClientDataSet;
  166.     dsBase: TDataSource;
  167.     //
  168.     FDataBaseName: String;
  169.     FTableName: String;
  170.     FList: TList;
  171.     FPk: TPk;
  172.     FLog: Boolean;
  173.     FFileLog: string;
  174.     FOnBeforeInsert: TTableEvent;
  175.     FOnBeforeUpdate: TTableEvent;
  176.     FOnBeforeDelete: TTableEvent;
  177.     FOnAfterPost: TDataSetNotifyEvent;
  178.     procedure doAfterPost(aSender: TObject);
  179.     procedure doFreeList;
  180.  
  181.     function hasFieldModified: boolean;
  182.  
  183.   protected
  184.     function get_TableName: String; virtual;
  185.  
  186.     function get_IFields(Index: Integer): IField; virtual;
  187.  
  188.     function FieldCount: Integer; virtual;
  189.  
  190.     function FieldByName(lcField: String): IField; virtual;
  191.  
  192.     function get_Log: Boolean;
  193.     procedure set_Log(Value: Boolean);
  194.  
  195.     function get_FileLog: String;
  196.     procedure set_FileLog(Value: String);
  197.  
  198.     function Insert: Integer; virtual;
  199.     function Update: Integer; virtual;
  200.     function Delete: Integer; virtual;
  201.     function Select(lcFields: String): Boolean; virtual;
  202.  
  203.     procedure AssignByIndex(loSource: ITable); virtual;
  204.     procedure AssignByName(loSource: ITable); virtual;
  205.  
  206.     function getBeforeInsert: TTableEvent; virtual;
  207.     procedure setBeforeInsert(Value: TTableEvent); virtual;
  208.  
  209.     function getBeforeUpdate: TTableEvent; virtual;
  210.     procedure setBeforeUpdate(Value: TTableEvent); virtual;
  211.  
  212.     function getBeforeDelete: TTableEvent; virtual;
  213.     procedure setBeforeDelete(Value: TTableEvent); virtual;
  214.  
  215.     function get_cdsDataSet: TClientDataSet; virtual;
  216.     procedure set_cdsDataSet(Value: TClientDataSet); virtual;
  217.  
  218.     // método para carregar os campos
  219.     procedure doLoadFields; virtual;
  220.  
  221.     // método para copiar a pk
  222.     procedure doCopyPk(laPk: Array of String);
  223.  
  224.     function isPk(lcField: String): Boolean;
  225.  
  226.     procedure AtualizarDataSet;
  227.  
  228.     //Parametros
  229.     procedure passToParams;
  230.  
  231.   public
  232.     constructor Create(lcDataBaseName, lcTableName: String; laPK: Array of String);
  233.     destructor Destroy; override;
  234.     //Eventos
  235.     property OnAfterPost: TDataSetNotifyEvent read FOnAfterPost write FOnAfterPost;
  236.   end;
  237.  
  238.   var
  239.     //Variaveis Globais
  240.     lnCont, i : Integer;
  241.     sSQL, lcNome, lcSep: string;
  242.     lvValue: variant;
  243.     llCanExecute: boolean;



continua...

  • 0

#3 adriano_servitec

adriano_servitec

    Advanced Member

  • Miembros
  • PipPipPip
  • 91 mensajes
  • LocationCuritiba-Pr - Brasil

Escrito 03 diciembre 2010 - 07:06



delphi
  1. implementation
  2.  
  3. { TField }
  4.  
  5. constructor TField.Create(lcName: String; lTMyFieldType: TMyFieldType; llPK: Boolean);
  6. begin
  7.   inherited Create;
  8.  
  9.   if lTMyFieldType = IPersist.ftUnknown then
  10.     raise Exception.Create('Tipo de Campo[' + lcName + '] inválido');
  11.  
  12.   FName := lcName;
  13.   FFieldType := lTMyFieldType;
  14.   FIsPk := llPk;
  15.   FValue := null;
  16.   FIsModified := False;
  17. end;
  18.  
  19. function TField.get_Date: TDateTime;
  20. begin
  21.   result := TUtil.VarToDateTime(FValue);
  22. end;
  23.  
  24. function TField.get_FieldType: TMyFieldType;
  25. begin
  26.   result := FFieldType;
  27. end;
  28.  
  29. function TField.get_Float: Double;
  30. begin
  31.   result := TUtil.VarToDouble(FValue);
  32. end;
  33.  
  34. function TField.get_Integer: Integer;
  35. begin
  36.   result := TUtil.VarToInteger(FValue);
  37. end;
  38.  
  39. function TField.get_IsPk: Boolean;
  40. begin
  41.   result := FIsPk;
  42. end;
  43.  
  44. function TField.get_IsModified: Boolean;
  45. begin
  46.   result := FIsModified;
  47. end;
  48.  
  49. function TField.get_Name: string;
  50. begin
  51.   result := UpperCase(FName);
  52. end;
  53.  
  54. function TField.get_String: string;
  55. begin
  56.   result := variants.VarToStr(FValue);
  57. end;
  58.  
  59. function TField.get_Value: Variant;
  60. begin
  61.   result := FValue;
  62. end;
  63.  
  64. procedure TField.set_Date(Value: TDateTime);
  65. begin
  66.   if (Value <> FValue) then
  67.     begin
  68.     FValue := Value;
  69.     FIsModified := True;
  70.     end;
  71. end;
  72.  
  73. procedure TField.set_FieldType(Value: TMyFieldType);
  74. begin
  75.   FFieldType := Value;
  76. end;
  77.  
  78. procedure TField.set_Float(Value: Double);
  79. begin
  80.   if (Value <> FValue) then
  81.     begin
  82.     FValue := Value;
  83.     FIsModified := True;
  84.     end;
  85. end;
  86.  
  87. procedure TField.set_Integer(Value: Integer);
  88. begin
  89.   if (Value <> FValue) then
  90.     begin
  91.     FValue := Value;
  92.     FIsModified := True;
  93.     end;
  94. end;
  95.  
  96. procedure TField.set_IsPk(Value: Boolean);
  97. begin
  98.   FIsPk := Value;
  99. end;
  100.  
  101. procedure TField.set_Name(Value: string);
  102. begin
  103.   FName := UpperCase(Value);
  104. end;
  105.  
  106. procedure TField.set_String(Value: String);
  107. begin
  108.   if (Value <> FValue) then
  109.     begin
  110.     FValue := Value;
  111.     FIsModified := True;
  112.     end;
  113. end;
  114.  
  115. procedure TField.set_Value(Value: Variant);
  116. begin
  117.   if (Value <> FValue) then
  118.     begin
  119.     FValue := Value;
  120.     FIsModified := True;
  121.     end;
  122. end;
  123.  
  124. { TUtil }
  125.  
  126. class function TUtil.FieldTypeToMyFieldType(Value: TFieldType): TMyFieldType;
  127. begin
  128.   case Value of
  129.     db.ftString: result := IPersist.ftString;
  130.  
  131.     db.ftSmallint,
  132.     db.ftInteger,
  133.     db.ftWord,
  134.     db.ftLargeint: result := IPersist.ftInteger;
  135.  
  136.     db.ftFloat,
  137.     db.ftCurrency,
  138.     db.ftBCD: result := IPersist.ftFloat;
  139.  
  140.     db.ftDate,
  141.     db.ftTime,
  142.     db.ftDateTime,
  143.     db.ftTimeStamp: result := IPersist.ftDate;
  144.  
  145.     db.ftBlob,
  146.     db.ftMemo,
  147.     db.ftFmtMemo: result := IPersist.ftMemo;
  148.   else
  149.     result := IPersist.ftUnknown;
  150.   end;
  151.  
  152. end;
  153.  
  154. class function TUtil.GetInterfaceByPointer(I: IUnknown): Pointer;
  155. begin
  156.   I._AddRef;
  157.   result := Pointer(I);
  158. end;
  159.  
  160. class function TUtil.MyFieldTypeToString(Value: TMyFieldType): String;
  161. const
  162.   ccFieldType: array[TMyFieldType] of String = ('ftString', 'ftMemo', 'ftFloat', 'ftInteger', 'ftDate', 'ftUnknown');
  163. begin
  164.   result := ccFieldType[Value];
  165. end;
  166.  
  167. class procedure TUtil.ReleaseInterfaceByPointer(P: Pointer);
  168. var
  169.   I: IUnknown;
  170. begin
  171.   Pointer(I) := P;
  172.   // a interface vai ser liberada ao sair do escopo
  173. end;
  174.  
  175. class function TUtil.VarToDateTime(Value: Variant): TDateTime;
  176. begin
  177.   try
  178.     result := variants.VarToDateTime(Value);
  179.   except
  180.     result := 0;
  181.   end;
  182. end;
  183.  
  184. class function TUtil.VarToDouble(Value: Variant): Integer;
  185. begin
  186.   try
  187.     result := Value;
  188.   except
  189.     result := 0;
  190.   end;
  191. end;
  192.  
  193. class function TUtil.VarToInteger(Value: Variant): Integer;
  194. begin
  195.   try
  196.     result := Value;
  197.   except
  198.     result := 0;
  199.   end;
  200. end;
  201.  
  202. { TTable }
  203.  
  204. constructor TTable.Create(lcDataBaseName, lcTableName: String; laPK: Array of String);
  205. begin
  206.   inherited Create;
  207.   //Autor: Adriano - Para usar com DBX chamando a uses do DM aonde esta�
  208.   FConection := TdmBase.Create(nil); //Incluido para DBX Componente de conexao
  209.   loQuery := TSQLDataSet.Create(nil); //SQLDataSet
  210.   loCDSLocal := TClientDataSet.Create(nil); //DataSet
  211.   pProvider := TDataSetProvider.Create(nil); //Provider
  212.   dsBase := TDataSource.Create(nil); //Datasource
  213.   //
  214.   dsBase.DataSet := loCDSLocal; //Seta o datasource ao dataset
  215.   FDataBaseName := lcDataBaseName;
  216.   FTableName := lcTableName;
  217.   FList := TList.Create;
  218.   FLog := False;
  219.   doCopyPk(laPk);
  220.   doLoadFields;
  221. end;
  222.  
  223. destructor TTable.Destroy;
  224. begin
  225.   doFreeList;
  226.   //Desalocar da memoria
  227.   FConection.Free;
  228.   loQuery.Free;
  229.   loQuery.Close;
  230. // loCDSLocal.Free;
  231. // loCDSLocal.Close;
  232.   pProvider.Free;
  233.   dsBase.Free;
  234.   inherited;
  235. end;
  236.  
  237. function TTable.isPk(lcField: String): Boolean;
  238. var
  239.   lnCont: Integer;
  240. begin
  241.   lcField := UpperCase(lcField);
  242.   result  := false;
  243.   for lnCont := Low(FPk) to High(FPk) do
  244.   if UpperCase(FPk[lnCont]) = lcField then
  245.   begin
  246.     result := true;
  247.     break;
  248.   end;
  249. end;
  250.  
  251. function TTable.getBeforeInsert: TTableEvent;
  252. begin
  253.   result := FOnBeforeInsert;
  254. end;
  255.  
  256. procedure TTable.setBeforeInsert(Value: TTableEvent);
  257. begin
  258.   FOnBeforeInsert := Value;
  259. end;
  260.  
  261. function TTable.getBeforeUpdate: TTableEvent;
  262. begin
  263.   result := FOnBeforeUpdate;
  264. end;
  265.  
  266. procedure TTable.setBeforeUpdate(Value: TTableEvent);
  267. begin
  268.   FOnBeforeUpdate := Value;
  269. end;
  270.  
  271. function TTable.getBeforeDelete: TTableEvent;
  272. begin
  273.   result := FOnBeforeDelete;
  274. end;
  275.  
  276. procedure TTable.setBeforeDelete(Value: TTableEvent);
  277. begin
  278.   FOnBeforeDelete := Value;
  279. end;
  280.  
  281. procedure TTable.AssignByIndex(loSource: ITable);
  282. var
  283.   lnCont: Integer;
  284. begin
  285.   for lnCont := 0 to loSource.FieldCount - 1 do
  286.     ITable(Self).Fields[lnCont].AsValue := loSource.Fields[lnCont].AsValue;
  287. end;
  288.  
  289. procedure TTable.AssignByName(loSource: ITable);
  290. var
  291.   lnCont : Integer;
  292.   lcField: String;
  293. begin
  294.   for lnCont := 0 to loSource.FieldCount - 1 do
  295.   begin
  296.     // nome do campo do objeto origem
  297.     lcField := loSource.Fields[lnCont].Name;
  298.     // associo pelo nome
  299.     ITable(Self).FieldByName(lcField).AsValue := loSource.FieldByName(lcField).AsValue;
  300.   end;
  301. end;
  302.  
  303. procedure TTable.AtualizarDataSet;
  304. begin
  305.   loCDSLocal.Close;
  306.   loCDSLocal.CommandText :=  'SELECT * FROM ' + get_TableName;
  307.   loCDSLocal.Open;
  308. end;
  309.  
  310. function TTable.FieldByName(lcField: String): IField;
  311. var
  312.   lnCont: Integer;
  313. begin
  314.   result  := nil;
  315.   lcField := UpperCase(lcField);
  316.   for lnCont := 0 to FieldCount - 1 do
  317.   if ITable(Self).Fields[lnCont].Name = lcField then
  318.   begin
  319.     result := ITable(Self).Fields[lnCont];
  320.     break;
  321.   end;
  322. end;
  323.  
  324. function TTable.FieldCount: Integer;
  325. begin
  326.   result := FList.Count;
  327. end;
  328.  
  329. function TTable.get_cdsDataSet: TClientDataSet;
  330. begin
  331.   Result := loCDSLocal;
  332. end;
  333.  
  334. function TTable.get_FileLog: String;
  335. begin
  336.   result := FFileLog;
  337. end;
  338.  
  339. function TTable.get_IFields(Index: Integer): IField;
  340. begin
  341.   if Index < 0 then
  342.     raise Exception.Create('Índice ' + inttostr(Index) + ' fora da lista');
  343.  
  344.   if Index > (FList.Count - 1) then
  345.     raise Exception.Create('Índice ' + inttostr(Index) + ' fora da lista');
  346.  
  347.   result := IUnknown(FList.Items[Index]) as IField;
  348. end;



continua..
  • 0

#4 adriano_servitec

adriano_servitec

    Advanced Member

  • Miembros
  • PipPipPip
  • 91 mensajes
  • LocationCuritiba-Pr - Brasil

Escrito 03 diciembre 2010 - 07:07



delphi
  1. function TTable.get_Log: Boolean;
  2. begin
  3.   result := FLog;
  4. end;
  5.  
  6. function TTable.get_TableName: String;
  7. begin
  8.   result := FTableName;
  9. end;
  10.  
  11. function TTable.hasFieldModified: boolean;
  12. var
  13.   lnCont: Integer;
  14. begin
  15.   result := false;
  16.   for lnCont := 0 to FieldCount - 1 do
  17.   if get_IFields(lnCont).IsModified then
  18.   begin
  19.     result := true;
  20.     break;
  21.   end;
  22. end;
  23.  
  24. procedure TTable.doAfterPost(aSender: TObject);
  25. begin
  26.   if loCDSLocal.Active = False then
  27.     loCDSLocal.Active := True;
  28.   loCDSLocal.ApplyUpdates(0);
  29. end;
  30.  
  31. procedure TTable.doCopyPk(laPk: array of String);
  32. var
  33.   lnTam: Integer;
  34.   lnCont: Integer;
  35. begin
  36.   lnTam := High(laPk);
  37.   SetLength(FPk, lnTam + 1);
  38.   for lnCont := low(laPk) to lnTam do
  39.     FPk[lnCont] := laPk[lnCont];
  40. end;
  41.  
  42. procedure TTable.doFreeList;
  43. var
  44.   lnCont: Integer;
  45. begin
  46.   for lnCont := FieldCount - 1 downto 0 do
  47.   begin
  48.     // FList[lnCont] eh um ponteiro que aponta para uma interface
  49.     TUtil.ReleaseInterfaceByPointer(FList[lnCont]);
  50.     FList[lnCont] := nil;
  51.   end;
  52.   FList.Pack;
  53.   FList.Free;
  54. end;
  55.  
  56. procedure TTable.doLoadFields;
  57. var
  58.   loQuery : TSQLQuery;
  59.   lnCont  : Integer;
  60.   loField : IField;
  61. begin
  62.   loQuery := TSQLQuery.Create(nil);
  63.   try
  64.     loQuery.SQLConnection := FConection.Conexao;//FDataBaseName;
  65.     loQuery.SQL.Clear;
  66.     loQuery.SQL.Add('SELECT * FROM ' + ITable(Self).TableName + ' WHERE 1=2');
  67.     loQuery.Open;
  68.  
  69.     for lnCont := 0 to loQuery.FieldCount - 1 do
  70.     begin
  71.       loField := TField.Create(loQuery.Fields[lnCont].FieldName,
  72.                               TUtil.FieldTypeToMyFieldType(loQuery.Fields[lnCont].DataType),
  73.                               isPk(loQuery.Fields[lnCont].FieldName));
  74.  
  75.       // lista de ponteiros para interface
  76.       FList.Add(TUtil.GetInterfaceByPointer(loField));
  77.     end;
  78.  
  79.   finally
  80.     loQuery.Close;
  81.     loQuery.Free;
  82.   end;
  83. end;
  84.  
  85. procedure TTable.set_cdsDataSet(Value: TClientDataSet);
  86. begin
  87.   loCDSLocal := Value;
  88. end;
  89.  
  90. procedure TTable.set_FileLog(Value: String);
  91. begin
  92.   FFileLog := Value;
  93. end;
  94.  
  95. procedure TTable.set_Log(Value: Boolean);
  96. begin
  97.   FLog := Value;
  98. end;
  99. //*****************************************************************************
  100.  
  101. //CliendDataSet
  102. function TTable.Insert: Integer;
  103. begin
  104.   result := 0;
  105.   // se não há modificação, então não há inclusão
  106.   if not hasFieldModified then
  107.     exit;
  108.   try
  109.     // Nomes
  110.     loCDSLocal.Name := 'loCDSLocal';
  111.     pProvider.Name  := 'pProvider';
  112.     loQuery.Name    := 'loQuery';
  113.  
  114.     {Comando criado para conectar do DBX}
  115.     loQuery.SQLConnection := FConection.Conexao;//FDataBaseName;
  116.     loQuery.CommandType  := ctQuery; //Modo query
  117.  
  118.     // Configs de Criação
  119.     loCDSLocal.StoreDefs := True;
  120.     pProvider.Options:=[poAllowCommandText];
  121.  
  122.     // Configs
  123.     loCDSLocal.SetProvider(pProvider);  //Tem que setar o provider no dataset desta forma
  124.     pProvider.DataSet := loQuery; //O dsprovider recebe o sqldataset do dbx
  125.     //  *******************************************
  126.  
  127.     //Foi alterado do original agora uso como string e não ADD para usar no CDS
  128.     sSQL := 'INSERT INTO ' + FTableName + '(';
  129.     // field list
  130.     lcSep := '';
  131.     for lnCont := 0 to FieldCount - 1 do
  132.     if get_IFields(lnCont).IsModified then
  133.     begin
  134.       lcNome := get_IFields(lnCont).Name;
  135.       sSQL := sSQL + lcSep + lcNome ;
  136.       lcSep  := ',';
  137.     end;
  138.  
  139.     sSQL := sSQL + ')';
  140.     //Passando os values
  141.     sSQL := sSQL + ' Values ( ';
  142.     // value list
  143.     lcSep := '';
  144.     for lnCont := 0 to FieldCount - 1 do
  145.     if get_IFields(lnCont).IsModified then
  146.     begin
  147.       lcNome := get_IFields(lnCont).Name;
  148.       sSQL := sSQL + lcSep + ':' + lcNome;
  149.       lcSep  := ',';
  150.     end;
  151.  
  152.     sSQL := sSQL + ')';
  153.     //Passando o SQL no dataset
  154.     loCDSLocal.CommandText := sSQL;
  155.  
  156.     //Chamando a procedure params
  157.     passToParams;
  158.  
  159.     // retorna o valor da função
  160.     if ITable(Self).UseLog then
  161.     begin
  162.       if Trim(ITable(Self).FileLog) = EmptyStr then
  163.         raise Exception.Create('FileLog não pode ser vazio!');
  164.  
  165.       loCDSLocal.SaveToFile(ITable(Self).FileLog);
  166.     end;
  167.  
  168.     // verifico se o evento foi programado
  169.     llCanExecute := true;
  170.     if Assigned(FOnBeforeInsert) then
  171.       FOnBeforeInsert(self, llCanExecute);
  172.  
  173.     // testo a variavel
  174.     if not llCanExecute then
  175.       raise Exception.Create('Processo interrompido pelo usuário!');
  176.  
  177.     //Executa o dataset
  178.     loCDSLocal.Execute;
  179.  
  180.     //Atualizar Dataset
  181.     AtualizarDataSet;
  182.  
  183.     Result := 1; //loCDSLocal.RowsAffected;    //Autor: Adriano Não funciona
  184.   except
  185.     on e: exception do
  186.       raise Exception.Create(E.Message + ' on TTable.Insert ');
  187.   end;
  188. end;
  189.  
  190. function TTable.Delete: Integer;
  191. begin
  192.   result := 0;
  193.   // se não há modificação, então não há inclusão
  194.   if not hasFieldModified then
  195.     exit;
  196.   try
  197.     // Nomes
  198.     loCDSLocal.Name := 'loCDSLocal';
  199.     pProvider.Name  := 'pProvider';
  200.     loQuery.Name    := 'loQuery';
  201.  
  202.     {Comando criado para conectar do DBX}
  203.     loQuery.SQLConnection := FConection.Conexao;//FDataBaseName;
  204.     loQuery.CommandType  := ctQuery; //Modo query
  205.  
  206.     // Configs de Criação
  207.     loCDSLocal.StoreDefs := True;
  208.     pProvider.Options:=[poAllowCommandText];
  209.  
  210.     // Configs
  211.     loCDSLocal.SetProvider(pProvider);  //Tem que setar o provider no dataset desta forma
  212.     pProvider.DataSet := loQuery; //O dsprovider recebe o sqldataset do dbx
  213.     //  *******************************************
  214.  
  215.     //Foi alterado do original agora uso como string e não ADD para usar no CDS
  216.     sSQL := 'DELETE FROM ' + FTableName +' WHERE ';
  217.     // value list
  218.     lcSep := '';
  219.     for lnCont := 0 to FieldCount - 1 do
  220.     if get_IFields(lnCont).IsPk then
  221.     begin
  222.       lcNome := get_IFields(lnCont).Name;
  223.       sSQL := sSQL + lcSep + lcNome + ' = ' + ':' + lcNome;
  224.       lcSep  := ' AND ';
  225.     end;
  226.  
  227.     //Passando o SQL no dataset
  228.     loCDSLocal.CommandText := sSQL;
  229.  
  230.     //Chamando a procedure params
  231.     passToParams;
  232.  
  233.     // retorna o valor da função
  234.     if ITable(Self).UseLog then
  235.     begin
  236.       if Trim(ITable(Self).FileLog) = EmptyStr then
  237.         raise Exception.Create('FileLog não pode ser vazio!');
  238.  
  239.       loCDSLocal.SaveToFile(ITable(Self).FileLog);
  240.     end;
  241.  
  242.     // verifico se o evento foi programado
  243.     llCanExecute := true;
  244.     if Assigned(FOnBeforeDelete) then
  245.       FOnBeforeDelete(self, llCanExecute);
  246.  
  247.     // testo a variavel
  248.     if not llCanExecute then
  249.       raise Exception.Create('Processo interrompido pelo usuário!');
  250.  
  251.     loCDSLocal.Execute;
  252.  
  253.     //Atualizar Dataset
  254.     AtualizarDataSet;
  255.  
  256.     Result := 1; //loCDSLocal.RowsAffected;
  257.  
  258.   except
  259.     on e: exception do
  260.       raise Exception.Create(E.Message + ' on TTable.Delete ');
  261.   end;
  262. end;
  263.  
  264. function TTable.Update: Integer;
  265. begin
  266.   result := 0;
  267.   // se não há modificação, então não há inclusão
  268.   if not hasFieldModified then
  269.     exit;
  270.   try
  271.     // Nomes
  272.     loCDSLocal.Name := 'loCDSLocal';
  273.     pProvider.Name  := 'pProvider';
  274.     loQuery.Name    := 'loQuery';
  275.  
  276.     {Comando criado para conectar do DBX}
  277.     loQuery.SQLConnection := FConection.Conexao;//FDataBaseName;
  278.     loQuery.CommandType  := ctQuery; //Modo query
  279.  
  280.     // Configs de Criação
  281.     loCDSLocal.StoreDefs := True;
  282.     pProvider.Options:=[poAllowCommandText];
  283.  
  284.     // Configs
  285.     loCDSLocal.SetProvider(pProvider);  //Tem que setar o provider no dataset desta forma
  286.     pProvider.DataSet := loQuery; //O dsprovider recebe o sqldataset do dbx
  287.     //  *******************************************
  288.  
  289.     //Foi alterado do original agora uso como string e não ADD para usar no CDS
  290.     sSQL := 'UPDATE ' + FTableName +'  SET ';
  291.  
  292.     // field list
  293.     lcSep := '';
  294.     for lnCont := 0 to FieldCount - 1 do
  295.       if get_IFields(lnCont).IsModified then
  296.         if not get_IFields(lnCont).IsPk then
  297.         begin
  298.           lcNome := get_IFields(lnCont).Name;
  299.           sSQL := sSQL + lcSep + lcNome + ' = ' + ':' + lcNome;
  300.           lcSep  := ',';
  301.         end;
  302.  
  303.       sSQL := sSQL + ' WHERE ';
  304.  
  305.       // value list
  306.       lcSep := '';
  307.       for lnCont := 0 to FieldCount - 1 do
  308.         if get_IFields(lnCont).IsPk then
  309.         begin
  310.           lcNome := get_IFields(lnCont).Name;
  311.           sSQL := sSQL + lcSep + lcNome + ' = ' + ':' + lcNome;
  312.           lcSep  := ' AND ';
  313.         end;
  314.  
  315.       //Passando o SQL no dataset
  316.       loCDSLocal.CommandText := sSQL;
  317.  
  318.       //Chamando a procedure params
  319.       passToParams;
  320.  
  321.       // retorna o valor da função
  322.       if ITable(Self).UseLog then
  323.       begin
  324.         if Trim(ITable(Self).FileLog) = EmptyStr then
  325.           raise Exception.Create('FileLog não pode ser vazio!');
  326.  
  327.         loCDSLocal.SaveToFile(ITable(Self).FileLog);
  328.         end;
  329.  
  330.       // verifico se o evento foi programado
  331.       llCanExecute := true;
  332.       if Assigned(FOnBeforeUpdate) then
  333.         FOnBeforeUpdate(self, llCanExecute);
  334.  
  335.       // testo a variavel
  336.       if not llCanExecute then
  337.         raise Exception.Create('Processo interrompido pelo usuário!');
  338.  
  339.       loCDSLocal.Execute;
  340.  
  341.       //Atualizar Dataset
  342.       AtualizarDataSet;
  343.  
  344.       Result := 1; //loQuery.RowsAffected;
  345.   except
  346.     on e: exception do
  347.       raise Exception.Create(E.Message + ' on TTable.Update ');
  348.   end;
  349. end;
  350.  
  351. function TTable.Select(lcFields: String): Boolean;
  352. begin
  353.   result := false;
  354.   try
  355.     // Nomes
  356.     loCDSLocal.Name := 'loCDSLocal';
  357.     pProvider.Name  := 'pProvider';
  358.     loQuery.Name    := 'loQuery';
  359.  
  360.     {Comando criado para conectar do DBX}
  361.     loQuery.SQLConnection := FConection.Conexao;//FDataBaseName;
  362.     loQuery.CommandType  := ctQuery; //Modo query
  363.  
  364.     // Configs de Criação
  365.     loCDSLocal.StoreDefs := True;
  366.     //
  367.     pProvider.Options:=[poAllowCommandText];
  368.  
  369.     // Configs
  370.     loCDSLocal.SetProvider(pProvider);  //Tem que setar o provider no dataset desta forma
  371.     pProvider.DataSet := loQuery; //O dsprovider recebe o sqldataset do dbx
  372.     //  *******************************************
  373.  
  374.     // preparar o dataset
  375.     sSQL :=  'SELECT ' + lcFields + ' FROM ' + get_TableName +
  376.     ' WHERE ';
  377.  
  378.     // value list
  379.     lcSep := '';
  380.     for lnCont := 0 to FieldCount - 1 do
  381.     if get_IFields(lnCont).IsPk then
  382.     begin
  383.       lcNome := get_IFields(lnCont).Name;
  384.       sSQL :=  sSQL + lcSep + lcNome + ' LIKE ' + ':' + lcNome ;
  385.       lcSep := ' AND ';
  386.     end;
  387.  
  388.     //Passando o SQL no dataset
  389.     loCDSLocal.CommandText := sSQL;
  390.  
  391.     //Chamando a procedure params
  392.     passToParams;
  393.  
  394.     // retorna o valor da função
  395.     if ITable(Self).UseLog then
  396.     begin
  397.       if Trim(ITable(Self).FileLog) = EmptyStr then
  398.         raise Exception.Create('FileLog não pode ser vazio!');
  399.  
  400.       loCDSLocal.SaveToFile(ITable(Self).FileLog);
  401.     end;
  402.  
  403.     loCDSLocal.Open;
  404.  
  405.     result := not loCDSLocal.IsEmpty;
  406.  
  407.     for lnCont := 0 to loCDSLocal.FieldCount - 1 do
  408.     begin
  409.       // inicializo todos como NULL
  410.       Self.FieldByName(loCDSLocal.Fields[lnCont].FieldName).AsValue := null;
  411.       // se alguma linha foi retornada
  412.       // atualiza o valor do campo I da lista
  413.       if result then
  414.         Self.FieldByName(loCDSLocal.Fields[lnCont].FieldName).AsValue := loCDSLocal.Fields[lnCont].Value;
  415.     end;
  416.   except
  417.     on e: exception do
  418.       raise Exception.Create(E.Message + ' on TTable.Select ');
  419.   end;
  420. end;
  421.  
  422. //Exclusivo para uso do clientdataset
  423. procedure TTable.passToParams;
  424. begin
  425.   // param list
  426.   for lnCont := 0 to FieldCount - 1 do
  427.   if get_IFields(lnCont).IsModified then
  428.   begin
  429.     lcNome  := get_IFields(lnCont).Name;
  430.     lvValue := get_IFields(lnCont).AsValue;
  431.  
  432.     case get_IFields(lnCont).FieldType of
  433.       ftString:
  434.         begin
  435.           loCDSLocal.Params.ParamByName(lcNome).DataType := db.ftString;
  436.           loCDSLocal.Params.ParamByName(lcNome).Value    := lvValue;
  437.         end;
  438.  
  439.       ftMemo:
  440.         begin
  441.           loCDSLocal.Params.ParamByName(lcNome).DataType := db.ftString;
  442.           loCDSLocal.Params.ParamByName(lcNome).Value    := lvValue;
  443.         end;
  444.  
  445.       ftFloat:
  446.         begin
  447.           loCDSLocal.Params.ParamByName(lcNome).DataType := db.ftFloat;
  448.           loCDSLocal.Params.ParamByName(lcNome).Value    := lvValue;
  449.         end;
  450.  
  451.       ftInteger:
  452.         begin
  453.           loCDSLocal.Params.ParamByName(lcNome).DataType := db.ftInteger;
  454.           loCDSLocal.Params.ParamByName(lcNome).Value    := lvValue;
  455.         end;
  456.  
  457.       ftDate:
  458.         begin
  459.           loCDSLocal.Params.ParamByName(lcNome).DataType := db.ftDateTime;
  460.  
  461.           if get_IFields(lnCont).AsDate = 0 then
  462.             lvValue := null
  463.           else
  464.             lvValue := get_IFields(lnCont).AsDate;
  465.  
  466.           loCDSLocal.Params.ParamByName(lcNome).Value := lvValue;
  467.         end;
  468.     else
  469.       raise Exception.Create('Campo ' + lcNome + ' com tipo de dados não esperado!');
  470.     end;
  471.   end;
  472. end;
  473.  
  474. end.



Hago un llamamiento a la persistencia de la clase, así
  • 0

#5 adriano_servitec

adriano_servitec

    Advanced Member

  • Miembros
  • PipPipPip
  • 91 mensajes
  • LocationCuritiba-Pr - Brasil

Escrito 03 diciembre 2010 - 07:10



delphi
  1. {Autor: Adriano
  2. Data da criação: 30/10/2010}
  3.  
  4. unit uCadastroBase;
  5.  
  6. interface
  7.  
  8. uses
  9.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  10.   Dialogs, XPMan, StdCtrls, Buttons, ExtCtrls, ComCtrls, JvExComCtrls,
  11.   JvComCtrls, JvExControls, JvNavigationPane, unTEditExitEnterColor, ImgList,
  12.   JvXPBar, jpeg, JvXPCore, JvXPContainer, Grids, DBGrids, DB, Mask, JvExMask,
  13.   JvToolEdit, JvDBControls, unTJvDBDateEditExitEnterColor, DBCtrls,
  14.   unTdbComboBoxExitEnterColor, uValidaEdtCmbEstadual, JvBaseEdits,
  15.   unTJvDBCalcEditExitEnterColor, unTdbMemoExitEnterColor,
  16.   unTdbEditExitEnterColor, uDsLocate, JvMaskEdit, JvArrowButton, JvColorBox,
  17.   JvColorButton, UnitButtonMenu, Menus, DBTables, SqlExpr, DBClient, UxTheme, Themes;
  18.  
  19. //Classes Adriano
  20. type
  21.   TInfStateForm = class
  22.     function SetStateForm: string; virtual; abstract;
  23.   end;
  24.  
  25.   TListagem = class(TInfStateForm)
  26.     function SetStateForm: string; override;
  27.   end;
  28.  
  29.   TCadastro = class(TInfStateForm)
  30.     function SetStateForm: string; override;
  31.   end;
  32.   //
  33.  
  34. type
  35.   PtForm = ^TfrmCadastroBase; //Tratando com ponteiro
  36.   TfrmCadastroBase = class(TForm)
  37.     Label50: TLabel;
  38.     StatusBar1: TStatusBar;
  39.     JvNavPanelHeader1: TJvNavPanelHeader;
  40.     Label1: TLabel;
  41.     PaginaPrincipal: TJvPageControl;
  42.     ModoListagem: TTabSheet;
  43.     ModoCadastro: TTabSheet;
  44.     GroupBox2: TGroupBox;
  45.     PanelTop: TPanel;
  46.     PanelButton: TPanel;
  47.     btInsert: TBitBtn;
  48.     btCancel: TBitBtn;
  49.     btEdit: TBitBtn;
  50.     btDelete: TBitBtn;
  51.     btLocate: TBitBtn;
  52.     btPost: TBitBtn;
  53.     PanelInformation: TPanel;
  54.     GroupBox9: TGroupBox;
  55.     Label51: TLabel;
  56.     cbtipo: TComboBox;
  57.     cbtodos: TCheckBox;
  58.     cbclientes: TComboBox;
  59.     EdtLocalizar: TEdtExitEnterColor;
  60.     Splitter2: TSplitter;
  61.     Panel2: TPanel;
  62.     JvXPContainer1: TJvXPContainer;
  63.     ImgLateral: TImage;
  64.     ImgMenuLateral: TImageList;
  65.     GroupBox1: TGroupBox;
  66.     dsLocal: TDataSource;
  67.     RadioButton1: TRadioButton;
  68.     RadioButton2: TRadioButton;
  69.     Label5: TLabel;
  70.     JvXPBar6: TJvXPBar;
  71.     JvXPBar8: TJvXPBar;
  72.     JvXPBar7: TJvXPBar;
  73.     PaginaExtra: TPageControl;
  74.     TabSheet7: TTabSheet;
  75.     TabSheet8: TTabSheet;
  76.     Panel1: TPanel;
  77.     TabSheet9: TTabSheet;
  78.     Panel3: TPanel;
  79.     GroupBox11: TGroupBox;
  80.     CheckBox1: TCheckBox;
  81.     CheckBox2: TCheckBox;
  82.     CheckBox3: TCheckBox;
  83.     CheckBox4: TCheckBox;
  84.     RadioGroup1: TRadioGroup;
  85.     GroupBox12: TGroupBox;
  86.     CheckBox9: TCheckBox;
  87.     CheckBox10: TCheckBox;
  88.     CheckBox5: TCheckBox;
  89.     CheckBox6: TCheckBox;
  90.     CheckBox7: TCheckBox;
  91.     CheckBox8: TCheckBox;
  92.     RadioGroup2: TRadioGroup;
  93.     GridBase: TDBGrid;
  94.     RadioGroup3: TRadioGroup;
  95.     GroupBox13: TGroupBox;
  96.     Label7: TLabel;
  97.     DateTimePicker1: TDateTimePicker;
  98.     DateTimePicker2: TDateTimePicker;
  99.     Label8: TLabel;
  100.     Localizar: TDataSetLocate;
  101.     ButtonMenu1: TButtonMenu;
  102.     ppImpressora: TPopupMenu;
  103.     Imprimir1: TMenuItem;
  104.     N1: TMenuItem;
  105.     CONFIGURARPGINA1: TMenuItem;
  106.     N2: TMenuItem;
  107.     IMPORTARPARAEXCEL1: TMenuItem;
  108.     N3: TMenuItem;
  109.     CONFIGURARPGINA2: TMenuItem;
  110.     JvXPBar1: TJvXPBar;
  111.     btClose: TBitBtn;
  112.     procedure ModoCadastroShow(Sender: TObject);
  113.     procedure ModoListagemShow(Sender: TObject);
  114.     procedure FormClose(Sender: TObject; var Action: TCloseAction);
  115.     procedure btCloseClick(Sender: TObject);
  116.     procedure FormCreate(Sender: TObject);
  117.     procedure FormShow(Sender: TObject);
  118.     procedure RadioGroup2Click(Sender: TObject);
  119.     procedure btInsertClick(Sender: TObject);
  120.     procedure ButtonMenu1Click(Sender: TObject);
  121.     procedure btLocateClick(Sender: TObject);
  122.     procedure EdtLocalizarChange(Sender: TObject);
  123.     procedure btDeleteClick(Sender: TObject);
  124.     procedure btEditClick(Sender: TObject);
  125.     procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  126.   private
  127.     procedure TrataAlgunsButtons(OK: Boolean);
  128.     procedure MyOnBeforeInsert(aSender: TObject; var PodeExecutar: Boolean);
  129.   public
  130.     Ponteiro : PtForm;
  131.     Destructor Destroy();
  132.   end;
  133.  
  134. var
  135.   frmCadastroBase: TForm;
  136.  
  137. implementation
  138.  
  139. uses uPrincipal, uFuncoesUniversais, uFuncForm, uDMBase, IPersist, uConexao;
  140.  
  141. {$R *.dfm}
  142.  
  143. { TfrmCadastroBase }
  144.  
  145. procedure TfrmCadastroBase.btCloseClick(Sender: TObject);
  146. begin
  147.   Self.Close;
  148. end;
  149.  
  150. procedure TfrmCadastroBase.btDeleteClick(Sender: TObject);
  151. var
  152.   loTable : IPersist.ITable;
  153.   i: Integer;
  154.   iInc: Double;
  155.   nDataSet: IPersist.TTable;
  156. begin
  157.   loTable := IPersist.TTable.Create(dmBase.Conexao.Name, 'USUARIOS', ['ID_USUARIO']);
  158.   loTable.UseLog := true;
  159.   loTable.FileLog := 'c:\filelog.log';
  160.   if GridBase.SelectedRows.Count > 1 then //Se o select for maior que um então é multselect
  161.   begin
  162.     //DeleteMultSelect(GridBase);
  163.     with GridBase.DataSource.DataSet do
  164.     begin
  165.       //for i := GridBase.SelectedRows.Count - 1 downto 0 do
  166.       for i := 0 to GridBase.SelectedRows.Count - 1 do
  167.       begin
  168.         GotoBookmark(Pointer(GridBase.SelectedRows.Items[i]));
  169.         loTable.FieldByName('ID_USUARIO').AsInteger := GridBase.DataSource.DataSet.FieldByName('ID_USUARIO').AsInteger;
  170.         loTable.Delete;
  171.       end;
  172.     end;
  173.     //GridBase.SelectedRows.Delete;
  174.     dsLocal.DataSet := loTable.TcdsDataSet;
  175.   end else
  176.   begin
  177.     loTable.FieldByName('ID_USUARIO').AsInteger := GridBase.DataSource.DataSet.FieldByName('ID_USUARIO').AsInteger;
  178.     loTable.Delete;
  179.     dsLocal.DataSet := loTable.TcdsDataSet;
  180.   end;
  181.   GridBase.Refresh;
  182. end;
  183.  
  184. procedure TfrmCadastroBase.btEditClick(Sender: TObject);
  185. var
  186.   loTable : IPersist.ITable;
  187.   iInc: Double;
  188.   nDataSet: IPersist.TTable;
  189. begin
  190.   loTable := IPersist.TTable.Create(dmBase.Conexao.Name, 'USUARIOS', ['ID_USUARIO']);
  191.   loTable.UseLog := true;
  192.   loTable.FileLog := 'c:\filelog.log';
  193.   loTable.FieldByName('ID_USUARIO').AsInteger := GridBase.DataSource.DataSet.FieldByName('ID_USUARIO').AsInteger;
  194.   loTable.FieldByName('USUARIO').AsString := 'SUPER';
  195.   loTable.FieldByName('SENHA').AsString := 'UP0014';
  196.   loTable.FieldByName('CONFSENHA').AsString := 'UP0014';
  197.   loTable.FieldByName('NIVEL').AsString := '2';
  198.   loTable.Update;
  199.   dsLocal.DataSet := loTable.TcdsDataSet;
  200.   GridBase.Refresh;
  201.  
  202. end;
  203.  
  204. procedure TfrmCadastroBase.btInsertClick(Sender: TObject);
  205. var
  206.   loTable : IPersist.ITable;
  207.   iInc: Double;
  208.   nDataSet: IPersist.TTable;
  209. begin
  210.  
  211.   //Comentario: Os parametros DBX são: O nome do SQLConnection, a Tabela e a Chave Primaria
  212.   loTable := IPersist.TTable.Create(dmBase.Conexao.Name, 'USUARIOS', ['ID_USUARIO']);
  213.   loTable.UseLog := true;
  214.   loTable.FileLog := 'c:\filelog.log';
  215.  
  216.   loTable.OnBeforeInsert := MyOnBeforeInsert;
  217.   //
  218.   iInc := dmBase.RetornaID('2');
  219.   with dmBase.cdsControle do
  220.   begin
  221.     Close;
  222.     CommandText := ' SELECT * FROM CONTROLE ';
  223.     Open;
  224.   end;
  225.   //
  226.  
  227.   loTable.FieldByName('ID_USUARIO').AsInteger :=  dmBase.cdsControleVALOR.AsInteger;
  228.   loTable.FieldByName('USUARIO').AsString := 'GENERICO';
  229.   loTable.FieldByName('SENHA').AsString := 'XBS111';
  230.   loTable.FieldByName('CONFSENHA').AsString := 'XBS111';
  231.   loTable.FieldByName('NIVEL').AsString := '1';
  232.   //Table.FieldByName('DATACRIACAO').AsString := '';
  233.   //Table.FieldByName('EXPIRAEM').AsString := '';
  234.   {loTable.FieldByName('GRUPO').AsString := '';
  235.   loTable.FieldByName('ADM').AsString := '';
  236.   loTable.FieldByName('ALTERARSENHA').AsString := 'N';
  237.   loTable.FieldByName('NAOEXPIRA').AsString := 'N';
  238.   loTable.FieldByName('IDEMPRESAS').AsString := '';
  239.   loTable.FieldByName('CRIAR_LOG_USUARIO').AsString := 'N';
  240.   loTable.FieldByName('EXIBIRHISTORICOAUDIT').AsString := 'N';
  241.   loTable.FieldByName('CHECARCONTROLES').AsString := 'N';
  242.   loTable.FieldByName('PRIVILEGIOADMIN').AsString := 'S';
  243.   loTable.FieldByName('PERMISSAOALTSENHA').AsString := 'S'; }
  244.  
  245.   loTable.Insert;
  246.   dsLocal.DataSet := loTable.TcdsDataSet;
  247.  
  248.   //ShowMessage('Registros Incluidos ' + inttostr(loTable.Insert));
  249. end;
  250.  
  251. procedure TfrmCadastroBase.btLocateClick(Sender: TObject);
  252. var
  253.     qryLocal: TSQLDataSet;
  254. begin
  255.   qryLocal := TSQLDataSet.Create(nil);
  256.   try
  257.     (* realiza a conexão com o banco *)
  258.     dsLocal.DataSet := qryLocal;
  259.     qryLocal.SQLConnection := TConexao.GetIntance(FIREBIRD);
  260.     qryLocal.CommandText := 'SELECT * FROM usuarios';
  261.     qryLocal.Open;
  262.   finally
  263.     FreeAndNil(qryLocal);
  264.   end;
  265. end;
  266.  
  267. procedure TfrmCadastroBase.ButtonMenu1Click(Sender: TObject);
  268. begin
  269.   ButtonMenu1.MenuButtonClick(Sender);
  270. end;
  271.  
  272. destructor TfrmCadastroBase.Destroy;
  273. var
  274.   PtAux: PtForm;
  275. begin
  276.   PtAux := Ponteiro;
  277.   inherited Destroy();
  278.   If ( PtAux^ <> Nil ) Then
  279.     PtAux^ := Nil;
  280. end;
  281.  
  282. procedure TfrmCadastroBase.EdtLocalizarChange(Sender: TObject);
  283. var
  284.   loTable : IPersist.ITable;
  285.   iInc: Double;
  286.   nDataSet: IPersist.TTable;
  287. begin
  288.  
  289.   //Comentario: Os parametros DBX são: O nome do SQLConnection, a Tabela e a Chave Primaria
  290.   loTable := IPersist.TTable.Create(dmBase.Conexao.Name, 'USUARIOS', ['USUARIO']);
  291.   loTable.UseLog := true;
  292.   loTable.FileLog := 'c:\filelog.log';
  293.   dsLocal.DataSet := loTable.TcdsDataSet;
  294.   loTable.FieldByName('USUARIO').AsString := AnsiUpperCase(EdtLocalizar.Text)+'%';
  295.   if loTable.Select('*') then
  296.  
  297. end;
  298.  
  299. procedure TfrmCadastroBase.FormClose(Sender: TObject; var Action: TCloseAction);
  300. begin
  301.   Action := caFree;
  302. end;
  303.  
  304. procedure TfrmCadastroBase.FormCreate(Sender: TObject);
  305. var
  306. CPanel : Integer;
  307. begin
  308.   //Este bloco serve para o panel não ficar na cor branca
  309.   for CPanel := 0 to Self.ComponentCount - 1 do
  310.     if (Self.Components[CPanel]) is TPanel then
  311.       with (Self.Components[CPanel] as TPanel) do
  312.           ParentBackground := False;
  313.   //
  314.   //centraliza o form
  315.   Left := (Screen.Width - Width ) div 2;
  316.   Top  := 0;
  317.   //Ao iniciar o form, deixar sempre com foco na primeira pagina
  318.   PaginaPrincipal.ActivePageIndex := 0;
  319.   PaginaExtra.ActivePageIndex := 0;
  320. end;
  321.  
  322. procedure TfrmCadastroBase.FormKeyDown(Sender: TObject; var Key: Word;
  323.   Shift: TShiftState);
  324. begin
  325.   case key of
  326.     {avança com enter}
  327.     vk_return : SendMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0);
  328.     {retorna com esc}
  329.     vk_escape : SendMessage(Self.Handle, WM_NEXTDLGCTL, 1 ,0);
  330.   end;
  331. end;
  332.  
  333. procedure TfrmCadastroBase.FormShow(Sender: TObject);
  334. var
  335.   i, iIdentificacaoForm: Integer;
  336. begin
  337.   //Variavel recebe a numeração da Tag para saber qual é o form
  338.   iIdentificacaoForm := Tag;
  339.   Caption := '[ Identificação do Formulário ] - TAG - ' + IntToStr(iIdentificacaoForm);
  340.   //Verificando as Tag do JvXPBar1
  341.   for i := 0 to JvXPBar1.Items.Count-1 do
  342.   begin
  343.     if JvXPBar1.Items[i].Tag = Tag then
  344.       JvXPBar1.Items[i].Enabled := False
  345.     else
  346.       JvXPBar1.Items[i].Enabled := True;
  347.   end;
  348.  
  349.   //Desabilitando tema XPManifest
  350.   if ThemeServices.ThemesEnabled then
  351.     SetWindowTheme(PaginaPrincipal.Handle, '', '');
  352.   SetWindowTheme( PaginaExtra.Handle, nil, '' );
  353. end;
  354.  
  355. procedure TfrmCadastroBase.ModoCadastroShow(Sender: TObject);
  356. begin
  357.   TrataAlgunsButtons(False);
  358. end;
  359.  
  360. procedure TfrmCadastroBase.ModoListagemShow(Sender: TObject);
  361. begin
  362.   TrataAlgunsButtons(True);
  363. end;
  364.  
  365. procedure TfrmCadastroBase.MyOnBeforeInsert(aSender: TObject;
  366.   var PodeExecutar: Boolean);
  367. begin
  368.   PodeExecutar := Pt_MessageDlgXe('Continua com a execução do método?','Mensagem do Sistema', mtConfirmation, [mbYes, mbNO], 0) = mrYes;
  369. end;
  370.  
  371. procedure TfrmCadastroBase.RadioGroup2Click(Sender: TObject);
  372. begin
  373.   case RadioGroup2.ItemIndex of
  374.     0: PaginaExtra.TabPosition := tpTop;
  375.     1: PaginaExtra.TabPosition := tpLeft;
  376.     2: PaginaExtra.TabPosition := tpBottom;
  377.     3: PaginaExtra.TabPosition := tpRight;
  378.   end;
  379. end;
  380.  
  381. procedure TfrmCadastroBase.TrataAlgunsButtons(OK: Boolean);
  382. var
  383.   obj: TInfStateForm; //Chamo o metodo da classe pai e os filhos dentro
  384.                       //não preciso neste caso chamar as classes filhos uma a uma.
  385. begin
  386.   if Ok = True then
  387.   begin
  388.     btLocate.Enabled := True;
  389.     ButtonMenu1.MainButton.Enabled  := True;
  390.     ButtonMenu1.MenuButton.Enabled  := True;
  391.     obj := TListagem.Create; //Então aqui eu instancio na classe filho pq herda da classe pai
  392.     PanelInformation.Caption := obj.SetStateForm;
  393.     obj.Free;
  394.   end
  395.   else
  396.   if Ok = False then
  397.   begin
  398.     btLocate.Enabled := False;
  399.     ButtonMenu1.MainButton.Enabled  := False;
  400.     ButtonMenu1.MenuButton.Enabled  := False;
  401.     obj := TCadastro.Create; //Então aqui eu instancio na classe filho pq herda da classe pai
  402.     PanelInformation.Caption := obj.SetStateForm;
  403.     obj.Free;
  404.   end;
  405. end;
  406.  
  407. { TListagem }
  408.  
  409. function TListagem.SetStateForm: string;
  410. begin
  411.   Result := 'Listagem';
  412. end;
  413.  
  414. { TCadastro }
  415.  
  416. function TCadastro.SetStateForm: string;
  417. begin
  418.   Result := 'Cadastro';
  419. end;
  420.  
  421. end.



No completar la clase, más están haciendo lo que fue diseñado, todo en programación orientada a objetos OOP

Espero que ayuda.
  • 0

#6 Delphius

Delphius

    Advanced Member

  • Administrador
  • 6.295 mensajes
  • LocationArgentina

Escrito 03 diciembre 2010 - 08:04

Hola Master23, ¡Tanto tiempo!

Bueno, la verdad es que explicar el paradigma OO no es algo que sea tan fácil, tampoco es que sea complicado; es tedioso... demanda mucho tiempo. En una cátedra de Lenguajes demandaría un semestre dar los conceptos, interpretarlos, fomentarlos, y luego todo un año para llegar a potenciarlos.

Aprender OO no es leer y ya está, el seguir los ejemplos de manuales y tutoriales puede ayudar a comprenderlos, pero extraer su mayor potencial es algo que se va cultivando...

No desesperes si te cuesta captar la onda.

Te recomiendo la lectura del capítulo dedicado a POO del libro La Cara Oculta. Te guiará. Luego te puedo recomendar los manuales sobre POO que escribí hace un tiempo. Son bastantes simples y se basan en ejemplos al estilo perro-gato y de ese modo evitar ofrecer mayores formalismos.

Para más adelante, cuando ya le hayas agarrado el gusto al paradigma puedes dar el salto y leer a Craig Larman en su libro UML y Patrones... Creeme que ese libro te cambiará radicalmente tu concepción OO y te fortalecerá enormemente... Además el que a lo largo de todo el libro de ejemplos basado en un único escenario y válido para la vida real: un sistema PDV ya no piensas en perros y gatos sino que descubres y ves a todo como potenciales clases.

El mayor problema y es lo que cuesta realmente a los estudiantes no es comprender sus conceptos como clase, herencia, objeto, etc... su problema radica en una falta de potenciar y enseñar a hacer análisis OO y trasladar las entidades de un contexto a un plano OO... Eso muy lamentablemente Master23 es algo que se aprende con la práctica; Craig ayuda mucho en el sentido del análisis OO pero luego está en dar el salto nosotros.

No temas preguntar a medida que te asaltan las dudas. Admito que tengo bastante pendiente elaborar un artículo que explique como dar el paso del pensamiento estructurado hacia el orientado a objetos... Cuando empieces a comprenderlo notarás que la diferencia entre ellos no es tan abrumadora... es más, es posible que hasta le encuentres ciertos parecidos.  ;)

Saludos,
  • 0

#7 Delphius

Delphius

    Advanced Member

  • Administrador
  • 6.295 mensajes
  • LocationArgentina

Escrito 05 diciembre 2010 - 11:50

Hola,
¿Alguna novedad Master23?
Espero que no pienses que soy vago y no quiero dar explicaciones bien profundas... es que es tedioso. Y el mayor peligro es dar un ejemplo como el que ha mostrado adriano puesto que existe la posibilidad de que te resulte chinesco si aún no le agarras la mano a los conceptos. Por ello es que es más fácil comprenderlo, inicialmente, en base a los ejemplos simples y no intentar demasiado a que la cabeza absorva un ejemplo real y tan completo como el que se muestra aquí.

Nos sería de utilidad el que nos comentes tus dudas a medida que vas estudiando y de allí vemos como irte guiando.
  • 0




IP.Board spam blocked by CleanTalk.