text
stringlengths
14
6.51M
unit Area; interface uses BaseObjects, Registrator, SysUtils; type TSimpleArea = class (TRegisteredIDObject) private FWells: TRegisteredIDObjects; function GetWells: TRegisteredIDObjects; public class function ShortenAreaName(AAreaName: string): string; function List(AListOption: TListOption = loBrief): string; override; property Wells: TRegisteredIDObjects read GetWells; constructor Create(ACollection: TIDObjects); override; destructor Destroy; override; end; TSimpleAreas = class (TRegisteredIDObjects) private function GetItems(Index: integer): TSimpleArea; public property Items[Index: integer]: TSimpleArea read GetItems; constructor Create; override; end; TArea = class (TSimpleArea) public constructor Create(ACollection: TIDObjects); override; end; TAreas = class (TSimpleAreas) private function GetItems(Index: integer): TArea; public property Items[Index: integer]: TArea read GetItems; constructor Create; override; end; implementation uses Facade, BaseFacades, AreaPoster, Math, Well; { TAreas } constructor TAreas.Create; begin inherited; FObjectClass := TArea; end; function TAreas.GetItems(Index: integer): TArea; begin Result := inherited Items[Index] as TArea; end; { TArea } constructor TArea.Create(ACollection: TIDObjects); begin inherited; FClassIDString := 'Площадь'; end; { TSimpleAreas } constructor TSimpleAreas.Create; begin inherited; FObjectClass := TSimpleArea; Poster := TMainFacade.GetInstance.DataPosterByClassType[TAreaDataPoster]; end; function TSimpleAreas.GetItems(Index: integer): TSimpleArea; begin Result := inherited Items[Index] as TSimpleArea; end; { TSimpleArea } constructor TSimpleArea.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Простая площадь'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TAreaDataPoster]; end; destructor TSimpleArea.Destroy; begin FreeAndNil(FWells); inherited; end; function TSimpleArea.GetWells: TRegisteredIDObjects; begin If not Assigned (FWells) then begin FWells := TSimpleWells.Create; FWells.OwnsObjects := true; FWells.Owner := Self; FWells.Reload('AREA_ID = ' + IntToStr(ID)); end; Result := FWells; end; function TSimpleArea.List(AListOption: TListOption): string; begin Result := trim(StringReplace(inherited List(AListOption), '(-ое)', '', [rfReplaceAll])); end; class function TSimpleArea.ShortenAreaName(AAreaName: string): string; begin AAreaName := StringReplace(AAreaName, ' (-ое)', '', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Восточно-', 'В-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Западно-', 'З-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Северо-', 'С-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Южно-', 'Ю-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Усть-', 'У-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Усть', 'У-', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Верхне', 'Вх', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Средне', 'Ср', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'Нижне', 'Нж', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'мыльк', '', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'ьская', '', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'ская', '', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'ная', '', [rfReplaceAll]); AAreaName := StringReplace(AAreaName, 'ая', '', [rfReplaceAll]); Result := AAreaName; end; end.
program matrix; const GROESSE2 = 5; type tMatrix = array [1..GROESSE2,1..GROESSE2] of integer; var X, A ,B,C,D,E: tMatrix; i, j,k : integer; function MatrixAusgabe(Matrix : tMatrix; GROESSE : integer) : boolean; { Gibt die Matrix auf der Konsole aus } var i, j : integer; begin MatrixAusgabe := true; for i := 1 to GROESSE do begin for j := 1 to GROESSE do write( Matrix[i,j]: 3,' '); writeln(); end end; function TransponierenA(A: tMatrix; GROESSE : integer) : tMatrix; { Transponiert die Matrix, vielleicht ... } var tauschPuffer, i, j : integer; begin for i := 1 to GROESSE-1 do for j := i+1 to GROESSE do begin tauschPuffer := A[i,j]; A[i,j] := A[j,i]; A[j,i] := tauschPuffer end; TransponierenA := A; writeln('TransponierenA='); MatrixAusgabe(A, GROESSE) end; function TransponierenB(A: tMatrix; GROESSE : integer) : tMatrix; { Transponiert die Matrix, vielleicht ... } var tauschPuffer, i, j : integer; begin for i := 1 to GROESSE do for j := 1 to i do begin tauschPuffer := A[i,j]; A[i,j] := A[j,i]; A[j,i] := tauschPuffer end; TransponierenB := A; writeln('TransponierenB='); MatrixAusgabe(A, GROESSE) end; function TransponierenC(A: tMatrix; GROESSE : integer) : tMatrix; { Transponiert die Matrix, vielleicht ... } var tauschPuffer, i, j : integer; begin for i := 1 to GROESSE do for j := 1 to GROESSE do begin tauschPuffer := A[i,j]; A[i,j] := A[j,i]; A[j,i] := tauschPuffer end; TransponierenC := A; writeln('TransponierenC='); MatrixAusgabe(A, GROESSE) end; function TransponierenD(A: tMatrix; GROESSE : integer) : tMatrix; { Transponiert die Matrix, vielleicht ... } var tauschPuffer, i, j : integer; begin for i := 1 to GROESSE do for j := 1 to GROESSE-i do begin tauschPuffer := A[i,j]; A[i,j] := A[j,i]; A[j,i] := tauschPuffer end; TransponierenD := A; writeln('TransponierenD='); MatrixAusgabe(A, GROESSE) end; function TransponierenE(A: tMatrix; GROESSE : integer) : tMatrix; { Transponiert die Matrix, vielleicht ... } var tauschPuffer, i, j : integer; begin for i := 1 to GROESSE-1 do for j := i+1 to GROESSE do begin tauschPuffer := A[i,j]; A[j,i] := A[i,j]; A[j,i] := tauschPuffer end; TransponierenE := A; writeln('TransponierenE='); MatrixAusgabe(A, GROESSE) end; BEGIN k := 1; for i := 1 to GROESSE2 do for j := 1 to GROESSE2 do begin X[i,j] := k; k := k+1; {if i=j then A[i,j] := i; if i>j then A[i,j] := i+j; if(i<j) then A[i,j] := i*j;} end; writeln('X='); MatrixAusgabe(X, GROESSE2); A := TransponierenA(X, GROESSE2); B := TransponierenB(X, GROESSE2); C := TransponierenC(X, GROESSE2); D := TransponierenD(X, GROESSE2); E := TransponierenE(X, GROESSE2); END.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela para confirmar a Cotação de Compra The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije @version 2.0 ******************************************************************************* } unit UCompraConfirmaCotacao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, CompraCotacaoVO, CompraCotacaoController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, Generics.Collections, Spin, JvSpin, CompraFornecedorCotacaoVO, PlatformDefaultStyleActnCtrls, ActnList, ActnMan, ActnCtrls, ToolWin, Biblioteca, System.Actions, Controller; type [TFormDescription(TConstantes.MODULO_COMPRAS, 'Confirma Cotação')] TFCompraConfirmaCotacao = class(TFTelaCadastro) BevelEdits: TBevel; EditDescricao: TLabeledEdit; EditDataCotacao: TLabeledDateEdit; GroupBoxItensCotacao: TGroupBox; GridCompraCotacaoDetalhe: TJvDBUltimGrid; GroupBoxFornecedores: TGroupBox; GridCompraFornecedorCotacao: TJvDBUltimGrid; DSCompraFornecedorCotacao: TDataSource; DSCompraCotacaoDetalhe: TDataSource; CDSCompraFornecedorCotacao: TClientDataSet; CDSCompraFornecedorCotacaoID: TIntegerField; CDSCompraFornecedorCotacaoID_FORNECEDOR: TIntegerField; CDSCompraFornecedorCotacaoID_COMPRA_COTACAO: TIntegerField; CDSCompraFornecedorCotacaoPRAZO_ENTREGA: TStringField; CDSCompraFornecedorCotacaoCONDICOES_PAGAMENTO: TStringField; CDSCompraFornecedorCotacaoVALOR_SUBTOTAL: TFMTBCDField; CDSCompraFornecedorCotacaoTAXA_DESCONTO: TFMTBCDField; CDSCompraFornecedorCotacaoVALOR_DESCONTO: TFMTBCDField; CDSCompraFornecedorCotacaoTOTAL: TFMTBCDField; CDSCompraCotacaoDetalhe: TClientDataSet; CDSCompraCotacaoDetalheID: TIntegerField; CDSCompraCotacaoDetalheID_COMPRA_FORNECEDOR_COTACAO: TIntegerField; CDSCompraCotacaoDetalheID_PRODUTO: TIntegerField; CDSCompraCotacaoDetalheQUANTIDADE: TFMTBCDField; CDSCompraCotacaoDetalheVALOR_UNITARIO: TFMTBCDField; CDSCompraCotacaoDetalheVALOR_SUBTOTAL: TFMTBCDField; CDSCompraCotacaoDetalheTAXA_DESCONTO: TFMTBCDField; CDSCompraCotacaoDetalheVALOR_DESCONTO: TFMTBCDField; CDSCompraCotacaoDetalheVALOR_TOTAL: TFMTBCDField; CDSCompraCotacaoDetalheQUANTIDADE_PEDIDA: TFMTBCDField; CDSCompraFornecedorCotacaoPERSISTE: TStringField; CDSCompraCotacaoDetalhePERSISTE: TStringField; CDSCompraCotacaoDetalhePRODUTONOME: TStringField; ActionToolBar3: TActionToolBar; ActionManager1: TActionManager; ActionGerarCsv: TAction; ActionLerCsvFornecedor: TAction; CDSCompraFornecedorCotacaoFORNECEDORNOME: TStringField; procedure FormCreate(Sender: TObject); procedure CDSCompraFornecedorCotacaoAfterEdit(DataSet: TDataSet); procedure CDSCompraCotacaoDetalheAfterEdit(DataSet: TDataSet); procedure GridDblClick(Sender: TObject); procedure CDSCompraFornecedorCotacaoAfterPost(DataSet: TDataSet); procedure CDSCompraCotacaoDetalheAfterPost(DataSet: TDataSet); procedure ActionGerarCsvExecute(Sender: TObject); procedure ActionLerCsvFornecedorExecute(Sender: TObject); private { Private declarations } function ValidarDadosInformados: Boolean; public { Public declarations } procedure GridParaEdits; override; procedure LimparCampos; override; procedure ControlaBotoes; override; // Controles CRUD function DoEditar: Boolean; override; function DoSalvar: Boolean; override; procedure ConfigurarLayoutTela; end; var FCompraConfirmaCotacao: TFCompraConfirmaCotacao; implementation uses UDataModule, CompraCotacaoDetalheVO, CompraFornecedorCotacaoController, CompraCotacaoDetalheController, Math, ViewCompraItemCotacaoVO, ViewCompraItemCotacaoController; {$R *.dfm} {$REGION 'Infra'} procedure TFCompraConfirmaCotacao.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TCompraCotacaoVO; ObjetoController := TCompraCotacaoController.Create; inherited; end; procedure TFCompraConfirmaCotacao.LimparCampos; begin inherited; CDSCompraFornecedorCotacao.EmptyDataSet; CDSCompraCotacaoDetalhe.EmptyDataSet; end; procedure TFCompraConfirmaCotacao.ConfigurarLayoutTela; begin if TCompraCotacaoVO(ObjetoVO).Situacao = 'F' then begin Application.MessageBox('Cotação já fechada. Os dados serão exibidos apenas para consulta.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); GridCompraFornecedorCotacao.ReadOnly := True; GridCompraCotacaoDetalhe.ReadOnly := True; end; EditDataCotacao.ReadOnly := True; EditDescricao.ReadOnly := True; PanelEdits.Enabled := True; end; procedure TFCompraConfirmaCotacao.ControlaBotoes; begin inherited; BotaoInserir.Visible := False; BotaoExcluir.Visible := False; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFCompraConfirmaCotacao.DoEditar: Boolean; begin Result := inherited DoEditar; ConfigurarLayoutTela; if Result then begin EditDataCotacao.SetFocus; end; end; function TFCompraConfirmaCotacao.DoSalvar: Boolean; var CompraFornecedorCotacao: TCompraFornecedorCotacaoVO; CompraCotacaoDetalhe: TCompraCotacaoDetalheVO; DadosAlterados: Boolean; begin if TCompraCotacaoVO(ObjetoVO).Situacao <> 'F' then begin if ValidarDadosInformados then begin DadosAlterados := False; Result := inherited DoSalvar; if Result then begin try // Cotação Fornecedor e Seus Detalhes CDSCompraFornecedorCotacao.First; CDSCompraCotacaoDetalhe.DisableControls; while not CDSCompraFornecedorCotacao.Eof do begin if (CDSCompraFornecedorCotacaoPERSISTE.AsString = 'S') then begin DadosAlterados := True; CompraFornecedorCotacao := TCompraFornecedorCotacaoVO.Create; CompraFornecedorCotacao.Id := CDSCompraFornecedorCotacaoID.AsInteger; CompraFornecedorCotacao.IdFornecedor := CDSCompraFornecedorCotacaoID_FORNECEDOR.AsInteger; CompraFornecedorCotacao.IdCompraCotacao := TCompraCotacaoVO(ObjetoVO).Id; CompraFornecedorCotacao.PrazoEntrega := CDSCompraFornecedorCotacaoPRAZO_ENTREGA.AsString; CompraFornecedorCotacao.CondicoesPagamento := CDSCompraFornecedorCotacaoCONDICOES_PAGAMENTO.AsString; CompraFornecedorCotacao.ValorSubtotal := CDSCompraFornecedorCotacaoVALOR_SUBTOTAL.AsExtended; CompraFornecedorCotacao.TaxaDesconto := CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended; CompraFornecedorCotacao.ValorDesconto := CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended; CompraFornecedorCotacao.Total := CDSCompraFornecedorCotacaoTOTAL.AsExtended; //carrega os itens de cada fornecedor CompraFornecedorCotacao.ListaCompraCotacaoDetalhe := TObjectList<TCompraCotacaoDetalheVO>.Create; CDSCompraCotacaoDetalhe.First; while not CDSCompraCotacaoDetalhe.Eof do begin if (CDSCompraCotacaoDetalhePERSISTE.AsString = 'S') then begin CompraCotacaoDetalhe := TCompraCotacaoDetalheVO.Create; CompraCotacaoDetalhe.Id := CDSCompraCotacaoDetalheID.AsInteger; CompraCotacaoDetalhe.IdCompraFornecedorCotacao := CompraFornecedorCotacao.Id; CompraCotacaoDetalhe.IdProduto := CDSCompraCotacaoDetalheID_PRODUTO.AsInteger; CompraCotacaoDetalhe.Quantidade := CDSCompraCotacaoDetalheQUANTIDADE.AsExtended; CompraCotacaoDetalhe.ValorUnitario := CDSCompraCotacaoDetalheVALOR_UNITARIO.AsExtended; CompraCotacaoDetalhe.ValorSubtotal := CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsExtended; CompraCotacaoDetalhe.TaxaDesconto := CDSCompraCotacaoDetalheTAXA_DESCONTO.AsExtended; CompraCotacaoDetalhe.ValorDesconto := CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended; CompraCotacaoDetalhe.ValorTotal := CDSCompraCotacaoDetalheVALOR_TOTAL.AsExtended; CompraFornecedorCotacao.ListaCompraCotacaoDetalhe.Add(CompraCotacaoDetalhe); end; CDSCompraCotacaoDetalhe.Next; end; TCompraCotacaoVO(ObjetoVO).ListaCompraFornecedorCotacao.Add(CompraFornecedorCotacao) end; CDSCompraFornecedorCotacao.Next; end; CDSCompraFornecedorCotacao.First; CDSCompraCotacaoDetalhe.First; CDSCompraCotacaoDetalhe.EnableControls; if DadosAlterados then begin TCompraCotacaoVO(ObjetoVO).Situacao := 'C'; TController.ExecutarMetodo('CompraFornecedorCotacaoController.TCompraFornecedorCotacaoController', 'Altera', [TCompraCotacaoVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); except Result := False; end; end; end else Exit(False); end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFCompraConfirmaCotacao.GridParaEdits; var Filtro: String; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TCompraCotacaoVO(TController.BuscarObjeto('CompraCotacaoController.TCompraCotacaoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditDataCotacao.Date := TCompraCotacaoVO(ObjetoVO).DataCotacao; EditDescricao.Text := TCompraCotacaoVO(ObjetoVO).Descricao; // Fornecedores da Cotação Filtro := 'ID_COMPRA_COTACAO=' + QuotedStr(IntToStr(TCompraCotacaoVO(ObjetoVO).Id)); TCompraFornecedorCotacaoController.SetDataSet(CDSCompraFornecedorCotacao); TController.ExecutarMetodo('CompraFornecedorCotacaoController.TCompraFornecedorCotacaoController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista'); // Itens da Cotação - Baixa todos e controla o mestre/detalhe local através do ClientDataset Filtro := 'ID_COTACAO=' + QuotedStr(IntToStr(TCompraCotacaoVO(ObjetoVO).Id)); TViewCompraItemCotacaoController.SetDataSet(CDSCompraCotacaoDetalhe); TController.ExecutarMetodo('ViewCompraItemCotacaoController.TViewCompraItemCotacaoController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista'); end; end; procedure TFCompraConfirmaCotacao.CDSCompraCotacaoDetalheAfterPost(DataSet: TDataSet); begin if CDSCompraCotacaoDetalheID.AsInteger = 0 then CDSCompraCotacaoDetalhe.Delete; //Se alterar algum item, será necessário alterar seu cabeçalho CDSCompraFornecedorCotacao.Edit; CDSCompraFornecedorCotacaoPERSISTE.AsString := 'S'; CDSCompraFornecedorCotacao.Post; end; procedure TFCompraConfirmaCotacao.CDSCompraFornecedorCotacaoAfterEdit(DataSet: TDataSet); begin CDSCompraFornecedorCotacaoPERSISTE.AsString := 'S'; end; procedure TFCompraConfirmaCotacao.CDSCompraFornecedorCotacaoAfterPost(DataSet: TDataSet); begin if CDSCompraFornecedorCotacaoID.AsInteger = 0 then CDSCompraFornecedorCotacao.Delete; end; procedure TFCompraConfirmaCotacao.CDSCompraCotacaoDetalheAfterEdit(DataSet: TDataSet); begin CDSCompraCotacaoDetalhePERSISTE.AsString := 'S'; end; procedure TFCompraConfirmaCotacao.GridDblClick(Sender: TObject); begin inherited; ConfigurarLayoutTela; end; {$ENDREGION} {$REGION 'Actions'} function TFCompraConfirmaCotacao.ValidarDadosInformados: Boolean; var Mensagem: String; TotalDetalhe: Extended; begin CDSCompraCotacaoDetalhe.DisableControls; CDSCompraFornecedorCotacao.First; while not CDSCompraFornecedorCotacao.Eof do begin if (CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended = 0) and (CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended <> 0) then Mensagem := Mensagem + #13 + 'Taxa do desconto não corresponde ao valor do desconto. Registro cabeçalho. [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if (CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended <> 0) and (CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended = 0) then Mensagem := Mensagem + #13 + 'Taxa do desconto não corresponde ao valor do desconto. Registro cabeçalho. [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if (CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended <> 0) and (CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended <> 0) then if FloatToStrF(CDSCompraFornecedorCotacaoVALOR_SUBTOTAL.AsExtended * CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended / 100, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Valor do desconto calculado de forma incorreta. Registro cabeçalho. [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if FloatToStrF(CDSCompraFornecedorCotacaoVALOR_SUBTOTAL.AsExtended - CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraFornecedorCotacaoTOTAL.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Valor total calculado de forma incorreta (Total = SubTotal - Desconto). Registro cabeçalho. [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; // TotalDetalhe := 0; CDSCompraCotacaoDetalhe.First; while not CDSCompraCotacaoDetalhe.Eof do begin if (CDSCompraCotacaoDetalheTAXA_DESCONTO.AsExtended = 0) and (CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended <> 0) then Mensagem := Mensagem + #13 + 'Taxa do desconto não corresponde ao valor do desconto. Registro detalhe. [Id Produto = ' + CDSCompraCotacaoDetalheID_PRODUTO.AsString + '] - [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if (CDSCompraCotacaoDetalheTAXA_DESCONTO.AsExtended <> 0) and (CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended = 0) then Mensagem := Mensagem + #13 + 'Taxa do desconto não corresponde ao valor do desconto. Registro detalhe. [Id Produto = ' + CDSCompraCotacaoDetalheID_PRODUTO.AsString + '] - [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if (CDSCompraCotacaoDetalheTAXA_DESCONTO.AsExtended <> 0) and (CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended <> 0) then if FloatToStrF(CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsExtended * CDSCompraCotacaoDetalheTAXA_DESCONTO.AsExtended / 100, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Valor do desconto calculado de forma incorreta. Registro detalhe. [Id Produto = ' + CDSCompraCotacaoDetalheID_PRODUTO.AsString + '] - [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if FloatToStrF(CDSCompraCotacaoDetalheQUANTIDADE.AsExtended * CDSCompraCotacaoDetalheVALOR_UNITARIO.AsExtended, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Valor subtotal calculado de forma incorreta (SubTotal = Quantidade * Valor Unitário). Registro detalhe. [Id Produto = ' + CDSCompraCotacaoDetalheID_PRODUTO.AsString + '] - [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; if FloatToStrF(CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsExtended - CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraCotacaoDetalheVALOR_TOTAL.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Valor total calculado de forma incorreta (Total = SubTotal - Desconto). Registro detalhe. [Id Produto = ' + CDSCompraCotacaoDetalheID_PRODUTO.AsString + '] - [Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + ']'; TotalDetalhe := TotalDetalhe + CDSCompraCotacaoDetalheVALOR_TOTAL.AsExtended; CDSCompraCotacaoDetalhe.Next; end; if FloatToStrF(TotalDetalhe, ffCurrency, 18, 2) <> FloatToStrF(CDSCompraFornecedorCotacaoTOTAL.AsExtended, ffCurrency, 18, 2) then Mensagem := Mensagem + #13 + 'Soma dos itens não bate com o valor total. Registro cabeçalho. Id Fornecedor = ' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString; CDSCompraFornecedorCotacao.Next; end; CDSCompraFornecedorCotacao.First; CDSCompraCotacaoDetalhe.First; CDSCompraCotacaoDetalhe.EnableControls; // if Mensagem <> '' then begin Application.MessageBox(PChar('Ocorreram erros na validação dos dados informados. Lista de erros abaixo: ' + #13 + Mensagem), 'Erro do sistema', MB_OK + MB_ICONERROR); Result := False; end else Result := True; end; procedure TFCompraConfirmaCotacao.ActionGerarCsvExecute(Sender: TObject); var NomeArquivo: String; begin try CDSCompraFornecedorCotacao.DisableControls; CDSCompraFornecedorCotacao.First; while not CDSCompraFornecedorCotacao.Eof do begin NomeArquivo := 'FornecedorCotacao.' + IntToStr(TCompraCotacaoVO(ObjetoVO).Id) + '.' + CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString + '.csv'; FDataModule.ExportarCSV.FileName := NomeArquivo; FDataModule.ExportarCSV.Grid := GridCompraCotacaoDetalhe; FDataModule.ExportarCSV.ExportGrid; CDSCompraFornecedorCotacao.Next; end; CDSCompraFornecedorCotacao.First; CDSCompraFornecedorCotacao.EnableControls; Application.MessageBox('Arquivos gerados com sucesso!', 'Informação do sistema', MB_OK + MB_ICONINFORMATION); except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a geração dos arquivos. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; end; procedure TFCompraConfirmaCotacao.ActionLerCsvFornecedorExecute(Sender: TObject); var OpcoesArquivo, ConteudoArquivo: TStringList; Arquivo: String; i: Integer; SubTotal, TotalDesconto, TotalGeral: Extended; begin if FDataModule.OpenDialog.Execute then begin try try OpcoesArquivo := TStringList.Create; ConteudoArquivo := TStringList.Create; // Arquivo := ExtractFileName(FDataModule.OpenDialog.FileName); Split('.', Arquivo, OpcoesArquivo); if StrToInt(OpcoesArquivo[1]) <> TCompraCotacaoVO(ObjetoVO).Id then begin Application.MessageBox('O arquivo selecionado não pertence a cotação!', 'Informação do sistema', MB_OK + MB_ICONINFORMATION); Exit; end; if OpcoesArquivo[2] <> CDSCompraFornecedorCotacaoID_FORNECEDOR.AsString then begin Application.MessageBox('O arquivo selecionado não pertence ao fornecedor!', 'Informação do sistema', MB_OK + MB_ICONINFORMATION); Exit; end; ConteudoArquivo.LoadFromFile(Arquivo); SubTotal := 0; TotalDesconto := 0; TotalGeral := 0; // CDSCompraCotacaoDetalhe.DisableControls; for i := 1 to ConteudoArquivo.Count - 1 do begin OpcoesArquivo.Clear; ExtractStrings([';'],[], PChar(ConteudoArquivo[i]), OpcoesArquivo); { OpcoesArquivo[0] = Id Produto OpcoesArquivo[1] = Nome do Produto OpcoesArquivo[2] = Quantidade OpcoesArquivo[3] = Valor Unitário OpcoesArquivo[4] = Valor Subtotal OpcoesArquivo[5] = Taxa Desconto OpcoesArquivo[6] = Valor Desconto OpcoesArquivo[7] = Valor Total } CDSCompraCotacaoDetalhe.First; while not CDSCompraCotacaoDetalhe.Eof do begin if CDSCompraCotacaoDetalheID_PRODUTO.AsString = OpcoesArquivo[0] then begin CDSCompraCotacaoDetalhe.Edit; CDSCompraCotacaoDetalheVALOR_UNITARIO.AsString := OpcoesArquivo[3]; CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsString := OpcoesArquivo[4]; CDSCompraCotacaoDetalheTAXA_DESCONTO.AsString := OpcoesArquivo[5]; CDSCompraCotacaoDetalheVALOR_DESCONTO.AsString := OpcoesArquivo[6]; CDSCompraCotacaoDetalheVALOR_TOTAL.AsString := OpcoesArquivo[7]; CDSCompraCotacaoDetalhe.Post; // SubTotal := SubTotal + CDSCompraCotacaoDetalheVALOR_SUBTOTAL.AsExtended; TotalDesconto := TotalDesconto + CDSCompraCotacaoDetalheVALOR_DESCONTO.AsExtended; TotalGeral := TotalGeral + CDSCompraCotacaoDetalheVALOR_TOTAL.AsExtended; end; CDSCompraCotacaoDetalhe.Next; end; end; CDSCompraCotacaoDetalhe.EnableControls; CDSCompraCotacaoDetalhe.First; // Atualiza cabeçalho CDSCompraFornecedorCotacao.Edit; CDSCompraFornecedorCotacaoVALOR_SUBTOTAL.AsExtended := SubTotal; CDSCompraFornecedorCotacaoVALOR_DESCONTO.AsExtended := TotalDesconto; CDSCompraFornecedorCotacaoTOTAL.AsExtended := TotalGeral; CDSCompraFornecedorCotacaoTAXA_DESCONTO.AsExtended := RoundTo(TotalDesconto / TotalGeral, -2) * 100; CDSCompraFornecedorCotacao.Post; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a importação do arquivo. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally OpcoesArquivo.Free; ConteudoArquivo.Free; end; end; end; {$ENDREGION} end.
{*******************************************************} { } { Borland Delphi 7 } { Win32 Tray Icon Unit } { } { } { Copyright (c) Kolesnev Denis (Poseidon) } { } { } {*******************************************************} unit TrayIcon; interface uses Windows, SysUtils, ShellAPI, Forms, Classes, Messages; type TBalloonTimeout = 10..30; TBalloonIconType = (bitNone, // нет иконки bitInfo, // информационная иконка (синяя) bitWarning, // иконка восклицания (жёлтая) bitError); // иконка ошибки (красная) type NotifyIconData_50 = record // определённая в shellapi.h cbSize: DWORD; Wnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array[0..MAXCHAR] of AnsiChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array[0..MAXBYTE] of AnsiChar; uTimeout: UINT; szInfoTitle: array[0..63] of AnsiChar; dwInfoFlags: DWORD; end{record}; const NIF_INFO = $00000010; NIIF_NONE = $00000000; NIIF_INFO = $00000001; NIIF_WARNING = $00000002; NIIF_ERROR = $00000003; function GetApplicationIcon : hIcon; stdcall; function AddTrayIcon (const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String): Boolean; stdcall; function AddTrayIconMsg(const Window: HWND; const IconID: Byte; const Icon: HICON; const Msg: Cardinal; const Hint: String): Boolean; stdcall; function DeleteTrayIcon (const Window: HWND; const IconID: Byte): Boolean; stdcall; function ShowBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: TBalloonTimeout; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType): Boolean; stdcall; function ModifyTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String): Boolean; stdcall; function AnimateToTray(const Form: TForm):boolean; stdcall; function AnimateFromTray(const Form: TForm):boolean; stdcall; implementation {получение иконки приложения} function GetApplicationIcon : hIcon; begin Result := CopyIcon(Application.Icon.Handle); end; {добавление иконки} function AddTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; if Hint = '' then begin uFlags := NIF_ICON; end{if} else begin uFlags := NIF_ICON or NIF_TIP; StrPCopy(szTip, Hint); end{else}; hIcon := Icon; end{with}; Result := Shell_NotifyIcon(NIM_ADD, @NID); end; {добавляет иконку с call-back сообщением} function AddTrayIconMsg(const Window: HWND; const IconID: Byte; const Icon: HICON; const Msg: Cardinal; const Hint: String): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; if Hint = '' then begin uFlags := NIF_ICON or NIF_MESSAGE; end{if} else begin uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP; StrPCopy(szTip, Hint); end{else}; uCallbackMessage := Msg; hIcon := Icon; end{with}; Result := Shell_NotifyIcon(NIM_ADD, @NID); end; {изменяет иконку} function ModifyTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; if Hint = '' then begin uFlags := NIF_ICON or NIF_MESSAGE; end{if} else begin uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP; StrPCopy(szTip, Hint); end{else}; hIcon := Icon; end{with}; Result := Shell_NotifyIcon(NIM_MODIFY, @NID); end; {удаляет иконку} function DeleteTrayIcon(const Window: HWND; const IconID: Byte): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; end{with}; Result := Shell_NotifyIcon(NIM_DELETE, @NID); end; {показать округлённое окошко подсказки} function ShowBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: TBalloonTimeout; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType): Boolean; const aBalloonIconTypes : array[TBalloonIconType] of Byte = (NIIF_NONE, NIIF_INFO, NIIF_WARNING, NIIF_ERROR); var NID_50 : NotifyIconData_50; begin FillChar(NID_50, SizeOf(NotifyIconData_50), 0); with NID_50 do begin cbSize := SizeOf(NotifyIconData_50); Wnd := Window; uID := IconID; uFlags := NIF_INFO; StrPCopy(szInfo, BalloonText); uTimeout := Timeout * 1000; StrPCopy(szInfoTitle, BalloonTitle); dwInfoFlags := aBalloonIconTypes[BalloonIconType]; end{with}; Result := Shell_NotifyIcon(NIM_MODIFY, @NID_50); end; {анимация сворачивания в трей} function AnimateToTray(const Form: TForm):boolean; begin DrawAnimatedRects(Form.Handle, IDANI_CAPTION, Form.BoundsRect, Rect(Screen.Width,Screen.Height,Screen.Width,Screen.Height)); end; {анимация восстановления из трея} function AnimateFromTray(const Form: TForm):boolean; begin DrawAnimatedRects(Form.Handle, IDANI_CAPTION,Rect(Screen.Width, Screen.Height,Screen.Width,Screen.Height),Form.BoundsRect,); end; End.
{***************************************************************************} { } { DelphiWebDriver } { } { Copyright 2017 inpwtepydjuf@gmail.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit Commands.CreateSession; interface uses CommandRegistry, Vcl.Forms, HttpServerCommand; type /// <summary> /// Handles 'POST' '/session' /// </summary> TCreateSessionCommand = class(TRESTCommand) public class function GetCommand: String; override; class function GetRoute: String; override; procedure Execute(AOwner: TForm); override; end; implementation uses Commands, Session; class function TCreateSessionCommand.GetCommand: String; begin result := 'POST'; end; class function TCreateSessionCommand.GetRoute: String; begin result := '/session'; end; procedure TCreateSessionCommand.Execute(AOwner: TForm); var request : String; session : TSession; begin request := self.StreamContents; session := TSession.Create(request); Commands.Sessions.Add(session); ResponseJSON(session.GetSessionDetails); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PONTO_HORARIO_AUTORIZADO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit PontoHorarioAutorizadoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ViewPessoaColaboradorVO; type [TEntity] [TTable('PONTO_HORARIO_AUTORIZADO')] TPontoHorarioAutorizadoVO = class(TVO) private FID: Integer; FID_COLABORADOR: Integer; FDATA_HORARIO: TDateTime; FTIPO: String; FCARGA_HORARIA: String; FENTRADA01: String; FSAIDA01: String; FENTRADA02: String; FSAIDA02: String; FENTRADA03: String; FSAIDA03: String; FENTRADA04: String; FSAIDA04: String; FENTRADA05: String; FSAIDA05: String; FHORA_FECHAMENTO_DIA: String; //Transientes FColaboradorNome: String; FColaboradorVO: TViewPessoaColaboradorVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_COLABORADOR', 'Id Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR; [TColumnDisplay('COLABORADOR.NOME', 'Requisitante', 250, [ldGrid, ldLookup, ldCombobox], ftString, 'ViewPessoaColaboradorVO.TViewPessoaColaboradorVO', True)] property ColaboradorNome: String read FColaboradorNome write FColaboradorNome; [TColumn('DATA_HORARIO', 'Data Horario', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataHorario: TDateTime read FDATA_HORARIO write FDATA_HORARIO; [TColumn('TIPO', 'Tipo', 8, [ldGrid, ldLookup, ldCombobox], False)] property Tipo: String read FTIPO write FTIPO; [TColumn('CARGA_HORARIA', 'Carga Horaria', 64, [ldGrid, ldLookup, ldCombobox], False)] property CargaHoraria: String read FCARGA_HORARIA write FCARGA_HORARIA; [TColumn('ENTRADA01', 'Entrada01', 64, [ldGrid, ldLookup, ldCombobox], False)] property Entrada01: String read FENTRADA01 write FENTRADA01; [TColumn('SAIDA01', 'Saida01', 64, [ldGrid, ldLookup, ldCombobox], False)] property Saida01: String read FSAIDA01 write FSAIDA01; [TColumn('ENTRADA02', 'Entrada02', 64, [ldGrid, ldLookup, ldCombobox], False)] property Entrada02: String read FENTRADA02 write FENTRADA02; [TColumn('SAIDA02', 'Saida02', 64, [ldGrid, ldLookup, ldCombobox], False)] property Saida02: String read FSAIDA02 write FSAIDA02; [TColumn('ENTRADA03', 'Entrada03', 64, [ldGrid, ldLookup, ldCombobox], False)] property Entrada03: String read FENTRADA03 write FENTRADA03; [TColumn('SAIDA03', 'Saida03', 64, [ldGrid, ldLookup, ldCombobox], False)] property Saida03: String read FSAIDA03 write FSAIDA03; [TColumn('ENTRADA04', 'Entrada04', 64, [ldGrid, ldLookup, ldCombobox], False)] property Entrada04: String read FENTRADA04 write FENTRADA04; [TColumn('SAIDA04', 'Saida04', 64, [ldGrid, ldLookup, ldCombobox], False)] property Saida04: String read FSAIDA04 write FSAIDA04; [TColumn('ENTRADA05', 'Entrada05', 64, [ldGrid, ldLookup, ldCombobox], False)] property Entrada05: String read FENTRADA05 write FENTRADA05; [TColumn('SAIDA05', 'Saida05', 64, [ldGrid, ldLookup, ldCombobox], False)] property Saida05: String read FSAIDA05 write FSAIDA05; [TColumn('HORA_FECHAMENTO_DIA', 'Hora Fechamento Dia', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraFechamentoDia: String read FHORA_FECHAMENTO_DIA write FHORA_FECHAMENTO_DIA; //Transientes [TAssociation('ID', 'ID_COLABORADOR')] property ColaboradorVO: TViewPessoaColaboradorVO read FColaboradorVO write FColaboradorVO; end; implementation constructor TPontoHorarioAutorizadoVO.Create; begin inherited; FColaboradorVO := TViewPessoaColaboradorVO.Create; end; destructor TPontoHorarioAutorizadoVO.Destroy; begin FreeAndNil(FColaboradorVO); inherited; end; initialization Classes.RegisterClass(TPontoHorarioAutorizadoVO); finalization Classes.UnRegisterClass(TPontoHorarioAutorizadoVO); end.
unit Controler.Sort; interface uses System.Diagnostics, System.Classes, Vcl.ExtCtrls, Model.Board, Model.SortResults, View.Board, View.SortResults, Thread.SortControler; type TSortAlgorithm = (saBubbleSort, saQuickSort, saInsertionSort); TSortControler = class protected FBoard: TBoard; FSortResult: TSortResults; FBoardView: IBoardView; FSortResultView: ISortResultsView; FControlerThread: TSortControlerThread; public constructor Create(ABoard: TBoard; ASortResult: TSortResults; ABoardView: IBoardView; ASortResultView: ISortResultsView); destructor Destroy; override; procedure DoSort(SortAlgorithm: TSortAlgorithm); end; implementation uses System.SysUtils, Winapi.Windows; constructor TSortControler.Create(ABoard: TBoard; ASortResult: TSortResults; ABoardView: IBoardView; ASortResultView: ISortResultsView); begin inherited Create(); FBoard := ABoard; FBoardView := ABoardView; FSortResult := ASortResult; FSortResultView := ASortResultView; end; destructor TSortControler.Destroy; begin FBoard.Free; FSortResult.Free; if (FControlerThread <> nil) and FControlerThread.IsRunning then FControlerThread.Terminate; inherited; end; procedure TSortControler.DoSort(SortAlgorithm: TSortAlgorithm); var StopWatch: TStopwatch; ASortResult: TSortResults; begin StopWatch := TStopWatch.StartNew; ASortResult := FSortResult; FControlerThread := TSortControlerThread.CreateAndInit( procedure begin case SortAlgorithm of saBubbleSort: FBoard.SortBubble; saQuickSort: FBoard.SortQuick; saInsertionSort: FBoard.SortInsertion; else raise Exception.Create('Not supported'); end; end, procedure begin ASortResult.ElapsedTime := StopWatch.Elapsed; end); end; end.
(*************************************************************** * * KIET NGUYEN * * OS LAB 4: BANKER'S ALGORITHM * * DR MIKE SCHERGER * ***************************************************************) Program banker; { Program to do Banking Algorithm. } (*************************************************************** * * Global variables and type declarations * ***************************************************************) Type oneD_array = array of integer; twoD_array = array of array of integer; Var F : Text; filename: String; state: Boolean; proc: Integer; res: Integer; resource: array of Integer; available: array of Integer; request: array of Integer; max: twoD_array; allocation: twoD_array; need: twoD_array; proc_req,I,J: Integer; (*************************************************************** * * updateAvailable(proc_req): * update the AVAILABLE array * return: TRUE if the update is valid * FALSE if the update cannot be granted * ***************************************************************) function updateAvailable(): boolean; var temp: integer; begin for I:=0 to res-1 do begin temp := Available[I] - Request[I]; if(temp < 0) then begin exit(false); end else begin Available[I] := temp; end; end; updateAvailable := true; end; (************************************************************************************* * * updateAllocation(): * update the ALLOCATION array after the request is granted to a specific process * *************************************************************************************) procedure updateAllocation(proc_req: integer); begin for I:=0 to res-1 do Allocation[proc_req][I] := Allocation[proc_req][I] + Request[I]; end; (************************************************************************************* * * updateNeed(): * update the NEED array after the request is granted to a specific process * *************************************************************************************) function updateNeed(procno: integer): boolean; var temp: integer; begin for I:=0 to res-1 do begin temp := Need[procno][I] - Request[I]; if(temp < 0) then begin exit(false); end else begin Need[procno][I] := temp; end; end; updateNeed := true; end; (*************************************************************** * * getRequest(): * Assume to grant request to the process * ***************************************************************) function getRequest(): boolean; var retval, successUpdateAvailable, successUpdateNeed: boolean; begin successUpdateAvailable := updateAvailable(); successUpdateNeed := updateNeed(proc_req); if( (successUpdateAvailable = true) and (successUpdateNeed = true) ) then begin updateAllocation(proc_req); updateNeed(proc_req); retval := true; end else retval := false; getRequest := retval; end; (************************************************************************************ * * print1D(): a general procedure to print the content of any 1D array * parameter: the 1D array to be printed * ************************************************************************************) procedure print1D(toBePrinted: oneD_array); begin writeln('A B C'); for J:=0 to res-1 do begin write(toBePrinted[J], ' '); end; writeln(); writeln(); end; (***************************************************************************************** * * print2D(): a general procedure to print the content of any 2D array * parameter: the 2D array to be printed * *****************************************************************************************) procedure print2D(toBePrinted: twoD_array); begin writeln(' A B C'); for I:=0 to proc-1 do begin write(I,': '); for J:=0 to res-1 do begin write(toBePrinted[I, J], ' '); end; writeln(); end; writeln(); end; (***************************************************************************************** * * printResult(): print the 5 following arrays' content: Resource, Available, Max, Need, Allocation * *****************************************************************************************) procedure printResult(); begin //Print Resource array writeln('The Resource Vector is:...'); print1D(resource); //Print Available array writeln('The Available Vector is:...'); print1D(available); writeln(); //Print Max array writeln('The Max Matrix is:...'); print2D(max); //Print Allocation array writeln('The Allocation Matrix is:...'); print2D(allocation); //Print Need array: writeln('The Need Matrix is:...'); print2D(need); writeln(); end; (*************************************************************************************** * * Check if the NEED vector of a particular process is smaller than the * current available vector * * Return: TRUE if the need is smaller than available * FALSE otherwise. * ***************************************************************************************) function check(num: integer; available1: array of integer): boolean; var start: integer; begin for start := 0 to res-1 do begin if ( available1[start] < need[num][start]) then begin exit(false); end; end; //result := true; check := true; end; (******************************************************************************************* * * Function banker checks if the system will be in the safe state if the request * granted. * * return: TRUE if request can be granted * FALSE if system ends up in an unsafe state * ******************************************************************************************) function isSafe(available1: array of integer; alloc: twoD_array): boolean; var result, allocated: boolean; finish: array of Boolean; work: array of Integer; index,a,b: integer; begin setlength(finish, proc); setlength(work, res); index := 0; //Initialize the Finish array to FALSE; for a:= 0 to proc-1 do begin finish[a] := FALSE; end; //Initialize Work = Available for a:=0 to res-1 do begin work[a] := available1[a]; end; while (index < proc) do begin allocated := false; for a:= 0 to (proc-1) do begin if( (finish[a] = false) and check(a,available1) ) then begin for b:= 0 to (res-1) do begin available1[b] := available1[b] + alloc[a][b]; end; writeln('allocated process ', a); allocated := true; finish[a] := true; index := index+1; end; end; if(allocated = false) then break; end; if(index = proc) then begin result := true; end else begin result:= false; end; isSafe := result; writeln(); end; (************************************************************************************* * * Read from the text file an one-dimensional array into the specified parameter 1-D array * @parameter: the 1-D array that will store the inputs * *************************************************************************************) procedure readInput1D(arrayToRead: OneD_array); begin for J:=0 to res-1 do begin Read(F, arrayToRead[J]); end; end; (************************************************************************************* * * Read from the text file an two-dimensional array into the specified parameter 2-D array * @parameter: the 2-D array that will store the inputs * *************************************************************************************) procedure readInput2D(arrayToRead: TwoD_array); begin for I:=0 to proc-1 do begin for J:=0 to res-1 do begin Read(F, arrayToRead[I, J]); end; end; end; (************************************************************************************* * * inputHandle(): Read in all the required array * * Assumption: the user must prepare the data in a correct format for the program to read * *************************************************************************************) procedure inputHandle(); var C: Char; code: integer; begin Assign (F,filename); Reset (F); Read(F, proc); writeln('# of processes = ', proc); Read(F, res); writeln('# of resources = ', res); writeln(); //define size for the array: setlength(array, size); setlength(resource, res); setlength(available, res); setlength(request, res); setlength(max, proc, res); setlength(allocation, proc, res); setlength(need, proc, res); //Read resource vector readInput1D(resource); //Read Available vector readInput1D(available); //Read Max 2-D array readInput2D(max); //Read allocation 2-D array readInput2D(allocation); //Get Need 2-D array: for I:=0 to proc-1 do begin for J:=0 to res-1 do begin need[I, J] := max[I, J] - allocation[I, J]; end; end; //read in two chars read(F, C); read(F, C); //read in the process that requests the resources read(F, C); //convert the char read to the process number val(C,proc_req,code); //read 1 char read(F, C); // read request vector readInput1D(request); Close (F); end; (************************************************************************************* * * Main method: Call many subroutines to read in the matrices, do the safety algorithm * and check the second time * *************************************************************************************) begin //check for the correct number of parameter counts if(paramCount = 1) then begin filename := paramStr(1); writeln(); end else begin writeln('Please enter correct FILE NAME'); readln(filename); end; //read in the input from the text file inputHandle(); //first print the contents of all the array needed printResult(); //do the Banker's Algorithm the first time state := isSafe(available, allocation); if(state = true) then begin //if the first test is passed, read in the request vector and do the algorithm //the second time writeln('THE SYSTEM IS IN A SAFE STATE'); writeln('Process ', proc_req,': The Request Vector is:...'); writeln('A B C'); for J:=0 to res-1 do begin write(request[J], ' '); end; writeln(); //check if the request meets basic requirements if ( getRequest() = true) then begin writeln('proceed to check'); state := isSafe(available, allocation); if(state = true) then begin writeln('THE REQUEST CAN BE GRANTED: NEW STATE FOLLOWS:'); //second print printResult(); //expect to have the original matrix end else begin // system is not in a safe state, terminate program. writeln('THE REQUEST CANNOT BE GRANTED'); //writeln('THE SYSTEM IS NOT IN A SAFE STATE'); exit(); end; end else begin writeln('THE REQUEST CANNOT BE GRANTED'); exit(); end; end else begin // system is not in a safe state, terminate program. writeln('THE SYSTEM IS NOT IN A SAFE STATE'); exit(); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.factory.interfaces; interface uses DB, Classes, ormbr.monitor; type TDriverName = (dnMSSQL, dnMySQL, dnFirebird, dnSQLite, dnInterbase, dnDB2, dnOracle, dnInformix, dnPostgreSQL, dnADS, dnASA, dnAbsoluteDB, dnMongoDB); /// <summary> /// Unit : ormbr.driver.connection.pas /// Classe : TDriverResultSet<T: TDataSet> /// </summary> IDBResultSet = interface ['{A8ECADF6-A9AF-4610-8429-3B0A5CD0295C}'] function GetFetchingAll: Boolean; procedure SetFetchingAll(const Value: Boolean); procedure Close; function NotEof: Boolean; function RecordCount: Integer; function FieldDefs: TFieldDefs; function GetFieldValue(AFieldName: string): Variant; overload; function GetFieldValue(AFieldIndex: Integer): Variant; overload; function GetFieldType(AFieldName: string): TFieldType; function FieldByName(AFieldName: string): IDBResultSet; function AsString: string; function AsInteger: Integer; function AsFloat: Double; function AsCurrency: Currency; function AsExtended: Extended; function AsDateTime: TDateTime; function AsVariant: Variant; function AsBoolean: Boolean; function Value: Variant; property FetchingAll: Boolean read GetFetchingAll write SetFetchingAll; end; IDBQuery = interface ['{0588C65B-2571-48BB-BE03-BD51ABB6897F}'] procedure SetCommandText(ACommandText: string); function GetCommandText: string; procedure ExecuteDirect; function ExecuteQuery: IDBResultSet; property CommandText: string read GetCommandText write SetCommandText; end; IDBConnection = interface ['{4520C97F-8777-4D14-9C14-C79EF86957DB}'] procedure Connect; procedure Disconnect; procedure StartTransaction; procedure Commit; procedure Rollback; procedure ExecuteDirect(const ASQL: string); overload; procedure ExecuteDirect(const ASQL: string; const AParams: TParams); overload; procedure ExecuteScript(const ASQL: string); procedure AddScript(const ASQL: string); procedure ExecuteScripts; procedure SetCommandMonitor(AMonitor: ICommandMonitor); function InTransaction: Boolean; function IsConnected: Boolean; function GetDriverName: TDriverName; function CreateQuery: IDBQuery; function CreateResultSet: IDBResultSet; function ExecuteSQL(const ASQL: string): IDBResultSet; function CommandMonitor: ICommandMonitor; end; IDBTransaction = interface ['{EB46599C-A021-40E4-94E2-C7507781562B}'] procedure StartTransaction; procedure Commit; procedure Rollback; function InTransaction: Boolean; end; implementation end.
unit Aurelius.Types.Proxy; {$I Aurelius.inc} interface type TProxyType = (Single, List); IProxyInfo = interface function ProxyType: TProxyType; function ClassName: string; function MemberName: string; function Key: Variant; end; IProxyController = interface function LoadProxyValue: TObject; function ProxyInfo: IProxyInfo; end; Proxy<T: class> = record private FValue: T; FController: IProxyController; FLoaded: Boolean; function GetValue: T; procedure SetValue(const Value: T); public procedure Load; procedure SetInitialValue(AValue: T); procedure DestroyValue; class operator Equal(Left, Right: Proxy<T>): Boolean; class operator NotEqual(Left, Right: Proxy<T>): Boolean; property Value: T read GetValue write SetValue; end; implementation { Proxy<T> } procedure Proxy<T>.DestroyValue; begin if FValue <> nil then FValue.Free; end; class operator Proxy<T>.Equal(Left, Right: Proxy<T>): Boolean; begin Result := Left.GetValue = Right.GetValue; end; function Proxy<T>.GetValue: T; begin // No need to check for FLoaded, just optimization if not FLoaded then Load; Result := FValue; end; procedure Proxy<T>.Load; var OldValue: T; begin if FLoaded then Exit; // If you change any code from below, review TMappingExplorer.ForceProxyLoad! if FController <> nil then begin OldValue := FValue; FValue := T(FController.LoadProxyValue); if (FController.ProxyInfo <> nil) and (FController.ProxyInfo.ProxyType = TProxyType.List) and (OldValue <> nil) then OldValue.Free; end; FLoaded := True; end; class operator Proxy<T>.NotEqual(Left, Right: Proxy<T>): Boolean; begin Result := Left.GetValue <> Right.GetValue; end; procedure Proxy<T>.SetInitialValue(AValue: T); begin FValue := AValue; end; procedure Proxy<T>.SetValue(const Value: T); begin FValue := Value; FLoaded := True; end; end.
{******************************************************************************} { } { XML Data Binding } { } { Generated on: 08/31/2006 4:09:03 PM } { Generated from: C:\DelphiStuff8\Projects\ScreenBuilder\TabExport.xml } { Settings stored in: C:\DelphiStuff8\Projects\ScreenBuilder\TabExport.xdb } { } {******************************************************************************} unit TabExport; interface uses xmldom, XMLDoc, XMLIntf, Variants; type { Forward Decls } IXMLTabRecordsType = interface; IXMLTabRecordType = interface; { IXMLTabRecordsType } IXMLTabRecordsType = interface(IXMLNodeCollection) ['{9471D857-BD11-4740-988D-F4741776C2DA}'] { Property Accessors } function Get_TabRecord(Index: Integer): IXMLTabRecordType; { Methods & Properties } function Add: IXMLTabRecordType; function Insert(const Index: Integer): IXMLTabRecordType; property TabRecord[Index: Integer]: IXMLTabRecordType read Get_TabRecord; default; end; { IXMLTabRecordType } IXMLTabRecordType = interface(IXMLNode) ['{7E0CF8E1-D68A-4F98-A362-B2574D63FC3D}'] { Property Accessors } function Get_TabID: Integer; function Get_TabDescription: WideString; function Get_TabLabel: WideString; function Get_TabComponents: WideString; function Get_TabLastMod: TDateTime; function Get_TabCreated: TDateTime; function Get_TabInformation: WideString; function Get_LayoutType: WideString; function Get_PrintLayout: Boolean; procedure Set_TabID(Value: Integer); procedure Set_TabDescription(Value: WideString); procedure Set_TabLabel(Value: WideString); procedure Set_TabComponents(Value: WideString); procedure Set_TabLastMod(Value: TDateTime); procedure Set_TabCreated(Value: TDateTime); procedure Set_TabInformation(Value: WideString); procedure Set_LayoutType(Value: WideString); procedure Set_PrintLayout(Value: Boolean); { Methods & Properties } property TabID: Integer read Get_TabID write Set_TabID; property TabDescription: WideString read Get_TabDescription write Set_TabDescription; property TabLabel: WideString read Get_TabLabel write Set_TabLabel; property TabComponents: WideString read Get_TabComponents write Set_TabComponents; property TabLastMod: TDateTime read Get_TabLastMod write Set_TabLastMod; property TabCreated: TDateTime read Get_TabCreated write Set_TabCreated; property TabInformation: WideString read Get_TabInformation write Set_TabInformation; property LayoutType: WideString read Get_LayoutType write Set_LayoutType; property PrintLayout: Boolean read Get_PrintLayout write Set_PrintLayout; end; { Forward Decls } TXMLTabRecordsType = class; TXMLTabRecordType = class; { TXMLTabRecordsType } TXMLTabRecordsType = class(TXMLNodeCollection, IXMLTabRecordsType) protected { IXMLTabRecordsType } function Get_TabRecord(Index: Integer): IXMLTabRecordType; function Add: IXMLTabRecordType; function Insert(const Index: Integer): IXMLTabRecordType; public procedure AfterConstruction; override; end; { TXMLTabRecordType } TXMLTabRecordType = class(TXMLNode, IXMLTabRecordType) protected { IXMLTabRecordType } function Get_TabID: Integer; function Get_TabDescription: WideString; function Get_TabLabel: WideString; function Get_TabComponents: WideString; function Get_TabLastMod: TDateTime; function Get_TabCreated: TDateTime; function Get_TabInformation: WideString; function Get_LayoutType: WideString; function Get_PrintLayout: Boolean; procedure Set_TabID(Value: Integer); procedure Set_TabDescription(Value: WideString); procedure Set_TabLabel(Value: WideString); procedure Set_TabComponents(Value: WideString); procedure Set_TabLastMod(Value: TDateTime); procedure Set_TabCreated(Value: TDateTime); procedure Set_TabInformation(Value: WideString); procedure Set_LayoutType(Value: WideString); procedure Set_PrintLayout(Value: Boolean); end; { Global Functions } function GetTabRecords(Doc: IXMLDocument): IXMLTabRecordsType; function LoadTabRecords(const FileName: WideString): IXMLTabRecordsType; function NewTabRecords: IXMLTabRecordsType; const TargetNamespace = ''; implementation { Global Functions } function GetTabRecords(Doc: IXMLDocument): IXMLTabRecordsType; begin Result := Doc.GetDocBinding('TabRecords', TXMLTabRecordsType, TargetNamespace) as IXMLTabRecordsType; end; function LoadTabRecords(const FileName: WideString): IXMLTabRecordsType; begin Result := LoadXMLDocument(FileName).GetDocBinding('TabRecords', TXMLTabRecordsType, TargetNamespace) as IXMLTabRecordsType; end; function NewTabRecords: IXMLTabRecordsType; begin Result := NewXMLDocument.GetDocBinding('TabRecords', TXMLTabRecordsType, TargetNamespace) as IXMLTabRecordsType; end; { TXMLTabRecordsType } procedure TXMLTabRecordsType.AfterConstruction; begin RegisterChildNode('TabRecord', TXMLTabRecordType); ItemTag := 'TabRecord'; ItemInterface := IXMLTabRecordType; inherited; end; function TXMLTabRecordsType.Get_TabRecord(Index: Integer): IXMLTabRecordType; begin Result := List[Index] as IXMLTabRecordType; end; function TXMLTabRecordsType.Add: IXMLTabRecordType; begin Result := AddItem(-1) as IXMLTabRecordType; end; function TXMLTabRecordsType.Insert(const Index: Integer): IXMLTabRecordType; begin Result := AddItem(Index) as IXMLTabRecordType; end; { TXMLTabRecordType } function TXMLTabRecordType.Get_TabID: Integer; begin Result := ChildNodes['TabID'].NodeValue; end; procedure TXMLTabRecordType.Set_TabID(Value: Integer); begin ChildNodes['TabID'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabDescription: WideString; begin Result := ChildNodes['TabDescription'].Text; end; procedure TXMLTabRecordType.Set_TabDescription(Value: WideString); begin ChildNodes['TabDescription'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabLabel: WideString; begin Result := ChildNodes['TabLabel'].Text; end; procedure TXMLTabRecordType.Set_TabLabel(Value: WideString); begin ChildNodes['TabLabel'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabComponents: WideString; begin Result := ChildNodes['TabComponents'].Text; end; procedure TXMLTabRecordType.Set_TabComponents(Value: WideString); begin ChildNodes['TabComponents'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabLastMod: TDateTime; begin Result := VarToDateTime(ChildNodes['TabLastMod'].NodeValue); end; procedure TXMLTabRecordType.Set_TabLastMod(Value: TDateTime); begin ChildNodes['TabLastMod'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabCreated: TDateTime; begin Result := VarToDateTime(ChildNodes['TabCreated'].NodeValue); end; procedure TXMLTabRecordType.Set_TabCreated(Value: TDateTime); begin ChildNodes['TabCreated'].NodeValue := Value; end; function TXMLTabRecordType.Get_TabInformation: WideString; begin Result := ChildNodes['TabInformation'].Text; end; procedure TXMLTabRecordType.Set_TabInformation(Value: WideString); begin ChildNodes['TabInformation'].NodeValue := Value; end; function TXMLTabRecordType.Get_LayoutType: WideString; begin Result := ChildNodes['LayoutType'].Text; end; procedure TXMLTabRecordType.Set_LayoutType(Value: WideString); begin ChildNodes['LayoutType'].NodeValue := Value; end; function TXMLTabRecordType.Get_PrintLayout: Boolean; begin Result := ChildNodes['PrintLayout'].NodeValue; end; procedure TXMLTabRecordType.Set_PrintLayout(Value: Boolean); begin ChildNodes['PrintLayout'].NodeValue := Value; end; end.
unit Geral.Model; interface uses Generics.Collections, mORMot, SynCommons; type /// CFGGERA Table // - type definition auto-generated by SynDBExplorer 1.18.3124 at 2016-12-27 16:24:12 // from REPLICACAO.CFGGERA // - note that the ORM will add one missing ID field via: // $ ALTER TABLE REPLICACAO.CFGGERA ADD ID NUMBER(22,0) NOT NULL PRIMARY KEY TSQLCFGGERA = class(TSQLRecord) protected fCPMFSGERA: RawUTF8; fCATXJUPRE: RawUTF8; fCPADCGERA: RawUTF8; fNPTODGERA: Currency; fNBNOSCFG: Int64; fCANCTGERA: RawUTF8; fNMEANGERA: Int64; fNPI5EGERA: Currency; fCGERVGERA: RawUTF8; fCICTRGERA: RawUTF8; fCGMOVFISC: RawUTF8; fCIFATGERA: RawUTF8; fCVRUCCFG: RawUTF8; fCBLCDGERA: RawUTF8; fNDIPSGERA: Int64; fCBPINGERA: RawUTF8; fCDTPEGERA: RawUTF8; fCBLLCGERA: RawUTF8; fCCPERGERA: RawUTF8; fCMLFMGERA: RawUTF8; fCUICEGERA: RawUTF8; fCCJLIGERA: RawUTF8; fCBLCCGERA: RawUTF8; fCPFDIGERA: RawUTF8; fCAPAPGERA: RawUTF8; fCGARPGERA: RawUTF8; fCPAPOFCFG: RawUTF8; fCPCTEGERA: RawUTF8; fCPTPDGERA: RawUTF8; fCCJEMGERA: RawUTF8; fCMAPDGERA: RawUTF8; fCGAIFTCFG: RawUTF8; fCTPPEGERA: RawUTF8; fCTPPOGERA: RawUTF8; fCUPDVGERA: RawUTF8; fCPACPGERA: RawUTF8; fCPACCGERA: RawUTF8; fCAAVAGERA: RawUTF8; fNTMDAGER: Currency; published /// match CFGGERA.CPMFSGERA [VARCHAR2 1 0 0] property CPMFSGERA: RawUTF8 index 1 read fCPMFSGERA write fCPMFSGERA; /// match CFGGERA.CATXJUPRE [VARCHAR2 1 0 0] property CATXJUPRE: RawUTF8 index 1 read fCATXJUPRE write fCATXJUPRE; /// match CFGGERA.CPADCGERA [VARCHAR2 1 0 0] property CPADCGERA: RawUTF8 index 1 read fCPADCGERA write fCPADCGERA; /// match CFGGERA.NPTODGERA [NUMBER 22 15 2] property NPTODGERA: Currency read fNPTODGERA write fNPTODGERA; /// match CFGGERA.NBNOSCFG [NUMBER 22 0 0] property NBNOSCFG: Int64 read fNBNOSCFG write fNBNOSCFG; /// match CFGGERA.CANCTGERA [VARCHAR2 1 0 0] property CANCTGERA: RawUTF8 index 1 read fCANCTGERA write fCANCTGERA; /// match CFGGERA.NMEANGERA [NUMBER 22 6 0] * property NMEANGERA: Int64 read fNMEANGERA write fNMEANGERA; /// match CFGGERA.NPI5EGERA [NUMBER 22 5 2] * property NPI5EGERA: Currency read fNPI5EGERA write fNPI5EGERA; /// match CFGGERA.CGERVGERA [VARCHAR2 1 0 0] * property CGERVGERA: RawUTF8 index 1 read fCGERVGERA write fCGERVGERA; /// match CFGGERA.CICTRGERA [VARCHAR2 1 0 0] * property CICTRGERA: RawUTF8 index 1 read fCICTRGERA write fCICTRGERA; /// match CFGGERA.CGMOVFISC [CHAR 1 0 0] * property CGMOVFISC: RawUTF8 index 1 read fCGMOVFISC write fCGMOVFISC; /// match CFGGERA.CIFATGERA [VARCHAR2 1 0 0] * property CIFATGERA: RawUTF8 index 1 read fCIFATGERA write fCIFATGERA; /// match CFGGERA.CVRUCCFG [VARCHAR2 1 0 0] * property CVRUCCFG: RawUTF8 index 1 read fCVRUCCFG write fCVRUCCFG; /// match CFGGERA.CBLCDGERA [VARCHAR2 1 0 0] * property CBLCDGERA: RawUTF8 index 1 read fCBLCDGERA write fCBLCDGERA; /// match CFGGERA.NDIPSGERA [NUMBER 22 3 0] * property NDIPSGERA: Int64 read fNDIPSGERA write fNDIPSGERA; /// match CFGGERA.CBPINGERA [VARCHAR2 1 0 0] * property CBPINGERA: RawUTF8 index 1 read fCBPINGERA write fCBPINGERA; /// match CFGGERA.CDTPEGERA [VARCHAR2 1 0 0] * property CDTPEGERA: RawUTF8 index 1 read fCDTPEGERA write fCDTPEGERA; /// match CFGGERA.CBLLCGERA [VARCHAR2 1 0 0] * property CBLLCGERA: RawUTF8 index 1 read fCBLLCGERA write fCBLLCGERA; /// match CFGGERA.CCPERGERA [VARCHAR2 1 0 0] * property CCPERGERA: RawUTF8 index 1 read fCCPERGERA write fCCPERGERA; /// match CFGGERA.CMLFMGERA [VARCHAR2 1 0 0] * property CMLFMGERA: RawUTF8 index 1 read fCMLFMGERA write fCMLFMGERA; /// match CFGGERA.CUICEGERA [VARCHAR2 1 0 0] * property CUICEGERA: RawUTF8 index 1 read fCUICEGERA write fCUICEGERA; /// match CFGGERA.CCJLIGERA [VARCHAR2 1 0 0] * property CCJLIGERA: RawUTF8 index 1 read fCCJLIGERA write fCCJLIGERA; /// match CFGGERA.CBLCCGERA [VARCHAR2 1 0 0] * property CBLCCGERA: RawUTF8 index 1 read fCBLCCGERA write fCBLCCGERA; /// match CFGGERA.CPFDIGERA [VARCHAR2 1 0 0] * property CPFDIGERA: RawUTF8 index 1 read fCPFDIGERA write fCPFDIGERA; /// match CFGGERA.CAPAPGERA [VARCHAR2 1 0 0] * property CAPAPGERA: RawUTF8 index 1 read fCAPAPGERA write fCAPAPGERA; /// match CFGGERA.CGARPGERA [VARCHAR2 1 0 0] * property CGARPGERA: RawUTF8 index 1 read fCGARPGERA write fCGARPGERA; /// match CFGGERA.CPAPOFCFG [VARCHAR2 1 0 0] * property CPAPOFCFG: RawUTF8 index 1 read fCPAPOFCFG write fCPAPOFCFG; /// match CFGGERA.CPCTEGERA [CHAR 1 0 0] * property CPCTEGERA: RawUTF8 index 1 read fCPCTEGERA write fCPCTEGERA; /// match CFGGERA.CPTPDGERA [VARCHAR2 1 0 0] * property CPTPDGERA: RawUTF8 index 1 read fCPTPDGERA write fCPTPDGERA; /// match CFGGERA.CCJEMGERA [VARCHAR2 1 0 0] * property CCJEMGERA: RawUTF8 index 1 read fCCJEMGERA write fCCJEMGERA; /// match CFGGERA.CMAPDGERA [VARCHAR2 1 0 0] * property CMAPDGERA: RawUTF8 index 1 read fCMAPDGERA write fCMAPDGERA; /// match CFGGERA.CGAIFTCFG [VARCHAR2 1 0 0] * property CGAIFTCFG: RawUTF8 index 1 read fCGAIFTCFG write fCGAIFTCFG; /// match CFGGERA.CTPPEGERA [VARCHAR2 1 0 0] * property CTPPEGERA: RawUTF8 index 1 read fCTPPEGERA write fCTPPEGERA; /// match CFGGERA.CTPPOGERA [VARCHAR2 1 0 0] * property CTPPOGERA: RawUTF8 index 1 read fCTPPOGERA write fCTPPOGERA; /// match CFGGERA.CUPDVGERA [VARCHAR2 1 0 0] * property CUPDVGERA: RawUTF8 index 1 read fCUPDVGERA write fCUPDVGERA; /// match CFGGERA.CPACPGERA [VARCHAR2 1 0 0] * property CPACPGERA: RawUTF8 index 1 read fCPACPGERA write fCPACPGERA; /// match CFGGERA.CPACCGERA [VARCHAR2 1 0 0] * property CPACCGERA: RawUTF8 index 1 read fCPACCGERA write fCPACCGERA; /// match CFGGERA.CAAVAGERA [VARCHAR2 1 0 0] * property CEMPRCFG: RawUTF8 index 1 read fCAAVAGERA write fCAAVAGERA; /// match CFGGERA.NTMDAGER [NUMBER 22 3 2] * property NTMDAGER: Currency read fNTMDAGER write fNTMDAGER; end; {* [Entity, Table('CFGGERA')] [Model('Geral')] [Id('FNCODCCFG', TIdGenerator.IdentityOrSequence)] TConfigGeralX = class protected [Column('NCODCCFG')] FNCODCCFG: Cardinal; [Column('CEMPRCFG')] FCEMPRCFG: String; public property Id: Cardinal read FNCODCCFG write FNCODCCFG; property Empresa: String read FCEMPRCFG write FCEMPRCFG; end; *} implementation end.
unit DCPrijndael; {$MODE Delphi} interface uses Classes, Sysutils, Crypto; const BC= 4; MAXROUNDS= 14; type { TCipherRijndael } TCipherRijndael= class(TCipher) protected numrounds: longword; rk, drk: array[0..MAXROUNDS,0..7] of DWord; procedure InitKey(const Key; Size: longword); override; public destructor Destroy; override; class function Algorithm: TCipherAlgorithm; override; class function BlockSize: Integer; override; class function MaxKeySize: integer; override; class function SelfTest: boolean; override; procedure EncryptBlock(const InData; var OutData); override; procedure DecryptBlock(const InData; var OutData); override; end; implementation {$R-}{$Q-} {$I DCPrijndael.inc} class function TCipherRijndael.MaxKeySize: integer; begin Result:= 256; end; class function TCipherRijndael.Algorithm: TCipherAlgorithm; begin Result:= caRijndael; end; class function TCipherRijndael.BlockSize: Integer; begin Result := 128; end; class function TCipherRijndael.SelfTest: boolean; const Key1: array[0..15] of byte= ($00,$01,$02,$03,$05,$06,$07,$08,$0A,$0B,$0C,$0D,$0F,$10,$11,$12); InData1: array[0..15] of byte= ($50,$68,$12,$A4,$5F,$08,$C8,$89,$B9,$7F,$59,$80,$03,$8B,$83,$59); OutData1: array[0..15] of byte= ($D8,$F5,$32,$53,$82,$89,$EF,$7D,$06,$B5,$06,$A4,$FD,$5B,$E9,$C9); Key2: array[0..23] of byte= ($A0,$A1,$A2,$A3,$A5,$A6,$A7,$A8,$AA,$AB,$AC,$AD,$AF,$B0,$B1,$B2, $B4,$B5,$B6,$B7,$B9,$BA,$BB,$BC); InData2: array[0..15] of byte= ($4F,$1C,$76,$9D,$1E,$5B,$05,$52,$C7,$EC,$A8,$4D,$EA,$26,$A5,$49); OutData2: array[0..15] of byte= ($F3,$84,$72,$10,$D5,$39,$1E,$23,$60,$60,$8E,$5A,$CB,$56,$05,$81); Key3: array[0..31] of byte= ($00,$01,$02,$03,$05,$06,$07,$08,$0A,$0B,$0C,$0D,$0F,$10,$11,$12, $14,$15,$16,$17,$19,$1A,$1B,$1C,$1E,$1F,$20,$21,$23,$24,$25,$26); InData3: array[0..15] of byte= ($5E,$25,$CA,$78,$F0,$DE,$55,$80,$25,$24,$D3,$8D,$A3,$FE,$44,$56); OutData3: array[0..15] of byte= ($E8,$B7,$2B,$4E,$8B,$E2,$43,$43,$8C,$9F,$FF,$1F,$0E,$20,$58,$72); var Block: array[0..15] of byte; Cipher: TCipherRijndael; begin FillChar(Block, SizeOf(Block), 0); Cipher:= TCipherRijndael.Create(@Key1,SizeOf(Key1) * 8); Cipher.EncryptBlock(InData1,Block); Result:= boolean(CompareMem(@Block,@OutData1,16)); Cipher.DecryptBlock(Block,Block); Cipher.Free; Result:= Result and boolean(CompareMem(@Block,@InData1,16)); Cipher := TCipherRijndael.Create(@Key2,Sizeof(Key2)*8); Cipher.EncryptBlock(InData2,Block); Result:= Result and boolean(CompareMem(@Block,@OutData2,16)); Cipher.DecryptBlock(Block,Block); Cipher.Free; Result:= Result and boolean(CompareMem(@Block,@InData2,16)); Cipher := TCipherRijndael.Create(@Key3,Sizeof(Key3)*8); Cipher.EncryptBlock(InData3,Block); Result:= Result and boolean(CompareMem(@Block,@OutData3,16)); Cipher.DecryptBlock(Block,Block); Cipher.Free; Result:= Result and boolean(CompareMem(@Block,@InData3,16)); end; procedure InvMixColumn(a: PByteArray; BC: byte); var j: longword; begin for j:= 0 to (BC-1) do PDWord(@(a^[j*4]))^:= PDWord(@U1[a^[j*4+0]])^ xor PDWord(@U2[a^[j*4+1]])^ xor PDWord(@U3[a^[j*4+2]])^ xor PDWord(@U4[a^[j*4+3]])^; end; procedure TCipherRijndael.InitKey(const Key; Size: longword); var KC, ROUNDS, j, r, t, rconpointer: longword; tk: array[0..MAXKC-1,0..3] of byte; begin Size:= Size div 8; FillChar(tk,Sizeof(tk),0); Move(Key,tk,Size); if Size<= 16 then begin KC:= 4; Rounds:= 10; end else if Size<= 24 then begin KC:= 6; Rounds:= 12; end else begin KC:= 8; Rounds:= 14; end; numrounds:= rounds; r:= 0; t:= 0; j:= 0; while (j< KC) and (r< (rounds+1)) do begin while (j< KC) and (t< BC) do begin rk[r,t]:= PDWord(@tk[j])^; Inc(j); Inc(t); end; if t= BC then begin t:= 0; Inc(r); end; end; rconpointer:= 0; while (r< (rounds+1)) do begin tk[0,0]:= tk[0,0] xor S[tk[KC-1,1]]; tk[0,1]:= tk[0,1] xor S[tk[KC-1,2]]; tk[0,2]:= tk[0,2] xor S[tk[KC-1,3]]; tk[0,3]:= tk[0,3] xor S[tk[KC-1,0]]; tk[0,0]:= tk[0,0] xor rcon[rconpointer]; Inc(rconpointer); if KC<> 8 then begin for j:= 1 to (KC-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; end else begin for j:= 1 to ((KC div 2)-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; tk[KC div 2,0]:= tk[KC div 2,0] xor S[tk[KC div 2 - 1,0]]; tk[KC div 2,1]:= tk[KC div 2,1] xor S[tk[KC div 2 - 1,1]]; tk[KC div 2,2]:= tk[KC div 2,2] xor S[tk[KC div 2 - 1,2]]; tk[KC div 2,3]:= tk[KC div 2,3] xor S[tk[KC div 2 - 1,3]]; for j:= ((KC div 2) + 1) to (KC-1) do PDWord(@tk[j])^:= PDWord(@tk[j])^ xor PDWord(@tk[j-1])^; end; j:= 0; while (j< KC) and (r< (rounds+1)) do begin while (j< KC) and (t< BC) do begin rk[r,t]:= PDWord(@tk[j])^; Inc(j); Inc(t); end; if t= BC then begin Inc(r); t:= 0; end; end; end; Move(rk,drk,Sizeof(rk)); for r:= 1 to (numrounds-1) do InvMixColumn(@drk[r],BC); end; destructor TCipherRijndael.Destroy; begin numrounds:= 0; FillChar(rk,Sizeof(rk),0); FillChar(drk,Sizeof(drk),0); inherited Destroy; end; procedure TCipherRijndael.EncryptBlock(const InData; var OutData); var r: longword; tempb: array[0..MAXBC-1,0..3] of byte; a: array[0..MAXBC,0..3] of byte; begin PDword(@a[0,0])^:= PDword(@InData)^; PDword(@a[1,0])^:= PDword(pointer(@InData)+4)^; PDword(@a[2,0])^:= PDword(pointer(@InData)+8)^; PDword(@a[3,0])^:= PDword(pointer(@InData)+12)^; for r:= 0 to (numrounds-2) do begin PDWord(@tempb[0])^:= PDWord(@a[0])^ xor rk[r,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor rk[r,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor rk[r,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor rk[r,3]; PDWord(@a[0])^:= PDWord(@T1[tempb[0,0]])^ xor PDWord(@T2[tempb[1,1]])^ xor PDWord(@T3[tempb[2,2]])^ xor PDWord(@T4[tempb[3,3]])^; PDWord(@a[1])^:= PDWord(@T1[tempb[1,0]])^ xor PDWord(@T2[tempb[2,1]])^ xor PDWord(@T3[tempb[3,2]])^ xor PDWord(@T4[tempb[0,3]])^; PDWord(@a[2])^:= PDWord(@T1[tempb[2,0]])^ xor PDWord(@T2[tempb[3,1]])^ xor PDWord(@T3[tempb[0,2]])^ xor PDWord(@T4[tempb[1,3]])^; PDWord(@a[3])^:= PDWord(@T1[tempb[3,0]])^ xor PDWord(@T2[tempb[0,1]])^ xor PDWord(@T3[tempb[1,2]])^ xor PDWord(@T4[tempb[2,3]])^; end; PDWord(@tempb[0])^:= PDWord(@a[0])^ xor rk[numrounds-1,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor rk[numrounds-1,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor rk[numrounds-1,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor rk[numrounds-1,3]; a[0,0]:= T1[tempb[0,0],1]; a[0,1]:= T1[tempb[1,1],1]; a[0,2]:= T1[tempb[2,2],1]; a[0,3]:= T1[tempb[3,3],1]; a[1,0]:= T1[tempb[1,0],1]; a[1,1]:= T1[tempb[2,1],1]; a[1,2]:= T1[tempb[3,2],1]; a[1,3]:= T1[tempb[0,3],1]; a[2,0]:= T1[tempb[2,0],1]; a[2,1]:= T1[tempb[3,1],1]; a[2,2]:= T1[tempb[0,2],1]; a[2,3]:= T1[tempb[1,3],1]; a[3,0]:= T1[tempb[3,0],1]; a[3,1]:= T1[tempb[0,1],1]; a[3,2]:= T1[tempb[1,2],1]; a[3,3]:= T1[tempb[2,3],1]; PDWord(@a[0])^:= PDWord(@a[0])^ xor rk[numrounds,0]; PDWord(@a[1])^:= PDWord(@a[1])^ xor rk[numrounds,1]; PDWord(@a[2])^:= PDWord(@a[2])^ xor rk[numrounds,2]; PDWord(@a[3])^:= PDWord(@a[3])^ xor rk[numrounds,3]; PDword(@OutData)^:= PDword(@a[0,0])^; PDword(pointer(@OutData)+4)^:= PDword(@a[1,0])^; PDword(pointer(@OutData)+8)^:= PDword(@a[2,0])^; PDword(pointer(@OutData)+12)^:= PDword(@a[3,0])^; end; procedure TCipherRijndael.DecryptBlock(const InData; var OutData); var r: longword; tempb: array[0..MAXBC-1,0..3] of byte; a: array[0..MAXBC,0..3] of byte; begin PDword(@a[0,0])^:= PDword(@InData)^; PDword(@a[1,0])^:= PDword(pointer(@InData)+4)^; PDword(@a[2,0])^:= PDword(pointer(@InData)+8)^; PDword(@a[3,0])^:= PDword(pointer(@InData)+12)^; for r:= NumRounds downto 2 do begin PDWord(@tempb[0])^:= PDWord(@a[0])^ xor drk[r,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor drk[r,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor drk[r,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor drk[r,3]; PDWord(@a[0])^:= PDWord(@T5[tempb[0,0]])^ xor PDWord(@T6[tempb[3,1]])^ xor PDWord(@T7[tempb[2,2]])^ xor PDWord(@T8[tempb[1,3]])^; PDWord(@a[1])^:= PDWord(@T5[tempb[1,0]])^ xor PDWord(@T6[tempb[0,1]])^ xor PDWord(@T7[tempb[3,2]])^ xor PDWord(@T8[tempb[2,3]])^; PDWord(@a[2])^:= PDWord(@T5[tempb[2,0]])^ xor PDWord(@T6[tempb[1,1]])^ xor PDWord(@T7[tempb[0,2]])^ xor PDWord(@T8[tempb[3,3]])^; PDWord(@a[3])^:= PDWord(@T5[tempb[3,0]])^ xor PDWord(@T6[tempb[2,1]])^ xor PDWord(@T7[tempb[1,2]])^ xor PDWord(@T8[tempb[0,3]])^; end; PDWord(@tempb[0])^:= PDWord(@a[0])^ xor drk[1,0]; PDWord(@tempb[1])^:= PDWord(@a[1])^ xor drk[1,1]; PDWord(@tempb[2])^:= PDWord(@a[2])^ xor drk[1,2]; PDWord(@tempb[3])^:= PDWord(@a[3])^ xor drk[1,3]; a[0,0]:= S5[tempb[0,0]]; a[0,1]:= S5[tempb[3,1]]; a[0,2]:= S5[tempb[2,2]]; a[0,3]:= S5[tempb[1,3]]; a[1,0]:= S5[tempb[1,0]]; a[1,1]:= S5[tempb[0,1]]; a[1,2]:= S5[tempb[3,2]]; a[1,3]:= S5[tempb[2,3]]; a[2,0]:= S5[tempb[2,0]]; a[2,1]:= S5[tempb[1,1]]; a[2,2]:= S5[tempb[0,2]]; a[2,3]:= S5[tempb[3,3]]; a[3,0]:= S5[tempb[3,0]]; a[3,1]:= S5[tempb[2,1]]; a[3,2]:= S5[tempb[1,2]]; a[3,3]:= S5[tempb[0,3]]; PDWord(@a[0])^:= PDWord(@a[0])^ xor drk[0,0]; PDWord(@a[1])^:= PDWord(@a[1])^ xor drk[0,1]; PDWord(@a[2])^:= PDWord(@a[2])^ xor drk[0,2]; PDWord(@a[3])^:= PDWord(@a[3])^ xor drk[0,3]; PDword(@OutData)^:= PDword(@a[0,0])^; PDword(pointer(@OutData)+4)^:= PDword(@a[1,0])^; PDword(pointer(@OutData)+8)^:= PDword(@a[2,0])^; PDword(pointer(@OutData)+12)^:= PDword(@a[3,0])^; end; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtDlgs, ExtCtrls, BZImageViewer, BZColors, BZGraphic, BZBitmap, BZBItmapIO; type TMainForm = class(TForm) btnLoad : TButton; btnStop : TButton; btnPlay : TButton; btnPause : TButton; Button1 : TButton; Button2 : TButton; chkRaw : TCheckBox; chkTransparent : TCheckBox; ImageView : TBZImageViewer; Label1 : TLabel; Label2 : TLabel; lblCounter : TLabel; OPD : TOpenPictureDialog; Panel1 : TPanel; Timer1 : TTimer; procedure btnLoadClick(Sender : TObject); procedure btnPauseClick(Sender : TObject); procedure btnPlayClick(Sender : TObject); procedure btnStopClick(Sender : TObject); procedure Button1Click(Sender : TObject); procedure Button2Click(Sender : TObject); procedure chkTransparentChange(Sender : TObject); procedure FormClose(Sender : TObject; var CloseAction : TCloseAction); procedure Timer1Timer(Sender : TObject); private FFrameCount, FCurrentFrameIndex : Integer; FTest : TBZBitmap; procedure DoOnFrameChange(Sender:TObject); public end; var MainForm : TMainForm; implementation {$R *.lfm} { TMainForm } procedure TMainForm.btnLoadClick(Sender : TObject); begin if OPD.Execute then begin if Not(Assigned(FTest)) then begin FTest := TBZBitmap.Create; FTest.OnFrameChanged := @DoOnFrameChange; end; FTest.LoadFromFile(OPD.FileName); ImageView.Picture.LoadFromFile(OPD.FileName); FFrameCount := ImageView.Picture.Bitmap.ImageDescription.FrameCount; //ImageView.Picture.Bitmap.Layers.Count; FCurrentFrameIndex := 0; lblCounter.Caption := '0 / ' + FFrameCount.ToString; ImageView.Picture.Bitmap.RenderFrame(FCurrentFrameIndex); end; end; procedure TMainForm.btnPauseClick(Sender : TObject); begin Timer1.Enabled := False; ImageView.AnimationPause; FTest.PauseAnimate; end; procedure TMainForm.btnPlayClick(Sender : TObject); begin Timer1.Enabled := True; ImageView.AnimationStart; FTest.StartAnimate; end; procedure TMainForm.btnStopClick(Sender : TObject); begin Timer1.Enabled := False; ImageView.AnimationStop; FTest.StopAnimate; end; procedure TMainForm.Button1Click(Sender : TObject); begin if chkRaw.Checked then begin if ImageView.Picture.Bitmap.LayerIndex > 0 then ImageView.Picture.Bitmap.LayerIndex := ImageView.Picture.Bitmap.LayerIndex - 1; end else begin if FCurrentFrameIndex > 0 then FCurrentFrameIndex := FCurrentFrameIndex - 1; ImageView.Picture.Bitmap.RenderFrame(FCurrentFrameIndex); end; end; procedure TMainForm.Button2Click(Sender : TObject); begin if chkRaw.Checked then begin if ImageView.Picture.Bitmap.LayerIndex < ImageView.Picture.Bitmap.Layers.Count-1 then ImageView.Picture.Bitmap.LayerIndex := ImageView.Picture.Bitmap.LayerIndex + 1; end else begin if FCurrentFrameIndex < ImageView.Picture.Bitmap.Layers.Count-1 then FCurrentFrameIndex := FCurrentFrameIndex + 1; ImageView.Picture.Bitmap.RenderFrame(FCurrentFrameIndex); end; end; procedure TMainForm.chkTransparentChange(Sender : TObject); begin ImageView.DrawWithTransparency := not(ImageView.DrawWithTransparency); DoOnFrameChange(Self); end; procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction); begin Timer1.Enabled := False; if Assigned(FTest) then FreeAndNil(FTest); end; procedure TMainForm.Timer1Timer(Sender : TObject); begin lblCounter.Caption := ImageView.Picture.Bitmap.CurrentFrame.ToString + ' / ' + FFrameCount.ToString; end; procedure TMainForm.DoOnFrameChange(Sender : TObject); begin FTest.DrawToCanvas(panel1.Canvas,panel1.ClientRect, not(ImageView.DrawWithTransparency), true); end; end.
unit RRManagerEditAdditionalSubstructureInfoFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, RRManagerObjects, RRManagerbaseObjects, CommonComplexCombo; type // TfrmAdditionalSubstructureInfo = class(TFrame) TfrmAdditionalSubstructureInfo = class(TBaseFrame) gbxAll: TGroupBox; Label3: TLabel; edtBedHeight: TEdit; Label4: TLabel; edtArea: TEdit; cmplxNGK: TfrmComplexCombo; cmplxTrapType: TfrmComplexCombo; cmplxLayer: TfrmComplexCombo; private function GetSubstructure: TSubstructure; function GetHorizon: THorizon; { Private declarations } protected procedure FillControls; override; procedure ClearControls; override; procedure FillParentControls; override; public { Public declarations } property Horizon: THorizon read GetHorizon; property Substructure: TSubstructure read GetSubstructure; constructor Create(AOwner: TComponent); override; procedure Save; override; end; implementation {$R *.DFM} { TfrmAdditionalSubstructureInfo } procedure TfrmAdditionalSubstructureInfo.ClearControls; begin cmplxNGK.Clear; edtBedHeight.Clear; edtArea.Clear; cmplxTrapType.Clear; cmplxLayer.Clear; end; constructor TfrmAdditionalSubstructureInfo.Create(AOwner: TComponent); begin inherited; cmplxNGK.Caption := 'Нефтегазоносный подкомплекс'; cmplxNGK.FullLoad := true; cmplxNGK.DictName := 'TBL_OIL_COMPLEX_DICT'; cmplxTrapType.Caption := 'Тип ловушки'; cmplxTrapType.FullLoad := true; cmplxTrapType.DictName := 'TBL_TRAP_TYPE_DICT'; cmplxLayer.Caption := 'Продуктивный горизонт'; cmplxLayer.FullLoad := false; cmplxLayer.DictName := 'TBL_LAYER'; EditingClass := TSubstructure; ParentClass := THorizon; end; procedure TfrmAdditionalSubstructureInfo.FillControls; begin cmplxNGK.AddItem(Substructure.SubComplexID, Substructure.SubComplex); cmplxTrapType.AddItem(Substructure.TrapTypeID, Substructure.TrapType); end; procedure TfrmAdditionalSubstructureInfo.FillParentControls; begin inherited; cmplxNGK.AddItem(horizon.ComplexID, horizon.Complex); end; function TfrmAdditionalSubstructureInfo.GetHorizon: THorizon; begin Result := nil; if EditingObject is THorizon then Result := EditingObject as THorizon else if EditingObject is TSubstructure then Result := (EditingObject as TSubstructure).Horizon; end; function TfrmAdditionalSubstructureInfo.GetSubstructure: TSubstructure; begin Result := EditingObject as TSubstructure; end; procedure TfrmAdditionalSubstructureInfo.Save; begin if Assigned(Substructure) then begin Substructure.SubComplexID := cmplxNGK.SelectedElementID; Substructure.SubComplex := cmplxNGK.SelectedElementName; Substructure.TrapTypeID := cmplxTrapType.SelectedElementID; Substructure.TrapType := cmplxTrapType.SelectedElementName; end; end; end.
unit ConnectDirect; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Dialogs, Vcl.ActnList, BCControls.Edit, BCDialogs.Dlg, System.Actions; type TConnectDirectDialog = class(TDialog) ActionList: TActionList; CancelButton: TButton; DatabaserLabel: TLabel; HostEdit: TBCEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; OKAction: TAction; OKButton: TButton; UsernamePanel: TPanel; PasswordPanel: TPanel; HostPanel: TPanel; PortPanel: TPanel; SIDPanel: TPanel; ServiceNamePanel: TPanel; ButtonPanel: TPanel; PasswordEdit: TBCEdit; PasswordLabel: TLabel; PortEdit: TBCEdit; Separator1Panel: TPanel; ServiceNameEdit: TBCEdit; SIDEdit: TBCEdit; UsernameEdit: TBCEdit; UsernameLabel: TLabel; ProfilePanel: TPanel; ProfileLabel: TLabel; ProfileEdit: TBCEdit; procedure FormDestroy(Sender: TObject); procedure Formshow(Sender: TObject); procedure OKActionExecute(Sender: TObject); procedure ServiceNameEditChange(Sender: TObject); procedure SIDEditChange(Sender: TObject); private function GetHost: string; function GetPassword: string; function GetPort: string; function GetProfile: string; function GetServiceName: string; function GetSID: string; function GetUsername: string; procedure ClearFields; procedure SetHost(Value: string); procedure SetPassword(Value: string); procedure SetPort(Value: string); procedure SetProfile(Value: string); procedure SetServiceName(Value: string); procedure SetSID(Value: string); procedure SetUsername(Value: string); public function Open(Clear: Boolean): Boolean; property Profile: string read GetProfile write SetProfile; property Host: string read GetHost write SetHost; property Password: string read GetPassword write SetPassword; property Port: string read GetPort write SetPort; property ServiceName: string read GetServiceName write SetServiceName; property SID: string read GetSID write SetSID; property Username: string read GetUsername write SetUsername; end; function ConnectDirectDialog(AOwner: TComponent): TConnectDirectDialog; implementation {$R *.DFM} uses Lib, BCCommon.StyleUtils; var FConnectDirectDialog: TConnectDirectDialog; function ConnectDirectDialog(AOwner: TComponent): TConnectDirectDialog; begin if not Assigned(FConnectDirectDialog) then FConnectDirectDialog := TConnectDirectDialog.Create(AOwner); Result := FConnectDirectDialog; SetStyledFormSize(Result); end; procedure TConnectDirectDialog.FormDestroy(Sender: TObject); begin FConnectDirectDialog := nil; end; procedure TConnectDirectDialog.Formshow(Sender: TObject); begin PortEdit.Left := UsernameEdit.Left; { style fix } ProfileEdit.SetFocus; end; function TConnectDirectDialog.GetUsername: string; begin Result := UsernameEdit.Text end; procedure TConnectDirectDialog.SetUsername(Value: string); begin UsernameEdit.Text := Value end; function TConnectDirectDialog.GetPassword: string; begin Result := PasswordEdit.Text end; function TConnectDirectDialog.GetProfile: string; begin Result := ProfileEdit.Text end; procedure TConnectDirectDialog.SetPassword(Value: string); begin PasswordEdit.Text := Value end; function TConnectDirectDialog.GetHost: string; begin Result := HostEdit.Text end; procedure TConnectDirectDialog.SetHost(Value: string); begin HostEdit.Text := Value end; function TConnectDirectDialog.GetPort: string; begin Result := PortEdit.Text end; procedure TConnectDirectDialog.SetPort(Value: string); begin PortEdit.Text := Value end; procedure TConnectDirectDialog.SetProfile(Value: string); begin ProfileEdit.Text := Value; end; function TConnectDirectDialog.GetSID: string; begin Result := SIDEdit.Text end; procedure TConnectDirectDialog.SetSID(Value: string); begin SIDEdit.Text := Value end; function TConnectDirectDialog.GetServiceName: string; begin Result := ServiceNameEdit.Text end; procedure TConnectDirectDialog.SetServiceName(Value: string); begin ServiceNameEdit.Text := Value end; procedure TConnectDirectDialog.OKActionExecute(Sender: TObject); begin if UsernameEdit.Text = '' then begin ShowMessage(TEXT_USERNAME); UsernameEdit.SetFocus; Exit; end; if PasswordEdit.Text = '' then begin ShowMessage(TEXT_PASSWORD); PasswordEdit.SetFocus; Exit; end; ModalResult := mrOK end; procedure TConnectDirectDialog.ClearFields; begin Username := ''; Password := ''; Host := ''; Port := ''; SID := ''; ServiceName := ''; end; function TConnectDirectDialog.Open(Clear: Boolean): Boolean; begin if Clear then ClearFields; Result := ShowModal = mrOk; end; procedure TConnectDirectDialog.ServiceNameEditChange(Sender: TObject); begin SIDEdit.Enabled := Trim(ServiceNameEdit.Text) = ''; end; procedure TConnectDirectDialog.SIDEditChange(Sender: TObject); begin ServiceNameEdit.Enabled := Trim(SIDEdit.Text) = ''; end; end.
unit uAllocators; interface uses Classes; {$i DelphiVersion_defines.inc} type {$IFNDEF DELPHI2009} NativeUInt = Cardinal; {$ENDIF} TBlockEvent = procedure(ABlockPtr : Pointer) of object; TFastHeap = class private FTrackBlockArrays: Boolean; FTrackedBlocks: TList; function GetCurrentBlockRefCount: Integer; procedure TrackBlockArray(ABlockArray: Pointer); protected FStartBlockArray : Pointer; FNextOffset : NativeUInt; FPageSize: NativeUInt; FTotalUsableSize : NativeUInt; FOnAllocBlock : TBlockEvent; FOnDeallocBlock : TBlockEvent; procedure AllocateMemory(var APtr: Pointer; ASize: NativeUInt); function AllocBlockInPage(APage: Pointer; AOffset: NativeUInt): Pointer; procedure AllocNewBlockArray; procedure DeallocateMemory(APtr: Pointer); public destructor Destroy; override; procedure DeAlloc(Ptr: Pointer); property CurrentBlockRefCount: Integer read GetCurrentBlockRefCount; property TrackBlockArrays: Boolean read FTrackBlockArrays write FTrackBlockArrays; property OnAllocBlock : TBlockEvent read FOnAllocBlock write FOnAllocBlock; property OnDeallocBlock : TBlockEvent read FOnDeallocBlock write FOnDeallocBlock; end; TFixedBlockHeap = class(TFastHeap) protected FBlockSize : NativeUInt; FOriginalBlockSize: NativeUInt; public constructor Create(ABlockSize, ABlockCount: NativeUInt); overload; constructor Create(AClass: TClass; ABlockCount: NativeUInt); overload; function Alloc: Pointer; property OriginalBlockSize: NativeUInt read FOriginalBlockSize; end; TVariableBlockHeap = class(TFastHeap) public constructor Create(APoolSize: NativeUInt); function Alloc(ASize: NativeUInt): Pointer; end; function DeAlloc(Ptr: Pointer) : Boolean; implementation {$IFDEF USEFASTMM4} {$IFDEF WIN64} This configuration is not supported {$ENDIF} {$ENDIF} uses SysUtils {$IFDEF USEFASTMM4} ,FastMM4 {$ENDIF}{$IFDEF DELPHIXE2} ,Types {$ENDIF}; const Aligner = sizeof (NativeUInt) - 1; MAGIC_NUMBER = $73737300; type PPage = ^TPage; PBlock = ^TBlock; TBlockHeader = record PagePointer : PPage; {$IFDef OVERALLOC} MagicNumber : NativeUInt; {$ENDIF} end; TBlock = record Header : TBlockHeader; Data : array [0..MaxInt - sizeof(PPage) - sizeof(NativeUInt) - 16] of byte; end; TPageHeader = record RefCount : NativeUInt; end; TPage = record Header : TPageHeader; FirstBlock : TBlock; end; procedure _FreeMem(Ptr : pointer); {$IFDEF USEFASTMM4} asm {$IfDef FullDebugMode} jmp DebugFreeMem {$Else} jmp FastFreeMem {$Endif} {$ELSE} begin FreeMem(Ptr); {$ENDIF} end; function _GetMem(ASize: NativeUInt): Pointer; {$IFDEF USEFASTMM4} asm {$IfDef FullDebugMode} jmp DebugGetMem {$ELSE} jmp FastGetMem {$ENDIF} {$ELSE} begin GetMem(Result, ASize); {$ENDIF} end; function DeAlloc(Ptr: Pointer) : boolean; {$IfNDef MEMLEAKPROFILING} asm {$IFDEF WIN64} mov rcx, qword ptr [rcx - offset TBlock.Data + offset TBlock.Header.PagePointer] // Move to RAX pointer to start of block sub qword ptr [rcx + TPage.Header.RefCount], 1 // Decrement by one reference counter of block jnz @@Return // If zero flag was set, means reference counter reached zero if not then return no further action sub rsp, 20h call _FreeMem add rsp, 20h mov rax, True ret @@Return: mov rax, False {$ELSE} mov eax, dword ptr [eax - offset TBlock.Data + offset TBlock.Header.PagePointer] // Move to EAX pointer to start of block sub dword ptr [eax + TPage.Header.RefCount], 1 // Decrement by one reference counter of block jnz @@Return // If zero flag was set, means reference counter reached zero if not then return no further action call _FreeMem mov eax, True ret @@Return: mov eax, False {$ENDIF} {$Else} begin FreeMem(Ptr); {$EndIf} end; { TFastHeap } destructor TFastHeap.Destroy; var i : integer; begin if FStartBlockArray <> nil then begin dec (PPage(FStartBlockArray).Header.RefCount); if FTrackBlockArrays or (PPage(FStartBlockArray).Header.RefCount <= 0) then DeallocateMemory(FStartBlockArray); end; if FTrackedBlocks <> nil then begin for i := 0 to FTrackedBlocks.Count - 1 do DeallocateMemory(FTrackedBlocks[i]); FreeAndNil(FTrackedBlocks); end; inherited; end; procedure TFastHeap.AllocNewBlockArray; begin if (FStartBlockArray <> nil) and (PPage(FStartBlockArray).Header.RefCount = 1) then FNextOffset := sizeof (TPageHeader) else begin if FStartBlockArray <> nil then begin dec (PPage(FStartBlockArray).Header.RefCount); if FTrackBlockArrays then TrackBlockArray(FStartBlockArray); end; AllocateMemory(FStartBlockArray, FPageSize); PPage(FStartBlockArray).Header.RefCount := 1; FNextOffset := sizeof (TPageHeader); end; end; procedure TFastHeap.DeAlloc(Ptr: Pointer); var Page : Pointer; begin if FTrackBlockArrays and (FTrackedBlocks <> nil) then Page := PBlock(NativeUInt(Ptr) - sizeof(TBlockHeader))^.Header.PagePointer else Page := nil; if uAllocators.DeAlloc(Ptr) then begin if assigned(FOnDeallocBlock) then FOnDeallocBlock(Ptr); if FTrackBlockArrays and (FTrackedBlocks <> nil) and (Page <> nil) then FTrackedBlocks.Remove(Page); end; end; procedure TFastHeap.AllocateMemory(var APtr: Pointer; ASize: NativeUInt); begin APtr := _GetMem(ASize); if assigned(OnAllocBlock) then OnAllocBlock(APtr); end; procedure TFastHeap.DeallocateMemory(APtr: Pointer); begin if assigned(OnDeallocBlock) then OnDeallocBlock(APtr); _FreeMem(APtr); end; function TFastHeap.AllocBlockInPage(APage: Pointer; AOffset: NativeUInt): Pointer; begin Result := Pointer (NativeUInt(APage) + AOffset); PBlock(Result).Header.PagePointer := APage; {$IFDef OVERALLOC} PBlock(Result).Header.MagicNumber := MAGIC_NUMBER; {$ENDIF} inc (PPage(APage).Header.RefCount); Result := @PBlock(Result).Data; end; function TFastHeap.GetCurrentBlockRefCount: Integer; begin Result := PPage(FStartBlockArray).Header.RefCount; end; procedure TFastHeap.TrackBlockArray(ABlockArray: Pointer); begin if FTrackedBlocks = nil then FTrackedBlocks := TList.Create; FTrackedBlocks.Add(ABlockArray); end; { TFixedBlockHeap } constructor TFixedBlockHeap.Create(ABlockSize, ABlockCount: NativeUInt); begin inherited Create; FOriginalBlockSize := ABlockSize; FBlockSize := (ABlockSize + sizeof(TBlockHeader) + Aligner) and (not Aligner); FTotalUsableSize := FBlockSize * ABlockCount; FPageSize := FTotalUsableSize + sizeof (TPageHeader); FNextOffset := FPageSize; end; constructor TFixedBlockHeap.Create(AClass: TClass; ABlockCount: NativeUInt); begin Create (AClass.InstanceSize, ABlockCount); end; function TFixedBlockHeap.Alloc: Pointer; begin {$IfNDef MEMLEAKPROFILING} if FNextOffset >= FPageSize then AllocNewBlockArray; Result := AllocBlockInPage(FStartBlockArray, FNextOffset); inc (FNextOffset, FBlockSize); {$Else} GetMem(result, FBlockSize); {$EndIf} end; { TVariableBlockHeap } constructor TVariableBlockHeap.Create(APoolSize: NativeUInt); begin inherited Create; FTotalUsableSize := (APoolSize + Aligner) and (not Aligner); FPageSize := FTotalUsableSize + sizeof (TPageHeader); FNextOffset := FPageSize; end; function TVariableBlockHeap.Alloc(ASize: NativeUInt): Pointer; begin {$IfNDef MEMLEAKPROFILING} ASize := (ASize + sizeof (TBlockHeader) + Aligner) and (not Aligner); // Align size to native word size bits if ASize <= FTotalUsableSize then begin if FNextOffset + ASize >= FPageSize then AllocNewBlockArray; Result := AllocBlockInPage(FStartBlockArray, FNextOffset); inc (FNextOffset, ASize); end else begin AllocateMemory(Result, sizeof(TPageHeader) + ASize); PPage(Result).Header.RefCount := 0; Result := AllocBlockInPage(PPage(Result), sizeof(TPageHeader)); end; {$Else} GetMem(result, ASize); {$EndIf} end; end.
var a,b,s:ansistring; n,i,ans:longint; function sgcd(a,b:ansistring):ansistring; var la,lb,i,j:longint; begin if length(a)>length(b) then exit(sgcd(b,a)); la:=length(a); lb:=length(b); for i:=1 to lb div la do for j:=1 to la do if a[j]<>b[j+la*(i-1)] then exit(''); if lb mod la=0 then exit(a) else exit(sgcd(copy(b,lb-(lb mod la)+1,lb mod la),a)); end; function check(k:longint):boolean; var i,j:longint; begin for i:=1 to (n div k)-1 do for j:=1 to k do if s[j]<>s[j+i*k] then exit(false); exit(true); end; begin readln(a); readln(b); s := sgcd(a,b); if s='' then begin writeln(0);halt; end else n:=length(s); for i:=1 to trunc(sqrt(n)) do if n mod i=0 then begin if check(i) then inc(ans); if i*i<>n then if check(n div i) then inc(ans); end; writeln(ans); end.
{******************************************************************************* 作者: dmzn@ylsoft.com 2007-11-20 描述: 监控系统菜单管理单元 约定: &.TMenuItemData.FFlag 1.该标记用来设定菜单项的一些行为,它包括用"|"来分割的一组标识. 2.NB:标识该菜单项显示在Navbar导航栏上 *******************************************************************************} unit USysMenu; interface uses Windows, Classes, DB, SysUtils, UMgrMenu, ULibFun, USysConst, USysPopedom, UDataModule; const cMenuFlag_SS = '|'; //分割符,Split Symbol cMenuFlag_NB = 'NB'; //显示在导航栏上,Navbar cMenuFlag_NSS = '_'; //分隔符,Name Split Symbol type TMenuManager = class(TBaseMenuManager) protected function QuerySQL(const nSQL: string; var nDS: TDataSet; var nAutoFree: Boolean): Boolean; override; {*查询*} function ExecSQL(const nSQL: string): integer; override; {*执行写操作*} function GetItemValue(const nItem: integer): string; override; function IsTableExists(const nTable: string): Boolean; override; {*查询表*} public function MenuName(const nEntity,nMenuID: string): string; {*构建菜单名*} end; var gMenuManager: TMenuManager = nil; //全局菜单管理器 implementation //------------------------------------------------------------------------------ //Desc: 执行SQL语句 function TMenuManager.ExecSQL(const nSQL: string): integer; begin FDM.Command.Close; FDM.Command.SQL.Text := nSQL; Result := FDM.Command.ExecSQL; end; //Desc: 检测nTable表是否存在 function TMenuManager.IsTableExists(const nTable: string): Boolean; var nList: TStrings; begin nList := TStringList.Create; try FDM.ADOConn.GetTableNames(nList); Result := nList.IndexOf(nTable) > -1; finally nList.Free; end; end; //Desc: 执行SQL查询 function TMenuManager.QuerySQL(const nSQL: string; var nDS: TDataSet; var nAutoFree: Boolean): Boolean; begin FDM.SQLQuery.Close; FDM.SQLQuery.SQL.Text := nSQL; FDM.SQLQuery.Open; nDS := FDM.SQLQuery; Result := nDS.RecordCount > 0; end; //Desc: 构建实体nEntity中nMenuID菜单项的组建名称 function TMenuManager.MenuName(const nEntity, nMenuID: string): string; begin Result := nEntity + cMenuFlag_NSS + nMenuID; end; function TMenuManager.GetItemValue(const nItem: integer): string; begin Result := gSysParam.FTableMenu; end; initialization gMenuManager := TMenuManager.Create; finalization FreeAndNil(gMenuManager); end.
unit UProdutoController; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Forms, UProduto, UProdutoDAO, TypInfo, Variants, RTTI; type TProdutoController = class public Function Salvar(Produto: TProduto) : Boolean; function Deletar(Produto : TProduto) : Boolean; procedure ValidarDados(Produto : TProduto); end; implementation uses StrUtils, SysUtils, Dialogs, UBDados, UValidador; { TProdutoController } function TProdutoController.Deletar(Produto: TProduto): Boolean; Var Query : TFDQuery; ProdutoDAO : TProdutoDAO; begin Result := False; try Query := TFDQuery.Create(Application); Query.Connection := BDados.BDados; ProdutoDAO := TProdutoDAO.Create; if (ProdutoDAO.ExcluirProduto(Query,Produto)) then Result := True; finally Begin FreeAndNil(ProdutoDAO); FreeAndNil(Query); End; end; end; Function TProdutoController.Salvar(Produto: TProduto) : Boolean; Var Query : TFDQuery; ProdutoDAO : TProdutoDAO; begin Result := False; ValidarDados(Produto); try Query := TFDQuery.Create(Application); Query.Connection := BDados.BDados; ProdutoDAO := TProdutoDAO.Create; if (Produto.Codigo = -1) and (ProdutoDAO.InsereProduto(Query,Produto)) then Result := True Else if (ProdutoDAO.AlteraProduto(Query, Produto)) then Result := True; finally Begin FreeAndNil(ProdutoDAO); FreeAndNil(Query); End; end; end; procedure TProdutoController.ValidarDados(Produto : TProduto); var Contexto: TRttiContext; Tipo: TRttiType; Propriedade: TRttiProperty; Atributo: TCustomAttribute; begin Contexto := TRttiContext.Create; Tipo := Contexto.GetType(TProduto.ClassInfo); for Propriedade in Tipo.GetProperties do begin for Atributo in Propriedade.GetAttributes do if Atributo is TValidador then if not TValidador(Atributo).ValidarValor(Propriedade, Produto) then begin ShowMessage('Valor não preenchido: ' + (Atributo as TValidador).Descricao); Abort; end; end; end; end.
(****************************************************************************** * * * Project: - * * File : Unicode Registry class * * 20xx-xx-xx * * * * Michael Puff http://www.michael-puff.de * * * ******************************************************************************) {$I CompilerSwitches.inc} unit MpuRegistry; interface uses windows; type TMpuRegistry = class(TObject) private FHostIs64: Boolean; FhkResult: HKEY; FMachine: PWideChar; FhKey: HKEY; function IsHost64Bit: Boolean; function GetMachine: WideString; function GetHKey: HKEY; public // constructor Create(const Machine: string; hKey: HKEY); constructor CreateW(const Machine: WideString; hKey: HKEY); destructor Destroy; override; function Connect: LongInt; function CreateKey(const SubKey: string): LongInt; function CreateKeyW(const SubKey: WideString): LongInt; function OpenKey(const SubKey: string; samDesired: REGSAM): LongInt; function OpenKeyW(const SubKey: WideString; samDesired: REGSAM): LongInt; function ReadInt(const ValueName: string; var Value: Integer): LongInt; function ReadIntW(const ValueName: WideString; var Value: Integer): LongInt; function ReadByte(const ValueName: string; var Value: Byte; default: Byte = 0): LongInt; function ReadByteW(const ValueName: WideString; var Value: Byte; default: Byte = 0): LongInt; function ReadBool(const ValueName: string; var Value: Boolean; default: Boolean = True): LongInt; function ReadBoolW(const ValueName: string; var Value: Boolean; default: Boolean = True): LongInt; function ReadString(const ValueName: string; var Value: string): LongInt; function ReadStringW(const ValueName: WideString; var Value: WideString): LongInt; function WriteInt(const ValueName: string; Value: Integer): LongInt; function WriteIntW(const ValueName: WideString; Value: Integer): LongInt; function WriteByte(const ValueName: string; Value: Byte): LongInt; function WriteByteW(const ValueName: WideString; Value: Byte): LongInt; function WriteBool(const ValueName: string; Value: Boolean): LongInt; function WriteBoolW(const ValueName: WideString; Value: Boolean): LongInt; function WriteString(const ValueName: string; Value: string): LongInt; function WriteStringW(const ValueName: WideString; const Value: WideString): LongInt; function DeleteValueName(const ValueName: string): LongInt; function DeleteSubKey(const SubKey: string): LongInt; property Machine: WideString read GetMachine; property hKey: HKEY read GetHKey; end; const KEY_WOW64_64KEY = $0100; implementation constructor TMpuRegistry.CreateW(const Machine: WideString; hKey: HKEY); begin inherited Create; FMachine := PWideChar(Machine); FhKey := hKey; FHostIs64 := IsHost64Bit; end; destructor TMpuRegistry.Destroy; begin RegCloseKey(FhkResult); inherited Destroy; end; ///// Methods ////////////////////////////////////////////////////////////////// function TMpuRegistry.Connect: LongInt; begin result := RegConnectRegistryW(FMachine, FhKey, FhkResult); end; function TMpuRegistry.CreateKey(const SubKey: string): LongInt; begin result := CreateKeyW(SubKey); end; function TMpuRegistry.CreateKeyW(const SubKey: WideString): LongInt; begin result := RegCreateKeyExW(FhKey, PWideChar(SubKey), 0, nil, REG_OPTION_NON_VOLATILE, KEY_WRITE, nil, FhkResult, nil); end; function TMpuRegistry.OpenKey(const SubKey: string; samDesired: REGSAM): LongInt; begin if FHostIs64 then result := OpenKeyW(SubKey, samDesired or KEY_WOW64_64KEY) else result := OpenKeyW(SubKey, samDesired); end; function TMpuRegistry.OpenKeyW(const SubKey: WideString; samDesired: REGSAM): LongInt; begin if FHostIs64 then result := RegOpenKeyExW(FhkResult, PWideChar(SubKey), 0, samDesired or KEY_WOW64_64KEY, FhkResult) else result := RegOpenKeyExW(FhkResult, PWideChar(SubKey), 0, samDesired, FhkResult); end; function TMpuRegistry.ReadInt(const ValueName: string; var Value: Integer): LongInt; begin result := ReadIntW(ValueName, Value); end; function TMpuRegistry.ReadIntW(const ValueName: WideString; var Value: Integer): LongInt; var cbData: Integer; lpType: DWORD; begin // get size of required data result := RegQueryValueExW(FhkResult, PWideChar(ValueName), nil, @lpType, @Value, @cbData); if cbData <> 0 then begin result := RegQueryValueExW(FhkResult, PWideChar(ValueName), nil, @lpType, @Value, @cbData); end; end; function TMpuRegistry.ReadByte(const ValueName: string; var Value: Byte; default: Byte = 0): LongInt; begin result := ReadByteW(ValueName, Value, default); end; function TMpuRegistry.ReadByteW(const ValueName: WideString; var Value: Byte; default: Byte = 0): LongInt; var temp: Integer; begin result := ReadIntW(ValueName, temp); if Result = ERROR_SUCCESS then Value := Byte(temp) else Value := default; end; function TMpuRegistry.ReadBool(const ValueName: string; var Value: Boolean; default: Boolean = True): LongInt; begin Result := ReadBoolW(ValueName, Value, default); end; function TMpuRegistry.ReadBoolW(const ValueName: string; var Value: Boolean; default: Boolean = True): LongInt; var temp: Integer; begin Result := ReadIntW(ValueName, temp); if Result = ERROR_SUCCESS then Value := Boolean(temp) else Value := default; end; function TMpuRegistry.ReadString(const ValueName: string; var Value: string): LongInt; var cbData: Integer; lpType: DWORD; Buffer: PChar; begin // get size of required data result := RegQueryValueEx(FhkResult, PChar(ValueName), nil, @lpType, nil, @cbData); if cbData <> 0 then begin GetMem(Buffer, cbData); try result := RegQueryValueEx(FhkResult, PChar(ValueName), nil, @lpType, Pointer(Buffer), @cbData); Value := Buffer; // <- hier AccessViolation finally FreeMem(Buffer); end; end; end; function TMpuRegistry.ReadStringW(const ValueName: WideString; var Value: WideString): LongInt; var cbData: Integer; lpType: DWORD; Buffer: PWideChar; begin // get size of required data result := RegQueryValueExW(FhkResult, PWideChar(ValueName), nil, @lpType, nil, @cbData); if cbData <> 0 then begin GetMem(Buffer, cbData); try result := RegQueryValueExW(FhkResult, PWideChar(ValueName), nil, @lpType, Pointer(Buffer), @cbData); Value := Buffer; finally FreeMem(Buffer); end; end; end; function TMpuRegistry.WriteInt(const ValueName: string; Value: Integer): LongInt; begin result := WriteIntW(ValueName, Value); end; function TMpuRegistry.WriteIntW(const ValueName: WideString; Value: Integer): LongInt; begin result := RegSetValueExW(FhkResult, PWideChar(ValueName), 0, REG_DWORD, @Value, sizeof(Integer)); end; function TMpuRegistry.WriteByte(const ValueName: string; Value: Byte): LongInt; begin result := WriteIntW(ValueName, Value); end; function TMpuRegistry.WriteByteW(const ValueName: WideString; Value: Byte): LongInt; begin result := WriteIntW(ValueName, Value); end; function TMpuRegistry.WriteBool(const ValueName: string; Value: Boolean): LongInt; begin result := WriteInt(ValueName, ord(Value)); end; function TMpuRegistry.WriteBoolW(const ValueName: WideString; Value: Boolean): LongInt; begin result := WriteIntW(ValueName, ord(Value)); end; function TMpuRegistry.WriteString(const ValueName: string; Value: string): LongInt; begin result := RegSetValueEx(FhkResult, PChar(ValueName), 0, REG_SZ, PChar(Value), length(Value)); end; function TMpuRegistry.WriteStringW(const ValueName: WideString; const Value: WideString): LongInt; begin result := RegSetValueExW(FhkResult, PWideChar(ValueName), 0, REG_SZ, PWideChar(Value), (Length(Value) + 1) * SizeOf(WideChar)); end; function TMpuRegistry.DeleteValueName(const ValueName: string): LongInt; begin result := RegDeleteValue(FhkResult, PChar(ValueName)); end; function TMpuRegistry.DeleteSubKey(const SubKey: string): LongInt; begin result := RegDeleteKey(FhkResult, PChar(SubKey)); end; //// Propterties /////////////////////////////////////////////////////////////// function TMpuRegistry.GetMachine: WideString; begin result := FMachine; end; function TMpuRegistry.GetHKey: HKEY; begin result := FhKey; end; //////////////////////////////////////////////////////////////////////////////// function TMpuRegistry.IsHost64Bit: Boolean; type TIsWow64Process = function(Handle: THandle; var Res: BOOL): BOOL; stdcall; var IsWow64Result: BOOL; IsWow64Process: TIsWow64Process; begin IsWow64Process := GetProcAddress(GetModuleHandle('kernel32'), 'IsWow64Process'); if Assigned(IsWow64Process) then begin IsWow64Process(GetCurrentProcess, IsWow64Result); Result := IsWow64Result; end else // Function not implemented: can't be running on Wow64 Result := False; end; end.
unit sql.connection.DBExpress; interface uses System.Classes, System.SysUtils, Generics.Collections, Data.DB, Data.SqlExpr, Data.FMTBcd, Data.DBXCommon, SimpleDS, Datasnap.DBClient, Data.DBXFirebird, Data.DBXMySQL, Data.DBXMsSQL, Data.DBXOracle, sql.consts, sql.connection; type TSQLConnectionDBX = Class(TDBConnection) private FConnection : TSQLConnection; FTransact : TTransactionDesc; FDBXReaders : TObjectList<TDBXReader>; function FactorySDS : TSimpleDataSet; function FactoryQry : TSQLQuery; public constructor Create; Override; destructor Destroy; Override; function Connect : Boolean; Override; procedure Disconnect; Override; function Connected : Boolean; Override; function IsStart(Transact : Integer = 1) : Boolean; Override; function Start(Transact : Integer = 1) : Boolean; Override; function Commit(Transact : Integer = 1) : Boolean; Override; function Rollback(Transact : Integer = 1) : Boolean; Override; function ExecuteScript(Value : TStrings; OnProgress : TOnProgress) : Boolean; Override; function Execute(Value : String) : Boolean; Override; function Execute(Value : TStrings) : Boolean; Override; function Execute(Value : TStrings; Blobs : TList<TBlobData>) : Boolean; Override; function Open(Value : String) : TDataSet; Override; function Open(Value : TStrings) : TDataSet; Override; function Open(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Override; procedure Open(DataSet : TDataSet; Value : String); Override; function OpenQry(Value : String) : TDataSet; Override; function OpenExec(Value : String) : TDataSet; Override; function OpenExec(Value : TStrings) : TDataSet; Override; function OpenExec(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Override; procedure SortIndex(Value : TDataSet; AscFields, DescFields : String); Override; End; implementation { TSQLConnectionDBX } function TSQLConnectionDBX.Commit(Transact : Integer): Boolean; begin Result := IsStart; Try If Result Then FConnection.Commit(FTransact); Result := True; Except On E:Exception Do Begin Error := E.Message; Result := False; End; End; end; function TSQLConnectionDBX.Connect: Boolean; procedure SetFirebird; begin With FConnection Do begin DriverName := 'Firebird'; ConnectionName := 'FBConnection'; VendorLib := 'fbclient.dll'; Params.Values[TDBXPropertyNames.HostName] := DataBase.Server + '/'+ FormatFloat('0',DataBase.Port); //Params.Values[TDBXPropertyNames.Port] := FormatFloat('0',DataBase.Port); Params.Values[TDBXPropertyNames.Database] := DataBase.DataBase; Params.Values[TDBXPropertyNames.UserName] := DataBase.User; Params.Values[TDBXPropertyNames.Password] := DataBase.Password; Params.Values['SQLDialect'] := FormatFloat('0',DataBase.Dialect); //Params.Values[TDBXPropertyNames.ErrorResourceFile] := 'C:\bti\sqlerro.txt'; end; end; procedure SetSQLServer; begin With FConnection Do begin DriverName := 'MSSQL'; ConnectionName := 'MSSQLConnection'; Params.Values[TDBXPropertyNames.HostName] := DataBase.Server; Params.Values[TDBXPropertyNames.Port] := FormatFloat('0',DataBase.Port); Params.Values[TDBXPropertyNames.Database] := DataBase.DataBase; Params.Values[TDBXPropertyNames.UserName] := DataBase.User; Params.Values[TDBXPropertyNames.Password] := DataBase.Password; end; end; procedure SetMySQL; begin With FConnection Do begin DriverName := 'MySQL'; ConnectionName := 'MySQLConnection'; LibraryName := 'dbxmys.dll'; VendorLib := 'LIBMYSQL.dll'; Params.Values[TDBXPropertyNames.DriverName] := 'MySQL'; Params.Values[TDBXPropertyNames.HostName] := DataBase.Server; Params.Values[TDBXPropertyNames.Port] := FormatFloat('0',DataBase.Port); Params.Values[TDBXPropertyNames.Database] := DataBase.DataBase; Params.Values[TDBXPropertyNames.UserName] := DataBase.User; Params.Values[TDBXPropertyNames.Password] := DataBase.Password; end; end; procedure SetOracle; begin With FConnection Do begin end; end; begin Result := False; FConnection.LoginPrompt := False; Try Case SQL.SQLDB Of dbFirebird : SetFirebird; dbSQLServer: SetSQLServer; dbMySQL : SetMySQL; dbOracle : SetOracle; End; Finally Try FConnection.LoginPrompt := False; FConnection.Connected := True; Result := FConnection.Connected; Except On E : Exception Do Error := E.Message; End; End; end; constructor TSQLConnectionDBX.Create; begin inherited; FDBXReaders := TObjectList<TDBXReader>.Create; FConnection := TSQLConnection.Create(nil); FTransact.TransactionID := 1; FTransact.IsolationLevel := xilREADCOMMITTED; end; destructor TSQLConnectionDBX.Destroy; begin inherited; FreeAndNil(FDBXReaders); FreeAndNil(FConnection); end; procedure TSQLConnectionDBX.Disconnect; begin inherited; Try FConnection.Close; Except End; end; function TSQLConnectionDBX.Execute(Value: TStrings; Blobs: TList<TBlobData>): Boolean; var Qry : TSQLQuery; S : String; I : Integer; begin AddLog(Value); Error := ''; Try Qry := FactoryQry; For S in Value Do Begin If S.IsEmpty Then Continue; Qry.Close; Qry.SQL.Clear; Qry.SQL.Text := S; For I := 0 To (Qry.Params.Count - 1) Do Qry.Params[I].SetBlobData(Pointer(Blobs[I]),High(Blobs[I])); Try Start; Qry.ExecSQL; Result := True; Except On E:Exception Do Begin Result := False; Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally FreeAndNil(Qry); End; end; function TSQLConnectionDBX.ExecuteScript(Value: TStrings; OnProgress : TOnProgress): Boolean; var I, C : Integer; function IsContains(Values : Array Of String; Value : String) : Boolean; var X : Integer; Begin Result := False; For X := Low(Values) To High(Values) Do If Value.Contains(Values[X]) Then Exit(True); End; procedure DoOnProgress(Index, Max : Integer; Mens: String); begin If Assigned(OnProgress) Then OnProgress(Index,Max,Mens); end; begin Result := True; Try Disconnect; If (not Connect) Then Exit(False); C := 0; For I := 0 To (Value.Count - 1) Do Begin DoOnProgress(I,Value.Count - 1,'Executando Script'); If not Execute(Value[I]) Then Begin DoOnProgress(I,Value.Count - 1,'Erro ao executar Script'); Exit(False); End; If not IsContains(['trigger','alter','drop','create','view'],LowerCase(Value[I])) Then Begin Inc(C); If (C <= 1000) Then Continue; End; C := 0; If (not Commit) Then Begin DoOnProgress(I,Value.Count - 1,'Erro ao Gravar no Banco de dados (Commit)'); Exit(False); End; End; If (C > 0) And (not Commit) Then Begin DoOnProgress(I,Value.Count - 1,'Erro ao Gravar no Banco de dados (Commit)'); Exit(False); End; Finally Value.Clear; End; end; function TSQLConnectionDBX.Execute(Value: TStrings): Boolean; var S : String; begin Result := False; For S in Value Do Result := Execute(S); end; function TSQLConnectionDBX.Execute(Value: String): Boolean; var Qry : TSQLQuery; begin AddLog(Value); Error := ''; Try Qry := FactoryQry; Qry.SQL.Text := Value; Try Start; If (Trim(Value) <> '') Then Qry.ExecSQL(True); Result := True; Except On E:Exception Do Begin Result := False; Error := E.Message + '('+ Value +')'; AddLog(Error); End; End; Finally Qry.Close; FreeAndNil(Qry); End; end; function TSQLConnectionDBX.FactoryQry: TSQLQuery; begin Result := TSQLQuery.Create(FConnection); Result.SQLConnection := FConnection; Result.Close; end; function TSQLConnectionDBX.FactorySDS: TSimpleDataSet; begin Result := TSimpleDataSet.Create(FConnection); Result.Connection := FConnection; Result.Close; end; function TSQLConnectionDBX.IsStart(Transact : Integer): Boolean; begin Result := FConnection.InTransaction; end; function TSQLConnectionDBX.Open(Value: TStrings): TDataSet; var S : String; begin Result := nil; For S in Value Do Result := Open(S); end; function TSQLConnectionDBX.OpenExec(Value: String): TDataSet; var Qry : TSQLQuery; begin AddLog(Value); Qry := FactoryQry; Try Qry.SQL.Text := Value; Qry.Open; Finally Result := Qry; FDataSet.Add(Result); End; end; function TSQLConnectionDBX.OpenExec(Value: TStrings): TDataSet; var S : String; begin Result := nil; For S in Value Do Result := OpenExec(S); end; function TSQLConnectionDBX.Open(Value: String): TDataSet; var SDS : TSimpleDataSet; begin AddLog(Value); SDS := FactorySDS; Result := SDS; Try SDS.DataSet.CommandText := ''; SDS.DataSet.CommandText := Value; SDS.Open; Finally FDataSet.Add(Result); End; end; function TSQLConnectionDBX.Connected: Boolean; begin Result := (FConnection.Connected) And (FConnection.ConnectionState <> csStateClosed); end; function TSQLConnectionDBX.Rollback(Transact : Integer): Boolean; begin Result := IsStart(Transact); Try If Result Then FConnection.Rollback(FTransact); Result := True; Except Result := False; End; end; procedure TSQLConnectionDBX.SortIndex(Value: TDataSet; AscFields, DescFields : String); begin inherited; If (Value is TCustomClientDataSet) Then Begin With TClientDataSet(Value) Do Begin If IndexName <> '' Then DeleteIndex(IndexName); IndexName := ''; IndexDefs.Clear; AddIndex('_index',AscFields,[],DescFields); IndexName := '_index'; End; End; end; function TSQLConnectionDBX.Start(Transact : Integer): Boolean; begin Result := IsStart; Try If not Result Then FConnection.StartTransaction(FTransact); Result := True; Except Result := False; End; end; procedure TSQLConnectionDBX.Open(DataSet: TDataSet; Value: String); var SDS : TSimpleDataSet; begin AddLog(Value); SDS := TSimpleDataSet(DataSet); SDS.DisableControls; SDS.Close; Try Try SDS.IndexName := ''; SDS.IndexDefs.Clear; Except End; SDS.DataSet.CommandText := ''; SDS.DataSet.CommandText := Value; SDS.Open; Finally SDS.EnableControls; End; end; function TSQLConnectionDBX.Open(Value: TStrings; Blobs: TList<TBlobData>): TDataSet; var SDS : TSimpleDataSet; S : String; I : Integer; begin AddLog(Value); Error := ''; SDS := FactorySDS; Result := SDS; SDS.DisableControls; Try For S in Value Do Begin If S.IsEmpty Then Continue; Try SDS.Close; SDS.DataSet.CommandText := ''; SDS.DataSet.CommandText := S; For I := 0 To (SDS.DataSet.Params.Count - 1) Do SDS.DataSet.Params[I].SetBlobData(Pointer(Blobs[I]),High(Blobs[I])); SDS.Open; Except On E:Exception Do Begin Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally SDS.EnableControls; FDataSet.Add(Result); End; end; function TSQLConnectionDBX.OpenExec(Value: TStrings; Blobs: TList<TBlobData>): TDataSet; var Qry : TSQLQuery; S : String; I : Integer; begin AddLog(Value); Error := ''; Qry := FactoryQry; Try For S in Value Do Begin If S.IsEmpty Then Continue; Qry.Close; Qry.SQL.Clear; Qry.SQL.Text := S; For I := 0 To (Qry.Params.Count - 1) Do Qry.Params[I].SetBlobData(TValueBuffer(Blobs[I]),High(Blobs[I])); Try Start; Qry.Open; Except On E:Exception Do Begin Qry.Close; Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally Result := Qry; FDataSet.Add(Result) End; end; function TSQLConnectionDBX.OpenQry(Value: String): TDataSet; var Qry : TSQLQuery; begin AddLog(Value); Qry := FactoryQry; Result := Qry; Try Qry.SQL.Text := Value; Qry.Open; Finally FDataSet.Add(Result); End; end; end.
{----------------------------------------------------------} { CRLABEL.PAS - Running label } { by Michael Kochiashvili Kochini@iberiapac.ge } {----------------------------------------------------------} { This unit is public domain. You can add/rewrite code, but} {if you do it, please, let me know. If you have any } {suggestions for improvements, or if you find any bugs, } {please notify the author. } {----------------------------------------------------------} unit CRLabel; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; {$R *.RES} { TRunString - base class for running tools ------------------------------} type TRLabelStyle = ( rlNormal, rlRaised, rlLowered); TRDirection = ( rdStatic, rdRightToLeft, rdLeftToRight, rdTopToBottom, rdBottomToTop); type TRunString = class(TGraphicControl) private FLabelStyle : TRLabelStyle; { label style } FRunDirection : TRDirection; { running direction} FRText : string; { text to run} FSteps : integer; { steps} FSpeed : integer; { speed} FTimer : TTimer; FColor : TColor; { background color} FFont : TFont; { text font} FDepth : integer; { depth of raised or lowered label} FStepToView : integer; { Designing time only} FOnBegin, FOnStep, FOnEnd : TNotifyEvent; CurrentStep : integer; { step number when running} RTWidth, RTHeight : integer; { text width & height} CnX, CnY : integer; { } procedure LabelChanged(Sender: TObject); procedure SetLabelStyle( Value : TRLabelStyle); procedure SetDirection( Value : TRDirection); procedure SetRText( Value : string); procedure SetSteps( Value : integer); virtual; procedure SetSpeed( Value : integer); procedure SetColor( Value : TColor); procedure SetFont( Value : TFont); procedure SetDepth( Value : integer); procedure SetStepToView( Value : integer); procedure DoTextOut( ACanvas : TCanvas; x, y : integer; AText : string); protected procedure Paint; override; procedure TimerTick(Sender: TObject); property Depth : integer read FDepth write SetDepth default 1; property Direction : TRDirection read FRunDirection write SetDirection default rdRightToLeft; property RText : string read FRText write SetRText; { Designing time only. To view label at given step} property StepToView : integer read FStepToView write SetStepToView; { Events} property OnBegin : TNotifyEvent read FOnBegin write FOnBegin; property OnStep : TNotifyEvent read FOnStep write FOnStep; property OnEnd : TNotifyEvent read FOnEnd write FOnEnd; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Start runing. SStep is starting step number. if 0<SStep<Steps then new starting step is assigned else step number is not changed } procedure RLStart( SStep : integer); { Stop runing. Returns current step number} function RLStop : integer; { Reverse running direction} procedure RLReverse; { Get current step number} function GetCurrentStep : integer; published property LabelStyle : TRLabelStyle read FLabelStyle write SetLabelStyle default rlNormal; property Steps : integer read FSteps write SetSteps default 66; property Speed : integer read FSpeed write SetSpeed default 200; property Color : TColor read FColor write SetColor default clBtnFace; property RFont : TFont read FFont write SetFont; end; { TRunLabel --------------------------------------------------------------} type TRunLabel = class( TRunString) public published property Align; property Enabled; property ParentShowHint; property ShowHint; property Visible; { Propertis and events from TRunString} property LabelStyle; property Direction; property RText; property Steps; property Speed; property Color; property RFont; property StepToView; property OnBegin; property OnStep; property OnEnd; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TRunLabel]); end; { TRunString --------------------------------------------------------------} constructor TRunString.Create(AOwner: TComponent); begin inherited Create( AOwner); ControlStyle := ControlStyle - [csOpaque]; Width := 105; Height := 20; FColor := clBtnFace; FSteps := 66; FStepToView := FSteps DIV 2; CurrentStep := 0; FDepth := 1; FRunDirection := rdRightToLeft; FLabelStyle := rlNormal; FRText := 'Running label'; FFont := TFont.Create; with FFont do begin Name := 'System'; Size := 10; Color := clBlack; end; FFont.OnChange := LabelChanged; { Init timer} FTimer := TTimer.Create(Self); FSpeed := 200; with FTimer do begin Enabled := False; OnTimer := TimerTick; INterval := FSpeed; end; end; destructor TRunString.Destroy; begin FTimer.Free; FFont.Free; inherited Destroy; end; procedure TRunString.DoTextOut( ACanvas : TCanvas; x, y : integer; AText : string); begin with ACanvas do begin Font := FFont; Brush.Style := bsClear; { Draw text} case FLabelStyle of rlRaised : begin Font.Color := clBtnHighlight; TextOut( x, y, AText); Font.Color := clBtnShadow; TextOut( x + 2*FDepth, y + 2*FDepth, AText); end; rlLowered : begin Font.Color := clBtnShadow; TextOut( x, y, AText); Font.Color := clBtnHighlight; TextOut( x + 2*FDepth, y + 2*FDepth, AText); end; end; Font.Color := FFont.Color; TextOut( x + FDepth, y + FDepth, AText); end; end; procedure TRunString.Paint; var TmpBmp : TBitMap; TmpRect : TRect; StX, StY, CurStep : integer; PctDone : real; DC : HDC; begin TmpBmp := TBitMap.Create; try TmpBmp.Width := Width; TmpBmp.Height := Height; with TmpBmp.Canvas do begin Font := FFont; RTWidth := TextWidth( FRText) + 2 * FDepth; RTHeight := TextHeight( FRText) + 2 * FDepth; Brush.Color := FColor; Brush.Style := {bsClear} bsSolid; FillRect( ClipRect); end; { Calc center points} if RTWidth >= Width then CnX := 0 else CnX := ( Width - RTWidth) DIV 2; if RTHeight >= Height then CnY := 0 else CnY := ( Height - RTHeight) DIV 2; (* { Copy background in to the TmpBmp} TmpBmp.Canvas.CopyRect( TmpBmp.Canvas.ClipRect, Canvas, ClientRect); *) {Calculate percentages & starting points} if csDesigning in ComponentState then begin PctDone := FStepToView / FSteps; end else begin PctDone := CurrentStep / FSteps; end; case FRunDirection of rdRightToLeft : begin StY := CnY; StX := -RTWidth + round(( RTWidth + Width) * ( 1 - PctDone)); end; rdLeftToRight : begin StY := CnY; StX := -RTWidth + round(( RTWidth + Width) * ( PctDone)); end; rdBottomToTop : begin StX := CnX; StY := -RTHeight + round( ( RTHeight + Height) * ( PctDone)); end; rdTopToBottom : begin StX := CnX; StY := -RTHeight + round( ( RTHeight + Height) * ( 1 - PctDone)); end; else begin { static label} StX := CnX; StY := CnY; end end; DoTextOut( TmpBmp.Canvas, StX, StY, FRText); Canvas.Draw( 0, 0, TmpBmp); finally TmpBmp.Free; end; end; procedure TRunString.LabelChanged(Sender: TObject); begin with Canvas do begin Font := FFont; RTWidth := TextWidth( FRText) + 2 * FDepth; RTHeight := TextHeight( FRText) + 2 * FDepth; end; { Calc center points} if RTWidth >= Width then CnX := 0 else CnX := ( Width - RTWidth) DIV 2; if RTHeight >= Height then CnY := 0 else CnY := ( Height - RTHeight) DIV 2; Invalidate; end; procedure TRunString.SetLabelStyle( Value : TRLabelStyle); begin if FLabelStyle <> Value then begin FLabelStyle := Value; LabelChanged( Self); end; end; procedure TRunString.SetDirection( Value : TRDirection); begin if FRunDirection <> Value then begin FRunDirection := Value; end; end; procedure TRunString.SetRText( Value : string); begin if FRText <> Value then begin FRText := Value; LabelChanged( Self); end; end; procedure TRunString.SetSteps( Value : integer); begin if FSteps <> Value then begin FSteps := Value; if ( csDesigning in ComponentState) then begin FStepToView := FSteps DIV 2; Invalidate; end; end; end; procedure TRunString.SetSpeed( Value : integer); begin if FSpeed <> Value then begin FSpeed := Value; if Value > 1000 then FSpeed := 1000; if Value < 1 then FSpeed := 1; {Change the timer interval} if FTimer <> Nil then FTimer.Interval := FSpeed; end; end; procedure TRunString.SetColor( Value : TColor); begin if FColor <> Value then begin FColor := Value; LabelChanged( Self); end; end; procedure TRunString.SetFont( Value : TFont); begin FFont.Assign( Value); end; procedure TRunString.SetDepth( Value : integer); begin if FDepth <> Value then begin FDepth := Value; LabelChanged( Self); end; end; procedure TRunString.SetStepToView( Value : integer); begin if ( csDesigning in ComponentState) AND ( FStepToView <> Value) AND ( Value <= FSteps) AND ( Value >= 0) then begin FStepToView := Value; LabelChanged( Self); end; end; procedure TRunString.RLStart( SStep : integer); begin if FTimer.Enabled then exit; if ( SStep >= 0) AND ( SStep <= FSteps) then CurrentStep := SStep; FTimer.Enabled := true; end; function TRunString.RLStop : integer; begin FTimer.Enabled := false; Result := CurrentStep; end; procedure TRunString.RLReverse; begin if FRunDirection = rdStatic then exit; CurrentStep := FSteps - CurrentStep; case FRunDirection of rdLeftToRight : FRunDirection := rdRightToLeft; rdRightToLeft : FRunDirection := rdLeftToRight; rdTopToBottom : FRunDirection := rdBottomToTop; rdBottomToTop : FRunDirection := rdTopToBottom; end; end; function TRunString.GetCurrentStep : integer; begin Result := CurrentStep; end; procedure TRunString.TimerTick(Sender: TObject); begin if NOT FTimer.Enabled then exit; if ( CurrentStep = 0) AND Assigned( FOnBegin) then FOnBegin( Self); inc( CurrentStep); Paint; if Assigned( FOnStep) then FOnStep( Self); if CurrentStep >= FSteps then begin FTimer.Enabled := false; if Assigned(FOnEnd) then FOnEnd( Self); CurrentStep := 0; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016-2017 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSManagementConsole.FrameViews; interface uses System.Classes, FMX.StdCtrls, FMX.Forms, EMSManagementConsole.Data, FMX.Grid, System.Generics.Collections, EMSManagementConsole.FrameAdd, FMX.TabControl, EMSManagementConsole.Types, EMSManagementConsole.TypesViews, FMX.Controls, FMX.Controls.Presentation, FMX.Types, EMSManagementConsole.FramePush; type TViewsFrame = class(TFrame) ViewsControl: TTabControl; PushTabItem: TTabItem; PushFrame1: TPushFrame; private { Private declarations } FEMSConsoleData: TEMSConsoleData; // procedure OnTabItemClick(Sender: TObject); function CreateTab(const AName: string): TEMSTabItem; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DisableTabs(ATab: TEMSTabItem = nil); procedure EnableTabs; procedure CreateUsersView(const AUserID: string); procedure CreateGroupsView(const AGroupName: string); procedure CreateInstallationsView(const AInstallationID: string); procedure CreateEdgeModulesView(const AEdgePointID: string); procedure CreateResourcesView(const ARersourceID: string); property EMSConsoleData: TEMSConsoleData read FEMSConsoleData write FEMSConsoleData; end; implementation uses EMSManagementConsole.Consts; {$R *.fmx} { TViewsFrame } constructor TViewsFrame.Create(AOwner: TComponent); begin inherited; FEMSConsoleData := TEMSConsoleData.Create; CreateUsersView(''); CreateGroupsView(''); CreateInstallationsView(''); CreateEdgeModulesView(''); CreateResourcesView(''); ViewsControl.ActiveTab := PushTabItem; ViewsControl.Repaint; end; procedure TViewsFrame.CreateUsersView(const AUserID: string); var LTabItem: TEMSTabItem; begin LTabItem := CreateTab(strUsers); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2); end; procedure TViewsFrame.CreateGroupsView(const AGroupName: string); var LTabItem: TEMSTabItem; begin LTabItem := CreateTab(strGroups); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2); end; procedure TViewsFrame.CreateInstallationsView(const AInstallationID: string); var LTabItem: TEMSTabItem; begin LTabItem := CreateTab(strInstallations); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(4); {$IFNDEF DEBUG} LTabItem.FrameJSONGrid.AddItemButton.Visible := False; LTabItem.FrameJSONGrid.LabelAdd.Visible := False; {$ENDIF} end; procedure TViewsFrame.CreateEdgeModulesView(const AEdgePointID: string); var LTabItem: TEMSTabItem; begin LTabItem := CreateTab(strEdgeModules); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(4); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(5); LTabItem.FrameJSONGrid.AddItemButton.Visible := False; LTabItem.FrameJSONGrid.LabelAdd.Visible := False; end; procedure TViewsFrame.CreateResourcesView(const ARersourceID: string); var LTabItem: TEMSTabItem; begin LTabItem := CreateTab(strResources); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2); LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3); LTabItem.FrameJSONGrid.AddItemButton.Visible := False; LTabItem.FrameJSONGrid.LabelAdd.Visible := False; end; function TViewsFrame.CreateTab(const AName: string): TEMSTabItem; begin Result := nil; if AName = strUsers then Result := TEMSTabItem(ViewsControl.Insert(0, TUsersTabItem)); if AName = strGroups then Result := TEMSTabItem(ViewsControl.Insert(1, TGroupsTabItem)); if AName = strInstallations then Result := TEMSTabItem(ViewsControl.Insert(2, TInstallationTabItem)); if AName = strEdgeModules then Result := TEMSTabItem(ViewsControl.Insert(3, TEdgeModuleTabItem)); if AName = strResources then Result := TEMSTabItem(ViewsControl.Insert(4, TResourceTabItem)); Result.Name := AName + cTab; Result.Text := AName; Result.EMSConsoleData := FEMSConsoleData; ViewsControl.ActiveTab := Result; end; destructor TViewsFrame.Destroy; begin FEMSConsoleData.Free; inherited; end; procedure TViewsFrame.DisableTabs(ATab: TEMSTabItem = nil); var I: Integer; begin for I := 0 to ViewsControl.TabCount - 1 do if ATab <> ViewsControl.Tabs[I] then ViewsControl.Tabs[I].Enabled := False; end; procedure TViewsFrame.EnableTabs; var I: Integer; begin for I := 0 to ViewsControl.TabCount - 1 do ViewsControl.Tabs[I].Enabled := True; end; end.
unit UDAOLogin; interface uses SysUtils,StrUtils,Classes,DB,DBClient, zdataset, ZDbcIntfs, Variants, UUsuarioCarpetaDigi, UDMConexion; type TDAOLogin = class private public {CONSTRUCTORES Y DESTRUCTORES} { PROCEDIMIENTOS Y FUNCIONES } function ConsultarDatosUsuario(p_CodiUsua:string; p_ClavAcce:string): TUsuarioCarpetaDigi; end; implementation {$REGION 'METODOS PROPIOS'} function TDAOLogin.ConsultarDatosUsuario(p_CodiUsua: string; p_ClavAcce:string): TUsuarioCarpetaDigi; { FUNCION QUE BUSCA DATOS DE UN USUARIO } var QuerDatoUsua: TZQuery; begin Result:= TUsuarioCarpetaDigi.Create; try QuerDatoUsua:= TZQuery.Create(nil); QuerDatoUsua.Connection:= DMConexion.ZConexion; with QuerDatoUsua do begin Close; SQL.Clear; SQL.Add('SELECT USCA.codigousuariocarpeta, USCA.nombreusuariocarpeta, '); SQL.Add(' PEUS.idperfilusuario, PEUS.descripcionperfilusuario, USCA.habilitado '); SQL.Add(Format('FROM %s.USUARIOCARPETA USCA ', [DMConexion.esquema])); SQL.Add(Format('INNER JOIN %s.PERFILUSUARIO PEUS ON ' + 'PEUS.idperfilusuario = USCA.idperfilusuario', [DMConexion.esquema])); SQL.Add(' WHERE '); SQL.Add(Format(' USCA.codigousuariocarpeta = ''%s''',[p_CodiUsua])); SQL.Add(Format(' AND USCA.CLAVEUSUARIOCARPETA = MD5(''%s'')',[p_ClavAcce])); open; first; if not Eof then begin Result.CodigoUsuarioCarpeta := FieldByName('codigousuariocarpeta').Value; Result.NombreUsuarioCarpeta := FieldByName('nombreusuariocarpeta').Value; Result.IdPerfilCarpeta := FieldByName('idperfilusuario').Value; Result.DescripcionPerfilCarpeta := FieldByName('descripcionperfilusuario').Value; Result.Habilitado := FieldByName('habilitado').Value; end; end; except on E:exception do raise Exception.Create('No es posible consultar la información del Usuario.' + #10#13 + '* '+ e.Message); end; end; {$ENDREGION} {$REGION 'CONSTRUCTOR Y DESTRUCTOR'} {$ENDREGION} end.
{ Subroutine STRING_GENERIC_TNAM (INNAM,EXTENSIONS,TNAM) * * Create the generic tree name of a file given its name and a list * of possible extensions. INNAM is the name of the file. It can be * just a leaf name or an arbitrary tree name. EXTENSIONS is a PASCAL * STRING data type containing a list of possible file name extensions, * one of which may be on the end of the name in INNAM. TNAM is * returned as the full tree name of the name in INNAM without the file * name extension (if any). The first file name extension that matches * the end of the full treename of the file is the one used, even if * subsequent extensions would also have matched. TNAM is returned * the null string on any error. } module string_generic_tnam; define string_generic_tnam; %include 'string2.ins.pas'; procedure string_generic_tnam ( {generic tree name from file name and extensions} in innam: univ string_var_arg_t; {input file name (may be tree name)} in extensions: string; {list of extensions separated by blanks} in out tnam: univ string_var_arg_t); {output tree name without extension} var treenam: string_treename_t; {full tree name of file name in INNAM} begin treenam.max := sizeof(treenam.str); {set max var string lengths} string_treename (innam, treenam); {make full treename from input name} string_fnam_unextend (treenam, extensions, tnam); {remove file name extension if there} end;
unit CustomLogEntity; interface type TCustomLog = class public procedure Write(const aText: string); overload; virtual; abstract; procedure Write(const aTag, aText: string); overload; virtual; abstract; end; implementation end.
unit SocketTestCase; interface uses TestFramework, Classes, Windows, ZmqIntf; type TSocketTestCase = class(TTestCase) private context: IZMQContext; FZMQSocket: PZMQSocket; procedure MonitorEvent1( const event: TZMQEvent ); procedure MonitorEvent2( const event: TZMQEvent ); public procedure SetUp; override; procedure TearDown; override; published procedure TestSocketType; procedure TestrcvMore; procedure TestHWM; procedure TestSndHWM; procedure TestRcvHWM; procedure TestLastEndpoint; procedure TestAcceptFilter; procedure TestMonitor; procedure TestMonitorConnectDisconnect; procedure TestRcvTimeout; procedure TestSndTimeout; procedure TestAffinity; procedure TestIdentity; procedure TestRate; procedure TestRecoveryIvl; procedure TestSndBuf; procedure TestRcvBuf; procedure TestLinger; procedure TestReconnectIvl; procedure TestReconnectIvlMax; procedure TestBacklog; procedure TestFD; procedure TestEvents; procedure TestSubscribe; procedure TestunSubscribe; procedure SocketPair; end; implementation uses Sysutils; var ehandle1, ehandle2: THandle; zmqEvent: ^TZMQEvent; { TSimpleTestCase } procedure TSocketTestCase.SetUp; begin context := ZMQ.CreateContext; end; procedure TSocketTestCase.TearDown; begin context := nil; end; procedure TSocketTestCase.TestSocketType; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); Check( FZMQSocket.SocketType = st, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.Free; end; end; procedure TSocketTestCase.TestrcvMore; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); CheckEquals( False, FZMQSocket.rcvMore, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.Free; end; end; procedure TSocketTestCase.TestHWM; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); CheckEquals( 1000, FZMQSocket.HWM, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetHWM(42); CheckEquals( 42, FZMQSocket.HWM ); FZMQSocket.Free; end; end; procedure TSocketTestCase.TestSndHWM; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); CheckEquals( 1000, FZMQSocket.SndHWM, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetSndHWM(42); CheckEquals( 42, FZMQSocket.SndHWM ); FZMQSocket.Free; end; end; procedure TSocketTestCase.TestRcvHWM; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); CheckEquals( 1000, FZMQSocket.RcvHWM, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetRcvHWM(42); CheckEquals( 42, FZMQSocket.RcvHWM ); FZMQSocket.Free; end; end; procedure TSocketTestCase.TestLastEndpoint; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( '', FZMQSocket.LastEndpoint, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.bind('tcp://127.0.0.1:5555'); Sleep(10); CheckEquals( 'tcp://127.0.0.1:5555', FZMQSocket.LastEndpoint, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); finally FZMQSocket.unbind('tcp://127.0.0.1:5555'); Sleep(10); FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestAcceptFilter; var st: TZMQSocketType; begin //exit; // <---- WARN for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try FZMQSocket.bind('tcp://*:5555'); Sleep(10); FZMQSocket.AddAcceptFilter('192.168.1.1'); CheckEquals( '192.168.1.1', FZMQSocket.AcceptFilter(0), 'Add Accept Filter 1' ); FZMQSocket.AddAcceptFilter('192.168.1.2'); CheckEquals( '192.168.1.2', FZMQSocket.AcceptFilter(1), 'Add Accept Filter 2' ); FZMQSocket.SetAcceptFilter(0, '192.168.1.3'); CheckEquals( '192.168.1.3', FZMQSocket.AcceptFilter(0), 'Change Accept Filter 1' ); try // trying to set wrong value FZMQSocket.SetAcceptFilter(0, 'xraxsda'); CheckEquals( '192.168.1.3', FZMQSocket.AcceptFilter(0), 'Change Accept Filter 2' ); except on e: Exception do begin if ZMQ.IsZMQException(e) then begin CheckEquals( '192.168.1.3', FZMQSocket.AcceptFilter(0), 'set Invalid check 1' ); CheckEquals( '192.168.1.2', FZMQSocket.AcceptFilter(1), 'set Invalid check 2' ); end else raise; end; end; finally FZMQSocket.unbind('tcp://*:5555'); Sleep(10); FZMQSocket.Free; end; end; end; procedure TSocketTestCase.MonitorEvent1( const event: TZMQEvent ); begin zmqEvent^ := event; SetEvent( ehandle1 ); end; procedure TSocketTestCase.MonitorEvent2( const event: TZMQEvent ); begin zmqEvent^ := event; SetEvent( ehandle2 ); end; procedure TSocketTestCase.TestMonitor; var st: TZMQSocketType; begin New( zmqEvent ); ehandle1 := CreateEvent( nil, true, false, nil ); ehandle2 := CreateEvent( nil, true, false, nil ); for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); FZMQSocket.RegisterMonitor( MonitorEvent1 ); try FZMQSocket.bind( 'tcp://*:5555' ); WaitForSingleObject( ehandle1, INFINITE ); ResetEvent( ehandle1 ); CheckEquals( 'tcp://0.0.0.0:5555', zmqEvent.addr, 'addr not equal socket type: ' + IntToStr( Ord( st ) ) ); Check( zmqEvent.event = meListening, 'event should nbe meListening addr not equal socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.UnRegisterMonitor; FZMQSocket.RegisterMonitor( MonitorEvent2 ); sleep(100); FZMQSocket.unbind( 'tcp://*:5555' ); WaitForSingleObject( ehandle2, INFINITE ); ResetEvent( ehandle2 ); CheckEquals( 'tcp://0.0.0.0:5555', zmqEvent.addr, 'addr not equal socket type: ' + IntToStr( Ord( st ) ) ); Check( zmqEvent.event = meClosed, 'event should be meClosed addr not equal socket type: ' + IntToStr( Ord( st ) ) ); finally FZMQSocket.Free; sleep(200); end; end; CloseHandle( ehandle1 ); CloseHandle( ehandle2 ); Dispose( zmqEvent ); end; procedure TSocketTestCase.TestMonitorConnectDisconnect; const cAddr = 'tcp://127.0.0.1:5554'; var dealer: PZMQSocket; i: Integer; begin New( zmqEvent ); ehandle1 := CreateEvent( nil, true, false, nil ); ehandle2 := CreateEvent( nil, true, false, nil ); FZMQSocket := context.Socket( stRouter ); FZMQSocket.RegisterMonitor( MonitorEvent1 ); FZMQSocket.bind( cAddr ); WaitForSingleObject( ehandle1, INFINITE ); ResetEvent( ehandle1 ); CheckEquals( cAddr, zmqEvent.addr ); Check( zmqEvent.event = meListening ); for i := 0 to 10 do begin dealer := context.Socket( stDealer ); dealer.connect( cAddr ); WaitForSingleObject( ehandle1, INFINITE ); ResetEvent( ehandle1 ); CheckEquals( cAddr, zmqEvent.addr, 'connect, i : ' + IntToStr( i ) ); Check( zmqEvent.event = meAccepted, 'connect, i : ' + IntToStr( i ) ); sleep(100); dealer.Free; WaitForSingleObject( ehandle1, INFINITE ); ResetEvent( ehandle1 ); CheckEquals( cAddr, zmqEvent.addr, 'disconnect, i : ' + IntToStr( i ) ); Check( zmqEvent.event = meDisconnected, 'disconnect, i : ' + IntToStr( i ) ); sleep(100); end; //FZMQSocket.DeRegisterMonitor; context := nil; CloseHandle( ehandle1 ); CloseHandle( ehandle2 ); Dispose( zmqEvent ); end; procedure TSocketTestCase.TestRcvTimeout; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( -1, FZMQSocket.RcvTimeout, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetRcvTimeout(42); CheckEquals( 42, FZMQSocket.RcvTimeout ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestSndTimeout; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( -1, FZMQSocket.SndTimeout, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetSndTimeout(42); CheckEquals( 42, FZMQSocket.SndTimeout ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestAffinity; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 0, FZMQSocket.Affinity, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetAffinity(42); CheckEquals( 42, FZMQSocket.Affinity ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestIdentity; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( '', FZMQSocket.Identity, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetIdentity('mynewidentity'); CheckEquals( 'mynewidentity', FZMQSocket.Identity ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestRate; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try //CheckEquals( 100, FZMQSocket.Rate, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetRate(200); CheckEquals( 200, FZMQSocket.Rate ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestRecoveryIvl; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 10000, FZMQSocket.RecoveryIvl, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetRecoveryIvl(42); CheckEquals( 42, FZMQSocket.RecoveryIvl ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestSndBuf; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 0, FZMQSocket.SndBuf, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetSndBuf(100000); CheckEquals( 100000, FZMQSocket.SndBuf ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestRcvBuf; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 0, FZMQSocket.RcvBuf, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetRcvBuf(4096); CheckEquals( 4096, FZMQSocket.RcvBuf ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestLinger; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try //CheckEquals( -1, FZMQSocket.Linger, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); //Writeln('Socket type: '+IntToStr(ord(st))+' Default Linger: '+IntToStr(FZMQSocket.Linger)); CheckTrue( (FZMQSocket.Linger = -1) or (FZMQSocket.Linger = 0), 'Default check for socket type: ' + IntToStr( Ord( st ) ) +' ('+IntToStr(FZMQSocket.Linger)+')'); FZMQSocket.SetLinger(1024); CheckEquals( 1024, FZMQSocket.Linger ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestReconnectIvl; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 100, FZMQSocket.ReconnectIvl, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetReconnectIvl(2048); CheckEquals( 2048, FZMQSocket.ReconnectIvl ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestReconnectIvlMax; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 0, FZMQSocket.ReconnectIvlMax, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetReconnectIvlMax(42); CheckEquals( 42, FZMQSocket.ReconnectIvlMax ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestBacklog; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try CheckEquals( 100, FZMQSocket.Backlog, 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); FZMQSocket.SetBacklog(42); CheckEquals( 42, FZMQSocket.Backlog ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestFD; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try Check( Assigned( FZMQSocket.FD ) ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestEvents; var st: TZMQSocketType; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin FZMQSocket := context.Socket( st ); try //CheckEquals( True, FZMQSocket.GetEvents = [], 'Default check for socket type: ' + IntToStr( Ord( st ) ) ); finally FZMQSocket.Free; end; end; end; procedure TSocketTestCase.TestSubscribe; //var // filter: string; begin CheckTrue(True); { FZMQSocket := context.Socket( st ); try // TODO: Setup method call parameters FZMQSocket.Subscribe(filter); // TODO: Validate method results finally FZMQSocket.Free; end; } end; procedure TSocketTestCase.TestunSubscribe; //var // filter: string; begin CheckTrue(True); { FZMQSocket := context.Socket( st ); try // TODO: Setup method call parameters FZMQSocket.unSubscribe(filter); // TODO: Validate method results finally FZMQSocket.Free; end; } end; procedure TSocketTestCase.SocketPair; var socketbind, socketconnect: PZMQSocket; s: WideString; tsl: IZMQMsg; begin socketbind := context.Socket( stPair ); try socketbind.bind('tcp://127.0.0.1:5560'); socketconnect := context.Socket( stPair ); try socketconnect.connect('tcp://127.0.0.1:5560'); socketbind.SendString('Hello'); socketconnect.RecvString( s ); CheckEquals( 'Hello', s, 'String' ); socketbind.SendStrings(['Hello','World']); tsl := ZMQ.CreateMsg; try socketconnect.RecvMsg( tsl ); CheckEquals( 'Hello', tsl[0].S, 'Multipart 1 message 1' ); CheckEquals( 'World', tsl[1].S, 'Multipart 1 message 2' ); finally tsl := nil; end; tsl := ZMQ.CreateMsg; try tsl.AddStr('Hello'); tsl.AddStr('World'); socketbind.SendMsg( tsl ); socketconnect.RecvMsg( tsl ); CheckEquals( 'Hello', tsl[0].S, 'Multipart 2 message 1' ); CheckEquals( 'World', tsl[1].S, 'Multipart 2 message 2' ); finally tsl := nil; end; finally socketconnect.Free; end; finally socketbind.Free; end; end; initialization RegisterTest(TSocketTestCase.Suite); end.
PROGRAM CompareLengthString(INPUT, OUTPUT); CONST Equally = '0'; {=} Less = '1'; {<} More = '2'; {>} VAR F1, F2: TEXT; Ch: CHAR; PROCEDURE LetterComparison(VAR Ch1, Ch2, Result: CHAR); BEGIN {LetterComparison} IF (Ch1 < Ch2) THEN Result := Less ELSE IF (Ch1 > Ch2) THEN Result := More END; {LetterComparison} PROCEDURE StringComparison(VAR F1, F2: TEXT; VAR Result: CHAR); BEGIN {StringComparison} IF Result = Equally THEN IF (NOT(EOLN(F1))) AND (EOLN(F2)) THEN Result := More ELSE IF (EOLN(F1)) AND (NOT(EOLN(F2))) THEN Result := Less END; {StringComparison} PROCEDURE Lexico(VAR F1, F2: TEXT; VAR Result: CHAR); VAR Ch1, Ch2: CHAR; BEGIN {Lexico} RESET(F1); RESET(F2); Result := Equally; WHILE (NOT(EOLN(F1))) AND (NOT(EOLN(F2))) AND (Result = Equally) DO BEGIN READ(F1, Ch1); READ(F2, Ch2); LetterComparison(Ch1, Ch2, Result) END; StringComparison(F1, F2, Result) END; {Lexico} BEGIN {CompareLengthString} ASSIGN(F1, 'F1.TXT'); ASSIGN(F2, 'F2.TXT'); Lexico(F1, F2, Ch); WRITELN(Ch) {IF Ch = Equally THEN Ch := '='; //если не нравится оформление по заданию IF Ch = Less THEN Ch := '<'; IF Ch = More THEN Ch := '>'; WRITELN('F1 ', Ch, ' F2') } END. {CompareLengthString}
unit RRManagerEditMainHorizonInfoFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, CommonComplexCombo, StdCtrls, RRmanagerBaseObjects, RRManagerObjects, RRManagerBaseGUI; type // TfrmMainHorizonInfo = class(TFrame) TfrmMainHorizonInfo = class(TBaseFrame) gbxAll: TGroupBox; cmplxOrganization: TfrmComplexCombo; cmplxFirstStratum: TfrmComplexCombo; chbxOutOfFund: TCheckBox; private { Private declarations } function GetHorizon: TOldHorizon; function GetStructure: TOldStructure; protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; public { Public declarations } property Structure: TOldStructure read GetStructure; property Horizon: TOldHorizon read GetHorizon; constructor Create(AOwner: TComponent); override; procedure Save; override; end; implementation {$R *.DFM} { TfrmMainHorizonInfo } procedure TfrmMainHorizonInfo.ClearControls; begin cmplxOrganization.Clear; cmplxFirstStratum.Clear; if Assigned(Structure) then FEditingObject := Structure.Horizons.Add; end; constructor TfrmMainHorizonInfo.Create(AOwner: TComponent); begin inherited; EditingClass := TOldHorizon; ParentClass := TOldStructure; cmplxFirstStratum.Caption := 'Горизонт (от)'; cmplxFirstStratum.FullLoad := true; cmplxFirstStratum.DictName := 'TBL_CONCRETE_STRATUM'; cmplxOrganization.Caption := 'Организация-недропользователь'; cmplxOrganization.FullLoad := false; cmplxOrganization.DictName := 'TBL_ORGANIZATION_DICT'; end; procedure TfrmMainHorizonInfo.FillControls(ABaseObject: TBaseObject); var h: TOldHorizon; begin if not Assigned(ABaseObject) then H := Horizon else H := ABaseObject as TOldHorizon; cmplxOrganization.AddItem(H.OrganizationID, H.Organization); cmplxFirstStratum.AddItem(H.FirstStratumID, H.FirstStratum); // Check; end; procedure TfrmMainHorizonInfo.FillParentControls; begin inherited; ClearControls; cmplxOrganization.AddItem(Structure.OrganizationID, Structure.Organization); if Assigned(Structure) then FEditingObject := Structure.Horizons.Add; end; function TfrmMainHorizonInfo.GetHorizon: TOldHorizon; begin if EditingObject is TOldHorizon then Result := EditingObject as TOldHorizon else Result := nil; end; function TfrmMainHorizonInfo.GetStructure: TOldStructure; begin Result := nil; if EditingObject is TOldStructure then Result := EditingObject as TOldStructure else if EditingObject is TOldHorizon then Result := (EditingObject as TOldHorizon).Structure; end; procedure TfrmMainHorizonInfo.RegisterInspector; begin inherited; // регистрируем контролы, которые под инспектором Inspector.Add(cmplxFirstStratum.cmbxName, nil, ptString, 'горизонт (от)', false); end; procedure TfrmMainHorizonInfo.Save; begin inherited; if EditingObject is TOldStructure then FEditingObject := Structure.Horizons.Add; Horizon.OrganizationID := cmplxOrganization.SelectedElementID; Horizon.Organization := cmplxOrganization.SelectedElementName; Horizon.FirstStratumID := cmplxFirstStratum.SelectedElementID; Horizon.FirstStratum := cmplxFirstStratum.SelectedElementName; Horizon.SecondStratumID := cmplxFirstStratum.SelectedElementID; Horizon.SecondStratum := cmplxFirstStratum.SelectedElementName; Horizon.ComplexID := 0; Horizon.Complex := '<нет>'; Horizon.OutOfFund := chbxOutOfFund.Checked; end; end.
{$J+} {Writable constants} unit extbl13u; interface uses WinProcs, WinTypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OvcTCBmp, OvcTCGly, OvcTCBox, OvcTCmmn, OvcTCell, OvcTCStr, OvcTCEdt, OvcBase, OvcTable, StdCtrls, OvcUser, OvcData, OvcTCBEF, OvcTCPic, OvcPF; const MyMessage1 = WM_USER + 1; type MyDataRecord = record TF1 : String[10]; end; TForm1 = class(TForm) OvcTable1: TOvcTable; OvcController1: TOvcController; PF1: TOvcTCPictureField; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OvcTable1BeginEdit(Sender: TObject; RowNum: Longint; ColNum: Integer; var AllowIt: Boolean); private { Private declarations } public { Public declarations } procedure OnMyMessage1(var Msg : TMessage); message MyMessage1; end; var Form1: TForm1; MyData : array [1..9] of MyDataRecord; MyUserData : TOvcUserData; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var I, J : Integer; begin MyUserData := TOvcUserData.Create; MyUserData.UserCharSet[pmUser1] := ['A'..'C', '0'..'9']; Randomize; for I := 1 to 9 do with MyData[I] do begin TF1[0] := Chr(10); for J := 1 to 5 do TF1[J] := Chr(Ord('A') + (I - 1) mod 3); for J := 6 to 10 do TF1[J] := IntToStr(I)[1]; end; end; procedure TForm1.OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); begin Data := nil; if (RowNum > 0) and (RowNum < 10) then begin case ColNum of 1 : Data := @MyData[RowNum].TF1; end; end; end; procedure TForm1.OnMyMessage1(var Msg : TMessage); begin (PF1.CellEditor as TOvcPictureField).UserData := MyUserData; end; procedure TForm1.OvcTable1BeginEdit(Sender: TObject; RowNum: Longint; ColNum: Integer; var AllowIt: Boolean); begin { OnBeginEdit is called before the CellEditor exists, therefore you must post a message so that the cell can be created before trying to set the UserData property } AllowIt := True; if ColNum = 1 then PostMessage(Handle, MyMessage1, 0 , 0); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin MyUserData.Free; end; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ExtDlgs, ComCtrls, Spin, BZImageViewer, BZClasses, BZColors, BZGraphic, BZBitmap, {%H-}BZBitmapIO; type { TMainForm } TMainForm = class(TForm) Panel1 : TPanel; Panel2 : TPanel; Panel3 : TPanel; Panel4 : TPanel; GroupBox1 : TGroupBox; GroupBox2 : TGroupBox; ImgOriginal : TBZImageViewer; ImgResult : TBZImageViewer; OPD : TOpenPictureDialog; btnLoad : TButton; gbxOptions : TGroupBox; Label1 : TLabel; btnApply : TButton; rgBlurMethod : TRadioGroup; pbImageProgress : TProgressBar; lblAction : TLabel; Panel5 : TPanel; pnlMotionDirEdit : TPanel; Label2 : TLabel; fseMotionDir : TFloatSpinEdit; pnlRadiusEdit : TPanel; Label3 : TLabel; fseBlurRadius : TFloatSpinEdit; procedure btnLoadClick(Sender : TObject); procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); procedure btnApplyClick(Sender : TObject); procedure rgBlurMethodSelectionChanged(Sender : TObject); private FTempBmp : TBZBitmap; FApplyFilter : Boolean; protected FTotalProgress : Byte; Procedure DoFilterProgress(Sender: TObject; Stage: TBZProgressStage; PercentDone: Byte; RedrawNow: Boolean; Const R: TRect; Const Msg: String; Var aContinue: Boolean); public procedure ApplyFilter; end; var MainForm : TMainForm; implementation {$R *.lfm} uses BZMath; { TMainForm } procedure TMainForm.btnLoadClick(Sender : TObject); begin if OPD.Execute then begin FApplyFilter := False; FTempBmp.LoadFromFile(OPD.FileName); ImgOriginal.Picture.Bitmap.Assign(FTempBmp); ImgOriginal.Invalidate; rgBlurMethod.Enabled := true; btnApply.Enabled := True; gbxOptions.Enabled := True; pnlRadiusEdit.Enabled := False; pnlMotionDirEdit.Enabled := False; end; end; procedure TMainForm.FormCreate(Sender : TObject); begin FTempBmp := TBZBitmap.Create; FTempBmp.OnProgress := @DoFilterProgress; FTotalProgress := 0; end; procedure TMainForm.FormDestroy(Sender : TObject); begin FreeAndNil(FTempBmp); end; procedure TMainForm.btnApplyClick(Sender : TObject); begin ApplyFilter; end; procedure TMainForm.rgBlurMethodSelectionChanged(Sender : TObject); begin pnlRadiusEdit.Enabled := ((rgBlurMethod.ItemIndex >= 2) and (rgBlurMethod.ItemIndex < 12)) or (rgBlurMethod.ItemIndex = 13); pnlMotionDirEdit.Enabled := (rgBlurMethod.ItemIndex = 7) or (rgBlurMethod.ItemIndex = 10) or (rgBlurMethod.ItemIndex = 11) or (rgBlurMethod.ItemIndex = 13); end; Procedure TMainForm.DoFilterProgress(Sender : TObject; Stage : TBZProgressStage; PercentDone : Byte; RedrawNow : Boolean; Const R : TRect; Const Msg : String; Var aContinue : Boolean); begin Case Stage Of opsStarting, opsRunning: Begin FTotalProgress := PercentDone; lblAction.Caption := Msg + ' - ' + IntToStr(FTotalProgress) + '%'; pbImageProgress.Position := FTotalProgress; if FApplyFilter then begin if RedrawNow then Application.ProcessMessages; end else Application.ProcessMessages; End; opsEnding: Begin lblAction.Caption := ''; pbImageProgress.Position := 0; FTotalProgress := 0; End; End; end; procedure TMainForm.ApplyFilter; begin FApplyFilter := True; FTempBmp.BlurFilter.OnProgress := @DoFilterProgress; Case rgBlurMethod.ItemIndex of 0 : FTempBmp.BlurFilter.LinearBlur; 1 : FTempBmp.BlurFilter.FastBlur; 2 : FTempBmp.BlurFilter.BoxBlur(Round(fseBlurRadius.Value)); 3 : FTempBmp.BlurFilter.SplitBlur(Round(fseBlurRadius.Value)); 4 : FTempBmp.BlurFilter.GaussianSplitBlur(Round(fseBlurRadius.Value)); 5 : FTempBmp.BlurFilter.GaussianBlur(fseBlurRadius.Value); 6 : FTempBmp.BlurFilter.GaussianBoxBlur(fseBlurRadius.Value); 7 : FTempBmp.BlurFilter.MotionBlur(Round(fseMotionDir.Value), Round(fseBlurRadius.Value),1.0,0.0); 8 : FTempBmp.BlurFilter.RadialBlur(Round(fseBlurRadius.Value)); 9 : FTempBmp.BlurFilter.CircularBlur(Round(fseBlurRadius.Value)); 10 : FTempBmp.BlurFilter.ZoomBlur(FTempBmp.CenterX, FTempBmp.CenterY, Round(fseBlurRadius.Value),Round(fseMotionDir.Value),Round(fseMotionDir.Value)); 11 : FTempBmp.BlurFilter.RadialZoomBlur(FTempBmp.CenterX, FTempBmp.CenterY,Round(fseBlurRadius.Value),Round(fseMotionDir.Value)); 12 : FTempBmp.BlurFilter.FXAABlur; 13 : FTempBmp.BlurFilter.ThresholdBlur(fseBlurRadius.Value,ClampByte(Round(fseMotionDir.Value))); end; ImgResult.Picture.Bitmap.Assign(FTempBmp); ImgResult.Invalidate; FTempBmp.Assign(ImgOriginal.Picture.Bitmap); end; end.
(* Test and demo program for Libnodave, a free communication libray for Siemens S7. ********************************************************************** * WARNING: This and other test programs overwrite data in your PLC. * * DO NOT use it on PLC's when anything is connected to their outputs.* * This is alpha software. Use entirely on your own risk. * ********************************************************************** (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002, 2003. This is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Libnodave; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. *) uses nodave, tests {$ifdef WIN32} , windows {$endif} {$ifdef LINUX} ,oldlinux {$define UNIX_STYLE} {$endif} ; {$ifdef CYGWIN} {$define UNIX_STYLE} {$endif} procedure usage; begin writeln('Usage: testPPI [-d] [-w] serial port.'); writeln('-w will try to write to Flag words. It will overwrite FB0 to FB15 (MB0 to MB15) !'); writeln('-d will produce a lot of debug messages.'); writeln('-b will run benchmarks. Specify -b and -w to run write benchmarks.'); writeln('-m will run a test for multiple variable reads.'); writeln('-c will write 0 to the PLC memory used in write tests.'); writeln('-s will put the CPU in STOP mode.'); writeln('-r will put the CPU in RUN mode.'); writeln('--mpi=<number> will use number as the PPI adddres of the PLC. Default is 2.'); writeln('--ppi=<number> will use number as the PPI adddres of the PLC. Default is 2.'); writeln('--local=<number> will set the local PPI adddres to number. Default is 0.'); {$ifdef UNIX_STYLE} writeln('Example: testPPI -w /dev/ttyS0'); {$endif} {$ifdef WIN32} writeln('Example: testPPI -w COM1'); {$endif} end; var i, a,b,c,adrPos, doWrite, doBenchmark, doMultiple, doClear, doNewfunctions, doRun,doStop, res, saveDebug, plcMPI, localmpi: longint; d: single; di:pdaveInterface; dc:pdaveConnection; rs:daveResultSet; fds: _daveOSserialType; {$ifdef UNIX_STYLE} t1,t2:timeval; {$endif} {$ifdef WIN32} t1, t2:longint; {$endif} usec:double; p:PDU; pms:string; COMname: array[0..20] of char; begin USEC:=0; adrPos:=1; doWrite:=0; doBenchmark:=0; doMultiple:=0; doClear:=0; doNewfunctions:=0; doRun:=0; doStop:=0; plcMPI:=2; if (paramcount<1) then begin usage; halt(1); end; while (paramstr(adrPos)[1]='-') do begin if paramstr(adrPos)='-d' then begin (* daveDebug:=daveDebugAll; *) daveSetDebug(daveDebugAll); writeln('turning debug on'); end else if copy(paramstr(adrPos),1,6)='--mpi=' then begin val(copy(paramstr(adrPos),7,255),plcMPI,res); writeln('set PLC PPI adress to: ',plcMPI); end else if copy(paramstr(adrPos),1,6)='--ppi=' then begin val(copy(paramstr(adrPos),7,255),plcMPI,res); writeln('set PLC PPI adress to: ',plcMPI); end else if copy(paramstr(adrPos),1,8)='--local=' then begin val(copy(paramstr(adrPos),9,255),localMPI,res); writeln('setting local MPI adress to: ',localMPI); end else if paramstr(adrPos)='-w' then begin doWrite:=1; end else if paramstr(adrPos)='-b' then begin doBenchmark:=1; end else if paramstr(adrPos)='-m' then begin doMultiple:=1; end else if paramstr(adrPos)='-c' then begin doClear:=1; end else if paramstr(adrPos)='-n' then begin doNewfunctions:=1; end else if paramstr(adrPos)='-r' then begin doRun:=1; end else if paramstr(adrPos)='-s' then begin doStop:=1; end; adrPos:=adrPos+1; if (paramcount<adrPos) then begin usage; halt(1); end; end; writeln('fds',sizeof(fds)); pms:=paramstr(adrPos); move(pms[1], COMname,length(paramstr(adrPos))); COMname[length(paramstr(adrPos))+1]:=#0; fds.rfd:=setPort(COMname,'9600','E'); fds.wfd:=fds.rfd; writeln('fds.rfd ',longint(fds.rfd)); writeln('fds.wfd ',longint(fds.wfd)); if (fds.rfd>0) then begin di :=daveNewInterface(fds, 'IF1',localmpi, daveProtoPPI, daveSpeed187k); dc :=daveNewConnection(di,plcMPI,0,0); // insert your PPI address here (* // just try out what else might be readable in an S7-200 (on your own risk!): *) writeln('Trying to read 64 bytes (32 words) from data block 1. This is V memory of the 200.'); wait; res:=daveReadBytes(dc,daveDB,1,0,64,nil); if (res=0) then begin a:=daveGetU16(dc); writeln('VW0: ',a); a:=daveGetU16(dc); writeln('VW2: ',a); end; (* a:=daveGetU16at(dc,62); writeln('DB1:DW32: %d',a); *) writeln('Trying to read 16 bytes from FW0.'); wait; (* * Some comments about daveReadBytes(): * * The 200 family PLCs have the V area. This is accessed like a datablock with number 1. * This is not a quirk or convention introduced by libnodave, but the command transmitted * to the PLC is exactly the same that would read from DB1 of a 300 or 400. * * to read VD68 and VD72 use: * daveReadBytes(dc, daveDB, 1, 68, 6, nil); * to read VD68 and VD72 into your applications buffer appBuffer use: * daveReadBytes(dc, daveDB, 1, 68, 6, appBuffer); * to read VD68 and VD78 into your applications buffer appBuffer use: * daveReadBytes(dc, daveDB, 1, 68, 14, appBuffer); * this reads DBD68 and DBD78 and everything in between and fills the range * appBuffer+4 to appBuffer+9 with unwanted bytes, but is much faster than: * daveReadBytes(dc, daveDB, 1, 68, 4, appBuffer); * daveReadBytes(dc, daveDB, 1, 78, 4, appBuffer+4); *) res:=daveReadBytes(dc,daveFlags,0,0,16,nil); if (res=0) then begin (* * daveGetU32(dc); reads a word (2 bytes) from the current buffer position and increments * an internal pointer by 2, so next daveGetXXX() wil read from the new position behind that * word. *) a:=daveGetU32(dc); b:=daveGetU32(dc); c:=daveGetU32(dc); d:=daveGetFloat(dc); writeln('FD0: ',a); writeln('FD4: ',b); writeln('FD8: ',c); writeln('FD12:',d); (* d:=daveGetFloatAt(dc,12); writeln('FD12:',d); *) end; if(doNewfunctions<>0) then begin (* // saveDebug:=daveDebug; // daveDebug:=daveDebugAll; *) res:=daveReadBits(dc, daveInputs, 0, 2, 1,nil); writeln('function result:%d:=%s', res, daveStrerror(res)); // daveDebug:=0; res:=daveReadBits(dc, daveDB, 1, 1, 2,nil); writeln('function result:%d:=%s', res, daveStrerror(res)); res:=daveReadBits(dc, daveDB, 1, 1, 0,nil); writeln('function result:%d:=%s', res, daveStrerror(res)); res:=daveReadBits(dc, daveDB, 1, 1, 1,nil); writeln('function result:%d:=%s', res, daveStrerror(res)); a:=0; res:=daveWriteBytes(dc, daveOutputs, 0, 0, 1, @a); // daveDebug:=daveDebugAll; a:=1; res:=daveWriteBits(dc, daveOutputs, 0, 5, 1, @a); writeln('function result:', res,' = ', daveStrerror(res)); res:=daveReadBytes(dc, daveAnaOut, 0, 0, 1,nil); writeln('function result:%d:=%s', res, daveStrerror(res)); a:=2341; res:=daveWriteBytes(dc, daveAnaOut, 0, 0, 2,@a); writeln('function result:%d:=%s', res, daveStrerror(res)); // daveDebug:=saveDebug; end; if doRun<>0 then begin daveStart(dc); end; if doStop<>0 then begin daveStop(dc); end; if(doMultiple<>0) then begin writeln('Now testing read multiple variables.''This will read 1 Byte from inputs,''4 bytes from flags, 2 bytes from DB6'' and other 2 bytes from flags'); wait; davePrepareReadRequest(dc, @p); daveAddVarToReadRequest(@p,daveInputs,0,0,1); daveAddVarToReadRequest(@p,daveFlags,0,0,4); daveAddVarToReadRequest(@p,daveDB,6,20,2); daveAddVarToReadRequest(@p,daveSysInfo,0,0,24); daveAddVarToReadRequest(@p,daveFlags,0,12,2); daveAddVarToReadRequest(@p,daveAnaIn,0,0,2); daveAddVarToReadRequest(@p,daveAnaOut,0,0,2); res:=daveExecReadRequest(dc, @p, @rs); write('Input Byte 0: '); res:=daveUseResult(dc, @rs, 0); // first result if (res=0) then begin a:=daveGetU8(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); write('Flag DWord 0: '); res:=daveUseResult(dc, @rs, 1); // 2nd result if (res=0) then begin a:=daveGetS16(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); write('DB 6 Word 20 (not present in 200): '); res:=daveUseResult(dc, @rs, 2); // 3rd result if (res=0) then begin a:=daveGetS16(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); write('System Information: '); res:=daveUseResult(dc, @rs, 3); // 4th result if (res=0) then begin for i:=0 to 39 do begin a:=daveGetU8(dc); write(char(a)); end; writeln(''); end else writeln('*** Error: ',daveStrerror(res)); write('Flag Word 12: '); res:=daveUseResult(dc, @rs, 4); // 5th result if (res=0)then begin a:=daveGetU16(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); write('non existing result (we try to use 1 more than the number of items): '); res:=daveUseResult(dc, @rs, 4); // 5th result if (res=0)then begin a:=daveGetU16(dc); writeln(a); end else writeln('*** Error: %s',daveStrerror(res)); write('Analog Input Word 0:'); res:=daveUseResult(dc, @rs, 5); // 6th result if (res=0)then begin a:=daveGetU16(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); write('Analog Output Word 0:'); res:=daveUseResult(dc, @rs, 6); // 7th result if (res=0)then begin a:=daveGetU16(dc); writeln(a); end else writeln('*** Error: ',daveStrerror(res)); daveFreeResults(@rs); (* for (i:=0; i<rs.numResults;i++) begin r2:=@(rs.results[i]); writeln('result: %s length:%d',daveStrerror(r2->error), r2->length); res:=daveUseResult(dc, @rs, i); if (r2->length>0) _daveDump('bytes',r2->bytes,r2->length); if (r2->bytes!:=nil) begin _daveDump('bytes',r2->bytes,r2->length); d:=daveGetFloat(dc); writeln('FD12: %f',d); end end *) end; if(doWrite>0) then begin writeln('Now we write back these data after incrementing the first to by 1,2 and 3 and the first two floats by 1.1.'); wait; (* Attention! you need to daveSwapIed little endian variables before using them as a buffer for daveWriteBytes() or before copying them into a buffer for daveWriteBytes()! *) a:=daveSwapIed_32(a+1); daveWriteBytes(dc,daveFlags,0,0,4,@a); b:=daveSwapIed_32(b+2); daveWriteBytes(dc,daveFlags,0,4,4,@b); c:=daveSwapIed_32(c+3); daveWriteBytes(dc,daveFlags,0,8,4,@c); d:=toPLCfloat(d+1.1); daveWriteBytes(dc,daveFlags,0,12,4,@d); daveReadBytes(dc,daveFlags,0,0,16,nil); a:=daveGetU32(dc); b:=daveGetU32(dc); c:=daveGetU32(dc); d:=daveGetFloat(dc); writeln('FD0: ',a); writeln('FD4: ',b); writeln('FD8: ',c); writeln('FD12:',d); end; {doWrite} if(doClear>0) then begin writeln('Now writing 0 to the bytes FB0...FB15.'); wait(); a:=0; daveWriteBytes(dc,daveFlags,0,0,4,@a); daveWriteBytes(dc,daveFlags,0,4,4,@a); daveWriteBytes(dc,daveFlags,0,8,4,@a); daveWriteBytes(dc,daveFlags,0,12,4,@a); daveReadBytes(dc,daveFlags,0,0,16,nil); a:=daveGetU32(dc); b:=daveGetU32(dc); c:=daveGetU32(dc); d:=daveGetFloat(dc); writeln('FD0: %d',a); writeln('FD4: %d',b); writeln('FD8: %d',c); writeln('FD12: %f',d); end; { doClear} if(doBenchmark>0) then begin readBench(dc); if(doWrite>0)then begin writeBench(dc); end; {// doWrite} end; { // doBenchmark} halt(0); end else begin writeln('Couldn''t open serial port ',paramstr(adrPos)); halt(2); end; end. (* Changes: 07/19/04 added return values in main(). 09/09/04 applied patch for variable Profibus speed from Andrew Rostovtsew. 09/09/04 removed unused include byteswap.h 09/10/04 removed SZL read, it doesn?t work on 200 family. 09/11/04 added multiple variable read example code. *)
unit uOPCSetValueForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, aOPCLookupList, uOPCSetValueFrame; type TSetValueForm = class(TForm) SetValueFrame: TFrame1; Bevel1: TBevel; Button1: TButton; Button2: TButton; private { Private declarations } public { Public declarations } end; function ShowSetValueForm(var aValue: string; var aMoment: TDateTime; aLookupList: TaOPCLookupList; aRefAutoFill: Boolean; aHelpContext: THelpContext): boolean; implementation {$R *.dfm} function ShowSetValueForm(var aValue: string; var aMoment: TDateTime; aLookupList: TaOPCLookupList; aRefAutoFill: Boolean; aHelpContext: THelpContext): boolean; var aSetValueForm: TSetValueForm; begin aSetValueForm := TSetValueForm.Create(nil); try aSetValueForm.PopupParent := Application.MainForm; aSetValueForm.SetValueFrame.Value := aValue; aSetValueForm.SetValueFrame.Date := aMoment; aSetValueForm.SetValueFrame.RefAutoFill := aRefAutoFill; if Assigned(aLookupList) then aSetValueForm.SetValueFrame.Lookup := aLookupList.Items; aSetValueForm.SetValueFrame.UpdateClientAction; Result := aSetValueForm.ShowModal = mrOk; if Result then begin aValue := aSetValueForm.SetValueFrame.Value; aMoment := aSetValueForm.SetValueFrame.Date; end; finally aSetValueForm.Free; end; end; end.
unit LUX.GPU.OpenGL.Engine; interface //#################################################################### ■ uses System.Generics.Collections, Winapi.OpenGL, Winapi.OpenGLext, LUX, LUX.GPU.OpenGL, LUX.GPU.OpenGL.Buffer, LUX.GPU.OpenGL.Buffer.Verter, LUX.GPU.OpenGL.Buffer.Unifor, LUX.GPU.OpenGL.Shader, LUX.GPU.OpenGL.Progra; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortV TGLPortV = record private public Name :String; EleN :GLint; EleT :GLenum; Offs :GLuint; ///// constructor Create( const Name_:String; const EleN_:GLint; const EleT_:GLenum; const Offs_:GLuint = 0 ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortU TGLPortU = record private public Name :String; ///// constructor Create( const Name_:String ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortI TGLPortI = record private public Name :String; ///// constructor Create( const Name_:String ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsV TGLPortsV = class( TGLPorts<TGLPortV> ) private protected _Varray :TGLVarray; ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:TGLPortV ); override; procedure DelPort( const BinP_:GLuint; const Port_:TGLPortV ); override; public constructor Create( const Progra_:TGLProgra ); destructor Destroy; override; ///// メソッド procedure Add( const BinP_:GLuint; const Name_:String; const EleN_:GLint; const EleT_:GLenum; const Offs_:GLuint = 0 ); procedure Use; override; procedure Unuse; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsU TGLPortsU = class( TGLPorts<TGLPortU> ) private protected ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:TGLPortU ); override; procedure DelPort( const BinP_:GLuint; const Port_:TGLPortU ); override; public ///// メソッド procedure Add( const BinP_:GLuint; const Name_:String ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsI TGLPortsI = class( TGLPorts<TGLPortI> ) private protected ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:TGLPortI ); override; procedure DelPort( const BinP_:GLuint; const Port_:TGLPortI ); override; public ///// メソッド procedure Add( const BinP_:GLuint; const Name_:String ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLEngine IGLEngine = interface( IGLProgra ) ['{0B2FDEDE-30D3-439B-AC76-E61F9E028CD0}'] {protected} ///// アクセス function GetVerters :TGLPortsV; function GetUnifors :TGLPortsU; function GetImagers :TGLPortsI; {public} ///// プロパティ property Verters :TGLPortsV read GetVerters; property Unifors :TGLPortsU read GetUnifors; property Imagers :TGLPortsI read GetImagers; ///// メソッド procedure Use; procedure Unuse; end; TGLEngine = class( TGLProgra, IGLEngine ) private protected _Verters :TGLPortsV; _Unifors :TGLPortsU; _Imagers :TGLPortsI; ///// アクセス function GetVerters :TGLPortsV; function GetUnifors :TGLPortsU; function GetImagers :TGLPortsI; ///// イベント procedure DoOnLinked; override; public constructor Create; destructor Destroy; override; ///// プロパティ property Verters :TGLPortsV read GetVerters; property Unifors :TGLPortsU read GetUnifors; property Imagers :TGLPortsI read GetImagers; ///// メソッド procedure Use; override; procedure Unuse; override; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortV //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLPortV.Create( const Name_:String; const EleN_:GLint; const EleT_:GLenum; const Offs_:GLuint ); begin Name := Name_; EleN := EleN_; EleT := EleT_; Offs := Offs_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortU //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLPortU.Create( const Name_:String ); begin Name := Name_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortI //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLPortI.Create( const Name_:String ); begin Name := Name_; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsV //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsV.AddPort( const BinP_:GLuint; const Port_:TGLPortV ); var L :GLuint; begin L := _Progra.glGetVertLoca( Port_.Name ); with _Varray do begin Bind; glEnableVertexAttribArray( L ); with Port_ do begin case EleT of GL_INT :glVertexAttribIFormat( L, EleN, EleT, Offs ); GL_FLOAT :glVertexAttribFormat( L, EleN, EleT, GL_FALSE, Offs ); end; end; glVertexAttribBinding( L, BinP_ ); Unbind; end; end; procedure TGLPortsV.DelPort( const BinP_:GLuint; const Port_:TGLPortV ); var L :GLuint; begin L := _Progra.glGetVertLoca( Port_.Name ); with _Varray do begin Bind; glDisableVertexAttribArray( L ); Unbind; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLPortsV.Create( const Progra_:TGLProgra ); begin inherited; _Varray := TGLVarray.Create; end; destructor TGLPortsV.Destroy; begin _Varray.DisposeOf; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsV.Use; begin _Varray.Bind; end; procedure TGLPortsV.Unuse; begin _Varray.Unbind; end; //------------------------------------------------------------------------------ procedure TGLPortsV.Add( const BinP_:GLuint; const Name_:String; const EleN_:GLint; const EleT_:GLenum; const Offs_:GLuint = 0 ); var P :TGLPortV; begin with P do begin Name := Name_; EleN := EleN_; EleT := EleT_; Offs := Offs_; end; inherited Add( BinP_, P ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsU //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsU.AddPort( const BinP_:GLuint; const Port_:TGLPortU ); var L :GLuint; begin L := _Progra.glGetBlocLoca( Port_.Name ); glUniformBlockBinding( _Progra.ID, L, BinP_ ); end; procedure TGLPortsU.DelPort( const BinP_:GLuint; const Port_:TGLPortU ); begin end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsU.Add( const BinP_:GLuint; const Name_:String ); var P :TGLPortU; begin with P do begin Name := Name_; end; inherited Add( BinP_, P ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsI //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsI.AddPort( const BinP_:GLuint; const Port_:TGLPortI ); var L :GLuint; begin with _Progra do begin L := glGetUnifLoca( Port_.Name ); Use; glUniform1i( L, BinP_ ); Unuse; end; end; procedure TGLPortsI.DelPort( const BinP_:GLuint; const Port_:TGLPortI ); begin end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsI.Add( const BinP_:GLuint; const Name_:String ); var P :TGLPortI; begin with P do begin Name := Name_; end; inherited Add( BinP_, P ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLEngine //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TGLEngine.GetVerters :TGLPortsV; begin Result := _Verters; end; function TGLEngine.GetUnifors :TGLPortsU; begin Result := _Unifors; end; function TGLEngine.GetImagers :TGLPortsI; begin Result := _Imagers; end; /////////////////////////////////////////////////////////////////////// イベント procedure TGLEngine.DoOnLinked; begin _Verters.AddPorts; _Unifors.AddPorts; _Imagers.AddPorts; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLEngine.Create; begin inherited Create; _Verters := TGLPortsV.Create( Self ); _Unifors := TGLPortsU.Create( Self ); _Imagers := TGLPortsI.Create( Self ); end; destructor TGLEngine.Destroy; begin _Verters.DisposeOf; _Unifors.DisposeOf; _Imagers.DisposeOf; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGLEngine.Use; begin inherited; _Verters.Use; _Unifors.Use; _Imagers.Use; end; procedure TGLEngine.Unuse; begin _Verters.Unuse; _Unifors.Unuse; _Imagers.Unuse; inherited; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
{----------------------------------------------------------------------------------------------------------------------- # Unit ZPL2Barcodes # Unit for working with Zebra ZPL2 barcode commands. All measuring units and position information are measured in dots! For details on the ZPL2 commands please see the "ZPL2 Programming Guide" from Zebra. Author: TheDelphiCoder -----------------------------------------------------------------------------------------------------------------------} unit ZPL2Barcodes; interface uses Windows, SysUtils, Classes, Graphics, Math, ZPL2, zint, zint_render_bmp; type /// <summary> /// Base class for all ZPL2 Barcode items. /// </summary> TZPL2Barcode = class abstract(TZPL2TextLabelItem) strict protected function GetScale: single; virtual; abstract; procedure SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); virtual; abstract; /// <summary> /// Abstract method for setting parameters of the "TZintBarcode" object, is called in template method /// <see cref="GetBitmap"/>. /// </summary> procedure SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); virtual; abstract; public /// <summary> /// Template method for all Barcode types, must NOT be overriden in subclasses!. /// </summary> procedure GetBitmap(Bitmap: TBitmap); override; end; /// <summary> /// Base class for all ZPL2 1D Barcode items. /// </summary> TZPL2Barcode1D = class abstract(TZPL2Barcode) strict private /// <summary> /// Height of the barcode item. /// </summary> FHeight: word1_32000; /// <summary> /// Width of the narrow lines of the barcode item. /// </summary> FLinewidth: word1_32000; /// <summary> /// Prints the content of the barcode item in plain text below the barcode itself. /// </summary> FPrintInterpretationLine: boolean; /// <summary> /// The content is printed in plain text above the barcode, if /// <see cref="TZPL2Barcode1D|FPrintInterpretationLine" /> equals <c>true</c>; this option only affects labels printed with a /// ZPL2 printer. /// </summary> FPrintInterpretationLineAboveCode: boolean; procedure SetHeight(const Value: word1_32000); procedure SetLinewidth(const Value: word1_32000); procedure SetPrintInterpretationLine(const Value: boolean); procedure SetPrintInterpretationLineAboveCode(const Value: boolean); strict protected function GetScale: single; override; procedure SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); override; /// <summary> /// Sets parameters for 1D barcodes, must be overriden by subclasses and called in the derived method. /// </summary> procedure SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); override; public /// <summary> /// Returns the complete ZPL2 command of the item, including field origin and/or field separator and/or other /// data, if necessary. /// </summary> function AsString: string; override; constructor Create(AOwner: TComponent); override; published /// <summary> /// Property for the barcode height. /// </summary> property Height: word1_32000 read FHeight write SetHeight; /// <summary> /// Property for the narrow line width of the barcode. /// </summary> property Linewidth: word1_32000 read FLinewidth write SetLinewidth; /// <summary> /// Property for the intepretation line of the barcode. /// </summary> property PrintInterpretationLine: boolean read FPrintInterpretationLine write SetPrintInterpretationLine; /// <summary> /// Property for the position of the barcode interpretation line. /// </summary> property PrintInterpretationLineAboveCode: boolean read FPrintInterpretationLineAboveCode write SetPrintInterpretationLineAboveCode; end; /// <summary> /// Class for ZPL2 Barcode Code 128 item /// <note type="warning"> /// Only Type B is supported /// </note> /// </summary> TZPL2BarcodeCode128 = class(TZPL2Barcode1D) strict protected /// <summary> /// Method for returning the ZPL2 command of the item. /// </summary> function GetCommand: string; override; /// <summary> /// Sets parameters for Code128 barcode; inherited method MUST be called. /// </summary> procedure SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); override; public constructor Create(AOwner: TComponent); override; end; TZPL2BarcodeCode128Class = class of TZPL2BarcodeCode128; /// <summary> /// Class for ZPL2 Barcode Code 39 item. /// </summary> TZPL2BarcodeCode39 = class(TZPL2Barcode1D) strict private /// <summary> /// Switch for determining the useage of a checksum digit. /// </summary> FMod43CheckDigit: boolean; procedure SetMod43CheckDigit(const Value: boolean); strict protected /// <summary> /// Method for returning the ZPL2 command of the item. /// </summary> function GetCommand: string; override; /// <summary> /// Sets parameters for Code39 barcode; inherited method MUST be called. /// </summary> procedure SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); override; public constructor Create(AOwner: TComponent); override; published /// <summary> /// Property for the Mod43CheckDigit switch. /// </summary> property Mod43CheckDigit: boolean read FMod43CheckDigit write SetMod43CheckDigit; end; TZPL2BarcodeCode39Class = class of TZPL2BarcodeCode39; /// <summary> /// Class for ZPL2 Datamatrix item. /// </summary> TZPL2BarcodeDatamatrix = class(TZPL2Barcode) strict private /// <summary> /// Size of each individual symbol element. /// </summary> FModulsize: word1_4095; /// <summary> /// ECC level of the Datamatrix code, only ECC200 is used for Bitmap drawing. /// </summary> FQualityLevel: TZPL2QualityLevel; procedure SetModulsize(const Value: word1_4095); procedure SetQualityLevel(const Value: TZPL2QualityLevel); strict protected /// <summary> /// Method for returning the ZPL2 command of the item. /// </summary> function GetCommand: string; override; function GetScale: single; override; procedure SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); override; /// <summary> /// Sets parameters for Datamatrix code. /// </summary> procedure SetDrawingParams(Zint: TZintSymbol; RenderTarget: TZintRenderTargetBMP); override; public constructor Create(AOwner: TComponent); override; /// <summary> /// Returns the complete ZPL2 command of the item, including field origin and/or field separator and/or other /// data, if necessary. /// </summary> function AsString: string; override; published /// <summary> /// Property for the symbol element size of the Datamatrix code. /// </summary> property Modulsize: word1_4095 read FModulsize write SetModulsize; /// <summary> /// Property for the ECC quality level of the Datamatrix code. /// </summary> property QualityLevel: TZPL2QualityLevel read FQualityLevel write SetQualityLevel; end; TZPL2BarcodeDatamatrixClass = class of TZPL2BarcodeDatamatrix; /// <summary> /// Class for ZPL2 QR-Code item. /// </summary> TZPL2BarcodeQR = class(TZPL2Barcode) strict private /// <summary> /// Size of each individual symbol element. /// </summary> FMagnificationFactor: byte1_10; /// <summary> /// error correction level of the QR code. /// </summary> FErrorCorrectionLevel: TZPL2ErrorCorrectionLevel; procedure SetErrorCorrectionLevel(const Value: TZPL2ErrorCorrectionLevel); procedure SetMagnificationFactor(const Value: byte1_10); strict protected /// <summary> /// Method for returning the ZPL2 command of the item. /// </summary> function GetCommand: string; override; function GetScale: single; override; procedure SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); override; /// <summary> /// Sets parameters for QR code. /// </summary> procedure SetDrawingParams(Zint: TZintSymbol; RenderTarget: TZintRenderTargetBMP); override; public constructor Create(AOwner: TComponent); override; /// <summary> /// Returns the complete ZPL2 command of the item, including field origin and/or field separator and/or other /// data, if necessary. /// </summary> function AsString: string; override; published /// <summary> /// Property for the symbol element size of the QR code. /// </summary> property MagnificationFactor: byte1_10 read FMagnificationFactor write SetMagnificationFactor; /// <summary> /// Property for the error correction level of the QR code. /// </summary> property ErrorCorrectionLevel: TZPL2ErrorCorrectionLevel read FErrorCorrectionLevel write SetErrorCorrectionLevel; end; TZPL2BarcodeQRClass = class of TZPL2BarcodeQR; function CreateBarcodeCode128(const X, Y: word0_32000; const Text: string; const Height: word1_32000; const Linewidth: word1_32000 = 1; const PrintInterpretationLine: boolean = false; const PrintInterpretationLineAboveCode: boolean = false): TZPL2BarcodeCode128; function CreateBarcodeCode39(const X, Y: word0_32000; const Text: string; const Height: word1_32000; const Mod43CheckDigit: boolean = false; const Linewidth: word1_32000 = 1; const PrintInterpretationLine: boolean = false; const PrintInterpretationLineAboveCode: boolean = false): TZPL2BarcodeCode39; function CreateBarcodeDatamatrix(const X, Y: word0_32000; const Text: string; const Modulsize: word1_4095 = 3; const QualityLevel: TZPL2QualityLevel = ql_200): TZPL2BarcodeDatamatrix; function CreateBarcodeQR(const X, Y: word0_32000; const Text: string; const MagnificationFactor: byte1_10 = 3; const ErrorCorrectionLevel: TZPL2ErrorCorrectionLevel = eclStandardLevel): TZPL2BarcodeQR; implementation uses zint_helper; {$region 'Unit Methods'} function CreateBarcodeCode128(const X, Y: word0_32000; const Text: string; const Height: word1_32000; const Linewidth: word1_32000; const PrintInterpretationLine: boolean; const PrintInterpretationLineAboveCode: boolean): TZPL2BarcodeCode128; begin result := TZPL2BarcodeCode128.Create(nil); result.X := X; result.Y := Y; result.Text := Text; result.Height := Height; result.Linewidth := Linewidth; result.PrintInterpretationLine := PrintInterpretationLine; result.PrintInterpretationLineAboveCode := PrintInterpretationLineAboveCode; end; function CreateBarcodeCode39(const X, Y: word0_32000; const Text: string; const Height: word1_32000; const Mod43CheckDigit: boolean; const Linewidth: word1_32000; const PrintInterpretationLine: boolean; const PrintInterpretationLineAboveCode: boolean): TZPL2BarcodeCode39; begin result := TZPL2BarcodeCode39.Create(nil); result.X := X; result.Y := Y; result.Text := Text; result.Height := Height; result.Mod43CheckDigit := Mod43CheckDigit; result.Linewidth := Linewidth; result.PrintInterpretationLine := PrintInterpretationLine; result.PrintInterpretationLineAboveCode := PrintInterpretationLineAboveCode; end; function CreateBarcodeDatamatrix(const X, Y: word0_32000; const Text: string; const Modulsize: word1_4095; const QualityLevel: TZPL2QualityLevel): TZPL2BarcodeDatamatrix; begin result := TZPL2BarcodeDatamatrix.Create(nil); result.X := X; result.Y := Y; result.Text := Text; result.Modulsize := Modulsize; result.QualityLevel := QualityLevel; end; function CreateBarcodeQR(const X, Y: word0_32000; const Text: string; const MagnificationFactor: byte1_10; const ErrorCorrectionLevel: TZPL2ErrorCorrectionLevel): TZPL2BarcodeQR; begin result := TZPL2BarcodeQR.Create(nil); result.X := X; result.Y := Y; result.Text := Text; result.MagnificationFactor := MagnificationFactor; result.ErrorCorrectionLevel := ErrorCorrectionLevel; end; type EBitmapError = class(Exception); function RotateScanLine90(const angle: integer; const Bitmap: TBitmap): TBitmap; const MaxPixelCount = 65536; // or some other arbitrarily large value type TRGBArray = array[0..MaxPixelCount - 1] of TRGBTriple; pRGBArray = ^TRGBArray; { These four internal functions parallel the four cases in rotating a bitmap using the Pixels property. See the RotatePixels example on the Image Processing page of efg's Computer Lab for an example of the use of the Pixels property (which is very slow). } /// <summary> /// A Bitmap.Assign could be used for a simple copy. A complete example using ScanLine is included here to help /// explain the other three cases. /// </summary> function SimpleCopy: TBitmap; var i: integer; j: integer; rowIn: pRGBArray; rowOut: pRGBArray; begin result := TBitmap.Create; result.Width := Bitmap.Width; result.Height := Bitmap.Height; result.PixelFormat := Bitmap.PixelFormat; // only pf24bit for now // Out[i, j] = In[i, j] for j := 0 to Bitmap.Height - 1 do begin rowIn := Bitmap.ScanLine[j]; rowOut := result.ScanLine[j]; // Could optimize the following by using a function like CopyMemory // from the Windows unit. for i := 0 to Bitmap.Width - 1 do begin // Why does this crash with RowOut[i] := RowIn[i]? Alignment? // Use this longer form as workaround. with rowOut[i] do begin rgbtRed := rowIn[i].rgbtRed; rgbtGreen := rowIn[i].rgbtGreen; rgbtBlue := rowIn[i].rgbtBlue; end end end end { SimpleCopy }; function Rotate90DegreesCounterClockwise: TBitmap; var i: integer; j: integer; rowIn: pRGBArray; begin result := TBitmap.Create; result.Width := Bitmap.Height; result.Height := Bitmap.Width; result.PixelFormat := Bitmap.PixelFormat; // only pf24bit for now // Out[j, Right - i - 1] = In[i, j] for j := 0 to Bitmap.Height - 1 do begin rowIn := Bitmap.ScanLine[j]; for i := 0 to Bitmap.Width - 1 do pRGBArray(result.ScanLine[Bitmap.Width - i - 1])[j] := rowIn[i] end end { Rotate90DegreesCounterClockwise }; /// <summary> /// Could use <see cref="Rotate90DegreesCounterClockwise"/> twice to get a <c>Rotate180DegreesCounterClockwise</c>. /// Rotating 180 degrees is the same as a Flip and Reverse. /// </summary> function Rotate180DegreesCounterClockwise: TBitmap; var i: integer; j: integer; rowIn: pRGBArray; rowOut: pRGBArray; begin result := TBitmap.Create; result.Width := Bitmap.Width; result.Height := Bitmap.Height; result.PixelFormat := Bitmap.PixelFormat; // only pf24bit for now // Out[Right - i - 1, Bottom - j - 1] = In[i, j] for j := 0 to Bitmap.Height - 1 do begin rowIn := Bitmap.ScanLine[j]; rowOut := result.ScanLine[Bitmap.Height - j - 1]; for i := 0 to Bitmap.Width - 1 do rowOut[Bitmap.Width - i - 1] := rowIn[i] end end { Rotate180DegreesCounterClockwise }; /// <summary> /// Could use <see cref="Rotate90DegreesCounterClockwise"/> three times to get a Rotate270DegreesCounterClockwise. /// </summary> function Rotate270DegreesCounterClockwise: TBitmap; var i: integer; j: integer; rowIn: pRGBArray; begin result := TBitmap.Create; result.Width := Bitmap.Height; result.Height := Bitmap.Width; result.PixelFormat := Bitmap.PixelFormat; // only pf24bit for now // Out[Bottom - j - 1, i] = In[i, j] for j := 0 to Bitmap.Height - 1 do begin rowIn := Bitmap.ScanLine[j]; for i := 0 to Bitmap.Width - 1 do pRGBArray(result.ScanLine[i])[Bitmap.Height - j - 1] := rowIn[i] end end { Rotate270DegreesCounterClockwise }; begin if Bitmap.PixelFormat <> pf24bit then raise EBitmapError.Create('Can Rotate90 only 24-bit bitmap'); if (angle >= 0) and (angle mod 90 <> 0) then raise EBitmapError.Create('Rotate90: Angle not positive multiple of 90 degrees'); case (angle div 90) mod 4 of 0: result := SimpleCopy; 1: result := Rotate90DegreesCounterClockwise; // Anticlockwise for the Brits 2: result := Rotate180DegreesCounterClockwise; 3: result := Rotate270DegreesCounterClockwise else result := nil // avoid compiler warning end; end { RotateScanLine90 }; {$endregion} {$region 'TZPL2Barcode'} procedure TZPL2Barcode.GetBitmap(Bitmap: TBitmap); var bmp, bmp2: TBitmap; ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP; begin ZintSymbol := TZintSymbol.Create(nil); RenderTarget := TZintRenderTargetBMP.Create(nil); bmp := TBitmap.Create; bmp2 := nil; try try //bmp.PixelFormat := Bitmap.PixelFormat; bmp.PixelFormat := pf24bit; RenderTarget.Bitmap := bmp; RenderTarget.RenderAdjustMode := ramInflate; SetDrawingParams(ZintSymbol, RenderTarget); ZintSymbol.primary := StrToArrayOfChar(Text); ZintSymbol.Encode(Text); RenderTarget.Render(ZintSymbol); case Rotation of zrROTATE_90_DEGREES: bmp2 := RotateScanLine90(90, bmp); zrROTATE_180_DEGREES: bmp2 := RotateScanLine90(180, bmp); zrROTATE_270_DEGREES: bmp2 := RotateScanLine90(270, bmp); else bmp2 := RotateScanLine90(0, bmp); end; SetBitmapSize(Bitmap, bmp2); StretchBlt(Bitmap.Canvas.Handle, 0, 0, Bitmap.Width, Bitmap.Height, bmp2.Canvas.Handle, 0, 0, bmp2.Width, bmp2.Height, SRCCOPY); finally RenderTarget.Free; ZintSymbol.Free; bmp.Free; bmp2.Free; end; except raise end; end; {$endregion} {$region 'TZPL2Barcode1D' } function TZPL2Barcode1D.AsString: string; begin result := ZPL2_BY + IntToStr(FLinewidth) + GetFieldOrigin + GetCommand + GetFieldSeparator; end; constructor TZPL2Barcode1D.Create(AOwner: TComponent); begin inherited; ShowHint := true; Height := 20; Linewidth := 2; PrintInterpretationLine := false; PrintInterpretationLineAboveCode := false; end; function TZPL2Barcode1D.GetScale: single; begin result := FLinewidth / 1; end; procedure TZPL2Barcode1D.SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); begin Target_Bitmap.SetSize(Round(Source_Bitmap.Width * GetScale), Source_Bitmap.Height); end; procedure TZPL2Barcode1D.SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); begin RenderTarget.ShowText := FPrintInterpretationLine; RenderTarget.HeightDesired := Round(FHeight); if RenderTarget.ShowText then begin RenderTarget.HeightDesired := Round(RenderTarget.HeightDesired + RenderTarget.Font.Size * GetScale + RenderTarget.Whitespace.Bottom.Modules + RenderTarget.TextSpacing.Top.Modules); end; end; procedure TZPL2Barcode1D.SetHeight(const Value: word1_32000); begin FHeight := Value; Invalidate; end; procedure TZPL2Barcode1D.SetLinewidth(const Value: word1_32000); begin FLinewidth := Value; Invalidate; end; procedure TZPL2Barcode1D.SetPrintInterpretationLine(const Value: boolean); begin FPrintInterpretationLine := Value; Invalidate; end; procedure TZPL2Barcode1D.SetPrintInterpretationLineAboveCode(const Value: boolean); begin FPrintInterpretationLineAboveCode := Value; Invalidate; end; {$endregion} {$region 'TZPL2BarcodeCode128' } constructor TZPL2BarcodeCode128.Create(AOwner: TComponent); begin inherited; Text := 'Barcode128'; end; function TZPL2BarcodeCode128.GetCommand: string; begin // The last parameter (UCC check digit) is set to "N" by default! result := Format(ZPL2_BC + '%s,%u,%s,%s,%s', [ZPL2RotationChar[Rotation], Height, ZPL2YesNoChar[PrintInterpretationLine], ZPL2YesNoChar[PrintInterpretationLineAboveCode], ZPL2YesNoChar[false]]) + FormatTextForLabel; end; procedure TZPL2BarcodeCode128.SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); begin inherited; ZintSymbol.SymbolType := zsCODE128; end; {$endregion} {$region 'TZPL2BarcodeCode39' } constructor TZPL2BarcodeCode39.Create(AOwner: TComponent); begin inherited; Text := 'Barcode39'; Mod43CheckDigit := false; end; function TZPL2BarcodeCode39.GetCommand: string; begin result := Format(ZPL2_B3 + '%s,%s,%u,%s,%s,%s', [ZPL2RotationChar[Rotation], ZPL2YesNoChar[FMod43CheckDigit], Height, ZPL2YesNoChar[PrintInterpretationLine], ZPL2YesNoChar[PrintInterpretationLineAboveCode], ZPL2YesNoChar[false]]) + FormatTextForLabel; end; procedure TZPL2BarcodeCode39.SetDrawingParams(ZintSymbol: TZintSymbol; RenderTarget: TZintRenderTargetBMP); begin inherited; ZintSymbol.SymbolType := zsCODE39; end; procedure TZPL2BarcodeCode39.SetMod43CheckDigit(const Value: boolean); begin FMod43CheckDigit := Value; Invalidate; end; {$endregion} {$region 'TZPL2BarcodeDatamatrix' } function TZPL2BarcodeDatamatrix.AsString: string; begin result := GetFieldOrigin + GetCommand + GetFieldSeparator; end; constructor TZPL2BarcodeDatamatrix.Create(AOwner: TComponent); begin inherited; Text := 'Datamatrix'; ShowHint := true; Modulsize := 3; QualityLevel := ql_200; end; function TZPL2BarcodeDatamatrix.GetCommand: string; begin result := Format(ZPL2_BX + '%s,%u,%s,,,,~', [ZPL2RotationChar[Rotation], FModulsize, IntToStr(Ord(FQualityLevel))]) + FormatTextForLabel; end; function TZPL2BarcodeDatamatrix.GetScale: single; begin result := FModulsize; end; procedure TZPL2BarcodeDatamatrix.SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); begin Target_Bitmap.SetSize(Round(Source_Bitmap.Width * GetScale), Round(Source_Bitmap.Height * GetScale)); end; procedure TZPL2BarcodeDatamatrix.SetDrawingParams(Zint: TZintSymbol; RenderTarget: TZintRenderTargetBMP); begin Zint.SymbolType := zsDATAMATRIX; Zint.DatamatrixOptions.ForceSquare := true; Zint.DatamatrixOptions.Size := dmsAuto; RenderTarget.ShowText := false; end; procedure TZPL2BarcodeDatamatrix.SetModulsize(const Value: word1_4095); begin FModulsize := Value; Invalidate; end; procedure TZPL2BarcodeDatamatrix.SetQualityLevel(const Value: TZPL2QualityLevel); begin FQualityLevel := Value; Invalidate; end; {$endregion} {$region 'TZPL2BarcodeQR' } function TZPL2BarcodeQR.AsString: string; begin result := GetFieldOrigin + GetCommand + GetFieldSeparator; end; constructor TZPL2BarcodeQR.Create(AOwner: TComponent); begin inherited Create(AOwner); Text := 'QR-Code'; Rotation := zrNO_ROTATION; ShowHint := true; ErrorCorrectionLevel := eclHighDensityLevel; MagnificationFactor := 3; end; function TZPL2BarcodeQR.GetCommand: string; const MODEL = 2; begin result := Format(ZPL2_BQ + '%s,%u,%u', [ZPL2RotationChar[Rotation], MODEL, FMagnificationFactor]) + FormatTextForLabel; Insert(ZPL2ErrorCorrectionLevelChar[FErrorCorrectionLevel] + 'A,', result, Pos(ZPL2_FD, result) + Length(ZPL2_FD)); end; function TZPL2BarcodeQR.GetScale: single; begin result := FMagnificationFactor; end; procedure TZPL2BarcodeQR.SetBitmapSize(Target_Bitmap, Source_Bitmap: TBitmap); begin Target_Bitmap.SetSize(Round(Source_Bitmap.Width * GetScale), Round(Source_Bitmap.Height * GetScale)); end; procedure TZPL2BarcodeQR.SetDrawingParams(Zint: TZintSymbol; RenderTarget: TZintRenderTargetBMP); begin Zint.SymbolType := zsQRCODE; Zint.QRCodeOptions.Size := qrsAuto; case FErrorCorrectionLevel of eclHighDensityLevel: Zint.QRCodeOptions.ECCLevel := qreLevelL; eclStandardLevel: Zint.QRCodeOptions.ECCLevel := qreLevelM; eclHighReliabilityLevel: Zint.QRCodeOptions.ECCLevel := qreLevelQ; eclUltraHighReliabilityLevel: Zint.QRCodeOptions.ECCLevel := qreLevelH; end; RenderTarget.ShowText := false; end; procedure TZPL2BarcodeQR.SetErrorCorrectionLevel(const Value: TZPL2ErrorCorrectionLevel); begin FErrorCorrectionLevel := Value; Invalidate; end; procedure TZPL2BarcodeQR.SetMagnificationFactor(const Value: byte1_10); begin FMagnificationFactor := Value; Invalidate; end; {$endregion} end.
unit Ctl; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/Utils // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Uses SysUtils, IOUtils, PropSet, Log; Type TControlFile = Type TPropertySet; TCtlFileHelper = record helper for TControlFile public Constructor Create(ControlFilename: String); Function Read(ControlFilename: String): Boolean; Function InpFileName(const Name: string; Optional: Boolean = false): String; Function InpProperties(const Name: string; Optional: Boolean = false): TPropertySet; Function OutpFileName(const Name: string; Optional: Boolean = false): String; Function OutpProperties(const Name: string; Optional: Boolean = false): TPropertySet; end; Var CtlFile: TControlFile; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Constructor TCtlFileHelper.Create(ControlFilename: String); begin Read(ControlFilename); end; Function TCtlFileHelper.Read(ControlFilename: String): Boolean; begin ControlFileName := ExpandFileName(ControlFileName); if FileExists(ControlFileName) then begin Result := true; Self.NameValueSeparator := ':'; Self.PropertiesSeparator := ';'; Self.BaseDirectory := ExtractFileDir(ControlFileName); Self.AsStrings := TFile.ReadAllLines(ControlFileName); Self.Lock; end else begin Result := false; writeln('Control file does not exist'); end; end; Function TCtlFileHelper.InpFileName(const Name: string; Optional: Boolean = false): String; begin Result := ToFileName(Name); if Result <> '' then if FileExists(Result) then begin if LogFile <> nil then LogFile.InputFile(Name,Result); end else raise Exception.Create('File does not exist (' + Name + ')') else if not Optional then raise Exception.Create('Missing file name (' + Name + ')') end; Function TCtlFileHelper.InpProperties(const Name: string; Optional: Boolean = false): TPropertySet; Var Value: String; begin if Contains(Name,Value) and (Value <> '') then begin Result := TPropertySet.Create('=',';',true); Result.AsString := Value; if Result.Contains('file',Value) then begin Value := TPropertySet.BaseDirectory.AbsolutePath(Value); if FileExists(Value) then begin if LogFile <> nil then LogFile.InputFile(Name,Value); end else raise Exception.Create('File does not exist (' + Name + ')') end else raise Exception.Create('Missing file property (' + Name + ')') end else begin if not Optional then raise Exception.Create('Missing properties (' + Name + ')') end; end; Function TCtlFileHelper.OutpFileName(const Name: string; Optional: Boolean = false): String; begin Result := ToFileName(Name); if Result <> '' then begin if LogFile <> nil then LogFile.OutputFile(Name,Result); end else if not Optional then raise Exception.Create('Missing file name (' + Name + ')') end; Function TCtlFileHelper.OutpProperties(const Name: string; Optional: Boolean = false): TPropertySet; Var Value: String; begin if Contains(Name,Value) and (Value <> '') then begin Result := TPropertySet.Create('=',';',true); Result.AsString := Value; if Result.Contains('file',Value) then begin Value := TPropertySet.BaseDirectory.AbsolutePath(Value); if LogFile <> nil then LogFile.OutputFile(Name,Value); end else raise Exception.Create('Missing file property (' + Name + ')') end else begin if not Optional then raise Exception.Create('Missing properties (' + Name + ')') end; end; end.
{******************************************} { } { FastReport v2.53 } { Interpreter } { } {Copyright(c) 1998-2004 by FastReports Inc.} { } {******************************************} unit FR_Intrp; interface {$I FR.inc} uses Classes, SysUtils, FR_Pars {$IFDEF 1CScript} , interp_tp, sint_tr, interp_ex, memmngr{, debugW} {$ENDIF}; type // This is a simple Pascal-like interpreter. Input code can contain // if-then-else, while-do, repeat-until, for, goto operators, begin-end blocks. // Code can also contain expressions, variables, functions and methods. // There is three events for handling variables and functions(methods): // GetValue, SetValue and DoFunction. // To execute code, call PrepareScript and then DoScript. TfrInterpretator = class(TObject) protected FParser: TfrParser; {$IFDEF 1CScript} FInterpreter : TInterpreter; private FOnGetValue: TGetPValueEvent; procedure GetVariable(Sender : TObject; mIndex : Integer; VarName : String; var Ok : Boolean; var Result : TVariant); procedure SetVariable(Sender : TObject; mIndex : Integer; VarName : String; var Ok : Boolean; var Result : TVariant); procedure FOnSetValue(Value : TGetPValueEvent); {$ENDIF} public Global : Boolean; constructor Create; destructor Destroy; override; procedure GetValue(const Name: String; var Value: Variant); virtual; procedure SetValue(const Name: String; Value: Variant); virtual; procedure DoFunction(const name: String; p1, p2, p3: Variant; var val: Variant); virtual; procedure PrepareScript(MemoFrom, MemoTo, MemoErr: TStrings); virtual; procedure DoScript(Memo: TStrings); virtual; {$IFDEF 1CScript} function QueryValue(Name : String) : Variant; property OnGetValue: TGetPValueEvent read FOnGetValue write FOnSetValue; {$ENDIF} procedure SplitExpressions(Memo, MatchFuncs, SplitTo: TStrings; Variables: TfrVariables); end; implementation {$IFNDEF 1CScript} type TCharArray = Array[0..31999] of Char; PCharArray = ^TCharArray; lrec = record name: String[16]; n: Integer; end; {$ENDIF} const ttIf = #1; ttGoto = #2; ttProc = #3; {$IFNDEF 1CScript} var labels: Array[0..100] of lrec; labc: Integer; {$ENDIF} function Remain(const S: String; From: Integer): String; begin Result := Copy(s, From, MaxInt); end; function GetIdentify(const s: String; var i: Integer): String; var k: Integer; begin while (i <= Length(s)) and (s[i] <= ' ') do Inc(i); k := i; while (i <= Length(s)) and (s[i] > ' ') do Inc(i); Result := Copy(s, k, i - k); end; { TfrInterpretator } {$IFNDEF 1CScript} constructor TfrInterpretator.Create; begin inherited Create; FParser := TfrParser.Create; FParser.OnGetValue := GetValue; FParser.OnFunction := DoFunction; end; destructor TfrInterpretator.Destroy; begin FParser.Free; inherited Destroy; end; procedure TfrInterpretator.PrepareScript(MemoFrom, MemoTo, MemoErr: TStrings); var i, j, cur, lastp: Integer; s, bs: String; len: Integer; buf: PCharArray; Error: Boolean; CutList: TStringList; procedure DoCommand; forward; procedure DoBegin; forward; procedure DoIf; forward; procedure DoRepeat; forward; procedure DoWhile; forward; procedure DoGoto; forward; procedure DoEqual; forward; procedure DoExpression; forward; procedure DoSExpression; forward; procedure DoTerm; forward; procedure DoFactor; forward; procedure DoVariable; forward; procedure DoConst; forward; procedure DoLabel; forward; procedure DoFunc; forward; procedure DoFuncId; forward; function last: Integer; begin Result := MemoTo.Count; end; function CopyArr(cur, n: Integer): String; begin SetLength(Result, n); Move(buf^[cur], Result[1], n); end; procedure AddLabel(s: String; n: Integer); var i: Integer; f: Boolean; begin f := True; for i := 0 to labc - 1 do if labels[i].name = s then f := False; if f then begin labels[labc].name := s; labels[labc].n := n; Inc(labc); end; end; procedure SkipSpace; begin while (buf^[cur] <= ' ') and (cur < len) do Inc(cur); end; function GetToken: String; var n, j: Integer; label 1; begin 1: SkipSpace; j := cur; while (buf^[cur] > ' ') and (cur < len) do begin if (buf^[cur] = '{') and (buf^[j] <> #$27) then begin n := cur; while (buf^[cur] <> '}') and (cur < len) do Inc(cur); CutList.Add(IntToStr(n) + ' ' + IntToStr(cur - n + 1)); Move(buf^[cur + 1], buf^[n], len - cur); Dec(len, cur - n + 1); cur := n; goto 1; end else if (buf^[cur] = '/') and (buf^[cur + 1] = '/') and (buf^[j] <> #$27) then begin n := cur; while (buf^[cur] <> #13) and (cur < len) do Inc(cur); CutList.Add(IntToStr(n) + ' ' + IntToStr(cur - n + 1)); Move(buf^[cur + 1], buf^[n], len - cur); Dec(len, cur - n + 1); cur := n; goto 1; end; Inc(cur); end; Result := AnsiUpperCase(CopyArr(j, cur - j)); if Result = '' then Result := ' '; end; procedure AddError(s: String); var i, j, c: Integer; s1: String; begin Error := True; cur := lastp; SkipSpace; for i := 0 to CutList.Count - 1 do begin s1 := CutList[i]; j := StrToInt(Copy(s1, 1, Pos(' ', s1) - 1)); c := StrToInt(Copy(s1, Pos(' ', s1) + 1, 255)); if lastp >= j then Inc(cur, c); end; Inc(cur); i := 0; c := 0; j := 0; while i < MemoFrom.Count do begin s1 := MemoFrom[i]; if c + Length(s1) + 1 < cur then c := c + Length(s1) + 1 else begin j := cur - c; break; end; Inc(i); end; MemoErr.Add('Line ' + IntToStr(i + 1) + '/' + IntToStr(j) + ': ' + s); cur := lastp; end; procedure ProcessBrackets(var i: Integer); var c: Integer; fl1, fl2: Boolean; begin fl1 := True; fl2 := True; c := 0; Dec(i); repeat Inc(i); if fl1 and fl2 then if buf^[i] = '[' then Inc(c) else if buf^[i] = ']' then Dec(c); if fl1 then if buf^[i] = '"' then fl2 := not fl2; if fl2 then if buf^[i] = '''' then fl1 := not fl1; until (c = 0) or (i >= len); end; {----------------------------------------------} procedure DoDigit; begin while (buf^[cur] <= ' ') and (cur < len) do Inc(cur); if buf^[cur] in ['0'..'9'] then while (buf^[cur] in ['0'..'9']) and (cur < len) do Inc(cur) else Error := True; end; procedure DoBegin; label 1; begin 1:DoCommand; if Error then Exit; lastp := cur; bs := GetToken; if (bs = '') or (bs[1] = ';') then begin cur := cur - Length(bs) + 1; goto 1; end else if (bs = 'END') or (bs = 'END;') then cur := cur - Length(bs) + 3 else AddError('Need ";" or "end" here'); end; procedure DoIf; var nsm, nl, nl1: Integer; begin nsm := cur; DoExpression; if Error then Exit; bs := ttIf + ' ' + CopyArr(nsm, cur - nsm); nl := last; MemoTo.Add(bs); lastp := cur; if GetToken = 'THEN' then begin DoCommand; if Error then Exit; nsm := cur; if GetToken = 'ELSE' then begin nl1 := last; MemoTo.Add(ttGoto + ' '); bs := MemoTo[nl]; bs[2] := Chr(last); bs[3] := Chr(last div 256); MemoTo[nl] := bs; DoCommand; bs := MemoTo[nl1]; bs[2] := Chr(last); bs[3] := Chr(last div 256); MemoTo[nl1] := bs; end else begin bs := MemoTo[nl]; bs[2] := Chr(last); bs[3] := Chr(last div 256); MemoTo[nl] := bs; cur := nsm; end; end else AddError('Need "then" here'); end; procedure DoRepeat; label 1; var nl, nsm: Integer; begin nl := last; 1:DoCommand; if Error then Exit; lastp := cur; bs := GetToken; if bs = 'UNTIL' then begin nsm := cur; DoExpression; MemoTo.Add(ttIf + Chr(nl) + Chr(nl div 256) + CopyArr(nsm, cur - nsm)); end else if bs[1] = ';' then begin cur := cur - Length(bs) + 1; goto 1; end else AddError('Need ";" or "until" here'); end; procedure DoWhile; var nl, nsm: Integer; begin nl := last; nsm := cur; DoExpression; if Error then Exit; MemoTo.Add(ttIf + ' ' + CopyArr(nsm, cur - nsm)); lastp := cur; if GetToken = 'DO' then begin DoCommand; MemoTo.Add(ttGoto + Chr(nl) + Chr(nl div 256)); bs := MemoTo[nl]; bs[2] := Chr(last); bs[3] := Chr(last div 256); MemoTo[nl] := bs; end else AddError('Need "do" here'); end; procedure DoFor; var nsm, nl: Integer; loopvar: String; begin nsm := cur; DoEqual; if Error then Exit; bs := Trim(CopyArr(nsm, cur - nsm)); loopvar := Copy(bs, 1, Pos(':=', bs) - 1); lastp := cur; if GetToken = 'TO' then begin nsm := cur; DoExpression; if Error then Exit; nl := last; MemoTo.Add(ttIf + ' ' + loopvar + '<=' + CopyArr(nsm, cur - nsm)); lastp := cur; if GetToken = 'DO' then begin DoCommand; if Error then Exit; MemoTo.Add(loopvar + ' ' + loopvar + '+1'); MemoTo.Add(ttGoto + Chr(nl) + Chr(nl div 256)); bs := MemoTo[nl]; bs[2] := Chr(last); bs[3] := Chr(last div 256); MemoTo[nl] := bs; end else AddError('Need "do" here'); end else AddError('Need "to" here'); end; procedure DoGoto; var nsm: Integer; begin SkipSpace; nsm := cur; lastp := cur; DoDigit; if Error then AddError('"goto" label must be a number'); MemoTo.Add(ttGoto + Trim(CopyArr(nsm, cur - nsm))); end; procedure DoEqual; var s: String; n, nsm: Integer; begin nsm := cur; DoVariable; s := Trim(CopyArr(nsm, cur - nsm)) + ' '; lastp := cur; bs := GetToken; if (bs = ';') or (bs = '') or (bs = #0) or (bs = 'END') or (bs = 'ELSE') then begin s := Trim(CopyArr(nsm, lastp - nsm)); MemoTo.Add(ttProc + s + '(0)'); cur := lastp; end else if Pos(':=', bs) = 1 then begin cur := cur - Length(bs) + 2; nsm := cur; DoExpression; n := Pos('[', s); if n <> 0 then begin s := ttProc + 'SETARRAY(' + Copy(s, 1, n - 1) + ', ' + Copy(s, n + 1, Length(s) - n - 2) + ', ' + CopyArr(nsm, cur - nsm) + ')'; end else s := s + CopyArr(nsm, cur - nsm); MemoTo.Add(s); end else AddError('Need ":=" here'); end; {-------------------------------------} procedure DoExpression; var nsm: Integer; begin DoSExpression; nsm := cur; bs := GetToken; if (Pos('>=', bs) = 1) or (Pos('<=', bs) = 1) or (Pos('<>', bs) = 1) then begin cur := cur - Length(bs) + 2; DoSExpression; end else if (bs[1] = '>') or (bs[1] = '<') or (bs[1] = '=') then begin cur := cur - Length(bs) + 1; DoSExpression; end else cur := nsm; end; procedure DoSExpression; var nsm: Integer; begin DoTerm; nsm := cur; bs := GetToken; if (bs[1] = '+') or (bs[1] = '-') then begin cur := cur - Length(bs) + 1; DoSExpression; end else if Pos('OR', bs) = 1 then begin cur := cur - Length(bs) + 2; DoSExpression; end else cur := nsm; end; procedure DoTerm; var nsm: Integer; begin DoFactor; nsm := cur; bs := GetToken; if (bs[1] = '*') or (bs[1] = '/') then begin cur := cur - Length(bs) + 1; DoTerm; end else if (Pos('AND', bs) = 1) or (Pos('MOD', bs) = 1) then begin cur := cur - Length(bs) + 3; DoTerm; end else cur := nsm; end; procedure DoFactor; var nsm: Integer; begin nsm := cur; bs := GetToken; if bs[1] = '(' then begin cur := cur - Length(bs) + 1; DoExpression; SkipSpace; lastp := cur; if buf^[cur] = ')' then Inc(cur) else AddError('Need ")" here'); end else if bs[1] = '[' then begin cur := cur - Length(bs); ProcessBrackets(cur); SkipSpace; lastp := cur; if buf^[cur] = ']' then Inc(cur) else AddError('Need "]" here'); end else if (bs[1] = '+') or (bs[1] = '-') then begin cur := cur - Length(bs) + 1; DoExpression; end else if bs = 'NOT' then begin cur := cur - Length(bs) + 3; DoExpression; end else begin cur := nsm; DoVariable; if Error then begin Error := False; cur := nsm; DoConst; if Error then begin Error := False; cur := nsm; DoFunc; end; end; end; end; procedure DoVariable; begin SkipSpace; if (buf^[cur] in ['a'..'z', 'A'..'Z']) then begin Inc(cur); while buf^[cur] in ['0'..'9', '_', '.', 'A'..'Z', 'a'..'z'] do Inc(cur); if buf^[cur] = '(' then Error := True else if buf^[cur] = '[' then begin Inc(cur); DoExpression; if buf^[cur] <> ']' then Error := True else Inc(cur); end; end else Error := True; end; procedure DoConst; label 1; begin SkipSpace; if buf^[cur] = #$27 then begin 1: Inc(cur); while (buf^[cur] <> #$27) and (cur < len) do Inc(cur); if (cur < len) and (buf^[cur + 1] = #$27) then begin Inc(cur); goto 1; end; if cur = len then Error := True else Inc(cur); end else begin DoDigit; if buf^[cur] = '.' then begin Inc(cur); DoDigit; end; end; end; procedure DoLabel; begin DoDigit; if buf^[cur] = ':' then Inc(cur) else Error := True; end; procedure DoFunc; label 1; begin DoFuncId; if buf^[cur] = '(' then begin Inc(cur); SkipSpace; if buf^[cur] = ')' then begin Inc(cur); exit; end; 1: DoExpression; lastp := cur; SkipSpace; if buf^[cur] = ',' then begin Inc(cur); goto 1; end else if buf^[cur] = ')' then Inc(cur) else AddError('Need "," or ")" here'); end; end; procedure DoFuncId; begin SkipSpace; if buf^[cur] in ['A'..'Z', 'a'..'z'] then while buf^[cur] in ['0'..'9', '_', '.', 'A'..'Z', 'a'..'z'] do Inc(cur) else Error := True; end; procedure DoCommand; label 1; var nsm: Integer; begin 1:Error := False; nsm := cur; lastp := cur; bs := GetToken; if bs = 'BEGIN' then DoBegin else if bs = 'IF' then DoIf else if bs = 'REPEAT' then DoRepeat else if bs = 'WHILE' then DoWhile else if bs = 'FOR' then DoFor else if bs = 'GOTO' then DoGoto else if (bs = 'END') or (bs = 'END;') then begin cur := nsm; Error := False; end else if bs = 'UNTIL' then begin cur := nsm; Error := False; end else begin cur := nsm; DoLabel; if Error then begin Error := False; cur := nsm; DoVariable; if not Error then begin cur := nsm; DoEqual; end else begin cur := nsm; Error := False; DoExpression; MemoTo.Add(ttProc + Trim(CopyArr(nsm, cur - nsm))); end; end else begin AddLabel(Trim(CopyArr(nsm, cur - nsm)), last); goto 1; end; end; end; begin CutList := TStringList.Create; Error := False; GetMem(buf, 32000); FillChar(buf^, 32000, 0); len := 0; for i := 0 to MemoFrom.Count - 1 do begin s := MemoFrom[i] + #13; while Pos(#9, s) <> 0 do s[Pos(#9, s)] := ' '; Move(s[1], buf^[len], Length(s)); Inc(len, Length(s)); end; cur := 0; labc := 0; MemoTo.Clear; MemoErr.Clear; if len > 0 then DoCommand; FreeMem(buf, 32000); CutList.Free; for i := 0 to MemoTo.Count - 1 do if MemoTo[i][1] = ttGoto then begin s := Remain(MemoTo[i], 2) + ':'; for j := 0 to labc do if labels[j].name = s then begin s := MemoTo[i]; s[2] := Chr(labels[j].n); s[3] := Chr(labels[j].n div 256); MemoTo[i] := s; break; end; end else if MemoTo[i][1] = ttIf then begin s := FParser.Str2OPZ(Remain(MemoTo[i], 4)); MemoTo[i] := Copy(MemoTo[i], 1, 3) + s; end else if MemoTo[i][1] = ttProc then begin s := FParser.Str2OPZ(Remain(MemoTo[i], 2)); MemoTo[i] := Copy(MemoTo[i], 1, 1) + s; end else begin j := 1; GetIdentify(MemoTo[i], j); len := j; s := FParser.Str2OPZ(Remain(MemoTo[i], j)); MemoTo[i] := Copy(MemoTo[i], 1, len) + s; end; end; procedure TfrInterpretator.DoScript(Memo: TStrings); var i, j: Integer; s, s1: String; begin i := 0; while i < Memo.Count do begin s := Memo[i]; j := 1; if s[1] = ttIf then begin if FParser.CalcOPZ(Remain(s, 4)) = 0 then begin i := Ord(s[2]) + Ord(s[3]) * 256; continue; end; end else if s[1] = ttGoto then begin i := Ord(s[2]) + Ord(s[3]) * 256; continue; end else if s[1] = ttProc then begin s1 := Remain(s, 2); if AnsiUpperCase(s1) = 'EXIT(0)' then exit; FParser.CalcOPZ(s1); end else begin s1 := GetIdentify(s, j); SetValue(s1, FParser.CalcOPZ(Remain(s, j))); end; Inc(i); end; end; {$ELSE} constructor TfrInterpretator.Create; begin inherited Create; FInterpreter := TInterpreter.Create; { Точки останова и все такое потом } FParser := TfrParser.Create; FParser.OnGetValue := GetValue; FParser.OnFunction := DoFunction; FInterpreter.OnVariable := GetVariable; FInterpreter.OnSetVariable := SetVariable; Global := False; end; destructor TfrInterpretator.Destroy; begin FParser.Free; FInterpreter.Free; inherited Destroy; end; procedure TfrInterpretator.PrepareScript(MemoFrom, MemoTo, MemoErr: TStrings); var Stream : TMemoryStream; Module : TModule; Ident : PIdent; begin { 1. Прочитатать из MemoFrom в поток 2. Сделать трансляцию потока 3. Ошибки в MemoErr 4. Результат трансляции в MemoTo } If (MemoFrom.Text <> EmptyStr) or Global then begin Stream := TMemoryStream.Create; MemoFrom.SaveToStream(Stream); Stream.Seek(0, 0); If Global then Module := TModule.Create(mtGlobal, Stream, nil) else Module := TModule.Create(mtLocal, Stream, nil); If Global then begin while FInterpreter.Translator.ModuleList.Count > 0 do begin Try If TModule(FInterpreter.Translator.ModuleList.Objects[0]).ModuleType = mtGlobal then begin TModule(FInterpreter.Translator.ModuleList.Objects[0]).FInStream.Free; end; FInterpreter.Translator.ModuleList.Objects[0].Free; FInterpreter.Translator.ModuleList.Delete(0); except end; end; while FInterpreter.Translator.ExportNT.Count > 0 do begin Ident := PIdent(FInterpreter.Translator.ExportNT.Objects[0]); DelBlock(Ident); FInterpreter.Translator.ExportNT.Delete(0); end; end; FInterpreter.Translator.ModuleList.AddObject('', Module); FInterpreter.Translate(FInterpreter.Translator.ModuleList.Count); MemoErr.Text := Finterpreter.ErList.Text; MemoTo.Text := MemoFrom.Text; If not Global then begin FInterpreter.Translator.ModuleList.Delete(FInterpreter.Translator.ModuleList.Count - 1); { DWindowForm.DWindow.Text := Module.OpList.AsString + #$D#$A + Module.IList.AsString; DwindowForm.ShowModal; } Module.Free; Stream.Free; end; end; end; procedure TfrInterpretator.DoScript(Memo: TStrings); var Stream : TMemoryStream; Module : TModule; TempList : TStringList; begin { Выполнить оттранслированый код в Memo } If Memo.Text <> EmptyStr then begin If not Global then begin Stream := TMemoryStream.Create; Memo.SaveToStream(Stream); Stream.Seek(0, 0); Module := TModule.Create(mtLocal, Stream, nil); FInterpreter.Translator.ModuleList.AddObject('', Module); FInterpreter.ExecuteCode(FInterpreter.Translator.ModuleList.Count); Stream.Free; Module.Free; FInterpreter.Translator.ModuleList.Delete(FInterpreter.Translator.ModuleList.Count-1); end else begin TempList := TStringList.Create; PrepareScript(Memo, Memo, TempList); // If TempList.Text <> EmptyStr then ShowMessage(TempList.Text); TempList.Free; FInterpreter.ExecuteCode(1); end; end; end; {$ENDIF} procedure TfrInterpretator.SplitExpressions(Memo, MatchFuncs, SplitTo: TStrings; Variables: TfrVariables); {$IfNDEF 1CScript} var i, j: Integer; s: String; FuncSplitter: TfrFunctionSplitter; {$ENDIF} begin {$IfNDEF 1CScript} FuncSplitter := TfrFunctionSplitter.Create(MatchFuncs, SplitTo, Variables); i := 0; while i < Memo.Count do begin s := Memo[i]; j := 1; if s[1] = ttIf then FuncSplitter.Split(Remain(s, 4)) else if s[1] = ttProc then FuncSplitter.Split(Remain(s, 2)) else begin GetIdentify(s, j); FuncSplitter.Split(Remain(s, j)); end; Inc(i); end; FuncSplitter.Free; {$ENDIF} end; procedure TfrInterpretator.GetValue(const Name: String; var Value: Variant); begin // abstract method end; procedure TfrInterpretator.SetValue(const Name: String; Value: Variant); begin // abstract method end; procedure TfrInterpretator.DoFunction(const Name: String; p1, p2, p3: Variant; var val: Variant); begin // abstract method end; {$IFDEF 1CScript} procedure TfrInterpretator.GetVariable(Sender : TObject; mIndex : Integer; VarName : String; var Ok : Boolean; var Result : TVariant); begin Result.Obj := nil; Result.VarValue := Null; If Sender is TInterpreter then FParser.OnGetValue(VarName, Result.VarValue) else If Assigned(OnGetValue) then OnGetValue(VarName, Result.VarValue); If varIsNull(Result.VarValue) or VarIsEmpty(Result.VarValue) then Ok := False else Ok := True; end; procedure TfrInterpretator.SetVariable(Sender: TObject; mIndex: Integer; VarName: String; var Ok: Boolean; var Result: TVariant); begin SetValue(VarName, Result.VarValue); Ok := True; end; function TfrInterpretator.QueryValue(Name: String): Variant; var R : TVariant; begin // ShowMessage('query value'); R := FInterpreter.QueryValue(Name); Result := R.VarValue; end; procedure TfrInterpretator.FOnSetValue(Value : TGetPValueEvent); begin FOnGetValue := Value; end; {$ENDIF} end.
unit untWatchDogTimerRefresh; {$mode objfpc} interface uses Classes, SysUtils, IdTCPClient, IdGlobal, untUtils, Dialogs, untAdminTools; const ERROR_Success:integer=0; ERROR_Fail:integer=-1; ERROR_NoConnection=-2; type EnumProgramStatus=(ProgramStarted=0, ProgramRunning=1, ProgramClosing=2); type { TWatchDogTimerRefresh } TWatchDogTimerRefresh= class(TThread) private nPort:integer; strRemoteHost:string; nInterval:integer; bolResumeExecute:boolean; sckMain:TIdTCPClient; protected procedure Execute; override; public constructor Create(CreateSuspend: boolean;Host:string;Port:integer;Interval:integer); function ConnectToRemote:boolean; function SendMessage(StatusMessage:EnumProgramStatus):integer; function Send(Buffer:TIdBytes):integer; function SayBye:boolean; function Disconnect: boolean; end; implementation { TWatchDogTimerRefresh } procedure TWatchDogTimerRefresh.Execute; begin SendMessage(EnumProgramStatus.ProgramStarted); while(bolResumeExecute) do begin Sleep(nInterval); SendMessage(EnumProgramStatus.ProgramRunning); end; end; constructor TWatchDogTimerRefresh.Create(CreateSuspend: boolean;Host:string;Port: integer;Interval:integer); begin strRemoteHost:=Host; nPort:=Port; nInterval:=Interval; bolResumeExecute:=true; inherited Create(CreateSuspend); end; function TWatchDogTimerRefresh.ConnectToRemote: boolean; begin try sckMain:=TIdTCPClient.Create(nil); sckMain.Host:=self.strRemoteHost; sckMain.Port:=self.nPort; sckMain.Connect; Result:=true; except on E:Exception do begin WriteLog(E.ClassName+' error raised, with message : '+E.Message); Result:=false; //SoftReset; end; end; end; function TWatchDogTimerRefresh.Disconnect: boolean; begin try try if(sckMain.Connected) then sckMain.Disconnect; except on E:Exception do WriteLog('TWatchDogTimerRefresh.Disconnect: ' + E.Message); end; finally FreeAndNil(sckMain); end; end; function TWatchDogTimerRefresh.SendMessage(StatusMessage: EnumProgramStatus ): integer; var buffer: TIdBytes; begin SetLength(buffer, 8); buffer[0]:=byte(StatusMessage); if(not ConnectToRemote) then begin result:=ERROR_Fail; SetLength(buffer, 0); exit; end; if Send(buffer)<> ERROR_Success then begin result:=ERROR_Fail; Disconnect; SetLength(buffer, 0); exit; end; Disconnect(); SetLength(buffer, 0); end; function TWatchDogTimerRefresh.Send(Buffer: TIdBytes): integer; begin try sckMain.IOHandler.Write(Buffer); Result:=0; except on E:Exception do begin WriteLog('TWatchDogTimerRefresh.Send:' + E.Message); Result:=ERROR_Fail; end; end; end; function TWatchDogTimerRefresh.SayBye: boolean; begin bolResumeExecute:=false; SendMessage(EnumProgramStatus.ProgramClosing); end; end.
unit Teste.Calculadora; interface uses Classe.Calculadora, DUnitX.TestFramework; type [TestFixture] TCalculadoraTeste = class(TObject) private Calculadora: TCalculadora; public [Setup] procedure Setup; [TearDown] procedure TearDown; [TestCase('1 e 1','1,1,2')] [TestCase('1 e 5','1,5,6')] procedure TesteAdicao(AValue1, AValue2, Experado : integer); [TesteCase] procedure TesteFalha; end; implementation procedure TCalculadoraTeste.Setup; begin Calculadora := TCalculadora.Create; end; procedure TCalculadoraTeste.TearDown; begin Calculadora.Free; end; procedure TCalculadoraTeste.TesteAdicao(AValue1, AValue2, Experado: integer); var Atual : integer; begin Atual := Calculadora.Add(AValue1, AValue2); Assert.AreEqual(Atual, Experado, 'Teste passou com sucesso'); end; procedure TCalculadoraTeste.TesteFalha; begin Assert.Fail('Erro no método'); end; initialization TDUnitX.RegisterTestFixture(TCalculadoraTeste); end.
unit Delta.Properties; interface uses System.SysUtils, System.Classes, System.rtti, System.TypInfo, Delta.System.Classes, fmx.forms; procedure setPropertyValue(const Reference: Integer; const AName: string; const value: TValue); function getPropertyReference(const Reference: Integer; const AName: PAnsiChar) : Integer; stdcall; procedure setPropertyReference(const Reference: Integer; const AName: PAnsiChar; const value: Integer); stdcall; procedure setPropertyBoolean(const Reference: Integer; const AName: PAnsiChar; const value: Boolean); stdcall; procedure setPropertySmallInt(const Reference: Integer; const AName: PAnsiChar; const value: SmallInt); stdcall; function getPropertySmallInt(const Reference: Integer; const AName: PAnsiChar) : SmallInt; stdcall; procedure setPropertyInteger(const Reference: Integer; const AName: PAnsiChar; const value: Integer); stdcall; function getPropertyInteger(const Reference: Integer; const AName: PAnsiChar) : Integer; stdcall; procedure setPropertyCardinal(const Reference: Integer; const AName: PAnsiChar; const value: Cardinal); stdcall; function getPropertyCardinal(const Reference: Integer; const AName: PAnsiChar) : Cardinal; stdcall; procedure setPropertySingle(const Reference: Integer; const AName: PAnsiChar; const value: Single); stdcall; function getPropertySingle(const Reference: Integer; const AName: PAnsiChar) : Single; stdcall; procedure setPropertyString(const Reference: Integer; const AName: PAnsiChar; const value: WideString); stdcall; procedure getPropertyString(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; procedure setPropertyEnum(const Reference: Integer; const AName: PAnsiChar; const value: PAnsiChar); stdcall; procedure getPropertyEnum(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; procedure setPropertySet(const Reference: Integer; const AName: PAnsiChar; const value: PAnsiChar); stdcall; function getIntegerIndexedPropertyReference(const Reference: Integer; const AName: PAnsiChar; const Index: Integer): Integer; stdcall; exports setPropertyEnum, getPropertyEnum, setPropertySet, setPropertyReference, setPropertySmallInt, getPropertySmallInt, setPropertyInteger, setPropertyBoolean, setPropertyString, setPropertySingle, getPropertySingle, setPropertyCardinal, getPropertyReference, getPropertyInteger, getPropertyCardinal, getPropertyString, getIntegerIndexedPropertyReference; implementation procedure setPropertyValue(const Reference: Integer; const AName: string; const value: TValue); var context: TRttiContext; rttiType: TRttiType; prop: TRttiProperty; obj: TObject; begin context := TRttiContext.Create; try try obj := TObject(Reference); rttiType := (context.GetType(obj.ClassType)); prop := rttiType.GetProperty(AName); prop.SetValue(obj, value); except on E: Exception do writeln(E.ClassName + ' error raised, with message : ' + E.Message); end; finally context.Free; end; end; function getPropertyValue(const Reference: Integer; const AName: string): TValue; var context: TRttiContext; rttiType: TRttiType; prop: TRttiProperty; obj: TObject; begin context := TRttiContext.Create; try try obj := TObject(Reference); rttiType := (context.GetType(obj.ClassType)); prop := rttiType.GetProperty(AName); result := prop.getValue(obj); except on E: Exception do writeln(E.ClassName + ' error raised, with message : ' + E.Message); end; finally context.Free; end; end; function getIndexedPropertyValue(const Reference: Integer; const AName: string; const Index: Integer): TValue; var context: TRttiContext; rttiType: TRttiType; prop: TRttiIndexedProperty; obj: TObject; begin context := TRttiContext.Create; try try obj := TObject(Reference); rttiType := (context.GetType(obj.ClassType)); prop := rttiType.GetIndexedProperty(AName); result := prop.getValue(obj, [Index]) except on E: Exception do writeln(E.ClassName + ' error raised, with message : ' + E.Message); end; finally context.Free; end; end; procedure setPropertySmallInt(const Reference: Integer; const AName: PAnsiChar; const value: SmallInt); stdcall; begin setPropertyValue(Reference, string(AName), value); end; function getPropertySmallInt(const Reference: Integer; const AName: PAnsiChar) : SmallInt; stdcall; begin result := getPropertyValue(Reference, string(AName)).AsType<SmallInt>; end; procedure setPropertyInteger(const Reference: Integer; const AName: PAnsiChar; const value: Integer); stdcall; begin setPropertyValue(Reference, string(AName), value); end; function getPropertyInteger(const Reference: Integer; const AName: PAnsiChar) : Integer; stdcall; begin result := getPropertyValue(Reference, string(AName)).AsInteger; end; procedure setPropertyBoolean(const Reference: Integer; const AName: PAnsiChar; const value: Boolean); stdcall; begin setPropertyValue(Reference, string(AName), value); end; procedure setPropertySingle(const Reference: Integer; const AName: PAnsiChar; const value: Single); stdcall; begin setPropertyValue(Reference, string(AName), value); end; function getPropertySingle(const Reference: Integer; const AName: PAnsiChar) : Single; stdcall; begin result := getPropertyValue(Reference, string(AName)).AsType<Single>; end; procedure setPropertyCardinal(const Reference: Integer; const AName: PAnsiChar; const value: Cardinal); stdcall; begin setPropertyValue(Reference, string(AName), value); end; function getPropertyCardinal(const Reference: Integer; const AName: PAnsiChar) : Cardinal; stdcall; begin result := getPropertyValue(Reference, string(AName)).AsType<Cardinal>; end; procedure setPropertyString(const Reference: Integer; const AName: PAnsiChar; const value: WideString); stdcall; begin setPropertyValue(Reference, string(AName), string(value)); end; procedure getPropertyString(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; var s: String; begin s := getPropertyValue(Reference, string(AName)).AsString; value := s; end; procedure setPropertyEnum(const Reference: Integer; const AName: PAnsiChar; const value: PAnsiChar); stdcall; var context: TRttiContext; rttiType: TRttiType; prop: TRttiProperty; obj: TObject; v: TValue; I: Integer; begin context := TRttiContext.Create; try obj := TObject(Reference); rttiType := (context.GetType(obj.ClassType)); prop := rttiType.GetProperty(string(AName)); I := GetEnumValue(prop.PropertyType.Handle, string(value)); TValue.Make(I, prop.PropertyType.Handle, v); prop.SetValue(obj, v); finally context.Free; end; end; procedure getPropertyEnum(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; var s: String; begin s := getPropertyValue(Reference, string(AName)).AsString; value := s; end; procedure setPropertySet(const Reference: Integer; const AName: PAnsiChar; const value: PAnsiChar); stdcall; var context: TRttiContext; rttiType: TRttiType; prop: TRttiProperty; obj: TObject; v: TValue; I: Integer; begin context := TRttiContext.Create; try obj := TObject(Reference); rttiType := (context.GetType(obj.ClassType)); prop := rttiType.GetProperty(string(AName)); I := StringToSet(prop.PropertyType.Handle, string(value)); TValue.Make(I, prop.PropertyType.Handle, v); prop.SetValue(obj, v); finally context.Free; end; end; procedure setPropertyReference(const Reference: Integer; const AName: PAnsiChar; const value: Integer); stdcall; var obj: TObject; begin if value = -1 then obj := nil else obj := TObject(value); setPropertyValue(Reference, string(AName), obj); end; function getPropertyReference(const Reference: Integer; const AName: PAnsiChar) : Integer; stdcall; begin result := Integer(getPropertyValue(Reference, string(AName)).AsObject); end; function getIntegerIndexedPropertyReference(const Reference: Integer; const AName: PAnsiChar; const Index: Integer): Integer; stdcall; begin result := Integer(getIndexedPropertyValue(Reference, string(AName), Index) .AsObject); end; end.
unit MBRTUMasterDispatcher; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles, LoggerItf, MBRTURequestBase, MBRTUMasterDispatcherTypes, MBRTUPortAdapter; type { TMBRTUMasterDispatcher } TMBRTUMasterDispatcher = class(TObjectLogged) private FOwnedRequests : Boolean; FPortList : THashedStringList; function GetPortForName(AName : String): TMBRTUPortAdapter; function GetPorts(Index : Integer): TMBRTUPortAdapter; function GetPortsCount: Integer; procedure SetOwnedRequests(AValue: Boolean); function SearchPort(APortName : String) : TMBRTUPortAdapter; protected procedure SetLogger(const AValue: IDLogger); override; public constructor Create; virtual; destructor Destroy; override; function AddPort(APortParam : TMBDispPortParam) : TMBRTUPortAdapter; function DeletePort(APortParam : TMBDispPortParam) : TMBRTUPortAdapter; overload; function DeletePort(Index : Integer) : TMBRTUPortAdapter; overload; procedure Clear; // поставить запрос в пул постоянного опроса function AddPoolObject(APortParam : TMBDispPortParam; var ARequest : TMBRTURequestBase) : Boolean; // выполнить одиночный запрос function SendSingleRequest(APortParam : TMBDispPortParam; var ARequest : TMBRTURequestBase) : Boolean; procedure Start; procedure Stop; property PortsCount : Integer read GetPortsCount; property Ports[Index : Integer] : TMBRTUPortAdapter read GetPorts; property PortForName[AName : String] : TMBRTUPortAdapter read GetPortForName; property OwnedRequests : Boolean read FOwnedRequests write SetOwnedRequests default True; end; implementation uses MBRTUMasterDispatcherFunc; { TMBRTUMasterDispatcher } constructor TMBRTUMasterDispatcher.Create; begin FPortList := THashedStringList.Create; FOwnedRequests := True; end; destructor TMBRTUMasterDispatcher.Destroy; begin Clear; FreeAndNil(FPortList); inherited Destroy; end; procedure TMBRTUMasterDispatcher.Start; var TempCount, i : Integer; begin TempCount := PortsCount-1; for i := 0 to TempCount do Ports[i].Start; end; procedure TMBRTUMasterDispatcher.Stop; var TempCount, i : Integer; begin TempCount := PortsCount-1; for i := 0 to TempCount do Ports[i].Stop; end; function TMBRTUMasterDispatcher.GetPortForName(AName : String): TMBRTUPortAdapter; begin Result := SearchPort(AName); end; function TMBRTUMasterDispatcher.GetPorts(Index : Integer): TMBRTUPortAdapter; begin Result := TMBRTUPortAdapter(FPortList.Objects[Index]); end; function TMBRTUMasterDispatcher.GetPortsCount: Integer; begin Result := FPortList.Count; end; function TMBRTUMasterDispatcher.SearchPort(APortName: String): TMBRTUPortAdapter; var i : Integer; begin Result := nil; i := FPortList.IndexOf(APortName); if i = -1 then Exit; Result := TMBRTUPortAdapter(FPortList.Objects[i]); end; procedure TMBRTUMasterDispatcher.SetOwnedRequests(AValue: Boolean); var i : Integer; TempPort : TMBRTUPortAdapter; begin if FOwnedRequests = AValue then Exit; FOwnedRequests := AValue; for i := 0 to FPortList.Count-1 do begin TempPort := TMBRTUPortAdapter(FPortList.Objects[i]); TempPort.OwnedRequests := FOwnedRequests; end; end; procedure TMBRTUMasterDispatcher.SetLogger(const AValue: IDLogger); var i : Integer; TempPort : TMBRTUPortAdapter; begin inherited SetLogger(AValue); for i := 0 to FPortList.Count-1 do begin TempPort := TMBRTUPortAdapter(FPortList.Objects[i]); TempPort.Logger := Logger; end; end; function TMBRTUMasterDispatcher.AddPort(APortParam: TMBDispPortParam): TMBRTUPortAdapter; var TempName : String; begin TempName := GetPortAdapterIDStr(APortParam); Result := SearchPort(TempName); if Result <> nil then Exit; Result := TMBRTUPortAdapter.Create(APortParam); Result.Logger := Logger; Result.OwnedRequests := FOwnedRequests; FPortList.AddObject(TempName,Result); end; function TMBRTUMasterDispatcher.DeletePort(APortParam: TMBDispPortParam): TMBRTUPortAdapter; var TempName : String; i : Integer; begin Result := nil; TempName := GetPortAdapterIDStr(APortParam); i := FPortList.IndexOf(TempName); if i = -1 then Exit; Result := TMBRTUPortAdapter(FPortList.Objects[i]); FPortList.Delete(i); end; function TMBRTUMasterDispatcher.DeletePort(Index: Integer): TMBRTUPortAdapter; begin Result := TMBRTUPortAdapter(FPortList.Objects[Index]); FPortList.Delete(Index); end; procedure TMBRTUMasterDispatcher.Clear; var i, Count : Integer; TempPort : TMBRTUPortAdapter; begin Count := FPortList.Count-1; if Count = -1 then Exit; for i := Count downto 0 do begin TempPort := TMBRTUPortAdapter(FPortList.Objects[i]); FPortList.Delete(i); FreeAndNil(TempPort); end; end; function TMBRTUMasterDispatcher.AddPoolObject(APortParam : TMBDispPortParam; var ARequest : TMBRTURequestBase) : Boolean; var TempName : String; TempPort : TMBRTUPortAdapter; begin Result := False; TempName := GetPortAdapterIDStr(APortParam); TempPort := SearchPort(TempName); if TempPort = nil then TempPort := AddPort(APortParam); TempPort.AddPoolRequest(ARequest); Result := True; end; function TMBRTUMasterDispatcher.SendSingleRequest(APortParam: TMBDispPortParam; var ARequest: TMBRTURequestBase) : Boolean; var TempName : String; TempPort : TMBRTUPortAdapter; begin Result := False; TempName := GetPortAdapterIDStr(APortParam); TempPort := SearchPort(TempName); if TempPort = nil then TempPort := AddPort(APortParam); TempPort.SendSingleRequest(ARequest); Result := True; end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [CLIENTE] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit ClienteService; interface uses Cliente, Pessoa, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TClienteService = class(TServiceBase) private class procedure AnexarObjetosVinculados(AListaCliente: TObjectList<TCliente>); overload; class procedure AnexarObjetosVinculados(ACliente: TCliente); overload; public class function ConsultarLista: TObjectList<TCliente>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TCliente>; class function ConsultarObjeto(AId: Integer): TCliente; class procedure Inserir(ACliente: TCliente); class function Alterar(ACliente: TCliente): Integer; class function Excluir(ACliente: TCliente): Integer; end; var sql: string; implementation { TClienteService } class procedure TClienteService.AnexarObjetosVinculados(ACliente: TCliente); begin // Pessoa sql := 'SELECT * FROM PESSOA WHERE ID = ' + ACliente.IdPessoa.ToString; ACliente.Pessoa := GetQuery(sql).AsObject<TPessoa>; end; class procedure TClienteService.AnexarObjetosVinculados(AListaCliente: TObjectList<TCliente>); var Cliente: TCliente; begin for Cliente in AListaCliente do begin AnexarObjetosVinculados(Cliente); end; end; class function TClienteService.ConsultarLista: TObjectList<TCliente>; begin sql := 'SELECT * FROM CLIENTE ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TCliente>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TClienteService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TCliente>; begin sql := 'SELECT * FROM CLIENTE where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TCliente>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TClienteService.ConsultarObjeto(AId: Integer): TCliente; begin sql := 'SELECT * FROM CLIENTE WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TCliente>; AnexarObjetosVinculados(Result); end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TClienteService.Inserir(ACliente: TCliente); begin ACliente.ValidarInsercao; ACliente.Id := InserirBase(ACliente, 'CLIENTE'); end; class function TClienteService.Alterar(ACliente: TCliente): Integer; begin ACliente.ValidarAlteracao; Result := AlterarBase(ACliente, 'CLIENTE'); end; class function TClienteService.Excluir(ACliente: TCliente): Integer; begin ACliente.ValidarExclusao; Result := ExcluirBase(ACliente.Id, 'CLIENTE'); end; end.
unit uCreditCardValidator; interface uses SysUtils; type ICreditCardValidator = interface(IInvokable) ['{68553321-248C-4FD4-9881-C6B6B92B95AD}'] function IsCreditCardValid(aCreditCardNumber: string): Boolean; procedure DoNotCallThisEver; end; TCreditCardValidator = class(TInterfacedObject, ICreditCardValidator) function IsCreditCardValid(aCreditCardNumber: string): Boolean; procedure DoNotCallThisEver; end; ECreditCardValidatorException = class(Exception); implementation uses Dialogs; function TCreditCardValidator.IsCreditCardValid(aCreditCardNumber: string): Boolean; begin // Let's pretend this calls a SOAP server that charges $0.25 everytime // you use it. // For Demo purposes, we'll have the card be invalid if it the number 7 in it Result := Pos('7', aCreditCardNumber) <= 0; WriteLn('Ka-Ching! You were just charged $0.25'); if not Result then begin raise ECreditCardValidatorException.Create('Bad Credit Card! Do not accept!'); end; end; procedure TCreditCardValidator.DoNotCallThisEver; begin // This one will charge the company $500! We should never // call this! end; end.
unit Mesh; (* Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the gl3ds main unit. * * The Initial Developer of the Original Code is * Noeska Software. * Portions created by the Initial Developer are Copyright (C) 2002-2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * M van der Honing * Sascha Willems * Jan Michalowsky * *) interface uses classes, glmath, Material, Transform; type //texturemapping coords TMap = packed record tu: Single; tv: Single; end; //TODO: continue splitting up normal vertex and (texture)mapping (indices) //TODO: enable texturemapping indices in 3ds and msa //TODO: Enable face structure again make this a virtual mapping... //face structure (one triangle) // TFace = packed record // vertex: array [0..2] of word; //rewrite to xyz // normal: array [0..2] of word; //rewrite to xyz //texmap // neighbour: array [0..2] of word; // plane: TPlaneEq; // visible: Boolean; // end; //mesh data TBoneIdArray = array [0..3] of single; TBaseMesh = class; TBaseMeshClass = class of TBaseMesh; TBaseMesh = class(TTransformComponent) protected FMatrix: array of Single; FVisible: boolean; FId: Integer; Fmatid: array of word; Fmatname: array of string; FMaximum: T3dPoint; FMinimum: T3dPoint; FName: string; FVertexIndices: array of word; FNormalIndices: array of word; FMappingIndices: array of word; fBoneIndices: array of TBoneIdArray; fBoneWeights: array of TBoneIdArray; FNumVertexIndices: Integer; FNumVertex: Integer; FNumNormals: Integer; FNumNormalIndices: Integer; FNumMappings: Integer; FNumMappingIndices: Integer; FNumFaces: Integer; Fpivot: T3DPoint; FShadDisplayList: Integer; Fvertex: array of T3dpoint; Fvnormal: array of T3dPoint; Fmapping: array of TMap; fNumBones: integer; //fBoneId: TBoneIdArray; //array of bone id that can incluence a single vertex function GetBoneWeight(VertexIndex, WeightIndex: integer): single; procedure SetBoneWeight(VertexIndex, WeightIndex: integer; aValue: single); function GetVertexIndex(Index: integer): Word; procedure SetVertexIndex(Index: integer; Value: Word); function GetMap(Index: integer): Word; procedure SetMap(Index: integer; Value: Word); function GetFace(Index: integer): Word; procedure SetFace(Index: integer; Value: Word); function GetNormal(Index: integer): Word; procedure SetNormal(Index: integer; Value: Word); function GetBoneId(VertexIndex, BoneIndex: integer): single; // function GetFaces(Index: integer): TFace; // procedure SetFaces(Index: integer; Value: TFace); function GetMapping(Index: integer): TMap; function GetMatID(Index: integer): Word; procedure SetMatID(Index: integer; Value: Word); function GetNormals(Index: integer): T3dPoint; procedure SetNormals(Index: integer; Value: T3dPoint); function GetVertex(Index: integer): T3dPoint; procedure SetVertex(Index: integer; Value: T3dPoint); procedure SetMapping(Index: integer; Value: TMap); procedure SetNumberOfVertex(Value: Integer); procedure SetNumberOfIndices(Value: Integer); procedure SetNumberOfNormals(Value: Integer); procedure SetNumberOfNormalIndices(Value: Integer); // procedure SetNumberOfFaces(Value: Integer); procedure SetNumberOfMappings(Value: Integer); procedure SetNumberOfMappingIndices(Value: Integer); procedure SetBoneId(VertexIndex, BoneIndex: integer; aValue: single); function GetMatName(Index: integer): string; procedure SetMatName(Index: integer; Value: string); function GetValFromMatrix(Index: integer): Single; procedure SetValInMatrix(Index: integer; Value: Single); function GetNumMaterials: integer; function GetNumBones(): integer; procedure SetNumBones(aValue: integer); public destructor Destroy; override; procedure Init; virtual; abstract; procedure Render; virtual; abstract; procedure RenderBoundBox; virtual; abstract; procedure Assign(Source: TPersistent); override; procedure CalculateSize; procedure CalculateNormals; procedure AddFace(v1, v2, v3: T3DPoint; fmaterial: TBaseMaterial); property Visible: boolean read FVisible write FVisible; property Face[Index: integer]: Word read GetFace write SetFace; property Normal[Index: integer]: Word read GetNormal write SetNormal; property Map[Index: integer]: Word read GetMap write SetMap; //property Faces[Index: integer]: TFace read GetFaces write SetFaces; property MatName[Index: integer]: string read GetMatName write SetMatName; property BoneId[VertexIndex, BoneIndex: integer]: single read GetBoneId write SetBoneId; property BoneWeight[VertexIndex, WeightIndex: integer]: single read GetBoneWeight write SetBoneWeight; property Id: Integer read FId write FId; property Mapping[Index: integer]: TMap read GetMapping write SetMapping; property MatID[Index: integer]: Word read GetMatID write SetMatId; property Maximum: T3dPoint read FMaximum; property Minimum: T3dPoint read FMinimum; property Name: string read FName write FName; property Normals[Index: integer]: T3dPoint read GetNormals write SetNormals; property NumVertexIndices: Integer read FNumVertexIndices write SetNumberOfIndices; property NumVertex: Integer read FNumVertex write SetNumberOfVertex; property NumNormals: Integer read FNumNormals write SetNumberofNormals; property NumNormalIndices: Integer read FNumNormalIndices write SetNumberOfNormalIndices; property NumMappingIndices: Integer read FNumMappingIndices write SetNumberOfMappingIndices; property NumMappings: Integer read FNumMappings write SetNumberofMappings; property NumMaterials: Integer read GetNumMaterials; property NumBones: Integer read GetNumBones write SetNumBones; //number of bones that can influence a vertex in a mesh // property NumFaceRecords: Integer read FNumFaces write SetNumberOfFaces; property Vertex[Index: integer]: T3dPoint read GetVertex write SetVertex; property VertexIndices[Index: integer]: Word read GetVertexIndex write SetVertexIndex; property Pivot: T3dPoint read FPivot write FPivot; //TODO: move to 3ds only? property Matrix[Index: integer]: Single read GetValFromMatrix write SetValInMatrix; //TODO: move to 3ds only? end; //TMesh = class(TBaseMesh) //end; implementation uses SysUtils; function TBaseMesh.GetNumMaterials: integer; begin if FMatId = nil then result:=0 else result:=High(FMatId); end; function TBaseMesh.GetNumBones: integer; begin result := fnumbones; end; procedure TBaseMesh.SetNumBones(AValue: integer); begin fnumbones:=aValue; end; destructor TBaseMesh.Destroy; begin FName := ''; SetLength(FVertex, 0); SetLength(FMatName, 0); SetLength(FVnormal, 0); SetLength(FMapping, 0); SetLength(FMatId, 1); //minimale lengte op 1 entry zetten???? SetLength(FVertexIndices, 0); Setlength(FNormalIndices, 0); Setlength(FMappingIndices,0); //SetLength(FBoneId, 0); SetLength(FBoneIndices, 0); SetLength(FBoneWeights, 0); FVertex := nil; FMatName := nil; FVnormal := nil; FMapping := nil; FMatId := nil; FVertexIndices := nil; FNormalIndices := nil; FMappingIndices := nil; FBoneIndices := nil; FBoneWeights := nil; //FBoneId := nil; inherited Destroy; end; procedure TBaseMesh.Assign(Source: TPersistent); begin //TODO: Implement copying of protected vars. if Source is TBaseMesh then begin with TBaseMesh(Source) do begin self.FMatrix:=FMatrix; self.FVisible:=FVisible; //self.Fboneid:= Fboneid; self.FboneIndices:= FboneIndices; self.FBoneWeights:= FboneWeights; //self.FDisplaylist:= FDisplaylist; self.FId:= FId; self.FVertexIndices:= FVertexIndices; self.Fmapping:= Fmapping; self.Fmatid:= Fmatid; self.Fmatname:= Fmatname; self.FMaximum:= FMaximum; self.FMinimum:= FMinimum; self.FName:= FName; self.Fnumnormalindices:= Fnumnormalindices; self.Fnormalindices:= Fnormalindices; self.FMappingIndices := FMappingIndices; self.FNumVertexIndices:= FNumVertexIndices; self.FNumMappingIndices:= FNumMappingIndices; self.FNumVertex:= FNumVertex; self.FNumNormals := FNumNormals; self.FNumMappings := FNumMappings; self.Fpivot:= Fpivot; self.FShadDisplayList:= FShadDisplayList; self.Fvertex:= Fvertex; self.Fvnormal:= Fvnormal; end; end else inherited; end; procedure TBaseMesh.CalculateSize; var f: Integer; x, y, z: Single; begin //am i allowed to assume the the first vertex is a minimum and/or maximum? FMinimum.x := FVertex[FVertexIndices[0]].x; FMinimum.y := FVertex[FVertexIndices[0]].y; FMinimum.z := FVertex[FVertexIndices[0]].z; FMaximum.x := FVertex[FVertexIndices[0]].x; FMaximum.y := FVertex[FVertexIndices[0]].y; FMaximum.z := FVertex[FVertexIndices[0]].z; for f := 0 to FNumVertexIndices - 1 do begin x := FVertex[FVertexIndices[f]].x; y := FVertex[FVertexIndices[f]].y; z := FVertex[FVertexIndices[f]].z; if x < FMinimum.x then FMinimum.x := x; if y < FMinimum.y then FMinimum.y := y; if z < FMinimum.z then FMinimum.z := z; if x > FMaximum.x then FMaximum.x := x; if y > FMaximum.y then FMaximum.y := y; if z > FMaximum.z then FMaximum.z := z; end; end; procedure TBaseMesh.CalculateNormals; var v, f: integer; vertexn: t3dpoint; summedvertexn: t3dpoint; tempvertexn : T3dpoint; //tempnormals : array of T3dPoint; shared: integer; begin if self.NumVertexIndices > 0 then begin //SetLength(tempnormals, self.NumVertex); //init tempnormals f := 0; while f <= self.NumVertexIndices -3 do // go through all vertexes and begin vertexn := CalcNormalVector(self.Vertex[self.Face[f]], self.Vertex[self.Face[f + 1]], self.Vertex[self.Face[f + 2]]); //add all normals and normalize tempvertexn:=vertexn;//Normalize(vertexn); //tempnormals[f div 3] := tempvertexn; //self.Normals[self.Face[f div 3]] := tempvertexn; self.Normals[f div 3] := tempvertexn; //TODO: should be in seperate pass // self.Normal[f] := self.Face[f]; // self.Normal[f + 1] := self.Face[f+1]; // self.Normal[f + 2] := self.Face[f+2]; self.Normal[f] := f div 3; self.Normal[f+1] := f div 3; self.Normal[f+2] := f div 3; f := f + 3; end; (* summedvertexn.x:=0.0; summedvertexn.y:=0.0; summedvertexn.z:=0.0; shared:=0; for v:=0 to self.NumVertex-1 do begin f:=0; while f <= self.NumVertexIndices -3 do begin if (self.Face[f]=v) or (self.Face[f+1]=v) or (self.Face[f+2]=v) then begin summedvertexn:=VectorAdd(summedvertexn, tempnormals[v]); shared:=shared+1; self.Normal[f] := f div 3; self.Normal[f+1] := f div 3; self.Normal[f+2] := f div 3; end; f:=f+3; end; self.Normals[v]:=Normalize(VectorDiv(summedvertexn, -shared)); summedvertexn.x:=0.0; summedvertexn.y:=0.0; summedvertexn.z:=0.0; shared:=0; end; *) //SetLength(tempnormals,0); end; end; function TBaseMesh.GetVertexIndex(Index: integer): Word; begin Result := FVertexIndices[index]; end; function TBaseMesh.GetMap(Index: integer): Word; begin Result := FMappingIndices[index]; end; function TBaseMesh.GetFace(Index: integer): Word; begin Result := FVertexIndices[index]; end; function TBaseMesh.GetBoneId(VertexIndex, BoneIndex: integer): single; begin Result := FBoneIndices[VertexIndex][BoneIndex]; end; function TBaseMesh.GetBoneWeight(VertexIndex, WeightIndex: integer): single; begin Result := FBoneWeights[VertexIndex][WeightIndex]; end; function TBaseMesh.GetMapping(Index: integer): TMap; begin Result := FMapping[index]; end; function TBaseMesh.GetMatID(Index: integer): Word; begin if fmatid <> nil then Result := FMatid[index] else Result := 0; end; procedure TBaseMesh.SetMatID(Index: Integer; Value: Word); begin FMatId[Index]:=Value; end; function TBaseMesh.GetNormals(Index: integer): T3dPoint; begin Result := FVnormal[index]; end; function TBaseMesh.GetValFromMatrix(Index: integer): Single; begin result := FMatrix[Index]; end; function TBaseMesh.GetVertex(Index: integer): T3dPoint; begin Result := FVertex[index]; end; procedure TBaseMesh.SetValInMatrix(Index: integer; Value: Single); begin FMatrix[Index]:=Value; end; procedure TBaseMesh.SetVertex(Index: integer; Value: T3DPoint); begin FVertex[index] :=Value; end; procedure TBaseMesh.SetVertexIndex(Index: integer; Value: word); begin FVertexIndices[index]:=Value; end; procedure TBaseMesh.SetMap(Index: integer; Value: word); begin FMappingIndices[index]:=Value; end; procedure TBaseMesh.SetMapping(Index: integer; Value: TMap); begin FMapping[index]:=Value; end; procedure TBaseMesh.AddFace(v1, v2, v3: T3DPoint; fmaterial: TBaseMaterial); begin //first add vertices FNumVertex := FNumVertex + 3; SetLength(FVertex, FNumVertex); //increase the number of indices FNumVertexIndices := FNumVertexIndices + 3; SetLength(FVertexIndices, FNumVertexIndices); //add the data FVertexIndices[FNumVertexIndices - 3] := FNumVertexIndices - 3; FVertexIndices[FNumVertexIndices - 2] := FNumVertexIndices - 2; FVertexIndices[FNumVertexIndices - 1] := FNumVertexIndices - 1; FVertex[FVertexIndices[FNumVertexIndices - 3]].x := v1.x; FVertex[FVertexIndices[FNumVertexIndices - 3]].y := v1.y; FVertex[FVertexIndices[FNumVertexIndices - 3]].z := v1.z; FVertex[FVertexIndices[FNumVertexIndices - 2]].x := v2.x; FVertex[FVertexIndices[FNumVertexIndices - 2]].y := v2.y; FVertex[FVertexIndices[FNumVertexIndices - 2]].z := v2.z; FVertex[FVertexIndices[FNumVertexIndices - 1]].x := v3.x; FVertex[FVertexIndices[FNumVertexIndices - 1]].y := v3.y; FVertex[FVertexIndices[FNumVertexIndices - 1]].z := v3.z; //add the material SetLength(FMatName, 1); FMatName[0] := fmaterial.Name; SetLength(FMatID, (FNumVertexIndices div 3)); //TODO: rewrite material usage.... //FMatId[(FNumVertexIndices div 3)] := fmaterial.TexID; //-1 //add mapping... SetLength(FMapping, FNumVertexIndices); FMapping[FVertexIndices[FNumVertexIndices - 3]].tu := v1.x; FMapping[FVertexIndices[FNumVertexIndices - 3]].tv := v1.y; FMapping[FVertexIndices[FNumVertexIndices - 2]].tu := v2.x; FMapping[FVertexIndices[FNumVertexIndices - 2]].tv := v2.y; FMapping[FVertexIndices[FNumVertexIndices - 1]].tu := v3.x; FMapping[FVertexIndices[FNumVertexIndices - 1]].tv := v3.y; end; procedure TBaseMesh.SetNumberOfVertex(Value: Integer); begin FNumVertex:=Value; SetLength(FVertex, Value); SetLength(FBoneIndices, Value); SetLength(FBoneWeights, Value); //SetLength(FMapping, Value); end; procedure TBaseMesh.SetBoneId(VertexIndex, BoneIndex: integer; aValue: single); begin FBoneIndices[VertexIndex][BoneIndex] := aValue; end; procedure TBaseMesh.SetBoneWeight(VertexIndex, WeightIndex: integer; aValue: single); begin FBoneWeights[VertexIndex][WeightIndex] := aValue; end; procedure TBaseMesh.SetMatName(Index: Integer; Value: string); begin //TODO: Rewrite... if ( Length(FMatName) <= Index ) then setlength(FMatName, Index+1); FMatName[Index] := Value; end; function TBaseMesh.GetMatName(Index: Integer): string; begin result := FMatName[Index]; end; procedure TBaseMesh.SetNumberOfIndices(Value: Integer); begin FNumVertexIndices := Value; fvertexindices:=nil; SetLength(FVertexIndices, 0); SetLength(FVertexIndices, Value); fmatid:=nil; SetLength(FMatId, 0); SetLength(FMatId, Value); end; procedure TBaseMesh.SetNumberOfMappings(Value: Integer); begin FNumMappings:=Value; SetLength(FMapping, Value); end; procedure TBaseMesh.SetNumberOfMappingIndices(Value: Integer); begin FNumMappingIndices := Value; SetLength(FMappingIndices, Value); end; procedure TBaseMesh.SetNumberOfNormals(Value: Integer); begin FNumNormals:=Value; //SetLength(FNormalIndices, Value); //TODO: should be removed here. SetLength(FVnormal, Value); end; procedure TBaseMesh.SetNumberOfNormalIndices(Value: Integer); begin FNumNormalIndices := Value; SetLength(FNormalIndices, Value); end; procedure TBaseMesh.SetFace(Index: Integer; Value: Word); begin FVertexIndices[Index] := Value; end; procedure TBaseMesh.SetNormals(Index: Integer; Value: T3dpoint); begin FVNormal[Index] := Value; end; function TBaseMesh.GetNormal(Index: Integer): Word; begin result:=FNormalIndices[Index]; end; procedure TBaseMesh.SetNormal(Index: Integer; Value: Word); begin FNormalIndices[Index]:=Value; end; end.
program auflager; uses crt,strings; const maxf:integer=10; festlager=1; loslager=2; rad:real=pi/180; type kraft = record f,fx,fy:real; alpha:real; lx,ly:real end; lager = record typ:integer; x,y:real; alpha:real; end; var f: array [0..10] of kraft; losl,festl:lager; Fl,Ff:kraft; anzahl_F:integer; ende:boolean; maxmb,maxq,maxt:real; maxmb_berechnet,auflager_berechnet,daten_vorhanden:boolean; s:string; procedure out_f(s:string; F:kraft); begin writeln( s,' Betrag: ',F.f:3:3,' N;',' Richtung:',F.alpha*180/pi:3:3,' Grad;'); writeln(' Fx: ',f.fx:3:3,' N; Fy: ',F.fy:3:3,' N;'); end; procedure wartetaste; begin writeln; writeln('Bitte eine Taste drcken.'); repeat until keypressed; readln end; procedure fehler(s:string); begin clrscr; textcolor(lightred+blink); gotoxy(30,12); writeln(s); delay(2000); textbackground(black); textcolor(white); end; { procedure readzahl(var x:real); const zeichen : set of char = ['1','2','3','4','5','6','7','8','9','0','-','+','.']; var c:char; temp:string; charok,ende:boolean; f:integer; begin ende:=false; repeat repeat c:=readkey; charok:=c in zeichen; until charok or (ord(c)=13); write(c); temp:=temp+c; until not charok; val(temp,x,f); writeln; end; } function frage:boolean; var c:char; begin write (' (j/n) ? '); c:=readkey; if c='j' then frage:=true else frage:=false; writeln (c); end; procedure read1r(s:string; var x:real); begin write(s); writeln(x:3:3); writeln; write('Wert „ndern'); if frage then begin gotoxy(wherex,wherey-3); write(s); readln(x); gotoxy(wherex,wherey-1); writeln(' '); gotoxy(wherex,wherey-1); write(s); writeln(x:3:3); gotoxy(wherex,wherey+1); writeln(' '); gotoxy(wherex,wherey-2); end else begin gotoxy(wherex,wherey-1); writeln(' '); gotoxy(wherex,wherey-2); end; end; procedure init_debug; begin { einfacher Tr„ger fr testzwecke, '0' im Men drcken buch seite 57 } anzahl_f:=1; with losl do begin x:=0.3; y:=0; alpha:=30*rad; typ:=loslager; end; with festl do begin x:=0; y:=0; alpha:=0; typ:=festlager; end; with f[1] do begin lx:=0.6; ly:=0.4; f:=350; alpha:=270*rad; fx:=0; fy:=0; end; daten_vorhanden:=true; maxmb_berechnet:=false; auflager_berechnet:=false; end; procedure init; var i:integer; n:real; s:string; ok:boolean; begin clrscr; ok:=false; maxmb_berechnet:=false; auflager_berechnet:=false; { A ..... Festlager B ..... Loslager Fa u. Fb immer in positiver Richtung A()---------------------------()B /\ /\ } with festl do begin writeln('Position Festlager eingeben (Nullpunkt beliebig):'); read1r('X-Koordinate:',x); read1r('Y-Koordinate:',y); end; with losl do begin writeln; writeln('Position Loslager eingeben:'); read1r('X-Koordinate:',x); read1r('Y-Koordinate:',y); alpha:=alpha/rad; read1r('Winkel zur positiven X-Achse:',alpha); alpha:=alpha*rad; end; writeln; repeat writeln; n:=anzahl_f; read1r('Anzahl der angreifenden Kr„fte (1..10; 0 => Ende):',n); gotoxy(wherex,wherey-2); until n<=10; writeln; writeln; if n=0 then halt; anzahl_f:=round(n); for i:=1 to anzahl_f do begin with f[i] do begin writeln('Kraft nummer ',i); writeln; read1r('X-Koordinate : ',lx); read1r('Y-Koordinate : ',ly); read1r('Betrag in Newton: ',f); read1r('Winkel zur positiven X-Achse in Grad: ',alpha); alpha:=alpha*rad; read1r('X-komponente in Newton: ',fx); read1r('Y-komponente in Newton: ',fy); if f=0 then begin f := sqrt(sqr(fx)+sqr(fy)); if fx<>0 then alpha := arctan(fy/fx) else alpha := pi*fy/abs(2*fy); end; writeln; end; end; daten_vorhanden:=true; end; function berechne_quadrant(xi,yi,xf,yf:real):integer; begin { in welchem Quadrant liegt (xi,yi) , wenn (xf,yf) den Nullpunkt eines rechtwinkligen Koordinatensystems bildet? } if (xi>=xf) and(yi>=yf) then berechne_quadrant:=1; if (xi< xf) and(yi>=yf) then berechne_quadrant:=2; if (xi< xf) and(yi< yf) then berechne_quadrant:=3; if (xi>=xf) and(yi< yf) then berechne_quadrant:=4; end; procedure berechne_auflager; var i:integer; em,emx,emy,efx,efy:real; xi,yi:real; quadrant:integer; begin clrscr; em:=0; emx:=0; emy:=0; efx:=0; efy:=0; { E M(festl) } for i:=1 to anzahl_f do begin with f[i] do begin quadrant:=berechne_quadrant(lx,ly,festl.x,festl.y); fx:=cos(alpha)*f; fy:=sin(alpha)*f; efx:=efx + fx; efy:=efy + fy; yi:=abs(ly-festl.y); xi:=abs(lx-festl.y); case quadrant of 1: begin emx:=emx + (-fx*yi); emy:=emy + (+fy*xi); end; 2: begin emx:=emx + (-fx*yi); emy:=emy + (-fy*xi); end; 3: begin emx:=emx + (+fx*yi); emy:=emy + (-fy*xi); end; 4: begin emx:=emx + (+fx*yi); emy:=emy + (+fy*xi); end; end; writeln('i=',i); writeln('Summe der Fxi : ',efx:3:3,'N'); writeln('Summe der Fyi : ',efy:3:3,'N'); writeln('Summe der Momente X: Fxi * yi =',fx:3:3,'N * ',yi:3:3,'m = ',emx:3:3,'Nm'); writeln('Summe der Momente Y: Fyi * xi =',fy:3:3,'N * ',xi:3:3,'m = ',emy:3:3,'Nm'); end; end; em:=emx + emy; writeln('Summe der Momente ges.: ',em:3:3,'Nm'); yi:=abs(losl.y-festl.y); xi:=abs(losl.x-festl.x); fl.alpha:=losl.alpha+pi/2; quadrant:=berechne_quadrant(losl.x,losl.y,festl.x,festl.y); case quadrant of 1: begin fl.f:=(-em)/(+sin(fl.alpha)*xi-cos(fl.alpha)*yi); end; 2: begin fl.f:=(-em)/(-sin(fl.alpha)*xi-cos(fl.alpha)*yi); end; 3: begin fl.f:=(-em)/(-sin(fl.alpha)*xi+cos(fl.alpha)*yi); end; 4: begin fl.f:=(-em)/(+sin(fl.alpha)*xi+cos(fl.alpha)*yi); end; end; fl.fx:=cos(fl.alpha)*fl.f; fl.fy:=sin(fl.alpha)*fl.f; ff.fx:=-(efx+fl.fx); ff.fy:=-(efy+fl.fy); ff.f:=sqrt(sqr(ff.fx)+sqr(ff.fy)); ff.alpha:=arctan(abs(ff.fy)/abs(ff.fx)); quadrant:=berechne_quadrant(ff.fx,ff.fy,0,0); case quadrant of 1: begin ff.alpha:=ff.alpha; end; 2: begin ff.alpha:=pi - ff.alpha; end; 3: begin ff.alpha:=pi + ff.alpha; end; 4: begin ff.alpha:=2*pi- ff.alpha; end; end; wartetaste; auflager_berechnet:=true; end; procedure ausgabe_auflager; var s:string; begin if auflager_berechnet then begin clrscr; writeln('Auflagerreaktionen'); writeln('=================='); writeln; writeln; out_f('Festlager :',ff); writeln; out_f('Loslager :',fl); writeln; writeln('Taste drcken'); repeat until keypressed; readln; end else begin clrscr; writeln('Auflager noch nicht berechnet!'); wartetaste; end; end; procedure mb(x:real; var mbx,q,t:real); var mfa,mfb:real; i:integer; begin mbx:=0; q:=0; t:=0; mfa:=0; mfb:=0; i:=1; repeat if f[i].lx<x then begin with f[i] do begin t:=t+fx; q:=q+fy; mbx:=mbx+fy*(x-lx); end; end; inc(i); until i>anzahl_f; if festl.x<x then begin t:=t+ff.fx; q:=q+ff.fy; mfa:=ff.fy*(x-festl.x); end else mfa:=0; if losl.x<x then begin t:=t+fl.fx; q:=q+fl.fy; mfb:=fl.fy*(x-losl.x); end else mfb:=0; mbx:=mfa + mfb + mbx; end; procedure berechne_mbq_beliebig; var x,q,t,mbx:real; i:integer; ende:boolean; begin ende:=false; clrscr; if auflager_berechnet then begin repeat writeln; read1r('Schnitt-X-Koordinate bitte eingeben (in meter):',x); mb(x,mbx,q,t); writeln('Mb an der stelle x=',x:3:3,'m betr„gt ',mbx:3:3,'Nm'); writeln('Q an der stelle x=',x:3:3,'m betr„gt ',q:3:3,'N'); writeln('T an der stelle x=',x:3:3,'m betr„gt ',t:3:3,'N'); write('Nochmal (j/n) ?'); repeat until keypressed; if readkey='n' then ende:=true; writeln; until ende; end else begin writeln('Zuerst schritte 1 u. 2 ausfhren !'); wartetaste; end; end; procedure berechne_maxmbq; var mbx,q,t,x_q,x_t,x_mb,xu,xo,x,sx,l:real; begin clrscr; x:=0; sx:=0; maxQ:=0; maxT:=0; maxMb:=0; mbx:=0; q:=0; t:=0; x_q:=0; x_t:=0; x_mb:=0; if festl.x>losl.x then l:=festl.x else l:=losl.x; read1r('untere Grenze:',xu); read1r('obere Grenze :',xo); read1r('Schrittweite bitte eingeben (in meter):',sx); writeln; x:=xu; while(x<(xo-sx)) do begin mb(x,mbx,q,t); if abs(mbx)>abs(maxMb) then begin maxMb:=mbx; x_mb:=x; end; if abs(t)>abs(maxt) then begin maxt:=t; x_t:=x; end; if abs(q)>abs(maxq) then begin maxq:=q; x_q:=x; end; x:=x+sx; writeln('x=',x:3:3); gotoxy(wherex,wherey-1); end; writeln; writeln; writeln('maxMb an der stelle x=',x_mb:3:3,'m betr„gt ',maxmb:3:3,'Nm'); writeln('maxQ an der stelle x=',x_q:3:3,'m betr„gt ',maxq:3:3,'N'); writeln('maxT an der stelle x=',x_t:3:3,'m betr„gt ',maxt:3:3,'N'); wartetaste; maxmb_berechnet:=true; end; procedure berechne_f_beliebig; begin end; procedure berechne_maxf; begin end; procedure dimensioniere; begin end; procedure menu; var wahl,c:integer; s:string; begin wahl:=-1; clrscr; writeln(' Tr„ber V1.0'); writeln(' ==========='); writeln; writeln; writeln; writeln(' 1......Dateneingabe'); if daten_vorhanden then textcolor(white) else textcolor(yellow); writeln(' 2......Auflagerreaktionen berechnen'); if auflager_berechnet then textcolor(white) else textcolor(yellow); writeln(' 3......Auflagerreaktionen anzeigen'); if auflager_berechnet then textcolor(white) else textcolor(yellow); writeln(' 4......Biegemoment Mb u. Querkraft Q an einer beliebigen'); writeln(' Stelle x anzeigen'); if auflager_berechnet then textcolor(white) else textcolor(yellow); writeln(' 5......max. Mb berechnen und anzeigen'); if auflager_berechnet then textcolor(white) else textcolor(yellow); writeln(' 6......Durchbiegung an einer beliebigen Stelle x'); writeln(' berechnen und anzeigen'); if auflager_berechnet then textcolor(white) else textcolor(yellow); writeln(' 7......maximale Durchbiegung anzeigen'); if maxmb_berechnet then textcolor(white) else textcolor(yellow); writeln(' 8......Dimensionierung'); textcolor(white); writeln; writeln(' 9......Programmende'); gotoxy(50,24); write('(C) 1994 by Stefan Eletzhofer'); gotoxy(10,20); while (wahl<0) or (wahl>9) and (c<>0) do begin write('Ihre Wahl:'); readln(s); val(s,wahl,c); end; case wahl of 0: init_debug; 1: if auflager_berechnet then begin init; auflager_berechnet:=false end else init; 2: if daten_vorhanden then berechne_auflager else fehler('Zuerst Daten eingeben!'); 3: if auflager_berechnet then ausgabe_auflager else fehler('Zuerst Auflager berechnen!'); 4: if auflager_berechnet then berechne_mbq_beliebig else fehler('Zuerst Auflager berechnen!'); 5: if auflager_berechnet then berechne_maxmbq else fehler('Zuerst Auflager berechnen!'); 6: if auflager_berechnet then berechne_f_beliebig else fehler('Zuerst Auflager berechnen!'); 7: if auflager_berechnet then berechne_maxf else fehler('Zuerst Auflager berechnen!'); 8: if maxmb_berechnet then dimensioniere else fehler('Zuerst maximales Biegemoment berechnen!'); 9: ende:=true; end; end; begin highvideo; textbackground(black); textcolor(white); ende:=false; maxmb_berechnet:=false; auflager_berechnet:=false; init_debug; daten_vorhanden:=false; repeat menu; until ende; end.
unit Commons; interface type TTestProc = procedure; procedure Run(const Desc: String; const TestProc: TTestProc); implementation uses System.SysUtils; procedure Run(const Desc: String; const TestProc: TTestProc); begin Write(Desc.PadRight(50, '.')); try TestProc(); WriteLn('OK'); except on E: Exception do begin WriteLn('FAILED'); WriteLn(E.Message); end; end; end; end.
(* * Renvoie le nombre de cellules vivantes autours de la case situ‚e dans le coin en haut … gauche. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildTopCircuLeftCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildTopCircuLeftCircu := tab[y, x + 1] + tab[y + 1, x] + tab[y + 1, x + 1] + tab[height - 1, x + 1] + tab[height - 1, x] + tab[height - 1, width - 1] + tab[y, width - 1] + tab[y + 1, width - 1]; End; (* * Renvoie le nombre de cellules vivantes autours de la case situ‚e dans coin en haut … droite. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildTopCircuRightCircu(var tab : arr; y, x : Integer) : Integer; Begin nbChildTopCircuRightCircu := tab[y, x - 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y + 1, 0] + tab[y, 0] + tab[height - 1, 0] + tab[height - 1, x] + tab[height - 1, x - 1]; End; (* * Renvoie le nombre de cellules vivantes autours d'une case situ‚e dans sur la premiŠre ligne. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildTopCircu(var tab : arr; y, x : Integer) : Integer; Begin nbChildTopCircu := tab[y, x -1] + tab[y, x + 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y + 1, x + 1] + tab[height - 1, x + 1] + tab[height - 1, x] + tab[height - 1, x - 1]; End; (* * Renvoie le nombre de cellules vivantes autours de la case situ‚e dans le coin en bas … gauche. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildBottomCircuLeftCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottomCircuLeftCircu := tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x + 1] + tab[y - 1, width - 1] + tab[y, width - 1] + tab[0, width - 1] + tab[0, x] + tab[0, x + 1]; End; (* * Renvoie le nombre de cellules vivantes autours de la case situ‚e dans le coin en bas … droite. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildBottomCircuRightCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottomCircuRightCircu := tab[y, x -1] + tab[y - 1, x] + tab[y - 1, x -1] + tab[0, x - 1] + tab[0, x] + tab[0, 0] + tab[y, 0] + tab[y - 1, 0]; End; (* * Renvoie le nombre de cellules vivantes autours d'une case situ‚e sur la derniŠre ligne. * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildBottomCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottomCircu := tab[y, x - 1] + tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x - 1] + tab[y -1, x + 1] + tab[0, x - 1] + tab[0, x] + tab[0, x + 1]; End; (* * Renvoie le nombre de cellules vivantes autours de la case situ‚e en d‚but de ligne (… gauche). * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildLeftCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildLeftCircu := tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x +1] + tab[y + 1, x] + tab[y + 1, x + 1] + tab[y + 1, width - 1] + tab[y, width - 1] + tab[y - 1, width -1]; End; (* * Renvoie le nombre de cellules vivantes autours de la case situ‚e en fin de ligne (… droite). * Le tableau est trait‚ de maniŠre circulaire, si l'index de la case adjacente est hors des limites du tableau, * elle va chercher la cellule situ‚e … l'autre extr‚mit‚e. *) Function nbChildRightCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildRightCircu := tab[y, x - 1] + tab[y - 1, x] + tab[y - 1, x - 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y - 1, 0] + tab[y, 0] + tab[y + 1, 0]; End; (* * Renvoie le nombre de cellules vivantes autours d'une case qui n'est pas sur une bordure. *) Function nbChildNormalCircu(var tab : arr; y, x: Integer) : Integer; Begin nbChildNormalCircu := tab[y, x + 1] + tab[y + 1, x + 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y, x - 1] + tab[y - 1, x - 1] + tab[y - 1, x] + tab[y - 1, x + 1]; End; (* * Met … jour la grille de maniŠre circulaire. Appelle la fonction permettant de d‚terminer le nombre de cellules adjacentes * qui sont vivantes. Appel des fonctions diff‚rentes si la cellule se situe sur un bord. * Une fois le nombre d'enfant obtenu, appel les fonctions qui d‚termine si la cellule doit vivre ou mourir au prochai tours. * Enfin stocke les donn‚es du tours suivant dans le tableau du tours courant. *) Procedure updateGridCircu(var tab1, tab2 : arr); var y, x, nbChild : Integer; Begin for y := 0 to height - 1 do begin for x := 0 to width - 1do begin //bottom if(y = 0) Then Begin if(x = 0) Then Begin nbChild := nbChildTopCircuLeftCircu(tab1, y, x); End Else if(x = width - 1) Then Begin nbChild := nbChildTopCircuRightCircu(tab1, y, x); End Else Begin nbChild := nbChildTopCircu(tab1, y, x); end; End Else if(y = height - 1) Then Begin if(x = 0) Then Begin nbChild := nbChildBottomCircuLeftCircu(tab1, y, x); end Else if(x = width - 1)Then Begin nbChild := nbChildBottomCircuRightCircu(tab1, y, x); End Else Begin nbChild := nbChildBottomCircu(tab1, y, x); end; End Else if(x = 0)Then Begin nbChild := nbChildLeftCircu(tab1, y, x); end Else if(x = width - 1)Then Begin nbChild := nbChildRightCircu(tab1, y, x); end Else Begin nbChild := nbChildNormalCircu(tab1, y, x); end; if(tab1[y, x] = 1) Then Begin updateLiving(tab2, y, x, nbChild); End Else Begin updateDead(tab2, y, x, nbChild); End; End; End; tab1 := tab2; end;
unit logsMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, logsSetting, ExtCtrls, StdCtrls, Buttons; type TFormMain = class(TForm) Memo1: TMemo; Panel1: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; StaticTextLogFile: TStaticText; StaticTextNoTh: TStaticText; StaticTextLifeTime: TStaticText; procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} procedure TFormMain.BitBtn1Click(Sender: TObject); begin Close; end; procedure TFormMain.BitBtn2Click(Sender: TObject); begin FormSetting.ShowModal; end; procedure TFormMain.FormShow(Sender: TObject); begin FormSetting.ReadSetting; StaticTextLogFile.Caption:='Файл записи логов: '+FormSetting.logSet.logFileName; StaticTextNoTh.Caption:='Количество потоков: '+IntToStr(FormSetting.logSet.numberOfThread); StaticTextLifeTime.Caption:='Время жизни записи в лог (сек.): '+IntToStr(FormSetting.logSet.OldClearTime); end; end.
{ Copyright (c) 2013 Jeroen Wiert Pluimers for BeSharp.net and Coding In Delphi. Full BSD License is available at http://BeSharp.codeplex.com/license } unit AnimalFormUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, AnimalClassesUnit, System.Rtti; type TAnimalForm = class(TForm) AnimalTypeRadioGroup: TRadioGroup; FillAnimalTypesButton: TButton; LogMemo: TMemo; ShowAnimalLocomotionsButton: TButton; ActionManager: TActionManager; FillAnimalTypesAction: TAction; ShowAnimalLocomotionsAction: TAction; procedure FillAnimalTypesActionExecute(Sender: TObject); procedure ShowAnimalLocomotionsActionExecute(Sender: TObject); procedure ShowAnimalLocomotionsActionUpdate(Sender: TObject); strict private function SupportsAndLog_Fails(const Instance: IInterface; out Intf; const IID: TGUID; const InterfaceTypeInfo: Pointer = nil): Boolean; function SupportsAndLog_Works(const Instance: IInterface; out Intf; const IID: TGUID; const InterfaceTypeInfo: Pointer = nil): Boolean; strict protected procedure Log(const Line: string); overload; virtual; procedure Log(AnimalClass: TClass); overload; virtual; public function GetAnimalClasses(): TArray<TAnimalClass>; function SupportsAndLog(const Instance: IInterface; const IID: TGUID; out Intf; const InterfaceTypeInfo: Pointer = nil): Boolean; overload; end; var AnimalForm: TAnimalForm; implementation uses RttiHelpers, LocomotionInterfacesUnit; {$R *.dfm} function TAnimalForm.GetAnimalClasses(): TArray<TAnimalClass>; begin // Without referencing the animal classes, no RTTI will be generated. // For the code in FillAnimalTypesActionExecute, it needs to be in the order of the hierarchy. Result := TArray<TAnimalClass>.Create( TAnimal, TBird, TDuck, TEmu, TPigeon, TFish, THerring, TSalmon, TShark, TInsect, TAnt, TButterfly, TMammal, TBat, TCat, TDog, THuman, TWhale ); end; procedure TAnimalForm.FillAnimalTypesActionExecute(Sender: TObject); var AnimalClass: TAnimalClass; RttiContext: TRttiContext; RttiTypes: TArray<TRttiType>; RttiType: TRttiType; Predicate: TPredicate<TRttiType>; begin // Basically two ways to do this: through the AnimalClasses, or through all of the classes through RTTI // first way: AnimalTypeRadioGroup.Items.Clear(); for AnimalClass in GetAnimalClasses() do begin Log(AnimalClass); AnimalTypeRadioGroup.Items.Add( StringOfChar(' ', 4*AnimalClass.ClassHierarchyDepth()-12) + AnimalClass.ClassName); end; AnimalTypeRadioGroup.ItemIndex := 0; // second way: Predicate := function(ARttiType: TRttiType): Boolean begin Result := ARttiType.GetUnitName = TAnimal.UnitName; Result := Result and ARttiType.IsInstance; end; RttiContext := TRttiContext.Create(); RttiTypes := RttiContext.FindTypes(Predicate); for RttiType in RttiTypes do begin Log(RttiType.AsInstance.MetaclassType); end; end; procedure TAnimalForm.Log(const Line: string); begin LogMemo.Lines.Add(Line); end; procedure TAnimalForm.Log(AnimalClass: TClass); begin Log(Format('%s (%s) %d', [ AnimalClass.QualifiedClassName, AnimalClass.ClassName, AnimalClass.ClassHierarchyDepth])); end; procedure TAnimalForm.ShowAnimalLocomotionsActionExecute(Sender: TObject); var AnimalClassName: string; AnimalClass: TAnimalClass; Animal: IInterface; Flying: IFlying; Jumping: IJumping; Running: IRunning; Swimming: ISwimming; begin Log(''); AnimalClassName := Trim(AnimalTypeRadioGroup.Items[AnimalTypeRadioGroup.ItemIndex]); Log(Format('Searching for an animal class matching %s', [AnimalClassName])); for AnimalClass in GetAnimalClasses() do begin if AnimalClass.ClassNameIs(AnimalClassName) then begin Log(Format('Constructing an instance of %s', [AnimalClassName])); Animal := AnimalClass.Create(Self.Log); Log(Format('Listing the interfaces supported by %s', [AnimalClassName])); if SupportsAndLog(Animal, IJumping, Jumping) then //, TypeInfo(IJumping)) then Jumping.Jump(); if SupportsAndLog(Animal, IFlying, Flying) then //, TypeInfo(IFlying)) then Flying.Fly(); if SupportsAndLog(Animal, IRunning, Running) then //, TypeInfo(IRunning)) then Running.Run(); if SupportsAndLog(Animal, ISwimming, Swimming) then //, TypeInfo(ISwimming)) then Swimming.Swim(); end; end; end; procedure TAnimalForm.ShowAnimalLocomotionsActionUpdate(Sender: TObject); var Enabled: Boolean; begin Enabled := AnimalTypeRadioGroup.Items.Count > 0; Enabled := Enabled and (AnimalTypeRadioGroup.ItemIndex <> -1); (Sender as TAction).Enabled := Enabled; end; { Interface support routines } function TAnimalForm.SupportsAndLog(const Instance: IInterface; const IID: TGUID; out Intf; const InterfaceTypeInfo: Pointer = nil): Boolean; begin Result := SupportsAndLog_Works(Instance, Intf, IID, InterfaceTypeInfo); // Result := SupportsAndLog_Fails(Instance, Intf, IID, InterfaceTypeInfo); end; function TAnimalForm.SupportsAndLog_Fails(const Instance: IInterface; out Intf; const IID: TGUID; const InterfaceTypeInfo: Pointer = nil): Boolean; var RttiContext: TRttiContext; Line: string; RttiType: TRttiType; begin // This works because we always call RttiContext.FindType(IID) even if no class implements the interface with the IID. // When no such class exists, FindType will return nil, and we AV when using RttiType. // That is demonstrated in RttiContext_GetTypes_vs_GetType_on_Interfaces_ConsoleProject.dproj if Instance is TObject then Line := TObject(Instance).ClassName; Result := Supports(Instance, IID, Intf); RttiContext := TRttiContext.Create(); try RttiType := RttiContext.FindType(IID); if not Assigned(RttiType) then if Assigned(InterfaceTypeInfo) then RttiType := RttiContext.GetType(InterfaceTypeInfo); if Result then begin Line := Format('%s implements %s', [Line, RttiType.Name]); Log(Line); end else begin Line := Format('%s does not implement %s', [Line, RttiType.Name]); Log(Line); end; finally RttiContext.Free; end; end; function TAnimalForm.SupportsAndLog_Works(const Instance: IInterface; out Intf; const IID: TGUID; const InterfaceTypeInfo: Pointer = nil): Boolean; var RttiContext: TRttiContext; Line: string; RttiType: TRttiType; begin // This works because we only call RttiContext.FindType(IID) when the interface with the IID actually is implemented by a class Result := Supports(Instance, IID, Intf); if Result then begin if Instance is TObject then Line := TObject(Instance).ClassName; RttiContext := TRttiContext.Create; try RttiType := RttiContext.FindType(IID); if not Assigned(RttiType) then if Assigned(InterfaceTypeInfo) then RttiType := RttiContext.GetType(InterfaceTypeInfo); Line := Format('%s implements %s', [Line, RttiType.Name]); Log(Line); finally RttiContext.Free; end; end; end; end.
unit smuAdministrativo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, smuBasico, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, dmuPrincipal, uTypes, uSQLGenerator, uQuery, Datasnap.Provider, uClientDataSet, uUtils, System.RegularExpressions, Datasnap.DBClient; type TsmAdministrativo = class(TsmBasico) qPessoa: TRfQuery; qPerfil: TRfQuery; qPerfilNOME: TStringField; qPessoaNOME: TStringField; qPessoaRG: TStringField; qPessoaCPF: TStringField; qPessoaENDERECO: TStringField; qPessoaLOGIN: TStringField; qPessoaSENHA: TStringField; qPerfil_Permissao: TRfQuery; qPerfil_PermissaoPERMISSAO: TStringField; qPerfil_PermissaoVISUALIZAR: TSmallintField; qPerfil_PermissaoINCLUIR: TSmallintField; qPerfil_PermissaoALTERAR: TSmallintField; qPerfil_PermissaoEXCLUIR: TSmallintField; qPessoaID: TIntegerField; qPessoaBAIRRO: TStringField; qPessoaCOMPLEMENTO: TStringField; qPerfilID: TIntegerField; qPerfil_PermissaoID: TIntegerField; qPerfil_PermissaoID_PERFIL: TIntegerField; qPessoa_Perfil: TRfQuery; qPessoa_PerfilID: TIntegerField; qPessoa_PerfilID_PESSOA: TIntegerField; qPessoa_PerfilID_PERFIL: TIntegerField; qPessoaEMAIL: TStringField; qPessoaCELULAR: TStringField; qPessoaTELEFONE: TStringField; qPessoaATIVO: TSmallintField; qOrganizacao: TRfQuery; qOrganizacao_Pessoa: TRfQuery; qOrganizacaoID: TIntegerField; qOrganizacaoNOME: TStringField; qOrganizacaoCNPJ: TStringField; qOrganizacaoINSCRICAO_ESTADUAL: TStringField; qOrganizacaoENDERECO: TStringField; qOrganizacaoBAIRRO: TStringField; qOrganizacaoCOMPLEMENTO: TStringField; qOrganizacaoTELEFONE: TStringField; qOrganizacao_PessoaID: TIntegerField; qOrganizacao_PessoaID_PESSOA: TIntegerField; qOrganizacao_PessoaID_ORGANIZACAO: TIntegerField; qOrganizacao_PessoaFUNCAO: TStringField; qProjeto: TRfQuery; qProjetoID: TIntegerField; qProjetoNOME: TStringField; qProjetoDATA_INICIO: TDateField; qProjetoDATA_TERMINO: TDateField; qPerfilTIPO: TSmallintField; qProjetoORCAMENTO: TBCDField; qProjeto_Organizacao: TRfQuery; qProjeto_Financiador: TRfQuery; qProjeto_FinanciadorID: TIntegerField; qProjeto_FinanciadorID_PROJETO: TIntegerField; qProjeto_FinanciadorID_FINANCIADOR: TIntegerField; qProjeto_OrganizacaoID: TIntegerField; qProjeto_OrganizacaoID_PROJETO: TIntegerField; qProjeto_OrganizacaoID_ORGANIZACAO: TIntegerField; qProjeto_Documento: TRfQuery; qProjeto_DocumentoID: TIntegerField; qProjeto_DocumentoID_PROJETO: TIntegerField; qProjeto_DocumentoNOME: TStringField; qProjeto_DocumentoDATA_UPLOAD: TSQLTimeStampField; qProjeto_DocumentoDOCUMENTO: TBlobField; qProjeto_Pessoa: TRfQuery; qProjeto_PessoaID: TIntegerField; qProjeto_PessoaID_PROJETO: TIntegerField; qProjeto_PessoaID_PESSOA: TIntegerField; qProjeto_PessoaFUNCAO: TStringField; qProjetoID_BANCO_CONTA_CORRENTE: TIntegerField; qProjeto_Financiador_Pagto: TRfQuery; qProjeto_Financiador_PagtoID: TIntegerField; qProjeto_Financiador_PagtoID_PROJETO_FINANCIADOR: TIntegerField; qProjeto_Financiador_PagtoVALOR: TBCDField; qProjeto_Financiador_PagtoDATA: TDateField; qProjeto_DocumentoNOME_ORIGINAL: TStringField; qPessoaTIPO: TSmallintField; qAtividade: TRfQuery; qAtividadeID: TIntegerField; qAtividadeNOME: TStringField; qAtividadeID_SOLICITANTE: TIntegerField; qAtividadeID_RESPONSAVEL: TIntegerField; qAtividadeSTATUS: TSmallintField; qAtividadeDATA_INICIAL: TSQLTimeStampField; qAtividadeDATA_FINAL: TSQLTimeStampField; qAtividade_Pessoa: TRfQuery; qAtividade_Projeto: TRfQuery; qAtividade_ProjetoID: TIntegerField; qAtividade_ProjetoID_ATIVIDADE: TIntegerField; qAtividade_ProjetoID_PROJETO: TIntegerField; qAtividade_PessoaID: TIntegerField; qAtividade_PessoaID_ATIVIDADE: TIntegerField; qAtividade_PessoaID_PESSOA: TIntegerField; qAtividade_PessoaFUNCAO: TStringField; qAtividade_Arquivo: TRfQuery; qAtividade_ArquivoID: TIntegerField; qAtividade_ArquivoID_ATIVIDADE: TIntegerField; qAtividade_ArquivoNOME: TStringField; qAtividade_ArquivoNOME_ORIGINAL: TStringField; qAtividade_Vinculo: TRfQuery; qAtividade_VinculoID: TIntegerField; qAtividade_VinculoTIPO_VINCULO: TSmallintField; qAtividade_Comentario: TRfQuery; qAtividade_ComentarioID: TIntegerField; qAtividade_ComentarioID_ATIVIDADE: TIntegerField; qAtividade_ComentarioID_PESSOA: TIntegerField; qAtividade_ComentarioDATA_HORA: TSQLTimeStampField; qAtividade_ArquivoARQUIVO: TBlobField; qAtividade_VinculoID_ATIVIDADE_ORIGEM: TIntegerField; qAtividadeID_PROJETO: TIntegerField; qAtividade_ArquivoDATA_UPLOAD: TSQLTimeStampField; qAtividade_ProjetoNOME_PROJETO: TStringField; qAtividade_VinculoNOME_ATIVIDADE_ORIGEM: TStringField; qAtividade_VinculoID_ATIVIDADE_VINCULO: TIntegerField; qAtividade_VinculoNOME_ATIVIDADE_VINCULO: TStringField; qProjetoSTATUS: TSmallintField; qAtividadeNOME_PROJETO: TStringField; qPessoaID_CIDADE: TIntegerField; qPessoaCIDADE: TStringField; qOrganizacaoID_CIDADE: TIntegerField; qOrganizacaoCIDADE: TStringField; qPessoaDATA_NASCIMENTO: TDateField; qPessoaOBSERVACAO: TStringField; qAtividadeDESCRICAO: TStringField; qAtividade_ArquivoDESCRICAO: TStringField; qAtividade_ComentarioCOMENTARIO: TStringField; qAtividade_ProjetoOBSERVACAO: TStringField; qAtividade_VinculoOBSERVACAO: TStringField; qOrganizacao_PessoaOBSERVACAO: TStringField; qPerfilDESCRICAO: TStringField; qProjetoDESCRICAO: TStringField; qProjeto_FinanciadorOBSERVACAO: TStringField; qAtividade_PessoaNOME_PESSOA: TStringField; qAtividade_PessoaNOME_ATIVIDADE: TStringField; qProjeto_Rubrica: TRfQuery; qProjeto_Area: TRfQuery; qProjeto_AreaID: TIntegerField; qProjeto_AreaID_PROJETO: TIntegerField; qProjeto_Financiador_PagtoPERCENTUAL: TBCDField; qOrganizacaoLOGO: TBlobField; qFundo: TRfQuery; qFundoID: TIntegerField; qFundoID_ORGANIZACAO: TIntegerField; qFundoNOME: TStringField; qFundoSALDO: TBCDField; qFundoDESCRICAO: TStringField; qProjeto_FinanciadorVALOR_FINANCIADO: TBCDField; qProjeto_Financiador_PagtoID_PROJETO_ORGANIZACAO: TIntegerField; qProjeto_Financiador_PagtoNOME_ORGANIZACAO: TStringField; qProjeto_Financiador_PagtoFORMA_PAGTO: TSmallintField; qPessoaCEP: TStringField; qFundoREQUER_AUTORIZACAO: TSmallintField; qAtividadeDATA_CADASTRO: TSQLTimeStampField; qAtividadeDATA_ALTERACAO: TSQLTimeStampField; qProjeto_RubricaCALC_VALOR_GASTO: TBCDField; qProjeto_RubricaCALC_VALOR_RECEBIDO: TBCDField; qOrganizacaoSITE: TStringField; qOrganizacaoEMAIL: TStringField; qAtividadeDATA_FINALIZACAO: TSQLTimeStampField; dspqAtividade: TDataSetProvider; qProjeto_AreaID_AREA_ATUACAO: TIntegerField; qArea_Atuacao: TRFQuery; qArea_Execucao: TRFQuery; qArea_ExecucaoID: TIntegerField; qArea_ExecucaoID_AREA_ATUACAO: TIntegerField; qArea_ExecucaoNOME: TStringField; qProjeto_AreaNOME: TStringField; qAtividadeID_AREA_ATUACAO: TIntegerField; qAtividadeID_AREA_EXECUCAO: TIntegerField; qAtividadeAREA_ATUACAO: TStringField; qAtividadeAREA_EXECUCAO: TStringField; qOrganizacaoLOGO_SECUNDARIA: TBlobField; qAtividadeNOME_SOLICITANTE: TStringField; qAtividadeNOME_RESPONSAVEL: TStringField; qProjeto_Finan_Pagto_Rubrica: TRFQuery; qProjeto_Finan_Pagto_RubricaID: TIntegerField; qProjeto_Finan_Pagto_RubricaID_PROJETO_RUBRICA: TIntegerField; qProjeto_Finan_Pagto_RubricaRUBRICA: TStringField; qProjeto_Finan_Pagto_RubricaID_PROJETO_FINANCIADOR_PAGTO: TIntegerField; qProjeto_Finan_Pagto_RubricaVALOR: TBCDField; qProjeto_RubricaID: TIntegerField; qProjeto_RubricaID_PROJETO: TIntegerField; qProjeto_RubricaID_RUBRICA: TIntegerField; qProjeto_RubricaORCAMENTO: TBCDField; qProjeto_RubricaGASTO: TBCDField; qProjeto_RubricaGASTO_TRANSFERENCIA: TBCDField; qProjeto_RubricaRECEBIDO: TBCDField; qProjeto_RubricaRECEBIDO_TRANSFERENCIA: TBCDField; qProjeto_RubricaAPROVISIONADO: TBCDField; qProjeto_RubricaSALDO_REAL: TBCDField; qProjeto_RubricaSALDO_PREVISTO: TBCDField; qProjeto_RubricaNOME_RUBRICA: TStringField; procedure qProjeto_RubricaCalcFields(DataSet: TDataSet); procedure dspqAtividadeAfterUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind); private { Private declarations } protected function fprMontarWhere(ipTabela, ipWhere: string; ipParam: TParam): string; override; public { Public declarations } end; var smAdministrativo: TsmAdministrativo; implementation {$R *.dfm} { TsmAdministrativo } procedure TsmAdministrativo.dspqAtividadeAfterUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind); var vaStatus: integer; begin inherited; if UpdateKind in [ukInsert, ukModify] then begin if (not VarIsNull(DeltaDS.FieldByName('STATUS').NewValue)) then begin if TryStrToInt(VarToStrDef(DeltaDS.FieldByName('STATUS').NewValue, ''), vaStatus) then begin if vaStatus in [Ord(saFinalizada), Ord(saCancelada)] then begin if DeltaDS.FieldByName('DATA_FINALIZACAO').IsNull then begin Connection.ExecSQL('update atividade set atividade.data_finalizacao = current_timestamp where atividade.id = :ID', [DeltaDS.FieldByName(TBancoDados.coId).OldValue]); Connection.Commit; end; end else begin Connection.ExecSQL('update atividade set atividade.data_finalizacao = null where atividade.id = :ID', [DeltaDS.FieldByName(TBancoDados.coId).OldValue]); Connection.Commit; end; end; end; end; end; function TsmAdministrativo.fprMontarWhere(ipTabela, ipWhere: string; ipParam: TParam): string; var vaValor, vaOperador: string; vaCodigos: TArray<integer>; begin Result := inherited; TUtils.ppuExtrairValorOperadorParametro(ipParam.Text, vaValor, vaOperador, TParametros.coDelimitador); if ipTabela = 'PESSOA' then begin if ipParam.Name = TParametros.coLogin then Result := TSQLGenerator.fpuFilterString(Result, ipTabela, 'login', vaValor, vaOperador) else if ipParam.Name = TParametros.coTipo then Result := TSQLGenerator.fpuFilterInteger(Result, ipTabela, 'tipo', TUtils.fpuConverterStringToArrayInteger(vaValor), vaOperador) end else if ipTabela = 'PROJETO' then begin if ipParam.Name = TParametros.coStatus then Result := TSQLGenerator.fpuFilterInteger(Result, ipTabela, 'STATUS', vaValor.ToInteger(), vaOperador) end else if ipTabela = 'ATIVIDADE' then begin if ipParam.Name = TParametros.coData then begin Result := Result + ' ((ATIVIDADE.DATA_INICIAL between ' + QuotedStr(FormatDateTime('dd.mm.yyyy', TUtils.fpuExtrairData(vaValor, 0))) + ' AND ' + QuotedStr(FormatDateTime('dd.mm.yyyy', TUtils.fpuExtrairData(vaValor, 1))) + ') or ' + '(ATIVIDADE.DATA_FINAL between ' + QuotedStr(FormatDateTime('dd.mm.yyyy', TUtils.fpuExtrairData(vaValor, 0))) + ' AND ' + QuotedStr(FormatDateTime('dd.mm.yyyy', TUtils.fpuExtrairData(vaValor, 1))) + ')) ' + vaOperador; end else if ipParam.Name = TParametros.coProjeto then begin vaCodigos := TUtils.fpuConverterStringToArrayInteger(vaValor); Result := TSQLGenerator.fpuFilterInteger(Result, ['ATIVIDADE', 'ATIVIDADE_PROJETO'], ['ID_PROJETO', 'ID_PROJETO'], [vaCodigos, vaCodigos], TOperadores.coOR, vaOperador); end; end; end; procedure TsmAdministrativo.qProjeto_RubricaCalcFields(DataSet: TDataSet); begin inherited; qProjeto_RubricaCALC_VALOR_GASTO.AsFloat := qProjeto_RubricaGASTO.AsFloat; qProjeto_RubricaCALC_VALOR_RECEBIDO.AsFloat := qProjeto_RubricaRECEBIDO.AsFloat; if qProjeto_RubricaGASTO_TRANSFERENCIA.AsFloat > qProjeto_RubricaRECEBIDO_TRANSFERENCIA.AsFloat then qProjeto_RubricaCALC_VALOR_GASTO.AsFloat := qProjeto_RubricaCALC_VALOR_GASTO.AsFloat + (qProjeto_RubricaGASTO_TRANSFERENCIA.AsFloat - qProjeto_RubricaRECEBIDO_TRANSFERENCIA.AsFloat) else if qProjeto_RubricaGASTO_TRANSFERENCIA.AsFloat < qProjeto_RubricaRECEBIDO_TRANSFERENCIA.AsFloat then qProjeto_RubricaCALC_VALOR_RECEBIDO.AsFloat := qProjeto_RubricaCALC_VALOR_RECEBIDO.AsFloat + (qProjeto_RubricaRECEBIDO_TRANSFERENCIA.AsFloat - qProjeto_RubricaGASTO_TRANSFERENCIA.AsFloat); end; end.
unit frexBMP; interface {$I FR.inc} uses Windows, SysUtils, Classes, Graphics, Math, UITypes, FR_BarC, FR_Class, FR_Shape; type TFrameSet = set of (Left, Top, Bottom, Right); TfrBMPExport = class(TComponent)// fake component end; TfrBMPExportFilter = class(TfrExportFilter) private LastY, CurrPage: Integer; Image: TBitmap; Canvas: TCanvas; function CalcRect(const x, y: Integer; const View: TfrView): TRect; function CalcFrameSet(const View: TfrView): TFrameSet; procedure DrawBackGround(const View: TfrView; const R: TRect); procedure DrawFrame(const View: TfrView; const R: TRect; const FrameSet: TFrameSet); procedure DrawBarCode(const View: TfrBarCodeView; const R: TRect); procedure DrawPicture(const View: TfrPictureView; const R: TRect); procedure DrawEndLine; procedure DrawShape(const View: TfrShapeObject; const R: TRect); public constructor Create(AStream: TStream); override; destructor Destroy; override; procedure OnBeginPage; override; procedure OnEndPage; override; procedure OnText(x, y: Integer; const Text: string; View: TfrView); override; procedure OnData(x, y: Integer; View: TfrView); override; end; implementation type TfrMemoView_ = class(TfrMemoView); procedure TfrBMPExportFilter.DrawEndLine; begin Canvas.Pen.Color := RGB(220, 220, 220); Canvas.Pen.Style := psDash; Canvas.Pen.Width := 1; Canvas.MoveTo(0, Pred(Image.Height)); Canvas.LineTo(Image.Width, Pred(Image.Height)); end; procedure TfrBMPExportFilter.DrawBackGround(const View: TfrView; const R: TRect); begin Canvas.Brush.Style := bsSolid; Canvas.Pen.Style := psClear; Canvas.Brush.Color := View.FillColor; Canvas.Rectangle(R); end; function TfrBMPExportFilter.CalcFrameSet(const View: TfrView): TFrameSet; begin Result := []; if ((View.FrameTyp and $F) = $F) and (View.FrameStyle = 0) then begin Result := [Left, Top, Bottom, Right]; end else begin if (View.FrameTyp and $1) <> 0 then Include(Result, Right); if (View.FrameTyp and $4) <> 0 then Include(Result, Left); if (View.FrameTyp and $2) <> 0 then Include(Result, Bottom); if (View.FrameTyp and $8) <> 0 then Include(Result, Top); end; end; procedure TfrBMPExportFilter.DrawFrame(const View: TfrView; const R: TRect; const FrameSet: TFrameSet); begin if FrameSet = [] then Exit; Canvas.Pen.Style := TPenStyle(View.FrameStyle); Canvas.Pen.Color := View.FrameColor; Canvas.Pen.Width := Round(View.FrameWidth - 0.5); if Top in FrameSet then begin Canvas.MoveTo(R.Left, R.Top); Canvas.LineTo(R.Right, R.Top); end; if Bottom in FrameSet then begin Canvas.MoveTo(R.Left, R.Bottom); Canvas.LineTo(R.Right, R.Bottom); end; if Left in FrameSet then begin Canvas.MoveTo(R.Left, R.Top); Canvas.LineTo(R.Left, R.Bottom); end; if Right in FrameSet then begin Canvas.MoveTo(Pred(R.Right), R.Top); Canvas.LineTo(Pred(R.Right), R.Bottom); end; end; procedure TfrBMPExportFilter.DrawBarCode(const View: TfrBarCodeView; const R: TRect); var TempDraw: TBitmap; oldX, oldY: Integer; begin oldX := View.x; oldY := View.y; View.x := 0; View.y := 0; TempDraw := TBitmap.Create; try TempDraw.Height := View.dy; TempDraw.Width := View.dx; TfrBarCodeView(View).Draw(TempDraw.Canvas); Canvas.Draw(R.Left, R.Top, TempDraw); finally FreeAndNil(TempDraw); end; View.x := oldX; View.y := oldY; end; procedure TfrBMPExportFilter.DrawPicture(const View: TfrPictureView; const R: TRect); begin Canvas.Draw(R.Left, R.Top, View.Picture.Graphic); end; procedure TfrBMPExportFilter.DrawShape(const View: TfrShapeObject; const R: TRect); begin seguir end; function TfrBMPExportFilter.CalcRect(const x, y: Integer; const View: TfrView): TRect; begin Result.Left := x; Result.Top := y + LastY; Result.Right := Result.Left + Round(View.dx); Result.Bottom := Result.Top + Round(View.dy); end; procedure TfrBMPExportFilter.OnText(x, y: Integer; const Text: string; View: TfrView); var R: TRect; TextTemp: String; begin if View is TfrMemoView then begin R := CalcRect(x, y, View); Canvas.Font.Assign(TfrMemoView_(View).Font); TextTemp := Text; Canvas.TextRect(R, TextTemp, [tfVerticalCenter]); end; end; procedure TfrBMPExportFilter.OnData(x, y: Integer; View: TfrView); var R: TRect; begin R := CalcRect(x, y, View); if View.FillColor <> clNone then DrawBackGround(View, R) else Canvas.Brush.Style := bsClear; if View is TfrBarCodeView then DrawBarCode(TfrBarCodeView(View), R) else if View is TfrPictureView then DrawPicture(TfrPictureView(View), R) else if View is TfrShapeObject then DrawShape(TfrShapeObject(View), R); DrawFrame(View, R, CalcFrameSet(View)); end; procedure TfrBMPExportFilter.OnBeginPage; var PrnInfo: TfrPrnInfo; begin PrnInfo := CurReport.EMFPages[CurrPage].PrnInfo; Image.Height := Image.Height + trunc(PrnInfo.Pgh); Image.Width := Max(Image.Width, trunc(PrnInfo.Pgw)); end; procedure TfrBMPExportFilter.OnEndPage; begin DrawEndLine; LastY := Image.Height; Inc(CurrPage); end; constructor TfrBMPExportFilter.Create(AStream: TStream); begin inherited; Image := TBitmap.Create; Canvas := Image.Canvas; LastY := 0; CurrPage := 0; end; destructor TfrBMPExportFilter.Destroy; begin Image.SaveToStream(Stream); Image.Free; inherited; end; initialization frRegisterExportFilter(TfrBMPExportFilter, 'Bitmap image (*.bmp)', '*.bmp'); end.
{ This software is Copyright (c) 2015 by Doddy Hackman. This is free software, licensed under: The Artistic License 2.0 The Artistic License Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } // Project Arsenal X 0.2 // (C) Doddy Hackman 2015 unit form_panelcontrol; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, sSkinManager, Vcl.StdCtrls, sGroupBox, sButton, sEdit, Vcl.ComCtrls, sStatusBar, sListBox, idHTTP, Vcl.Menus, Clipbrd; type Tpanelcontrol = class(TForm) sGroupBox1: TsGroupBox; txtTarget: TsEdit; btnScan: TsButton; sGroupBox2: TsGroupBox; lstLinks: TsListBox; status: TsStatusBar; menu: TPopupMenu; C1: TMenuItem; procedure btnScanClick(Sender: TObject); procedure C1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var panelcontrol: Tpanelcontrol; implementation {$R *.dfm} procedure Tpanelcontrol.C1Click(Sender: TObject); var password: string; begin if lstLinks.ItemIndex >= 0 then begin password := lstLinks.Items.Strings[lstLinks.ItemIndex]; Clipboard.AsText := password; end else begin MessageBox(0, Pchar('Select Link'), Pchar('Panel Control 0.2'), MB_ICONINFORMATION); end; end; procedure Tpanelcontrol.btnScanClick(Sender: TObject); const paths: array [1 .. 250] of string = ('admin/admin.asp', 'admin/login.asp', 'admin/index.asp', 'admin/admin.aspx', 'admin/login.aspx', 'admin/index.aspx', 'admin/webmaster.asp', 'admin/webmaster.aspx', 'asp/admin/index.asp', 'asp/admin/index.aspx', 'asp/admin/admin.asp', 'asp/admin/admin.aspx', 'asp/admin/webmaster.asp', 'asp/admin/webmaster.aspx', 'admin/', 'login.asp', 'login.aspx', 'admin.asp', 'admin.aspx', 'webmaster.aspx', 'webmaster.asp', 'login/index.asp', 'login/index.aspx', 'login/login.asp', 'login/login.aspx', 'login/admin.asp', 'login/admin.aspx', 'administracion/index.asp', 'administracion/index.aspx', 'administracion/login.asp', 'administracion/login.aspx', 'administracion/webmaster.asp', 'administracion/webmaster.aspx', 'administracion/admin.asp', 'administracion/admin.aspx', 'php/admin/', 'admin/admin.php', 'admin/index.php', 'admin/login.php', 'admin/system.php', 'admin/ingresar.php', 'admin/administrador.php', 'admin/default.php', 'administracion/', 'administracion/index.php', 'administracion/login.php', 'administracion/ingresar.php', 'administracion/admin.php', 'administration/', 'administration/index.php', 'administration/login.php', 'administrator/index.php', 'administrator/login.php', 'administrator/system.php', 'system/', 'system/login.php', 'admin.php', 'login.php', 'administrador.php', 'administration.php', 'administrator.php', 'admin1.html', 'admin1.php', 'admin2.php', 'admin2.html', 'yonetim.php', 'yonetim.html', 'yonetici.php', 'yonetici.html', 'adm/', 'admin/account.php', 'admin/account.html', 'admin/index.html', 'admin/login.html', 'admin/home.php', 'admin/controlpanel.html', 'admin/controlpanel.php', 'admin.html', 'admin/cp.php', 'admin/cp.html', 'cp.php', 'cp.html', 'administrator/', 'administrator/index.html', 'administrator/login.html', 'administrator/account.html', 'administrator/account.php', 'administrator.html', 'login.html', 'modelsearch/login.php', 'moderator.php', 'moderator.html', 'moderator/login.php', 'moderator/login.html', 'moderator/admin.php', 'moderator/admin.html', 'moderator/', 'account.php', 'account.html', 'controlpanel/', 'controlpanel.php', 'controlpanel.html', 'admincontrol.php', 'admincontrol.html', 'adminpanel.php', 'adminpanel.html', 'admin1.asp', 'admin2.asp', 'yonetim.asp', 'yonetici.asp', 'admin/account.asp', 'admin/home.asp', 'admin/controlpanel.asp', 'admin/cp.asp', 'cp.asp', 'administrator/index.asp', 'administrator/login.asp', 'administrator/account.asp', 'administrator.asp', 'modelsearch/login.asp', 'moderator.asp', 'moderator/login.asp', 'moderator/admin.asp', 'account.asp', 'controlpanel.asp', 'admincontrol.asp', 'adminpanel.asp', 'fileadmin/', 'fileadmin.php', 'fileadmin.asp', 'fileadmin.html', 'administration.html', 'sysadmin.php', 'sysadmin.html', 'phpmyadmin/', 'myadmin/', 'sysadmin.asp', 'sysadmin/', 'ur-admin.asp', 'ur-admin.php', 'ur-admin.html', 'ur-admin/', 'Server.php', 'Server.html', 'Server.asp', 'Server/', 'wpadmin/', 'administr8.php', 'administr8.html', 'administr8/', 'administr8.asp', 'webadmin/', 'webadmin.php', 'webadmin.asp', 'webadmin.html', 'administratie/', 'admins/', 'admins.php', 'admins.asp', 'admins.html', 'administrivia/', 'Database_Administration/', 'WebAdmin/', 'useradmin/', 'sysadmins/', 'admin1/', 'systemadministration/', 'administrators/', 'pgadmin/', 'directadmin/', 'staradmin/', 'ServerAdministrator/', 'SysAdmin/', 'administer/', 'LiveUser_Admin/', 'sysadmin/', 'typo3/', 'panel/', 'cpanel/', 'cPanel/', 'cpanel_file/', 'platz_login/', 'rcLogin/', 'blogindex/', 'formslogin/', 'autologin/', 'support_login/', 'meta_login/', 'manuallogin/', 'simpleLogin/', 'loginflat/', 'utility_login/', 'showlogin/', 'memlogin/', 'members/', 'login-redirect/', 'sublogin/', 'wplogin/', 'login1/', 'dirlogin/', 'login_db/', 'xlogin/', 'smblogin/', 'customer_login/', 'UserLogin/', 'loginus/', 'acct_login/', 'admin_area/', 'bigadmin/', 'project-admins/', 'phppgadmin/', 'pureadmin/', 'sqladmin/', 'radmind/', 'openvpnadmin/', 'wizmysqladmin/', 'vadmind/', 'ezsqliteadmin/', 'hpwebjetadmin/', 'newsadmin/', 'adminpro/', 'Lotus_Domino_Admin/', 'bbadmin/', 'vmailadmin/', 'Indy_admin/', 'ccp14admin/', 'irc-macadmin/', 'banneradmin/', 'sshadmin/', 'phpldapadmin/', 'macadmin/', 'administratoraccounts/', 'admin4_account/', 'admin4_colon/', 'radmind1/', 'SuperAdmin/', 'AdminTools/', 'cmsadmin/', 'SysAdmin2/', 'globes_admin/', 'cadmins/', 'phpSQLiteAdmin/', 'navSiteAdmin/', 'server_admin_small/', 'logo_sysadmin/', 'server/', 'database_administration/', 'power_user/', 'system_administration/', 'ss_vms_admin_sm/'); var target: string; nave: TIdHTTP; i: integer; begin if not(txtTarget.Text = '') then begin target := txtTarget.Text; lstLinks.Items.Clear; status.Panels[0].Text := '[+] Starting the scan'; form_panelcontrol.panelcontrol.Update; nave := TIdHTTP.Create(nil); nave.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0'; for i := Low(paths) to High(paths) do try status.Panels[0].Text := '[+] Testing : ' + paths[i]; form_panelcontrol.panelcontrol.Update; nave.Get(target + '/' + paths[i]); if nave.ResponseCode = 200 then lstLinks.Items.Add(target + '/' + paths[i]); except on E: EIdHttpProtocolException do; on E: Exception do; end; nave.Free; status.Panels[0].Text := '[+] Finished'; form_panelcontrol.panelcontrol.Update; end else begin MessageBox(0, 'Write Target', 'Panel Control 0.2', MB_ICONINFORMATION); end; end; end. // The End ?
unit MapiMail; interface uses Classes; type TMapiMail = class private Attachments : TStringList; Recipients : TStringList; Body : TStringList; Session : longint; Subject : string; public procedure AddRecipient(addr: string); procedure SetRecipients(addrlist: TStringList); procedure AddAttachment(filename: string); procedure SetAttachments(filenamelist: TStringList); procedure SetSubject(subj: string); procedure SetBody(lines: TStringList); function Logon: boolean; procedure Send; procedure Logoff; public constructor Create; destructor Destroy; override; end; implementation uses SysUtils, Windows, Registry, Dialogs; {$F+} { force far calls } ////////////////////////////////////////////////////////////////////////////// // // ===================== // Constants information // ===================== // const { Mapi recipient types } MAPI_ORIG = 0; { Recipient is message originator. } MAPI_TO = 1; { Recipient is primary recipient. } MAPI_CC = 2; { Recipient is copy recipient. } MAPI_BCC = 3; { Recipient is blind-copy recipient. } { Mapi whatisit} MAPI_UNREAD :ULONG = $0001; MAPI_RECEIPT_REQUESTED :ULONG = $0002; MAPI_SENT :ULONG = $0004; { Mapi logon flags } MAPI_LOGON_UI :ULONG = $0001; { Display logon UI } MAPI_NEW_SESSION :ULONG = $0002; { Don't get default if available. } MAPI_DIALOG :ULONG = $0008; { Prompt to resolve ambig. names } MAPI_UNREAD_ONLY :ULONG = $0020; { Only unread messages } MAPI_ENVELOPE_ONLY :ULONG = $0040; { Only header information } MAPI_PEEK :ULONG = $0080; { Don't mark message as read } MAPI_GUARANTEE_FIFO :ULONG = $0100; { Guarantee FIFO MAPIFindNext } MAPI_BODY_AS_FILE :ULONG = $0200; { Save body as first attachment } MAPI_AB_NOMODIFY :ULONG = $0400; { Don't modify PAB entries } MAPI_SUPPRESS_ATTACH :ULONG = $0800; { Header and body, no files } MAPI_FORCE_DOWNLOAD :ULONG = $1000; { Force message download from server } { Mapi whatisit? } MAPI_LONG_MSGID :ULONG = $4000; { Authorize MsgId of 512 char returned} { Mapi whatisit? } MAPI_OLE :ULONG = $0001; { Set if attachment is an OLE Object } MAPI_OLE_STATIC :ULONG = $0002; { Set if attachment is Static OLE } { Mapi error codes } SUCCESS_SUCCESS = 0; MAPI_USER_ABORT = 1; MAPI_E_FAILURE = 2; MAPI_E_LOGIN_FAILURE = 3; MAPI_E_DISK_FULL = 4; MAPI_E_INSUFFICIENT_MEMORY = 5; MAPI_E_ACCESS_DENIED = 6; MAPI_E_TOO_MANY_SESSIONS = 8; MAPI_E_TOO_MANY_FILES = 9; MAPI_E_TOO_MANY_RECIPIENTS = 10; MAPI_E_ATTACHMENT_NOT_FOUND = 11; MAPI_E_ATTACHMENT_OPEN_FAILURE = 12; MAPI_E_ATTACHMENT_WRITE_FAILURE = 13; MAPI_E_UNKNOWN_RECIPIENT = 14; MAPI_E_BAD_RECIPTYPE = 15; MAPI_E_NO_MESSAGES = 16; MAPI_E_INVALID_MESSAGE = 17; MAPI_E_TEXT_TOO_LARGE = 18; MAPI_E_INVALID_SESSION = 19; MAPI_E_TYPE_NOT_SUPPORTED = 20; MAPI_E_AMBIGUOUS_RECIPIENT = 21; MAPI_E_MESSAGE_IN_USE = 22; MAPI_E_NETWORK_FAILURE = 23; MAPI_E_INVALID_EDITFIELDS = 24; MAPI_E_INVALID_RECIPS = 25; MAPI_E_NOT_SUPPORTED = 26; type ULONG = longint; LHANDLE = longint; lPULONG = ^Longint; lPLHANDLE = ^LHANDLE; LPVOID = Pointer; type lpMapiFileDesc = ^TMapiFileDesc; TMapiFileDesc = record ulReserved : ULONG; { Reserved for future use. Must be 0 } flFlags : ULONG; { Flags } nPosition : ULONG; { Attachment position in message body } lpszPathName : PChar; { Full path name of attachment file } lpszFileName : PChar; { Original filename (optional) } lpFileType : Pointer; { Attachment file type (reserved) } end; TAttachArray = array[0..1] of TMapiFileDesc; TlpAttachArray = ^TAttachArray; type lpMapiRecipDesc = ^TMapiRecipDesc; lppMapiRecipDesc = ^lpMapiRecipDesc; TMapiRecipDesc = record ulReserved : ULONG; { Reserved for future use. Must be 0 } ulRecipClass : ULONG; { Recipient class - } { MAPI_TO, MAPI_CC, } { MAPI_BCC, MAPI_ORIG } lpszName : PChar; { Recipient name } lpszAddress : PChar; { Recipient address (optional) } ulEIDSize : ULONG; { Size (in bytes) of lpEntryID } lpEntryID : Pointer; { System-specific recipient reference } end; TRecipArray = array[0..1] of TMapiRecipDesc; TlpRecipArray = ^TRecipArray; type lpMapiMessage = ^TMapiMessage; TlppMapiMessage = ^lpMapiMessage; TMapiMessage = record ulReserved : ULONG; { Reserved for future use. Must be 0 } lpszSubject : PChar; { Message subject } lpszNoteText : PChar; { Message text } lpszMessageType : PChar; { Message class } lpszDateReceived : PChar; { In YYYY/MM/DD HH:MM format } lpszConversationID : PChar; { Conversation thread ID } flFlags : ULONG; { Unread, return receipt } lpOriginator : lpMapiRecipDesc; { Originator descriptor } nRecipCount : ULONG; { Number of recipients } lpRecips : lpMapiRecipDesc; { Recipient descriptors } nFileCount : ULONG; { Number of file attachments } lpFiles : lpMapiFileDesc; { Attachment descriptors } end; type TMapiFindNext = function(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageType: PChar; lpszSeedMessageID: PChar; flFlags: ULONG; ulReserved: ULONG; lpszMessageID: PChar): ULONG stdcall; TMapiLogoff = function(lhSession: LHANDLE; ulUIParam: ULONG; flFlags: ULONG; ulReserved: ULONG): ULONG stdcall; TMapiLogon = function(ulUIParam: ULONG; lpszName: PChar; lpszPassword: PChar; flFlags: ULONG; ulReserved: ULONG; lplhSession: LPLHANDLE): ULONG stdcall; TMapiSendMail = function(lhSession: LHANDLE; ulUIParam: ULONG; lpMessage: lpMapiMessage; flFlags: ULONG; ulReserved: ULONG): ULONG stdcall; TMapiReadMail = function(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageID: PChar; flFlags: ULONG; ulReserved: ULONG; lpMessage: lpMapiMessage): ULONG stdcall; TMapiDeleteMail = function(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageID: PChar; flFlags: ULONG; ulReserved: ULONG): ULONG stdcall; TMapiResolveName = function(lhSession: LHANDLE; ulUIParam: ULONG; lpszName: PChar; flFlags: ULONG; ulReserved: ULONG; lppRecips: lppMapiRecipDesc): ULONG; stdcall; TMapiFreeBuffer = function(pv: LPVOID): ULONG stdcall; TMapiAddress = function(lhSession: LHANDLE; ulUIParam: ULONG; lpszCaption: PChar; nEditFields: ULONG; lpszLabels: PChar; nRecips: ULONG; var lpRecips: TMapiRecipDesc; flFlags: ULONG; ulReserved: ULONG; lpnNewRecips: lpULONG; var lppNewRecips: lpMapiRecipDesc): ULONG stdcall; TMAPISaveMail = function(lhSession: LHANDLE; ulUIParam: ULONG; lpMessage: lpMapiMessage; flFlags: ULONG; ulReserved: ULONG; lpszMessageID: PChar): ULONG stdcall; var fnMapiFindNext: TMapiFindNext; fnMapiLogoff: TMapiLogoff; fnMapiLogon: TMapiLogon; fnMapiSendMail: TMapiSendMail; fnMapiReadMail: TMapiReadMail; fnMapiDeleteMail: TMapiDeleteMail; fnMapiResolveName: TMapiResolveName; fnMapiFreeBuffer: TMapiFreeBuffer; fnMapiAddress: TMapiAddress; fnMAPISaveMail: TMAPISaveMail; DLLHandle: THandle; ////////////////////////////////////////////////////////////////////////////// // // ============== // mapi.dll calls // ============== // function CheckMAPI: boolean; begin Result := (DLLHandle <> 0) end; function MapiFindNext(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageType: PChar; lpszSeedMessageID: PChar; flFlags: ULONG; ulReserved: ULONG; lpszMessageID: PChar): ULONG; begin Result := fnMapiFindNext(lhSession, ulUIParam, lpszMessageType, lpszSeedMessageID, flFlags, ulReserved, lpszMessageID); end; function MapiLogoff(lhSession: LHANDLE; ulUIParam: ULONG; flFlags: ULONG; ulReserved: ULONG): ULONG; begin Result := fnMapiLogoff( lhSession, ulUIParam, flFlags, ulReserved); end; function MapiLogon(ulUIParam: ULONG; lpszName: PChar; lpszPassword: PChar; flFlags: ULONG; ulReserved: ULONG; lplhSession: LPLHANDLE): ULONG; begin Result := fnMapiLogon( ulUIParam, lpszName, lpszPassword, flFlags, ulReserved, lplhSession); end; function MapiSendMail(lhSession: LHANDLE; ulUIParam: ULONG; lpMessage: lpMapiMessage; flFlags: ULONG; ulReserved: ULONG): ULONG; begin Result := fnMapiSendMail( lhSession, ulUIParam, lpMessage, flFlags, ulReserved); end; function MapiReadMail(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageID: PChar; flFlags: ULONG; ulReserved: ULONG; lpMessage: lpMapiMessage): ULONG; begin Result := fnMapiReadMail( lhSession, ulUIParam, lpszMessageID, flFlags, ulReserved, lpMessage); end; function MapiDeleteMail(lhSession: LHANDLE; ulUIParam: ULONG; lpszMessageID: PChar; flFlags: ULONG; ulReserved: ULONG): ULONG; begin Result := fnMapiDeleteMail( lhSession, ulUIParam, lpszMessageID, flFlags, ulReserved); end; function MapiResolveName(lhSession: LHANDLE; ulUIParam: ULONG; lpszName: PChar; flFlags: ULONG; ulReserved: ULONG; lppRecips: lppMapiRecipDesc): ULONG; begin Result := fnMapiResolveName( lhSession, ulUIParam, lpszName, flFlags, ulReserved, lppRecips); end; function MapiFreeBuffer(pv: LPVOID): ULONG; begin Result := fnMapiFreeBuffer(pv); end; function MapiAddress(lhSession: LHANDLE; ulUIParam: ULONG; lpszCaption: PChar; nEditFields: ULONG; lpszLabels: PChar; nRecips: ULONG; var lpRecips: TMapiRecipDesc; flFlags: ULONG; ulReserved: ULONG; lpnNewRecips: lpULONG; var lppNewRecips: lpMapiRecipDesc): ULONG; begin Result := fnMapiAddress( lhSession, ulUIParam, lpszCaption, nEditFields, lpszLabels, nRecips, lpRecips, flFlags, ulReserved, lpnNewRecips, lppNewRecips); end; function MAPISaveMail(lhSession: LHANDLE; ulUIParam: ULONG; lpMessage: lpMapiMessage; flFlags: ULONG; ulReserved: ULONG; lpszMessageID: PChar): ULONG; begin Result := fnMapiSaveMail( lhSession, ulUIParam, lpMessage, flFlags, ulReserved, lpszMessageID); end; function GetErrorDesc(code: integer): string; begin case code of 0: Result := 'SUCCESS_SUCCESS'; 1: Result := 'MAPI_USER_ABORT'; 2: Result := 'MAPI_E_FAILURE'; 3: Result := 'MAPI_E_LOGIN_FAILURE'; 4: Result := 'MAPI_E_DISK_FULL'; 5: Result := 'MAPI_E_INSUFFICIENT_MEMORY'; 6: Result := 'MAPI_E_ACCESS_DENIED'; 8: Result := 'MAPI_E_TOO_MANY_SESSIONS'; 9: Result := 'MAPI_E_TOO_MANY_FILES'; 10: Result := 'MAPI_E_TOO_MANY_RECIPIENTS'; 11: Result := 'MAPI_E_ATTACHMENT_NOT_FOUND'; 12: Result := 'MAPI_E_ATTACHMENT_OPEN_FAILURE'; 13: Result := 'MAPI_E_ATTACHMENT_WRITE_FAILURE'; 14: Result := 'MAPI_E_UNKNOWN_RECIPIENT'; 15: Result := 'MAPI_E_BAD_RECIPTYPE'; 16: Result := 'MAPI_E_NO_MESSAGES'; 17: Result := 'MAPI_E_INVALID_MESSAGE'; 18: Result := 'MAPI_E_TEXT_TOO_LARGE'; 19: Result := 'MAPI_E_INVALID_SESSION'; 20: Result := 'MAPI_E_TYPE_NOT_SUPPORTED'; 21: Result := 'MAPI_E_AMBIGUOUS_RECIPIENT'; 22: Result := 'MAPI_E_MESSAGE_IN_USE'; 23: Result := 'MAPI_E_NETWORK_FAILURE'; 24: Result := 'MAPI_E_INVALID_EDITFIELDS'; 25: Result := 'MAPI_E_INVALID_RECIPS'; 26: Result := 'MAPI_E_NOT_SUPPORTED'; else Result := 'Unknown error'; end; end; ////////////////////////////////////////////////////////////////////////////// // // =============== // class TMapiMail // =============== // constructor TMapiMail.Create; begin Attachments := TStringList.Create; Recipients := TStringList.Create; Body := TStringList.Create; end; destructor TMapiMail.Destroy; begin Attachments.Free; Recipients.Free; Body.Free; end; procedure TMapiMail.AddRecipient(addr: string); begin Recipients.Add(addr); end; procedure TMapiMail.SetRecipients(addrlist: TStringList); begin if Assigned(addrlist) then Recipients.Assign(addrlist) else Recipients.Clear; end; procedure TMapiMail.AddAttachment(filename: string); begin Attachments.Add(filename); end; procedure TMapiMail.SetAttachments(filenamelist: TStringList); begin if Assigned(filenamelist) then Attachments.Assign(filenamelist) else Attachments.Clear; end; procedure TMapiMail.SetBody(lines: TStringList); begin if Assigned(lines) then Body.Assign(lines) else Body.Clear; end; procedure TMapiMail.SetSubject(subj: string); begin Subject := subj; end; procedure TMapiMail.Logoff; begin MapiLogoff(Session, 0, 0, 0); end; function TMapiMail.Logon: boolean; const ProfileKey95 = 'Software\Microsoft\Windows Messaging Subsystem\Profiles'; ProfileKeyNT = 'Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles'; var ProfileKey: string; FProfile: string; Reg: TRegistry; begin Result := false; if not CheckMapi then Exit; Reg := TRegistry.Create; if Reg.KeyExists(ProfileKeyNT) then ProfileKey := ProfileKeyNT else ProfileKey := ProfileKey95; Reg.Rootkey := HKEY_CURRENT_USER; if Reg.OpenKey(ProfileKey, False) then try FProfile := Reg.Readstring('DefaultProfile'); except FProfile := ''; end; Reg.Free; if MapiLogon(0, PChar(FProfile), nil, 0, 0, @Session) = SUCCESS_SUCCESS then Result := true else if MapiLogon(0, nil, nil, MAPI_LOGON_UI, 0, @Session) = 0 then Result := true; end; procedure TMapiMail.Send; var MapiMessage : TMapiMessage; MapiRecipDesc : TMapiRecipDesc; MapiFileDesc : TMapiFileDesc; lpRecipArray : TlpRecipArray; lpRecip : lpMapiRecipDesc; lpAttachArray : TlpAttachArray; ResolveResult : longint; SMResult : longint; szRecipName : PChar; szSubject : PChar; szText : PChar; i : Integer; begin FillChar(MapiMessage, sizeof(TMapiMessage), 0); FillChar(MapiRecipDesc, sizeof(TMapiRecipDesc), 0); FillChar(MapiFileDesc, sizeof(TMapiFileDesc), 0); lpAttachArray := nil; lpRecipArray := nil; szRecipName := nil; szSubject := nil; szText := nil; try szSubject := StrNew(PChar(Subject)); MapiMessage.lpszSubject := szSubject; if Body.Count > 0 then begin szText := StrNew(PChar(Body.Text)); MapiMessage.lpszNoteText := szText; end; // set recipient list MapiMessage.nRecipCount := Recipients.Count; lpRecipArray := TlpRecipArray(StrAlloc(Recipients.Count*SizeOf(TMapiRecipDesc))); FillChar(lpRecipArray^, StrBufSize(PChar(lpRecipArray)), 0); for i:=0 to Recipients.Count-1 do begin ResolveResult := MapiResolveName(Session, 0, PChar(Recipients[i]), 0, 0, @lpRecip); if (ResolveResult = MAPI_E_AMBIGUOUS_RECIPIENT) or (ResolveResult = MAPI_E_UNKNOWN_RECIPIENT) then ResolveResult := MapiResolveName(Session, 0, PChar(Recipients[i]), MAPI_DIALOG, 0, @lpRecip); if ResolveResult = SUCCESS_SUCCESS then begin lpRecipArray[i].ulRecipClass := MAPI_TO; lpRecipArray[i].lpszName := StrNew(PChar(Recipients[i])); lpRecipArray[i].ulEIDSize := lpRecip^.ulEIDSize; lpRecipArray[i].lpEntryID := lpRecip^.lpEntryID; end; end; MapiMessage.lpRecips := @lpRecipArray^; // set attachment list MapiMessage.nFileCount := Attachments.Count; lpAttachArray := TlpAttachArray(StrAlloc(Attachments.Count*SizeOf(TMapiFileDesc))); FillChar(lpAttachArray^, StrBufSize(PChar(lpAttachArray)), 0); for i:=0 to Attachments.Count-1 do begin lpAttachArray[i].nPosition := Integer($FFFFFFFF); {Top of message} lpAttachArray[i].lpszPathName := StrNew(PChar(Attachments[i])); end; MapiMessage.lpFiles := @lpAttachArray^; // send mail SMResult := MapiSendMail(Session, 0, @MapiMessage, 0, 0); if SMResult <> SUCCESS_SUCCESS then ShowMessage('Mailer error: ' + GetErrorDesc(SMResult) + ' (code: ' + IntToStr(SMResult) + ')'); finally for i:=0 to Recipients.Count-1 do StrDispose(lpRecipArray[i].lpszName); for i:=0 to Attachments.Count-1 do StrDispose(lpAttachArray[i].lpszPathName); StrDispose(szText); StrDispose(szSubject); StrDispose(szRecipName); StrDispose(PChar(lpRecipArray)); end; end; ///////////////////////////////////////////////////////////////////////////// // // ===================== // Module initialization // ===================== // initialization DLLHandle := LoadLibrary('mapi32'); if DLLHandle <> 0 then begin @fnMapiFindNext := GetProcAddress(DLLHandle, 'MAPIFindNext'); @fnMapiLogoff := GetProcAddress(DLLHandle, 'MAPILogoff'); @fnMapiLogon := GetProcAddress(DLLHandle, 'MAPILogon'); @fnMapiSendMail := GetProcAddress(DLLHandle, 'MAPISendMail'); @fnMapiReadMail := GetProcAddress(DLLHandle, 'MAPIReadMail'); @fnMapiDeleteMail := GetProcAddress(DLLHandle, 'MAPIDeleteMail'); @fnMapiResolveName := GetProcAddress(DLLHandle, 'MAPIResolveName'); @fnMapiFreeBuffer := GetProcAddress(DLLHandle, 'MAPIFreeBuffer'); @fnMapiAddress := GetProcAddress(DLLHandle, 'MAPIAddress'); @fnMapiSaveMail := GetProcAddress(DLLHandle, 'MAPISaveMail'); end; finalization if DLLHandle <> 0 then FreeLibrary(DLLHandle); end.
unit untDeviceListenThread; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqldb, untParmakIzi, untGingyApiDefine, Windows, untStruct, untOnMatchedEventArgs, untOnNotMatchedEventArgs, Dialogs, untProgram, untUtils; type TEventHandler = procedure of object; type { TDeviceListenThread } TDeviceListenThread = class(TThread) protected procedure Execute; override; public bolStopListenerThread: boolean; bolPauseDevice: boolean; m_bStart, m_bShow: integer; RawTemplate: array of byte; m_nMatchResult: integer; strLocalDabasePath: string; pDC: HANDLE; setting: _SETTING; m_rcRect: TRect; gPrevious: integer; omeEvtMatchedArgs: TOnMatchedEventArgs; nmeEvtNotMatchedArgs: TOnNotMatchedEventArgs; EvtCapture: TEventHandler; EvtMatched: TGingyAPIMatchedEventHandler; EvtNotMatched: TGingyAPINotMatchedEventHandler; property OnCapture: TEventHandler read EvtCapture write EvtCapture; property OnMatched: TGingyAPIMatchedEventHandler read EvtMatched write EvtMatched; property OnNotMatched: TGingyAPINotMatchedEventHandler read EvtNotMatched write EvtNotMatched; constructor Create(CreateSuspend: boolean); function DisplaySnap: boolean; procedure DisplayCondition(nCondition: integer); procedure RaiseCaptureEvent; procedure RaiseOnMatchedEvent; procedure RaiseOnNotMatchedEvent; end; implementation { TDeviceListenThread } procedure TDeviceListenThread.DisplayCondition(nCondition: integer); begin m_nMatchResult := FAIL; if (nCondition = FINGER_TO_LIGHT) then begin if (gPrevious <> 1) then gPrevious := 1; end else if (ncondition = FINGER_TOO_DARK) then begin if (gPrevious <> 2) then gPrevious := 2; end else begin if (gPrevious <> 0) then gPrevious := 0; end; end; procedure TDeviceListenThread.RaiseCaptureEvent; begin if (Assigned(EvtCapture)) then begin EvtCapture; end; end; procedure TDeviceListenThread.RaiseOnMatchedEvent; begin if (Assigned(EvtMatched)) then EvtMatched(omeEvtMatchedArgs); end; procedure TDeviceListenThread.RaiseOnNotMatchedEvent; begin if (Assigned(EvtNotMatched)) then EvtNotMatched(nmeEvtNotMatchedArgs); end; function TDeviceListenThread.DisplaySnap: boolean; var rtn: integer; tckStart, tckEnd: DWORD; begin m_bShow := 0; Gingy_SnapShot; tckStart := GetTickCount; while True do begin rtn := Gingy_Capture; if (rtn = OK) then begin Gingy_Display(pDC, setting.bSize, 0, 0, m_rcRect.Right - m_rcRect.Left, m_rcRect.Bottom - m_rcRect.Top); break; end; DisplayCondition(rtn); tckEnd := GetTickCount - tckStart; if (tckEnd > 10000) then begin m_bStart := 0; Result := False; break; end; Gingy_Display(pDc, setting.bSize, 0, 0, m_rcRect.Right - m_rcRect.Left, m_rcRect.Bottom - m_rcRect.Top); end; if (m_bStart = 0) then begin m_bStart := 1; Result := False; exit; end; Result := True; end; procedure TDeviceListenThread.Execute; var nMaxScore, nRtn: integer; bScore: byte; dtCaptureTime: TDateTime; strCommandText: string; qryFingerPrints: TSQLQuery; piMatchedFinger: TParmakIzi; aryFingerData: array of byte; tmStart, tmEnd: DWORD; str: string; nRemoteVerifyResult: integer; begin nMaxScore := 0; bScore := 0; nRtn := FAIL; piMatchedFinger := nil; bScore := 0; strCommandText := 'select LiableId, FingerData,FingerIndex from FingerPrints'; while not bolStopListenerThread do begin if (bolPauseDevice) then begin Gingy_EndCap; sleep(100); continue; end; if (m_bStart <> 0) then begin m_bStart := 0; continue; end; if (Gingy_StartCap <> OK) then Continue; m_bStart := 1; if (not DisplaySnap) then begin m_bStart := 0; m_bShow := 0; Continue; end; m_bStart := 0; m_bShow := 1; Gingy_EndCap; nRtn := Gingy_Template(@RawTemplate[0]); if (nRtn <> OK) then continue; dtCaptureTime := Now; Synchronize(@RaiseCaptureEvent); m_nMatchResult := FAIL; omeEvtMatchedArgs := TOnMatchedEventArgs.Create(0, 0, Now, 0); tmStart := GetTickCount; {TODO:Test için burayı iptal ettim} nRemoteVerifyResult := RemoteDatabaseConn.VerifyFingerPrints(RawTemplate, StrToInt(Config.GetValue('LocationId')), setting.wSecurity, omeEvtMatchedArgs); tmEnd := GetTickCount; WriteLog('Total Süre:' + IntToStr(tmEnd - TmStart)); WriteLog('Max score:' + IntToStr(nMaxScore)); if (nRemoteVerifyResult = 0) then begin omeEvtMatchedArgs.dtCapturedTime:=Now; Synchronize(@RaiseOnMatchedEvent); FreeAndNil(omeEvtMatchedArgs); end else if (nRemoteVerifyResult = -1) then begin; if (Assigned(EvtNotMatched)) then begin nmeEvtNotMatchedArgs := TOnNotMatchedEventArgs.Create(omeEvtMatchedArgs.nMatchedLiableId, omeEvtMatchedArgs.nMatchedFingerIndex, dtCaptureTime, 0); Synchronize(@RaiseOnNotMatchedEvent); FreeAndNil(nmeEvtNotMatchedArgs); end; end else begin nMaxScore := 0; piMatchedFinger:=nil; qryFingerPrints := LocalDatabaseConn.ExecuteQuery(strCommandText); qryFingerPrints.Open; tmStart := GetTickCount; while (not qryFingerPrints.EOF) do begin SetLength(aryFingerData, MAX_TEMPLATE_LEN); aryFingerData := qryFingerPrints.FieldByName('FingerData').AsBytes; nRtn := Gingy_Verify(@RawTemplate[0], @aryFingerData[0], setting.wSecurity, @bScore); if (nMaxScore < bScore) then begin nMaxScore := bScore; if (Assigned(piMatchedFinger)) then FreeAndNil(piMatchedFinger); piMatchedFinger := TParmakIzi.Create(qryFingerPrints.FieldByName('LiableId').AsInteger, qryFingerPrints.FieldByName('FingerIndex').AsInteger, aryFingerData); if (nMaxScore >= 80) then break; end; qryFingerPrints.Next; end; tmEnd := GetTickCount; WriteLog('Total Süre:' + IntToStr(tmEnd - TmStart)); WriteLog('Max score:' + IntToStr(nMaxScore)); LocalDatabaseConn.ReturnDBQuery(qryFingerPrints); if (piMatchedFinger <> nil) and (nMaxScore >= setting.wPass) then begin omeEvtMatchedArgs := TOnMatchedEventArgs.Create(piMatchedFinger.nLiableId, piMatchedFinger.nFingerIndex, dtCaptureTime, nMaxScore); Synchronize(@RaiseOnMatchedEvent); FreeAndNil(omeEvtMatchedArgs); FreeAndNil(piMatchedFinger); end else begin if (Assigned(EvtNotMatched)) then begin nmeEvtNotMatchedArgs := TOnNotMatchedEventArgs.Create(-1, -1, dtCaptureTime, nMaxScore); Synchronize(@RaiseOnNotMatchedEvent); FreeAndNil(nmeEvtNotMatchedArgs); FreeAndNil(piMatchedFinger); end; end; end; end; end; constructor TDeviceListenThread.Create(CreateSuspend: boolean); begin FreeOnTerminate := True; gPrevious := 0; bolPauseDevice := False; bolStopListenerThread := False; setting.bMatchCount := 1; setting.bSize := IMAGE_LARGE; setting.wSecurity := 50; setting.wPass := 60; setting.Bright := DEFAULT_BRIGHT; setting.Contrast := DEFAULT_CONTRAST; SetLength(RawTemplate, 640); inherited Create(CreateSuspend); end; end.
unit MBDeviceArchiver; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles, LoggerItf, MBArchiverTypes, MBArchiverConst, MBRangeArchiver; type { TMBArchiverDevice } TMBArchiverDevice = class(TComponentLogged) private FActive : Boolean; FDelimiter : String; FFileName : String; FIsOwnIncomPack : Boolean; FIsTextArch : Boolean; FMaxFileLen : Cardinal; FPath : String; FDevNum : Byte; FRangesList : THashedStringList; function GetDelimiter: String; function GetDevNum: Byte; function GetFileName: String; function GetIsTextArch: Boolean; function GetMaxFileLen: Cardinal; function GetPath: String; function GetRangeArchivers(Index : Integer): TMBRangeArchiver; function GetRangeArchiversByStartAddr(AStartAddr : Word): TMBRangeArchiver; function GetRangeArchiversCount: Integer; procedure SetActive(AValue: Boolean); procedure SetDelimiter(AValue: String); procedure SetDevNum(AValue: Byte); procedure SetFileName(AValue: String); procedure SetIsOwnIncomPack(AValue: Boolean); procedure SetIsTextArch(AValue: Boolean); procedure SetMaxFileLen(AValue: Cardinal); procedure SetPath(AValue: String); public constructor Create(AOWner : TComponent); override; destructor Destroy; override; procedure AddRecordToArchive(ARecord : PMBArchRecord); overload; procedure AddRecordToArchive(ARecord : PMBArchRecordBool); overload; function AddRangeArchiver(ARangeStartAddr: Word; ARangeLen : Word; ARangeType : TMBArchiverRangeType = artWord) : TMBRangeArchiver; function SearchRangeArchiver(AStartAddr : Word) : TMBRangeArchiver; procedure DeleteRange(AIndex : Integer); overload; procedure DeleteRange(AStartAddr : Word); overload; procedure ClearRanges; procedure Start; procedure Stop; property Active : Boolean read FActive write SetActive; property RangeArchiversCount : Integer read GetRangeArchiversCount; property RangeArchivers[Index : Integer] : TMBRangeArchiver read GetRangeArchivers; property RangeArchiversByStartAddr[AStartAddr : Word] : TMBRangeArchiver read GetRangeArchiversByStartAddr; property Path : String read GetPath write SetPath {DefLinFilePath DefWinFilePath}; property FileName : String read GetFileName write SetFileName; property MaxFileLen : Cardinal read GetMaxFileLen write SetMaxFileLen default DefMaxFileSize; property IsTextArch : Boolean read GetIsTextArch write SetIsTextArch default True; property IsOwnIncomPack : Boolean read FIsOwnIncomPack write SetIsOwnIncomPack default True; property Delimiter : String read GetDelimiter write SetDelimiter {default DefColDelimiter}; property DevNum : Byte read GetDevNum write SetDevNum; end; implementation { TMBArchiverDevice } constructor TMBArchiverDevice.Create(AOWner: TComponent); begin inherited Create(AOWner); FActive := False; FDevNum := 1; FFileName := DefFileName; FIsTextArch := True; FIsOwnIncomPack := True; FMaxFileLen := DefMaxFileSize; {$ifdef UNIX} FPath := DefLinFilePath; {$ELSE} FPath := DefWinFilePath; {$ENDIF} FDelimiter := DefColDelimiter; FRangesList := THashedStringList.Create; end; destructor TMBArchiverDevice.Destroy; begin Stop; ClearRanges; FreeAndNil(FRangesList); inherited Destroy; end; function TMBArchiverDevice.GetDevNum: Byte; begin Result := FDevNum; end; function TMBArchiverDevice.GetDelimiter: String; begin Result := FDelimiter; end; function TMBArchiverDevice.GetFileName: String; begin Result := FFileName; end; function TMBArchiverDevice.GetIsTextArch: Boolean; begin Result := FIsTextArch; end; function TMBArchiverDevice.GetMaxFileLen: Cardinal; begin Result := FMaxFileLen; end; function TMBArchiverDevice.GetPath: String; begin Result := FPath; end; function TMBArchiverDevice.GetRangeArchivers(Index : Integer): TMBRangeArchiver; begin end; function TMBArchiverDevice.GetRangeArchiversByStartAddr(AStartAddr : Word): TMBRangeArchiver; begin end; function TMBArchiverDevice.GetRangeArchiversCount: Integer; begin Result := FRangesList.Count; end; procedure TMBArchiverDevice.SetActive(AValue: Boolean); begin if FActive=AValue then Exit; FActive:=AValue; end; procedure TMBArchiverDevice.SetDelimiter(AValue: String); begin if FDelimiter=AValue then Exit; FDelimiter:=AValue; end; procedure TMBArchiverDevice.SetDevNum(AValue: Byte); begin if FDevNum = AValue then Exit; FDevNum := AValue; end; procedure TMBArchiverDevice.SetFileName(AValue: String); begin if FFileName = AValue then Exit; FFileName := AValue; end; procedure TMBArchiverDevice.SetIsOwnIncomPack(AValue: Boolean); begin if FIsOwnIncomPack = AValue then Exit; FIsOwnIncomPack := AValue; end; procedure TMBArchiverDevice.SetIsTextArch(AValue: Boolean); begin if FIsTextArch = AValue then Exit; FIsTextArch := AValue; end; procedure TMBArchiverDevice.SetMaxFileLen(AValue: Cardinal); begin if FMaxFileLen = AValue then Exit; FMaxFileLen := AValue; end; procedure TMBArchiverDevice.SetPath(AValue: String); begin if FPath = AValue then Exit; FPath := AValue; end; procedure TMBArchiverDevice.AddRecordToArchive(ARecord: PMBArchRecord); begin end; procedure TMBArchiverDevice.AddRecordToArchive(ARecord: PMBArchRecordBool); begin end; function TMBArchiverDevice.AddRangeArchiver(ARangeStartAddr: Word; ARangeLen: Word; ARangeType: TMBArchiverRangeType): TMBRangeArchiver; begin end; function TMBArchiverDevice.SearchRangeArchiver(AStartAddr: Word): TMBRangeArchiver; begin end; procedure TMBArchiverDevice.DeleteRange(AIndex: Integer); begin end; procedure TMBArchiverDevice.DeleteRange(AStartAddr: Word); begin end; procedure TMBArchiverDevice.ClearRanges; begin end; procedure TMBArchiverDevice.Start; begin end; procedure TMBArchiverDevice.Stop; begin end; end.
unit Shippment; interface type TShippment = record OrderID: Integer; ShipmentDate: TDateTime; ShipperID: Integer; constructor Create (aOrderID: Integer; aShipmentDate: TDateTime; aShipperID: Integer); end; implementation { TShippment } constructor TShippment.Create(aOrderID: Integer; aShipmentDate: TDateTime; aShipperID: Integer); begin OrderID := aOrderID; ShipmentDate := aShipmentDate; ShipperID := aShipperID; end; end.
unit DMRestCalc; interface uses SysUtils, Classes, Controls, DB, ADODB, Constants; procedure SetParameterValues(Query: TADOQuery; Name: string; Value: Variant); function QueryValue(qry: TADOQuery; sqlStr: string): Variant; function QueryValue2(qry: TADOQuery; sqlStr: string; var FieldVal1: Variant; var FieldVal2: Variant): boolean; procedure QueryExecute(qry: TADOQuery; sqlStr: string; const Args: array of const); function GetMovingSql(ParamName1, ParamName2: string): string; function GetMovingExSql( ParamName1, ParamName2, ParamName3, ParamName4: string): string; function ConstructSelectMovingSql(qryMoving: TADOQuery; Date: TDateTime): string; function ConstructSelectMovingExSql(qryMoving: TADOQuery; BeginDate, EndDate: TDateTime): string; type TdmodRestCalc = class(TDataModule) qryRest: TADOQuery; qry: TADOQuery; private procedure ExecRestDel(Date: TDateTime); procedure ExecRestCalc(Date: TDateTime); public function GetMinOperationDate: TDateTime; function GetMaxOperationDate: TDateTime; function GetMinStorageDate: TDateTime; function GetMaxStorageDate: TDateTime; function GetMinDate: TDateTime; function GetMaxDate: TDateTime; function GetMaxMaxOperationDate( var Field1, Field2: TDateTime): boolean; function GetMinMaxStorageDate( var Field1, Field2: TDateTime): boolean; procedure CalculateRest(BeginDate, EndDate: TDateTime); overload; procedure CalculateRest(Date: TDateTime); overload; procedure CorrectRest(ProdId: Integer; RestDate: TDateTime; CorrectValue: Currency); procedure DeleteData(DelDate: TDateTime); end; var dmodRestCalc: TdmodRestCalc; implementation {$R *.dfm} uses DateUtils, DMMain, Variants, Math; const INSERT_MEAL_STORAGE_CLAUSE: string = 'insert into MealStorage ([Date], MealId, [Quantity]) %s '; const INSERT_MEAL_STORAGE_FIELDS: string = ' #%s# as [Date], Meal.Id as MealId, '+ ' iif(Storages.Storage is Null, 0, Storages.Storage) + '+ ' iif(Receipts.Receipt is Null, 0, Receipts.Receipt) - '+ ' iif(Charges.Charge is Null, 0, Charges.Charge) - '+ ' iif(DishCharges.DishCharge is Null, 0, DishCharges.DishCharge)'+ ' as Quantity '; const SELECT_MOVING_FIELDS: string = ' Meal.Id, Meal.Name, '+ ' iif(Storages.Storage is Null, 0, Storages.Storage) as Storage, '+ ' iif(Receipts.Receipt is Null, 0, Receipts.Receipt) as Receipt, '+ ' iif(Charges.Charge is Null, 0, Charges.Charge) as Charge, '+ ' iif(DishCharges.DishCharge is Null, 0, DishCharges.DishCharge) as DishCharge '; const SELECT_MOVING_EX_FIELDS: string = ' Meal.Id, Meal.Name, '+ ' iif(Storages.Storage is Null, 0, Storages.Storage) as Storage, '+ ' iif(Receipts.Receipt is Null, 0, Receipts.Receipt) as Receipt, '+ ' iif(Charges.Charge is Null, 0, Charges.Charge) as Charge, '+ ' iif(DishCharges.DishCharge is Null, 0, DishCharges.DishCharge) as DishCharge, '+ ' iif(ReceiptsEnd.Receipt is Null, 0, ReceiptsEnd.Receipt) as ReceiptEnd, '+ ' iif(ChargesEnd.Charge is Null, 0, ChargesEnd.Charge) as ChargeEnd, '+ ' iif(DishChargesEnd.DishCharge is Null, 0, DishChargesEnd.DishCharge) as DishChargeEnd '; const SELECT_MOVING : string = ' select %s '+ ' from '+ ' ( '+ ' ( '+ ' ( '+ ' Meal '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Storages '+ ' on Meal.Id = Storages.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Receipts '+ ' on Meal.Id = Receipts.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Charges '+ ' on Meal.Id = Charges.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as DishCharges '+ ' on Meal.Id = DishCharges.MealId '; const SELECT_MOVING_EX : string = ' select %s '+ ' from '+ ' ( '+ ' ( '+ ' ( '+ ' ( '+ ' ( '+ ' ( '+ ' Meal '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Storages '+ ' on Meal.Id = Storages.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Receipts '+ ' on Meal.Id = Receipts.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as Charges '+ ' on Meal.Id = Charges.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as DishCharges '+ ' on Meal.Id = DishCharges.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as ReceiptsEnd '+ ' on Meal.Id = ReceiptsEnd.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as ChargesEnd '+ ' on Meal.Id = ChargesEnd.MealId '+ ' ) '+ ' left join '+ ' ( '+ ' %s '+ ' ) as DishChargesEnd '+ ' on Meal.Id = DishChargesEnd.MealId '; const SELECT_MOVING_ORDER_CLAUSE: string = ' order by Name '; procedure SaveToFile(s: string); var fl: Text; begin AssignFile(fl, 'C:\Temp\log.txt'); Append(fl); Writeln(fl, s); CloseFile(fl); end; procedure SetParameterValues(Query: TADOQuery; Name: string; Value: Variant); var i: Integer; begin with Query.Parameters do for i := 0 to Count - 1 do if Items[i].Name = Name then Items[i].Value := Value; end; function QueryValue(qry: TADOQuery; sqlStr: string): Variant; begin Result := Null; with qry do begin SQL.Clear; SQL.Add(sqlStr); Open; try if not Eof then Result := Fields[0].Value; finally Close; end; end; end; function QueryValue2(qry: TADOQuery; sqlStr: string; var FieldVal1: Variant; var FieldVal2: Variant): boolean; begin Result := false; with qry do begin SQL.Clear; SQL.Add(sqlStr); Open; First; try if not Eof then begin FieldVal1 := Fields[0].Value; FieldVal2 := Fields[1].Value; Result := true; end; finally Close; end; end; end; procedure QueryExecute(qry: TADOQuery; sqlStr: string; const Args: array of const); var i: Integer; param: Variant; begin with qry do begin Close; SQL.Clear; SQL.Add(sqlStr); Parameters.ParseSQL(SQL.Text, true); for i := 0 to High(Args) do begin with Args[I] do begin case VType of vtInteger: param := VInteger; vtBoolean: param := VBoolean; vtChar: param := VChar; vtExtended: param := VExtended^; vtString: param := VString^; vtPChar: param := string(VPChar); vtObject: param := VObject.ClassName; vtClass: param := VClass.ClassName; vtAnsiString: param := string(VAnsiString); vtCurrency: param := VCurrency^; vtVariant: param := VVariant^; vtInt64: param := VInt64^; end; end; Parameters[i].Value := param; end; ExecSql; Close; end; end; function GetStoragesSelect(ParamName: string): string; begin Result := ' select MealId, Quantity as Storage from MealStorage '+ ' where Date = :'+ ParamName + ' '; end; function GetReceiptsSelect(ParamName1, ParamName2: string): string; begin Result := Format( ' select MealId, sum(Quantity) as Receipt '+ ' from '+ ' MealOperations '+ ' where OperationId = 1 '+ ' and MealOperations.OperationDate >= :%s '+ ' and MealOperations.OperationDate <= :%s '+ ' group by MealId ', [ParamName1, ParamName2]); end; function GetChargesSelect(ParamName1, ParamName2: string): string; begin Result := Format( ' select MealId, sum(Quantity) as Charge '+ ' from MealOperations '+ ' where OperationId = 2 '+ ' and MealOperations.OperationDate >= :%s '+ ' and MealOperations.OperationDate <= :%s '+ ' group by MealId ', [ParamName1, ParamName2]); end; function GetDishChargesSelect(ParamName1, ParamName2: string): string; begin Result := Format( ' select SoldDishComponents.MealId, '+ ' sum(DishesSelling.Count * SoldDishComponents.Quantity) as DishCharge '+ ' from DishesSelling '+ ' left join SoldDishComponents '+ ' on DishesSelling.Id = SoldDishComponents.SoldDishId '+ ' where '+ ' DishesSelling.SelDate >= :%s '+ ' and DishesSelling.SelDate <= :%s '+ ' group by SoldDishComponents.MealId ', [ParamName1, ParamName2]); end; function GetInsSqlStr(Date: TDateTime; ParamName1, ParamName2: string): string; var sDate: string; begin sDate := Format('%d/%d/%d', [MonthOf(Date), DayOf(Date), YearOf(Date)]); Result := Format(INSERT_MEAL_STORAGE_CLAUSE, [ Format(SELECT_MOVING, [ Format(INSERT_MEAL_STORAGE_FIELDS, [sDate]), GetStoragesSelect(ParamName1), GetReceiptsSelect(ParamName1, ParamName2), GetChargesSelect(ParamName1, ParamName2), GetDishChargesSelect(ParamName1, ParamName2) ]) ]); end; function GetMovingSql(ParamName1, ParamName2: string): string; begin Result := Format(SELECT_MOVING, [ SELECT_MOVING_FIELDS, GetStoragesSelect(ParamName1), GetReceiptsSelect(ParamName1, ParamName2), GetChargesSelect(ParamName1, ParamName2), GetDishChargesSelect(ParamName1, ParamName2) ]); Result := Result + SELECT_MOVING_ORDER_CLAUSE; end; function GetMovingExSql( ParamName1, ParamName2, ParamName3, ParamName4: string): string; begin SetLength(Result, 6000); StrFmt(PChar(Result), PChar(SELECT_MOVING_EX), [ SELECT_MOVING_EX_FIELDS, GetStoragesSelect(ParamName1), GetReceiptsSelect(ParamName1, ParamName2), GetChargesSelect(ParamName1, ParamName2), GetDishChargesSelect(ParamName1, ParamName2), GetReceiptsSelect(ParamName3, ParamName4), GetChargesSelect(ParamName3, ParamName4), GetDishChargesSelect(ParamName3, ParamName4) ]); StrCopy(PChar(Result) + StrLen(PChar(Result)), PChar(' ' + SELECT_MOVING_ORDER_CLAUSE)); end; function ConstructSelectMovingSql(qryMoving: TADOQuery; Date: TDateTime): string; begin qryMoving.Sql.Clear; qryMoving.Sql.Add(GetMovingSql('pBeginDate', 'pEndDate')); // create parameters list qryMoving.Parameters.ParseSQL(qryMoving.SQL.Text, true); SetParameterValues(qryMoving, 'pBeginDate', StartOfTheMonth(Date)); SetParameterValues(qryMoving, 'pEndDate', Floor(Date)); end; function ConstructSelectMovingExSql(qryMoving: TADOQuery; BeginDate, EndDate: TDateTime): string; begin qryMoving.Sql.Clear; qryMoving.Sql.Add(GetMovingExSql('pBeginDate', 'pEndDate', 'pBeginDate2', 'pEndDate2')); // create parameters list qryMoving.Parameters.ParseSQL(qryMoving.SQL.Text, true); SetParameterValues(qryMoving, 'pBeginDate', StartOfTheMonth(BeginDate)); SetParameterValues(qryMoving, 'pEndDate', Floor(IncDay(BeginDate, -1))); SetParameterValues(qryMoving, 'pBeginDate2', Floor(BeginDate)); SetParameterValues(qryMoving, 'pEndDate2', Floor(EndDate)); end; { TdmodRestCalc } procedure TdmodRestCalc.CalculateRest(BeginDate, EndDate: TDateTime); var CurDate: TDateTime; begin if EndDate >= BeginDate then begin CurDate := BeginDate; while CurDate <= EndDate do begin CalculateRest(CurDate); CurDate := IncMonth(CurDate); end; end; end; procedure TdmodRestCalc.CalculateRest(Date: TDateTime); begin ExecRestDel(Date); ExecRestCalc(Date); end; procedure TdmodRestCalc.ExecRestDel(Date: TDateTime); begin Date := StartOfTheMonth(Date); // first day of the month qryRest.Close; qryRest.SQL.Clear; qryRest.SQL.Add('delete from MealStorage where Date = :pDelDate'); qryRest.Parameters.ParseSQL(qryRest.SQL.Text, true); SetParameterValues(qryRest, 'pDelDate', Date); qryRest.ExecSQL; qryRest.Close; end; procedure TdmodRestCalc.ExecRestCalc(Date: TDateTime); var BeginDate, EndDate: TDateTime; begin EndDate := IncDay(Date, -1); // last day of the previous month BeginDate := StartOfTheMonth(EndDate); // first day of the previous month qryRest.Close; qryRest.SQL.Clear; qryRest.SQL.Add( GetInsSqlStr(Date, 'pBeginDate', 'pEndDate') // Date - date of the rests ); // create parameters list qryRest.Parameters.ParseSQL(qryRest.SQL.Text, true); SetParameterValues(qryRest, 'pBeginDate', BeginDate); SetParameterValues(qryRest, 'pEndDate', EndDate); qryRest.ExecSQL; qryRest.Close; end; function TdmodRestCalc.GetMaxOperationDate: TDateTime; var Date: Variant; begin Result := 0; // get max operation date Date := QueryValue(qry, 'select max(OperationDate) from MealOperations'); if (not VarIsNull(Date)) then Result := Date; // get max selling dishes date Date := QueryValue(qry, 'select max(SelDate) from DishesSelling'); if (not VarIsNull(Date)) and (Date > Result) then Result := Date; end; function TdmodRestCalc.GetMinOperationDate: TDateTime; var Date: Variant; begin Result := 0; // get min operation date Date := QueryValue(qry, 'select min(OperationDate) from MealOperations'); if (not VarIsNull(Date)) then Result := Date; // get min selling dishes date Date := QueryValue(qry, 'select min(SelDate) from DishesSelling'); if (not VarIsNull(Date)) and (Date < Result) then Result := Date; end; function TdmodRestCalc.GetMaxStorageDate: TDateTime; var Date: Variant; begin Result := 0; Date := QueryValue(qry, 'select max(Date) from MealStorage'); if (not VarIsNull(Date)) then Result := Date; end; function TdmodRestCalc.GetMinStorageDate: TDateTime; var Date: Variant; begin Result := 0; Date := QueryValue(qry, 'select min(Date) from MealStorage'); if (not VarIsNull(Date)) then Result := Date; end; function TdmodRestCalc.GetMaxDate: TDateTime; var Date: TDateTime; begin Result := GetMaxStorageDate; Date := GetMaxOperationDate; if Date > Result then Result := Date; end; function TdmodRestCalc.GetMinDate: TDateTime; var Date: TDateTime; begin Result := GetMinStorageDate; Date := GetMinOperationDate; if Date < Result then Result := Date; end; function TdmodRestCalc.GetMaxMaxOperationDate(var Field1, Field2: TDateTime): boolean; var F1, F2: Variant; res1, res2: boolean; begin res1 := QueryValue2(qry, 'select min(OperationDate), max(OperationDate) from MealOperations', F1, F2); if VarIsNull(F1) then res1 := false; if res1 = true then begin Field1 := F1; Field2 := F2; end; res2 := QueryValue2(qry, 'select min(SelDate), max(SelDate) from DishesSelling', F1, F2); if VarIsNull(F1) then res2 := false; if res2 = true then begin if F1 < Field1 then Field1 := F1; if F2 > Field2 then Field2 := F2; end; Result := res1 or res2; end; function TdmodRestCalc.GetMinMaxStorageDate(var Field1, Field2: TDateTime): boolean; var F1, F2: Variant; begin Result := QueryValue2(qry, 'select min(Date), max(Date) from MealStorage', F1, F2); if VarIsNull(F1) then Result := false; if Result = true then begin Field1 := F1; Field2 := F2; end; end; procedure TdmodRestCalc.CorrectRest(ProdId: Integer; RestDate: TDateTime; CorrectValue: Currency); var OperationId: Integer; begin if CorrectValue = 0 then Exit; if CorrectValue < 0 then begin CorrectValue := -CorrectValue; OperationId := TYPE_CHARGES; end else OperationId := TYPE_RECEIPTS; with qry do begin SQL.Clear; SQL.Add('insert into MealOperations'); SQL.Add('(OperationDate, MealId, Quantity, OperationId, Type)'); SQL.Add('values (:p1, :p2, :p3, :p4, :p5)'); Parameters.ParseSQL(qry.SQL.Text, true); Parameters[0].Value := RestDate; Parameters[1].Value := ProdId; Parameters[2].Value := CorrectValue; Parameters[3].Value := OperationId; Parameters[4].Value := SUBTYPE_CORRECTION; // Correction operation ExecSql(); Close; end; end; procedure TdmodRestCalc.DeleteData(DelDate: TDateTime); begin // delete sood dishes and its components QueryExecute(qry, 'delete from SoldDishComponents where SoldDishId in ' + '(select id from DishesSelling where SelDate < :p)', [DelDate]); QueryExecute(qry, 'delete from DishesSelling where SelDate < :p', [DelDate]); // delete month rests QueryExecute(qry, 'delete from MealStorage where Date < :p', [DelDate]); // delete meal operations QueryExecute(qry, 'delete from MealOperations where OperationDate < :p', [DelDate]); end; end.
unit PacketWrapperTests; interface uses SysUtils, Classes, eiTypes, eiConstants, eiProtocol, eiHelpers, TestFramework; type TPacketWrapperTest = class(TTestCase) private FOffset: ushort; FDataType: DataTypeEnum; FLength: DataLength; FPacket: EasyIpPacket; FWrapperPacket: IEasyIpProtocol; protected procedure SetUp; override; procedure TearDown; override; published procedure TestReadPacket; procedure TestWritePacket; end; implementation { TPacketWrapperTest } procedure TPacketWrapperTest.SetUp; begin inherited; FOffset := 5555; FDataType := dtFlag; FLength := 222; end; procedure TPacketWrapperTest.TearDown; begin inherited; end; procedure TPacketWrapperTest.TestReadPacket; var i: int; begin FPacket := TPacketFactory.GetReadPacket(FOffset, dtFlag, FLength); FWrapperPacket := TEasyIpProtocol.Create(pmRead); with FWrapperPacket do begin DataLength := FLength; DataType := FDataType; DataOffset := FOffset; end; Check(FPacket.SendDataType = FWrapperPacket.Packet.SendDataType); Check(FPacket.RequestDataType = FWrapperPacket.Packet.RequestDataType); Check(FPacket.RequestDataSize = FWrapperPacket.Packet.RequestDataSize); Check(FPacket.RequestDataOffsetServer = FWrapperPacket.Packet.RequestDataOffsetServer); for i := 1 to Length(FPacket.Data) do begin Check(FPacket.Data[i] = 0); Check(FWrapperPacket.Packet.Data[i] = 0); end; FWrapperPacket := nil; end; procedure TPacketWrapperTest.TestWritePacket; var i: int; begin FPacket := TPacketFactory.GetWritePacket(FOffset, dtFlag, FLength); FWrapperPacket := TEasyIpProtocol.Create(pmWrite); with FWrapperPacket do begin DataLength := FLength; DataType := FDataType; DataOffset := FOffset; end; Check(FPacket.SendDataType = FWrapperPacket.Packet.SendDataType); Check(FPacket.RequestDataType = FWrapperPacket.Packet.RequestDataType); Check(FPacket.SendDataSize = FWrapperPacket.Packet.SendDataSize); Check(FPacket.SendDataOffset = FWrapperPacket.Packet.SendDataOffset); for i := 1 to Length(FPacket.Data) do begin Check(FWrapperPacket.Packet.Data[i] = FPacket.Data[i]); end; FWrapperPacket := nil; end; initialization // TestFramework.RegisterTest(TPacketWrapperTest.Suite); end.
unit uChoiceIntervalExt; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Registry, IniFiles, StrUtils, uOPCInterval; type TChoiceIntervalExt = class(TForm) gbInterval: TGroupBox; dtFrom: TDateTimePicker; Label1: TLabel; tmFrom: TDateTimePicker; Label2: TLabel; dtTo: TDateTimePicker; tmTo: TDateTimePicker; bOk: TButton; bCancel: TButton; rbLastTime: TRadioButton; rbInterval: TRadioButton; eHours: TEdit; Label3: TLabel; cbPeriod: TComboBox; procedure FormShow(Sender: TObject); procedure rbLastTimeKeyPress(Sender: TObject; var Key: Char); procedure rbIntervalClick(Sender: TObject); procedure eHoursKeyPress(Sender: TObject; var Key: Char); procedure cbPeriodChange(Sender: TObject); procedure tmFromChange(Sender: TObject); private procedure ChangeKind; function GetKind: TOPCIntervalKind; procedure SetKind(const Value: TOPCIntervalKind); function GetDate1: TDateTime; function GetDate2: TDateTime; procedure SetDate1(const Value: TDateTime); procedure SetDate2(const Value: TDateTime); procedure UpdateEnabled; public procedure SetInterval(aInterval:TOPCInterval); procedure GetInterval(aInterval:TOPCInterval); property Date1:TDateTime read GetDate1 write SetDate1; property Date2:TDateTime read GetDate2 write SetDate2; property Kind :TOPCIntervalKind read GetKind write SetKind; end; function ShowIntervalForm(aInterval: TOPCInterval): boolean; implementation //var // ChoiceIntervalExt: TChoiceIntervalExt; function ShowIntervalForm(aInterval: TOPCInterval): boolean; begin with TChoiceIntervalExt.Create(nil) do begin try SetInterval(aInterval); if ShowModal = mrOk then begin GetInterval(aInterval); Result := true; end else Result := false; finally Free; end; end; end; {$R *.dfm} { TCinemaPropertyForm } procedure TChoiceIntervalExt.cbPeriodChange(Sender: TObject); var dow: integer; d,m,y: word; begin // день недели по нашему : пн-0, вт-1 ... вс-6 dow := DayOfWeek(Now); if dow = 1 then dow := 6 else dow := dow - 2; case cbPeriod.ItemIndex of 1: // сегодня begin Date1 := trunc(Now); Date2 := trunc(Now)+1; end; 2: // вчера begin Date1 := trunc(Now)-1; Date2 := trunc(Now); end; 3: // с начала недели begin Date1 := Trunc(Now - dow); Date2 := Trunc(Now)+1; end; 4: // предыдущая неделя begin Date2 := Trunc(Now - dow); Date1 := Trunc(Now - dow) - 7; end; 5: // с начала месяца begin DecodeDate(Now, y, m,d); Date1 := EncodeDate(y,m,1); Date2 := Trunc(Now)+1; end; 6: // прошлый месяц begin DecodeDate(Now, y, m,d); Date2 := EncodeDate(y,m,1); if m = 1 then begin y := y - 1; m := 12; end else m := m - 1; Date1 := EncodeDate(y,m,1); end; end; end; procedure TChoiceIntervalExt.ChangeKind; begin if rbInterval.Checked then Kind := ikInterval else Kind := ikShift; UpdateEnabled; end; procedure TChoiceIntervalExt.eHoursKeyPress(Sender: TObject; var Key: Char); begin if (Key = '.') or (Key = ',') then begin if pos(FormatSettings.DecimalSeparator,(Sender as TEdit).Text) = 0 then Key := FormatSettings.DecimalSeparator else begin Key := #0; beep; exit; end end; if not ( (Key = FormatSettings.DecimalSeparator) or (Key = Char(VK_BACK)) or (Key = Char(VK_DELETE)) or CharInSet(Key, ['0','1','2','3','4','5','6','7','8','9']) ) then begin Key := #0; beep; end end; procedure TChoiceIntervalExt.FormShow(Sender: TObject); begin ChangeKind; UpdateEnabled; end; function TChoiceIntervalExt.GetDate1: TDateTime; begin if tmFrom.Checked then Result := Trunc(dtFrom.DateTime) + Frac(tmFrom.DateTime) else Result := Trunc(dtFrom.DateTime); end; function TChoiceIntervalExt.GetDate2: TDateTime; begin if tmTo.Checked then Result := Trunc(dtTo.DateTime) + Frac(tmTo.DateTime) else Result := Trunc(dtTo.DateTime) + 1; end; procedure TChoiceIntervalExt.GetInterval(aInterval: TOPCInterval); begin aInterval.Kind := Kind; case aInterval.Kind of ikInterval: begin aInterval.SetInterval(Date1, Date2); aInterval.ShiftKind := TShiftKind(cbPeriod.ItemIndex); end; ikShift: if eHours.Text<>'' then aInterval.TimeShift := StrToFloat(eHours.Text)/24; end; end; function TChoiceIntervalExt.GetKind: TOPCIntervalKind; begin if rbInterval.Checked then Result := ikInterval // интервал else Result := ikShift;// последние часы end; procedure TChoiceIntervalExt.rbIntervalClick(Sender: TObject); begin ChangeKind; if rbInterval.Checked then ActiveControl := cbPeriod else ActiveControl := eHours; end; procedure TChoiceIntervalExt.rbLastTimeKeyPress(Sender: TObject; var Key: Char); begin ChangeKind; end; procedure TChoiceIntervalExt.SetDate1(const Value: TDateTime); begin dtFrom.Date := Trunc(Value); tmFrom.Time := Frac(Value); end; procedure TChoiceIntervalExt.SetDate2(const Value: TDateTime); begin dtTo.Date := Trunc(Value); tmTo.Time := Frac(Value); if Frac(Value) = 0 then dtTo.Date := dtTo.Date - 1; end; procedure TChoiceIntervalExt.SetInterval(aInterval: TOPCInterval); begin Kind := aInterval.Kind; Date1 := aInterval.Date1; Date2 := aInterval.Date2; cbPeriod.ItemIndex := Ord(aInterval.ShiftKind); eHours.Text := FormatFloat('0.##',aInterval.TimeShift*24); end; procedure TChoiceIntervalExt.SetKind(const Value: TOPCIntervalKind); begin case Value of ikInterval: rbInterval.Checked := true; ikShift : rbLastTime.Checked := true; end; end; procedure TChoiceIntervalExt.tmFromChange(Sender: TObject); begin cbPeriod.ItemIndex := 0; end; procedure TChoiceIntervalExt.UpdateEnabled; var i: Integer; begin case Kind of ikInterval: begin eHours.Enabled := false; gbInterval.Enabled := true; cbPeriod.Enabled := true; end; ikShift: begin eHours.Enabled := true; gbInterval.Enabled := false; cbPeriod.Enabled := false; end; end; for i := 0 to gbInterval.ControlCount - 1 do gbInterval.Controls[i].Enabled := gbInterval.Enabled; end; end.
unit uEditSoft; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Types, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uForm, ICSLanguages, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, PngBitBtn, XMLIntf, System.ImageList, Vcl.ImgList, PngImageList, Vcl.Menus, Vcl.ComCtrls, SynEdit, SynURIOpener, SynEditHighlighter, SynHighlighterURI; type TfrmEditSoft = class(TfrmForm) btnOk: TPngBitBtn; btnCancel: TPngBitBtn; btnSoftBrowse: TPngBitBtn; lePath: TLabeledEdit; leParams: TLabeledEdit; leName: TLabeledEdit; ImageIcon: TImage; OpenDialog1: TOpenDialog; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; lvProtocols: TListView; SynEditDefaultParams1: TSynEdit; TabSheetMemo: TTabSheet; SynEditMemo: TSynEdit; SynURISyn1: TSynURISyn; SynURIOpener1: TSynURIOpener; PngImageListLocations: TPngImageList; PngImageListTabs: TPngImageList; procedure FormShow(Sender: TObject); procedure btnSoftBrowseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lePathChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure PageControl1Change(Sender: TObject); private FSoftXMLNode: IXMLNode; FProtocolsXMLNode: IXMLNode; procedure FillControls; procedure SetImageIcon; public procedure ApplyXML; property SoftXMLNode: IXMLNode read FSoftXMLNode write FSoftXMLNode; // property ProtocolsXMLNode: IXMLNode read FProtocolsXMLNode write FProtocolsXMLNode; end; var frmEditSoft: TfrmEditSoft; implementation {$R *.dfm} uses ShlObj, uCommonTools, uClasses, uRegLite, uRegistry, uXMLTools, ShellAPI; { TfrmSoftEdit } procedure TfrmEditSoft.ApplyXML; var I: Integer; iNode: IXMLNode; begin xmlSetItemString(FSoftXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE, icsB64Encode(leName.Text)); xmlSetItemString(FSoftXMLNode.ChildNodes[ND_PATH], ND_PARAM_VALUE, icsB64Encode(lePath.Text)); xmlSetItemString(FSoftXMLNode.ChildNodes[ND_PARAMS], ND_PARAM_VALUE, icsB64Encode(leParams.Text)); xmlSetItemString(FSoftXMLNode.ChildNodes[ND_MEMO], ND_PARAM_VALUE, icsB64Encode(SynEditMemo.Text)); FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes.Clear; for I := 0 to lvProtocols.Items.Count - 1 do if lvProtocols.Items[I].Checked then begin iNode := FSoftXMLNode.ChildNodes[ND_PROTOCOLS].AddChild(ND_ITEM); xmlSetItemString(iNode, ND_PARAM_VALUE, xmlGetItemString(IXMLNode(lvProtocols.Items[I].Data), ND_PARAM_ID)); end; xmlSetItemString(FSoftXMLNode.ChildNodes[ND_PARAMSTRINGS1], ND_PARAM_VALUE, icsB64Encode(SynEditDefaultParams1.Lines.Text)); end; procedure TfrmEditSoft.btnSoftBrowseClick(Sender: TObject); begin inherited; OpenDialog1.InitialDir := lePath.Text; if not FileExists(OpenDialog1.InitialDir) and not DirectoryExists(OpenDialog1.InitialDir) then OpenDialog1.InitialDir := icsGetSpecialFolderLocation(Handle, CSIDL_PROGRAM_FILES); if OpenDialog1.Execute(Self.Handle) then lePath.Text := OpenDialog1.FileName; end; procedure TfrmEditSoft.SetImageIcon; var FName: String; begin FName := lePath.Text; if not FileExists(FName) then FName := icsGetLongPathName(FName); if FileExists(FName) then ImageIcon.Picture.Icon.Handle := icsGetIconHandleFromFileName(FName, False); end; procedure TfrmEditSoft.FillControls; var I, J: Integer; iNode: IXMLNode; LI: TListItem; begin leName.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE)); lePath.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PATH], ND_PARAM_VALUE)); SetImageIcon; leParams.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PARAMS], ND_PARAM_VALUE)); SynEditMemo.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_MEMO], ND_PARAM_VALUE)); lvProtocols.Items.BeginUpdate; try lvProtocols.Items.Clear; for I := 0 to FProtocolsXMLNode.ChildNodes.Count - 1 do begin iNode := FProtocolsXMLNode.ChildNodes[I]; LI := lvProtocols.Items.Add; LI.Caption := GetDisplayProtocolName(iNode); LI.ImageIndex := xmlGetItemInteger(iNode.ChildNodes[ND_LOCATION_ID], ND_PARAM_VALUE); LI.Data := Pointer(iNode); for J := 0 to FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes.Count - 1 do if xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes[J], ND_PARAM_VALUE) = xmlGetItemString(iNode, ND_PARAM_ID) then begin LI.Checked := True; Break; end; end; finally lvProtocols.Items.EndUpdate; end; SynEditDefaultParams1.Lines.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PARAMSTRINGS1], ND_PARAM_VALUE)); PageControl1.ActivePageIndex := 0; end; procedure TfrmEditSoft.FormClose(Sender: TObject; var Action: TCloseAction); var iNode: IXMLNode; begin inherited; iNode := FXML.DocumentElement.ChildNodes[ND_SOFTWARE]; xmlSetItemInteger(iNode, ND_PARAM_LEFT, Left); xmlSetItemInteger(iNode, ND_PARAM_TOP, Top); xmlSetItemInteger(iNode, ND_PARAM_WIDTH, Width); xmlSetItemInteger(iNode, ND_PARAM_HEIGHT, Height); end; procedure TfrmEditSoft.FormCreate(Sender: TObject); begin inherited; FProtocolsXMLNode := FXML.DocumentElement.ChildNodes[ND_PROTOCOLS]; end; procedure TfrmEditSoft.FormShow(Sender: TObject); var iNode: IXMLNode; begin inherited; iNode := FXML.DocumentElement.ChildNodes[ND_SOFTWARE]; SetBounds(xmlGetItemInteger(iNode, ND_PARAM_LEFT, Left), xmlGetItemInteger(iNode, ND_PARAM_TOP, Top), xmlGetItemInteger(iNode, ND_PARAM_WIDTH, Width), xmlGetItemInteger(iNode, ND_PARAM_HEIGHT, Height)); FillControls; end; procedure TfrmEditSoft.lePathChange(Sender: TObject); begin inherited; SetImageIcon; end; procedure TfrmEditSoft.PageControl1Change(Sender: TObject); begin inherited; if Visible then case PageControl1.ActivePageIndex of 1: SynEditDefaultParams1.SetFocus; 2: SynEditMemo.SetFocus; end; end; end.
{Megjegyzések: - Egy eszköztár esetén a ControlBar AutoSize tulajdonsága legyen True, mert úgysem mozgathatjuk lejjebb a ToolBar-t! - Egy eszköztár esetén is használjunk ControlBar-t, mert akkor a form kicsire állításával az eszköztár is szépen igazodik! - A ToolButton komponensek csoportosíthatók (Grouped) (ha pl. egyidőben csak az egyik lehet közülük lenyomva)! - ControlBar helyett használhatunk CoolBar-t is, csak akkor a ToolBar szélei mozgathatók, nem maga a ToolBar. - A ToolBar-ra SpeedButton-ok is feltehetők, de ezek csak nyomógomb jellegűek lehetnek (nincs Style tulajdonságuk), a ToolBar Flat se hat rájuk. Az ő képeiket a Glyph tulajdonságban lehet megadni (nem az ImageIndex-el), és ekkor ImageList sem kell. - Eszköztár alapjául a ControlBar, CoolBar komponenseken kívül, síma Panel is szolgálhat, amire ToolButton komponensek ugyan nem, de helyettük SpeedButton komponensek, ill. más egyéb komponensek (pl. ComboBox) tehetők és ezeket tetszés szerint pozícionálhatjuk a Panel komponensen. Az ilyen eszköztár persze nem igazodik automatikusan a form átméretezésekor, kis méret esetén ezek egyszerűen nem fognak látszani. Az eszköztár átméretezése ilyenkor a form OnResize eseménykezelőjében programozható. - A SpeedButton komponensek nem köthetők közvetlenül menüpontokhoz (nincs MenuItem tulajdonságuk), ezért a megfelelő menüpont esemény- kezelőjét rendeljük hozzá a SpeedButton OnClick eseményéhez!} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, ToolWin, ExtCtrls, StdCtrls, Menus, Buttons; type TForm1 = class(TForm) ControlBar1: TControlBar; ToolBar1: TToolBar; ImageList1: TImageList; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; ToolButton10: TToolButton; MainMenu1: TMainMenu; fajl: TMenuItem; uj: TMenuItem; megnyitas: TMenuItem; mentes: TMenuItem; nyomtatas: TMenuItem; N1: TMenuItem; kilepes: TMenuItem; szerkesztes: TMenuItem; kivagas: TMenuItem; masolas: TMenuItem; beillesztes: TMenuItem; PopupMenu1: TPopupMenu; egy: TMenuItem; ketto: TMenuItem; procedure Uzen(Sender:TObject); procedure kilepesClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} {Hogy lássuk a küldő objektum típusát és felbukkanó tippjét} procedure TForm1.Uzen(Sender:TObject); begin if Sender is TToolButton then ShowMessage('ToolButton:'+TToolButton(Sender).Hint) else if Sender is TMenuItem then ShowMessage('TMenuItem:'+TMenuItem(Sender).Hint); end; procedure TForm1.kilepesClick(Sender: TObject); begin Close; end; end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit typedump; interface uses typinfo; function GetDumpedTypeInfo(Root: PTypeInfo; Indent: AnsiString = ''): AnsiString; implementation uses sysutils; function AlignToPtr(P: Pointer): Pointer; inline; begin {$IFDEF FPC_REQUIRES_PROPER_ALIGNMENT} Result := Align(P,SizeOf(P)); {$ELSE FPC_REQUIRES_PROPER_ALIGNMENT} Result := P; {$ENDIF FPC_REQUIRES_PROPER_ALIGNMENT} end; function GetNextShortString(const Current: PShortString): PShortString; begin Result := PShortString(AlignToPtr(Pointer(Current)+Length(Current^)+1)); end; function GetDumpedTypeInfo(Root: PTypeInfo; Indent: AnsiString = ''): AnsiString; function GetTypeKindName(Kind: TTypeKind): AnsiString; begin case Kind of tkUnknown: Result := 'Unknown'; tkInteger: Result := 'Integer'; tkChar: Result := 'Char'; tkEnumeration: Result := 'Enumeration'; tkFloat: Result := 'Float'; tkSet: Result := 'Set'; tkMethod: Result := 'Method'; tkSString: Result := 'Short String'; tkLString: Result := 'LString'; tkAString: Result := 'AnsiString'; tkWString: Result := 'WideString'; tkVariant: Result := 'Variant'; tkArray: Result := 'Array'; tkRecord: Result := 'Record'; tkInterface: Result := 'Interface'; tkClass: Result := 'Class'; tkObject: Result := 'Object'; tkWChar: Result := 'WideChar'; tkBool: Result := 'Boolean'; tkInt64: Result := 'Int64'; tkQWord: Result := 'QWord'; tkDynArray: Result := 'Dynamic Array'; tkInterfaceRaw: Result := 'Raw Interface'; tkProcVar: Result := 'Procedure Variable'; tkUString: Result := 'UnicodeString'; tkUChar: Result := 'UnicodeChar'; tkHelper: Result := 'Helper'; tkFile: Result := 'File'; tkClassRef: Result := 'Class Reference'; tkPointer: Result := 'Pointer'; else Result := 'mystery'; end; end; procedure AddStringField(const FieldName: AnsiString; var Result: AnsiString; const Value: ShortString); begin if (Value <> '') then Result := Result + Indent + FieldName + ': ' + Value + #10 else Result := Result + Indent + FieldName + ': <unknown> ' + #10; end; procedure AddBooleanField(const FieldName: AnsiString; var Result: AnsiString; const Value: Boolean); begin if (Value) then Result := Result + Indent + FieldName + #10; end; type PCallConv = ^TCallConv; PParamFlags = ^TParamFlags; PManagedField = ^TManagedField; var Data: PTypeData; PropList: PPropList; ParamListData, ParamTypeData: Pointer; StringData, ResultType, ParamName, TypeName: PShortString; ResultTypeRef: PPTypeInfo; CCPtr: PCallConv; ParamFlagsPtr: PParamFlags; Index: LongInt; Count: SizeInt; ManagedField: PManagedField; ProcedureParam: PProcedureParam; PadString: ShortString; begin if (not Assigned(Root)) then begin Result := '<nil>' + #10; Exit; end; if (Root^.Name <> '') then Result := 'Type ' + Root^.Name + ' = ' + GetTypeKindName(Root^.Kind) + ':' + #10 else Result := 'Anonymous ' + GetTypeKindName(Root^.Kind) + ' type:' + #10; Indent := Indent + ' '; Data := GetTypeData(Root); case Root^.Kind of tkUnKnown, tkLString, tkWString, tkVariant, tkUString: Result := Result + Indent + '(no further information available)' + #10; tkAString: Result := Result + Indent + 'Code page: ' + IntToStr(Data^.CodePage) + #10; tkInteger, tkChar, tkEnumeration, tkWChar, tkSet, tkBool: begin Result := Result + Indent + 'Ordinal type: ' + GetEnumName(TypeInfo(TOrdType), Ord(Data^.OrdType)) + #10; if (Root^.Kind = tkSet) then begin Result := Result + Indent + 'Composite type: ' + GetDumpedTypeInfo(Data^.CompType, Indent); end else begin Result := Result + Indent + 'Range: ' + IntToStr(Data^.MinValue) + '..' + IntToStr(Data^.MaxValue) + #10; if (Root^.Kind = tkEnumeration) then begin Result := Result + Indent + 'Name list: ' + Data^.NameList; StringData := GetNextShortString(@Data^.NameList); if (Data^.MaxValue > Data^.MinValue) then for Index := Data^.MinValue+1 to Data^.MaxValue do {BOGUS Warning: Type size mismatch, possible loss of data / range check error} begin Result := Result + ', ' + StringData^; StringData := GetNextShortString(StringData); end; Result := Result + #10; AddStringField('Unit name', Result, StringData^); Result := Result + Indent + 'Base type: ' + GetDumpedTypeInfo(Data^.BaseType, Indent); end; end; end; tkFloat: begin Result := Result + Indent + 'Float type: ' + GetEnumName(TypeInfo(TFloatType), Ord(Data^.FloatType)) + #10; end; tkSString: begin Result := Result + Indent + 'Maximum length: ' + IntToStr(Data^.MaxLength) + #10; end; tkClass: begin Result := Result + Indent + 'Class name: ' + Data^.ClassType.ClassName + #10; AddStringField('Unit name', Result, Data^.UnitName); Result := Result + Indent + 'Properties: (' + IntToStr(Data^.PropCount) + ')' + #10; Count := GetPropList(Root, PropList); if (Count > 0) then for Index := 0 to Count-1 do {BOGUS Warning: Type size mismatch, possible loss of data / range check error} begin Result := Result + Indent + ' ' + PropList^[Index]^.Name + ': ' + GetDumpedTypeInfo(PropList^[Index]^.PropType, Indent + ' '); // XXX we could include further information about the property end; FreeMem(PropList); Result := Result + Indent + 'Parent class: ' + GetDumpedTypeInfo(Data^.ParentInfo, Indent); end; tkRecord: begin Result := Result + Indent + 'Record size: ' + IntToStr(Data^.RecSize) + ' bytes' + #10; Result := Result + Indent + 'Managed fields: (' + IntToStr(Data^.ManagedFldCount) + ')' + #10; ManagedField := AlignToPtr(Pointer(@Data^.ManagedFldCount) + SizeOf(Data^.ManagedFldCount)); FillChar(PadString, SizeOf(PadString), ' '); {BOGUS Hint: Local variable "PadString" does not seem to be initialized} for Index := 1 to Data^.ManagedFldCount do begin Count := Length(IntToStr(ManagedField^.FldOffset)); if (Count < 4) then SetLength(PadString, 4-Count) else SetLength(PadString, 0); Result := Result + Indent + ' +' + IntToStr(ManagedField^.FldOffset) + PadString + ' ' + GetDumpedTypeInfo(ManagedField^.TypeRef, Indent + ' '); ManagedField := AlignToPtr(Pointer(ManagedField) + SizeOf(TManagedField)); end; end; tkHelper: begin AddStringField('Unit name', Result, Data^.UnitName); Result := Result + Indent + 'Properties: (' + IntToStr(Data^.PropCount) + ')' + #10; Result := Result + Indent + ' (properties not shown)' + #10; // XXX ... Result := Result + Indent + 'Helper parent: ' + GetDumpedTypeInfo(Data^.HelperParent, Indent); Result := Result + Indent + 'Helper extends: ' + GetDumpedTypeInfo(Data^.ExtendedInfo, Indent); end; tkMethod: begin Result := Result + Indent + 'Method kind: ' + GetEnumName(TypeInfo(TMethodKind), Ord(Data^.MethodKind)) + #10; // get pointers set up ParamListData := @Data^.ParamList; ParamTypeData := @Data^.ParamList; for Index := 1 to Data^.ParamCount do begin ParamTypeData := AlignToPtr(ParamTypeData + SizeOf(TParamFlags)); ParamTypeData := AlignToPtr(ParamTypeData+Length(PShortString(ParamTypeData)^)+1); ParamTypeData := AlignToPtr(ParamTypeData+Length(PShortString(ParamTypeData)^)+1); end; if (Data^.MethodKind in [mkFunction, mkClassFunction]) then begin ResultType := PShortString(ParamTypeData); ParamTypeData := AlignToPtr(ParamTypeData + Length(PShortString(ParamTypeData)^)+1); ResultTypeRef := ParamTypeData; ParamTypeData := AlignToPtr(ParamTypeData + SizeOf(PTypeInfo)); end; CCPtr := PCallConv(ParamTypeData); ParamTypeData := AlignToPtr(ParamTypeData + SizeOf(TCallConv)); // output description in the order we want Result := Result + Indent + 'Calling convention: ' + GetEnumName(TypeInfo(TCallConv), Ord(CCPtr^)) + #10; Result := Result + Indent + 'Parameters: (' + IntToStr(Data^.ParamCount) + ')' + #10; for Index := 1 to Data^.ParamCount do begin ParamFlagsPtr := PParamFlags(ParamListData); ParamListData := AlignToPtr(ParamListData + SizeOf(TParamFlags)); ParamName := PShortString(ParamListData); TypeName := GetNextShortString(ParamName); Result := Result + Indent + ' ' + ParamName^ + ': ' + TypeName^ + ' (Flags: ' + SetToString(PTypeInfo(TypeInfo(TParamFlags)), Byte(ParamFlagsPtr^), True) + ')' + #10; Result := Result + Indent + ' ' + GetDumpedTypeInfo(PPTypeInfo(ParamTypeData)^, Indent + ' '); ParamListData := GetNextShortString(TypeName); ParamTypeData := AlignToPtr(ParamTypeData+SizeOf(PTypeInfo)); end; if (Data^.MethodKind in [mkFunction, mkClassFunction]) then Result := Result + Indent + 'Result type: ' + ResultType^ + ' -- ' + GetDumpedTypeInfo(ResultTypeRef^, Indent); end; tkProcVar: begin Result := Result + Indent + 'Flags: ' + IntToStr(Data^.ProcSig.Flags) + #10; Result := Result + Indent + 'Calling convention: ' + GetEnumName(TypeInfo(TCallConv), Ord(Data^.ProcSig.CC)) + #10; Result := Result + Indent + 'Parameters: (' + IntToStr(Data^.ProcSig.ParamCount) + ')' + #10; if (Data^.ProcSig.ParamCount > 0) then for Index := 0 to Data^.ProcSig.ParamCount-1 do {BOGUS Warning: Type size mismatch, possible loss of data / range check error} begin ProcedureParam := Data^.ProcSig.GetParam(Index); Result := Result + Indent + ' ' + ProcedureParam^.Name + ' (Flags: ' + IntToStr(ProcedureParam^.Flags) + '): ' + GetDumpedTypeInfo(ProcedureParam^.ParamType, Indent + ' '); end; Result := Result + Indent + 'Result type: ' + GetDumpedTypeInfo(Data^.ProcSig.ResultType, Indent); end; tkInt64: Result := Result + Indent + 'Range: ' + IntToStr(Data^.MinInt64Value) + '..' + IntToStr(Data^.MaxInt64Value) + #10; tkQWord: Result := Result + Indent + 'Range: ' + IntToStr(Data^.MinQWordValue) + '..' + IntToStr(Data^.MaxQWordValue) + #10; tkInterface: begin AddBooleanField('Is a Dual Dispatch interface', Result, ifDispInterface in Data^.IntfFlags); AddBooleanField('Is a Dispatch interface', Result, ifDispatch in Data^.IntfFlags); AddBooleanField('Has a GUID', Result, ifHasGuid in Data^.IntfFlags); AddBooleanField('Has a string GUID identifier', Result, ifHasStrGUID in Data^.IntfFlags); AddStringField('GUID', Result, '{' + IntToHex(Data^.GUID.Data1, 8) + '-' + IntToHex(Data^.GUID.Data2, 4) + '-' + IntToHex(Data^.GUID.Data3, 4) + '-' + IntToHex(Data^.GUID.Data4[0], 2) + IntToHex(Data^.GUID.Data4[1], 2) + IntToHex(Data^.GUID.Data4[2], 2) + IntToHex(Data^.GUID.Data4[3], 2) + IntToHex(Data^.GUID.Data4[4], 2) + IntToHex(Data^.GUID.Data4[5], 2) + IntToHex(Data^.GUID.Data4[6], 2) + IntToHex(Data^.GUID.Data4[7], 2) + '}'); StringData := GetNextShortString(@Data^.RawIntfUnit); AddStringField('GUID string', Result, StringData^); AddStringField('Unit name', Result, Data^.IntfUnit); Result := Result + Indent + 'Parent interface2: ' + GetDumpedTypeInfo(Data^.IntfParent, Indent); end; tkInterfaceRaw: begin AddBooleanField('Is a Dispatch interface', Result, ifDispatch in Data^.RawIntfFlags); AddBooleanField('Is a Dual Dispatch interface', Result, ifDispInterface in Data^.RawIntfFlags); AddBooleanField('Has a GUID', Result, ifHasGuid in Data^.RawIntfFlags); AddBooleanField('Has a string GUID identifier', Result, ifHasStrGUID in Data^.RawIntfFlags); AddStringField('GUID', Result, '{' + IntToHex(Data^.IID.Data1, 8) + '-' + IntToHex(Data^.IID.Data2, 4) + '-' + IntToHex(Data^.IID.Data3, 4) + '-' + IntToHex(Data^.IID.Data4[0], 2) + IntToHex(Data^.IID.Data4[1], 2) + IntToHex(Data^.IID.Data4[2], 2) + IntToHex(Data^.IID.Data4[3], 2) + IntToHex(Data^.IID.Data4[4], 2) + IntToHex(Data^.IID.Data4[5], 2) + IntToHex(Data^.IID.Data4[6], 2) + IntToHex(Data^.IID.Data4[7], 2) + '}'); StringData := GetNextShortString(@Data^.RawIntfUnit); AddStringField('GUID string', Result, StringData^); AddStringField('Unit name', Result, Data^.RawIntfUnit); Result := Result + Indent + 'Parent interface: ' + GetDumpedTypeInfo(Data^.RawIntfParent, Indent); end; tkArray: begin Result := Result + Indent + 'Size: ' + IntToStr(Data^.ArrayData.Size) + ' bytes' + #10; Result := Result + Indent + 'Element count: ' + IntToStr(Data^.ArrayData.ElCount) + #10; Result := Result + Indent + 'Dimensions: (' + IntToStr(Data^.ArrayData.DimCount) + ')' + #10; if (Data^.ArrayData.DimCount > 0) then for Index := 0 to Data^.ArrayData.DimCount-1 do // $R- Result := Result + Indent + ' ' + IntToStr(Index) + ': ' + GetDumpedTypeInfo(Data^.ArrayData.Dims[Index], Indent + ' '); Result := Result + Indent + 'Element type: ' + GetDumpedTypeInfo(Data^.ArrayData.ElType, Indent); end; tkDynArray: begin AddStringField('Unit name', Result, Data^.DynUnitName); Result := Result + Indent + 'Element size: ' + IntToStr(Data^.elSize) + ' bytes' + #10; Result := Result + Indent + 'Element type: ' + GetDumpedTypeInfo(Data^.elType, Indent); Result := Result + Indent + 'Element type two: ' + GetDumpedTypeInfo(Data^.elType2, Indent); Result := Result + Indent + 'Variable type: ' + IntToStr(Data^.varType) + #10; end; tkClassRef: Result := Result + Indent + 'Reference of ' + GetDumpedTypeInfo(Data^.InstanceType, Indent); tkPointer: Result := Result + Indent + 'Reference of ' + GetDumpedTypeInfo(Data^.InstanceType, Indent); else Result := Result + Indent + '(no further type information defined)' + #10; end; end; end.
{$include kode.inc} unit fx_kill; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_plugin, kode_types; type myPlugin = class(KPlugin) private FKill : Boolean; public procedure on_Create; override; procedure on_ParameterChange(AIndex:LongWord; AValue:Single); override; procedure on_ProcessSample(AInputs,AOutputs:PPSingle); override; end; KPluginClass = myPlugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, kode_const, kode_flags, kode_parameter, kode_utils; const txt_kill : array[0..1] of PChar = ('off','on'); //---------- procedure myPlugin.on_Create; begin // config FName := 'fx_kill'; FAuthor := 'skei.audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + fx_kill_id; KSetFlag(FFlags,kpf_perSample); // parameters appendParameter( KParamText.create('kill', 0, 2, txt_kill ) ); // plugin FKill := False; end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); begin case AIndex of 0 : if AValue >= 0.5 then FKill := True else FKill := False; end; end; //---------- procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle); begin if FKill then begin AOutputs[0]^ := 0; AOutputs[1]^ := 0; end else begin AOutputs[0]^ := AInputs[0]^; AOutputs[1]^ := AInputs[1]^; end; end; //---------------------------------------------------------------------- end.
unit URPNParser; {$mode objfpc}{$H+} interface uses Classes, SysUtils, UStack, Dialogs; type TQueueNode = record Value: string; Next: ^TQueueNode; end; { TRPNQueue } TRPNQueue = class RootNode: ^TQueueNode; constructor Create; destructor Destroy; override; procedure Flush; procedure Push(val: string); function Pop: string; end; function ParseRPN(OpsQueue: TRPNQueue): extended; implementation function ParseRPN(OpsQueue: TRPNQueue): extended; var Ops: TRPNQueue; Stack: TStack; StackValue: string; t, FirstOperand, SecondOperand, OpResult: extended; begin Ops := OpsQueue; OpResult := 0; Stack := TStack.Create; StackValue := Ops.Pop; while (StackValue <> '') do begin if (TryStrToFloat(StackValue, t)) then Stack.Push(StackValue) else begin case StackValue of '+','-','*','/': begin SecondOperand := StrToFloat(Stack.Pop); FirstOperand := StrToFloat(Stack.Pop); case StackValue of '+': OpResult := FirstOperand + SecondOperand; '-': OpResult := FirstOperand - SecondOperand; '*': OpResult := FirstOperand * SecondOperand; '/': OpResult := FirstOperand / SecondOperand; end; Stack.Push(FloatToStr(OpResult)); end; end; end; StackValue := Ops.Pop; end; Result := StrToFloat(Stack.Pop); FreeAndNil(Stack); Ops := nil; end; { TRPNQueue } constructor TRPNQueue.Create; begin RootNode := nil; end; destructor TRPNQueue.Destroy; begin inherited Destroy; Flush; end; procedure TRPNQueue.Flush; begin while (Pop <> '') do begin end; end; procedure TRPNQueue.Push(val: string); var node, prevnode: ^TQueueNode; begin if (RootNode = nil) then begin New(RootNode); RootNode^.Value := val; RootNode^.Next := nil; end else begin prevnode := RootNode; repeat node := prevnode^.Next; if (node <> nil) then prevnode := node; until node = nil; New(prevnode^.Next); prevnode^.Next^.Value := val; prevnode^.Next^.Next := nil; end; end; function TRPNQueue.Pop: string; var t: ^TQueueNode; begin if (RootNode = nil) then Result := '' else begin Result := RootNode^.Value; t := RootNode^.Next; Dispose(RootNode); RootNode := t; end; end; end.
{ IndySOAP: This unit defines a base component which plugs in to the leak tracking architecture } unit IdSoapComponent; {$I IdSoapDefines.inc} interface uses Classes, IdComponent, IdSoapDebug; type {============================================================================== Soap version support currently IndySoap only implements Version 1.1 } TIdSoapVersion = (IdSoapV1_1); { IdSoapV1_1: Soap Version 1.1 specification, as widely implemented. References SOAP http://www.w3.org/TR/2000/NOTE-SOAP-20000508 WSDL http://www.w3.org/TR/2001/NOTE-wsdl-20010315 } TIdSoapVersionSet = set of TIdSoapVersion; {==============================================================================} TIdSoapComponent = class(TIdComponent) Private FSerialNo : Cardinal; Public {$IFNDEF INDY_V10} constructor Create(AOwner: TComponent); Override; {$ENDIF} destructor Destroy; Override; {$IFDEF INDY_V10} procedure InitComponent; override; {$ENDIF} function TestValid(AClassType: TClass = NIL): Boolean; end; implementation { TIdSoapComponent } {$IFNDEF INDY_V10} constructor TIdSoapComponent.Create(AOwner: TComponent); begin inherited; {$IFDEF OBJECT_TRACKING} FSerialNo := IdObjectRegister(self); {$ENDIF} end; {$ENDIF} destructor TIdSoapComponent.Destroy; begin {$IFDEF OBJECT_TRACKING} IdObjectDeregister(self, FSerialNo); {$ENDIF} inherited; end; {$IFDEF INDY_V10} procedure TIdSoapComponent.InitComponent; begin inherited; {$IFDEF OBJECT_TRACKING} IdObjectRegister(self); {$ENDIF} end; {$ENDIF} function TIdSoapComponent.TestValid(AClassType: TClass): Boolean; begin {$IFDEF OBJECT_TRACKING} Result := IdObjectTestValid(self); {$ELSE} Result := Assigned(self); {$ENDIF} if Result and assigned(AClassType) then begin Result := self is AClassType; end; end; end.
unit omNativeLanguage; // by oMAR may20 // Cross platdform native language OS setting (Windows, iOS and Android) TODO: MacOS interface var // NativeLanguage is set at initialization NativeLanguage:String=''; // like 'pt-BR' ou 'en-US' implementation //----------------------------------------------------- uses {$IFDEF Android} FMX.Platform, //Om: plat services Androidapi.JNIBridge, Androidapi.Helpers, Androidapi.JNI.JavaTypes; {$ENDIF Android} {$IFDEF IOS} iOSapi.Foundation, iOSapi.AVFoundation, Macapi.Helpers; {$ENDIF IOS} {$IFDEF MSWINDOWS} Winapi.Windows; {$ENDIF MSWINDOWS} // Android --------------------------------------------------------- {$IFDEF Android} function getDeviceCountryCode:String; //platform specific get country code var Locale: JLocale; begin Result:='??'; Locale := TJLocale.JavaClass.getDefault; Result := JStringToString( Locale.getCountry ); if Length(Result) > 2 then Delete(Result, 3, MaxInt); end; function getOSLanguage:String; var LocServ: IFMXLocaleService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXLocaleService, IInterface(LocServ)) then Result := LocServ.GetCurrentLangID // 2 letter code, but a different one ???? instead of 'pt' it gives 'po' else Result := '??'; // if set Japanese on Android, LocaleService returns "jp", but other platform returns "ja" // so I think it is better to change "jp" to "ja" if (Result = 'jp') then Result := 'ja' else if (Result = 'po') then Result := 'pt'; end; procedure getNativeLanguage; // Android begin NativeLanguage := getOSLanguage+'-'+getDeviceCountryCode; // 'pt-BR' end; {$ENDIF Android} // iOS-------------------------------------------------------------- {$IFDEF IOS} function getOSLanguage:String; //default language 'es-ES' 'en-US' 'pt-BR' .. var Languages: NSArray; begin Languages := TNSLocale.OCClass.preferredLanguages; Result := TNSString.Wrap(Languages.objectAtIndex(0)).UTF8String; end; procedure getNativeLanguage; begin NativeLanguage := getOSLanguage; // 'pt-BR' end; {$ENDIF IOS} // Windows ------------------------------------------- {$IFDEF MSWINDOWS} // from https://stackoverflow.com/questions/19369809/delphi-get-country-codes-by-localeid/37981772#37981772 function LCIDToLocaleName(Locale: LCID; lpName: LPWSTR; cchName: Integer; dwFlags: DWORD): Integer; stdcall;external kernel32 name 'LCIDToLocaleName'; function LocaleIDString():string; var strNameBuffer : array [0..255] of WideChar; // 84 was len from original process online //localID : TLocaleID; // localID was 0, so didn't initialize, but still returned proper code page. // using 0 in lieu of localID : nets the same result, var not required. i : integer; begin Result := ''; // LOCALE_USER_DEFAULT vs. LOCALE_SYSTEM_DEFAULT // since XP LOCALE_USER_DEFAULT is considered good practice for compatibility if (LCIDToLocaleName(LOCALE_USER_DEFAULT, strNameBuffer, 255, 0) > 0) then for i := 0 to 255 do begin if strNameBuffer[i] = #0 then break else Result := Result + strNameBuffer[i]; end; if (Length(Result) = 0) and (LCIDToLocaleName(0, strNameBuffer, 255, 0) > 0) then for i := 0 to 255 do begin if strNameBuffer[i] = #0 then break else Result := Result + strNameBuffer[i]; end; if Length(Result) = 0 then Result := 'NR-NR' // defaulting to [No Reply - No Reply] end; procedure getNativeLanguage; begin NativeLanguage := LocaleIDString; // 'pt-BR' end; {$ENDIF MSWINDOWS} initialization getNativeLanguage; // get OS native language-country end.
unit manejador_proyecto; interface uses sysutils, classes, Vcl.Dialogs, GMClasses, manejador_proyecto_const ; type { tipo de proyecto } TProyectoTipo = (PTOutdoor, PTIndoor); { tamaño del proyecto } TProyectoAlcance = (PAPequenho, PAMedio, PAAlto); TProyecto = class private FAlcance: TProyectoAlcance; FTipo: TProyectoTipo; FNombre: string; FFilename: string; FTitulo: string; FCentro: TLatLng; procedure SetAlcance(const Value: TProyectoAlcance); procedure SetTipo(const Value: TProyectoTipo); procedure SetNombre(const Value: string); procedure SetFilename(const Value: string); procedure SetTitulo(const Value: string); procedure SetCentro(const Value: TLatLng); public constructor create; overload; procedure GuardarComo; procedure Abrir(Archivo: string); property Centro: TLatLng read FCentro write SetCentro; property Tipo: TProyectoTipo read FTipo write SetTipo; property Alcance: TProyectoAlcance read FAlcance write SetAlcance; property Nombre: string read FNombre write SetNombre; property Filename: string read FFilename write SetFilename; end; implementation { TProyecto } procedure TProyecto.Abrir(Archivo: string); begin {} showmessage('hola mundo'); end; constructor TProyecto.create; begin FNombre := def_nombre; { nombre del proyecto } FAlcance := PAPequenho; { alcance pequeño } FTipo := PTOutdoor; { proyecto outdoor } FFilename := extractfilepath(paramstr(0)) + '\' + FNombre + '.nsf'; fcentro := TLatLng.Create(0,0); end; procedure TProyecto.GuardarComo; var dlg: TSaveDialog; begin dlg := TSaveDialog.create(nil); dlg.Title := 'Guardar como'; dlg.Filter := def_filter; dlg.FilterIndex := 0; if dlg.Execute then begin FFilename := ChangeFileExt(dlg.Filename, def_ext_fil); end; end; procedure TProyecto.SetAlcance(const Value: TProyectoAlcance); begin FAlcance := Value; end; procedure TProyecto.SetCentro(const Value: TLatLng); begin FCentro := Value; end; procedure TProyecto.SetFilename(const Value: string); begin FFilename := Value; end; procedure TProyecto.SetNombre(const Value: string); begin FNombre := Value; end; procedure TProyecto.SetTipo(const Value: TProyectoTipo); begin FTipo := Value; end; procedure TProyecto.SetTitulo(const Value: string); begin FTitulo := Value; end; end.
unit sourcecodehandler; {$mode objfpc}{$H+} interface uses Classes, SysUtils, tcclib, AvgLvlTree; type TSourceCodeInfoCollection=class //contains all the registered TSourceCodeInfo objects. (This 'should' keep up the speed when there are tons of C scripts compiled with source) private Collection: TAvgLvlTree; function RangeLookup(Tree: TAvgLvlTree; Data1, Data2: pointer): integer; public function getSourceCodeInfo(address: ptruint):TSourceCodeInfo; procedure addSourceCodeInfo(SourceCodeInfo: TSourceCodeInfo); procedure removeSourceCodeInfo(SourceCodeInfo: TSourceCodeInfo); constructor create; end; var SourceCodeInfoCollection: TSourceCodeInfoCollection; implementation uses cefuncproc; type TCollectionEntry=record startaddress: ptruint; stopaddress: ptruint; sourceCodeInfo: TSourceCodeInfo; end; PCollectionEntry=^TCollectionEntry; function TSourceCodeInfoCollection.RangeLookup(Tree: TAvgLvlTree; Data1, Data2: pointer): integer; var e1,e2: PCollectionEntry; begin e1:=data1; e2:=data2; if InRangeQ(e1^.startaddress, e2^.startaddress, e2^.stopaddress+1) or InRangeQ(e2^.startaddress, e1^.startaddress, e1^.stopaddress+1) then exit(0); if e1^.startaddress<e2^.startaddress then exit(-1) else exit(1); end; procedure TSourceCodeInfoCollection.addSourceCodeInfo(SourceCodeInfo: TSourceCodeInfo); var e: PCollectionEntry; begin getmem(e,sizeof(TCollectionEntry)); SourceCodeInfo.getRange(e^.startaddress, e^.stopaddress); e^.sourceCodeInfo:=SourceCodeInfo; collection.Add(e); end; procedure TSourceCodeInfoCollection.removeSourceCodeInfo(SourceCodeInfo: TSourceCodeInfo); var searchkey: TCollectionEntry; n: TAvgLvlTreeNode; begin SourceCodeInfo.getRange(searchkey.startaddress, searchkey.stopaddress); n:=collection.Find(@searchkey); while n<>nil do begin if (n.data<>nil) then FreeMemAndNil(n.Data); collection.Delete(n); n:=collection.Find(@searchkey); end; end; function TSourceCodeInfoCollection.getSourceCodeInfo(address: ptruint):TSourceCodeInfo; var searchkey: TCollectionEntry; n: TAvgLvlTreeNode; begin searchkey.startaddress:=address; searchkey.stopaddress:=address; n:=collection.Find(@searchkey); if n<>nil then result:=PCollectionEntry(n.Data)^.sourceCodeInfo else result:=nil; end; constructor TSourceCodeInfoCollection.create; begin Collection:=TAvgLvlTree.CreateObjectCompare(@RangeLookup); end; end.
program testfunctions17(output); {test some sample functions from Cooper p.77-78} var myseed,i:integer; function Tan(Angle: real): real; {returns the tangent of its argument.} begin Tan := sin(Angle) / cos(Angle) end; function Even (Number: integer): boolean; begin Even := (Number mod 2) = 0 {We could have just said Even := not odd(Number).} end; function Random(var Seed: integer): real; {returns a pseudo-random number such that 0 <= Random(Seed) < 1} const Modulus = 65536; Multiplier = 25173; Increment = 13849; begin Seed := ((Multiplier*Seed) + Increment) mod Modulus; Random := Seed/Modulus end; function GreatestCommonDenominator(i,j:integer):integer; {returns the greatest common denominator of i and j.} begin if i < j then GreatestCommonDenominator := GreatestCommonDenominator(j,i) else if j=0 then GreatestCommonDenominator := i else GreatestCommonDenominator := GreatestCommonDenominator(j, i mod j) end; begin writeln('GCD of 8 and 12 should be 4: ', GreatestCommonDenominator(8,12)); writeln('GCD of 60 and 90 should be 30: ', GreatestCommonDenominator(60,90)); writeln('GCD 84723912 and 999331 should be 1 since 999331 is prime: ', GreatestCommonDenominator(84723912, 999331)); writeln('Is 48 even? ', Even(48)); writeln('Is -932 even? ', Even(-932)); writeln('Is 38121 even? ', Even(38121)); writeln('Tangent of Pi should be 0: ', Tan(3.14159)); writeln('Tangent of Pi/12 should be 0.267949...: ', Tan(3.14159/12)); writeln('Tangent of 16 Pi / 13 should be 0.885922...: ', Tan(16 * 3.14159 / 13)); myseed := 30973; writeln ('and now for some pseudo-random numbers'); for i := 0 to 10 do begin writeln(Random(myseed)); end; end.
unit ZXing.Helpers; { * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Implemented by E. Spelt for Delphi } {$IFDEF FPC} {$mode delphi}{$H+} {$ENDIF} interface type TIntegerArray = TArray<Integer>; TArray = class class function Clone(original: TIntegerArray): TIntegerArray; static; class function CopyInSameArray(const Input: TIntegerArray; StartIndex: Integer; Len: Integer): TIntegerArray; static; class procedure Copy(const Source: TIntegerArray; var Target: TIntegerArray; SI, DI, Cnt: integer); static; end; implementation class function TArray.Clone(original: TIntegerArray): TIntegerArray; var i: Integer; l: SmallInt; begin l := Length(original); Result := TIntegerArray.Create{$ifndef FPC}(){$endif}; SetLength(Result, l); for i := 0 to l - 1 do begin Result[i] := original[i]; end; end; class function TArray.CopyInSameArray(const Input: TIntegerArray; StartIndex: Integer; Len: Integer): TIntegerArray; var i, y: Integer; begin Result := TArray.Clone(Input); y := 0; for i := StartIndex to (StartIndex + Len -1) do begin Result[y] := Input[i]; inc(y); end; end; class procedure TArray.Copy(const Source: TIntegerArray; var Target: TIntegerArray; SI, DI, Cnt: integer); begin System.Move(Pointer(@Source[SI])^, Pointer(@Target[DI])^, Cnt * SizeOf(Integer)); end; end.
unit DbEditUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StorageUnit, DB, DbFormUnit; type { TDbEditFrame } TDbEditFrame = class(TFrame, IRememberable) EditBtn: TSpeedButton; procedure EditBtnClick(Sender: TObject); private FAutoInsert: Boolean; FDataSource: TDataSource; FForm: TDbFormForm; FFormClass: TDbFormFormClass; procedure SetDataSource(ADataSource: TDataSource); function GetForm: TDbFormForm; function GetFormVisible: Boolean; procedure SetFormVisible(AFormVisible: Boolean); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; protected { IRememberable } procedure SaveState(Storage: TStorage; const SectionName, Prefix: string); procedure LoadState(Storage: TStorage; const SectionName, Prefix: string); public property FormVisible: Boolean read GetFormVisible write SetFormVisible; property FormClass: TDbFormFormClass read FFormClass write FFormClass; property Form: TDbFormForm read GetForm; published property AutoInsert: Boolean read FAutoInsert write FAutoInsert; property DataSource: TDataSource read FDataSource write SetDataSource; end; implementation {$R *.dfm} { TDbEditFrame } procedure TDbEditFrame.SetDataSource(ADataSource: TDataSource); begin if FDataSource <> ADataSource then begin FDataSource := ADataSource; if ADataSource <> nil then ADataSource.FreeNotification(Self); if FForm <> nil then FForm.DataSource := DataSource; end; end; function TDbEditFrame.GetForm: TDbFormForm; begin if FForm = nil then begin Assert(FormClass <> nil, Format('FormClass is not assigned in %s', [Name])); FForm := FormClass.Create(Self); FForm.AutoInsert := AutoInsert; FForm.Caption := Hint; FForm.DataSource := DataSource; FForm.Frame := Self; end; Result := FForm; end; function TDbEditFrame.GetFormVisible: Boolean; begin Result := EditBtn.Down; end; procedure TDbEditFrame.SetFormVisible(AFormVisible: Boolean); begin if EditBtn.Down <> AFormVisible then begin Form.Visible := AFormVisible; EditBtn.Down := AFormVisible; end; end; procedure TDbEditFrame.EditBtnClick(Sender: TObject); begin Form.Visible := EditBtn.Down; end; procedure TDbEditFrame.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = DataSource) then DataSource := nil; end; { IRememberable } procedure TDbEditFrame.SaveState(Storage: TStorage; const SectionName, Prefix: string); begin SaveFormState(Form, SectionName, Prefix + Name + '.Form.'); Storage.WriteBool(SectionName, Prefix + Name + '.FormVisible', FormVisible); FormVisible := False; end; procedure TDbEditFrame.LoadState(Storage: TStorage; const SectionName, Prefix: string); begin LoadFormState(Form, SectionName, Prefix + Name + '.Form.'); FormVisible := Storage.ReadBool(SectionName, Prefix + Name + '.FormVisible', FormVisible); end; end.
unit uUTT; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, uGlobals, GdiPlus, GdiPlusHelpers, uSavePoint, Menus, ActnList; type TUTTLevel = (lvlLow, lvlHigh); PUTTModule = ^TUTTModule; TUTTModule = record id:integer; level: TUTTLevel; lable: string; task_from, task_to: integer; visible: boolean; // points: integer; color: TGPColor; end; TUTTModulesList = array of TUTTModule; TPointsPerVariant = array of integer; TfrmUTT = class(TForm) rgVariants: TRadioGroup; Panel3: TPanel; ScrollBox: TScrollBox; img: TImage; pnlTools: TPanel; btNext: TSpeedButton; btPrev: TSpeedButton; btResults: TSpeedButton; btAnswear: TSpeedButton; Label3: TLabel; txtAnswer: TEdit; Panel1: TPanel; PopupMenu1: TPopupMenu; mnuGoToPage: TMenuItem; ActionList: TActionList; actGoToPage: TAction; actAnswearClick: TAction; actResultClick: TAction; actNextClick: TAction; actPrevClick: TAction; procedure rgVariantsClick(Sender: TObject); procedure txtAnswerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); procedure actGoToPageExecute(Sender: TObject); procedure actAnswearClickExecute(Sender: TObject); procedure actResultClickExecute(Sender: TObject); procedure actNextClickExecute(Sender: TObject); procedure actPrevClickExecute(Sender: TObject); private { Private declarations } mode: Tmode; fTask: integer; fUTTTest: TUTTModulesList; answears: TAnswears; taskResultMask: TResultMask; savePoint: TSavePoint; procedure loadTask(aVariant, aTask: integer); procedure AllTaskCompleate(); function doLoadUTT: TUTTModulesList; procedure assignedVariant; procedure UpdateButtons(value: boolean); public { Public declarations } function getModuleByID(id: integer): PUTTModule; property ResultMask: TResultMask read taskResultMask; procedure clearUserResults(); procedure saveResults(); procedure send(); property UTTTModuleList: TUTTModulesList read fUTTTest; function pointByUserAndModule(us_id: integer; mdl: PUTTModule): integer; function pointsByUserAllVariant(us_id: integer; mdl: PUTTModule): TPointsPerVariant; procedure ShowUTT(); end; implementation uses uOGE, uTestResult, ActiveX, uData, XMLIntf; {$R *.dfm} { TfrmUTT } function TfrmUTT.pointByUserAndModule(us_id: integer; mdl: PUTTModule): integer; var i,j: integer; sp: TSavePoint; rm: TResultMask; begin result := 0; sp := TSavePoint.Create(us_id, self.ClassName); sp.Load; for i := 0 to rgVariants.Items.Count - 1 do begin rm := sp.asResultMask('MASK_' + intToStr(i + 1)); if rm = nil then continue; for j := mdl.task_from - 1 to mdl.task_to - 1 do if (j >= 0) and (j < length(rm)) and rm[j] then inc(result); end; sp.Free; end; function TfrmUTT.pointsByUserAllVariant(us_id: integer; mdl: PUTTModule): TPointsPerVariant; var i,j: integer; sp: TSavePoint; rm: TResultMask; begin result := nil; if mdl = nil then exit; setLength(result, rgVariants.Items.Count); sp := TSavePoint.Create(us_id, self.ClassName); sp.Load; for i := 0 to rgVariants.Items.Count - 1 do begin rm := sp.asResultMask('MASK_' + intToStr(i + 1)); if rm = nil then continue; for j := mdl.task_from - 1 to mdl.task_to - 1 do if (j >= 0) and (j < length(rm)) and rm[j] then inc(result[i]); end; sp.Free end; procedure TfrmUTT.assignedVariant; begin if rgVariants.ItemIndex < 0 then begin messageBox(handle, 'Для продолжения выберите вариант.', 'ОГЭ', MB_OK or MB_ICONERROR); abort; end; end; function TfrmUTT.getModuleByID(id: integer): PUTTModule; var i: integer; begin result := nil; for i := 0 to length(fUTTTest) - 1 do if (id = fUTTTest[i].id) then exit(@fUTTTest[i]); end; procedure TfrmUTT.AllTaskCompleate; begin mode := mNormal; // All tasks complete if messageBox(handle, PWideChar( 'Поздравляем! Все задания варианта ' + intToStr(rgVariants.ItemIndex + 1) + ' решены, Показать результаты?'), 'ОГЭ', MB_YESNO or MB_ICONINFORMATION) = mrYes then begin actResultClickExecute(self); end; end; procedure TfrmUTT.actAnswearClickExecute(Sender: TObject); var usrAnswear: double; TrueAnswear: boolean; begin assignedVariant(); if (answears = nil) or not (fTask in [1..UTT_TASK_COUNT]) or (fTask > length(answears)) or (trim(txtAnswer.Text) = '') then exit; usrAnswear := strToFloatEx(trim(txtAnswer.Text)); trueAnswear := abs(usrAnswear - self.answears[fTask - 1]) < e; if trueAnswear then begin if taskResultMask[fTask - 1] = false then begin taskResultMask[fTask - 1] := true; end else begin messageBox(self.Handle, 'Верно! Баллы за это задание уже были засчитаны.', 'ОГЭ', MB_OK or MB_ICONINFORMATION); end; if fTask = UTT_TASK_COUNT then begin if getNextFalseTask(fTask, taskResultMask, true) = ALL_TASK_COMPLETE then AllTaskCompleate() else actResultClickExecute(self) end else actNextClickExecute(Sender); end else begin actNextClickExecute(Sender); end; txtAnswer.Text := ''; end; procedure TfrmUTT.actResultClickExecute(Sender: TObject); var mr: TmodalResult; begin assignedVariant; mr := TfrmTestResult.showUTTResults; case mr of mrYes: mode := mNormal; mrNo: begin // Перейдем в режим прохода теста заново // Найдем первый не пройденый тест mode := mReTest; ftask := getNextFalseTask(fTask, taskResultMask, true); if fTask = ALL_TASK_COMPLETE then begin mode := mNormal; // All tasks complete exit end; loadTask(rgVariants.ItemIndex + 1, fTask); end; end; end; procedure TfrmUTT.actGoToPageExecute(Sender: TObject); var page: integer; begin assignedVariant; page := strToIntDef(InputBox('ОГЭ', 'Номер страницы', ''), 0); if page <= 0 then exit; if (page < 1) or (page > UTT_TASK_COUNT) then exit; fTask := page; loadTask(rgVariants.ItemIndex + 1, fTask); end; procedure TfrmUTT.actNextClickExecute(Sender: TObject); begin assignedVariant; if mode = mReTest then begin fTask := getNextFalseTask(fTask, taskResultMask); if fTask = ALL_TASK_COMPLETE then begin AllTaskCompleate(); exit; end; end else inc(fTask); if fTask > UTT_TASK_COUNT then fTask := UTT_TASK_COUNT; loadTask(rgVariants.ItemIndex + 1, fTask); end; procedure TfrmUTT.actPrevClickExecute(Sender: TObject); begin assignedVariant; if mode = mRetest then begin fTask := getPrevFalseTask(fTask, taskResultMask); if fTask = ALL_TASK_COMPLETE then begin AllTaskCompleate(); exit end; end else dec(fTask); if fTask < 1 then fTask := 1; loadTask(rgVariants.ItemIndex + 1, fTask); end; procedure TfrmUTT.UpdateButtons(value: boolean); var i: integer; begin for i := 0 to ActionList.ActionCount - 1 do begin TAction(ActionList.Actions[i]).Enabled := value end; end; procedure TfrmUTT.loadTask(aVariant, aTask: integer); var fileName, answearName: string; bmp: TBitmap; begin if (aVariant <= 0) or (aTask < 1) or (aTask > UTT_TASK_COUNT) then abort; img.Canvas.Brush.Color:=ClWhite; img.Canvas.FillRect(img.Canvas.ClipRect); ScrollBox.HorzScrollBar.Range := 0; ScrollBox.VertScrollBar.Range := 0; filename := format('%s/%d/%d.jpg', [UTT_DIR, aVariant, aTask]); bmp := LoadPage(fileName); if bmp = nil then begin rgVariants.ItemIndex := -1; UpdateButtons(false); exit; end; img.SetBounds(0, 0, bmp.Width, bmp.Height); img.Picture.Assign(bmp); bmp.Free; ScrollBox.HorzScrollBar.Range := img.Picture.Width; ScrollBox.VertScrollBar.Range := img.Picture.Height; if answears = nil then begin answearName := format('%s/answ.xml', [UTT_DIR]); answears := loadAnswears(dm.DataFile, answearName, aVariant); end; UpdateButtons(true); end; procedure TfrmUTT.clearUserResults; var i: integer; begin for i := 0 to UTT_TASK_COUNT - 1 do taskResultMask[i] := false; if (rgVariants.ItemIndex >= 0) then savepoint.Delete('MASK_' + intToStr(rgVariants.ItemIndex + 1)); end; procedure TfrmUTT.FormDestroy(Sender: TObject); begin if rgVariants.ItemIndex >= 0 then begin savePoint.addIntValue('VARIANT', rgVariants.ItemIndex + 1); savePoint.addIntValue('PAGE_' + intToStr(rgVariants.ItemIndex + 1), fTask); savePoint.Save; end; freeAndNil(savePoint) end; procedure TfrmUTT.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin with scrollBox.VertScrollBar do begin if (wheelDelta < 0) and (position < range) then position := position + increment else if (position > 0) then position := position - increment end; end; procedure TfrmUTT.FormResize(Sender: TObject); begin pnlTools.Left := (Panel3.Width div 2) - (pnlTools.Width div 2); end; procedure TfrmUTT.rgVariantsClick(Sender: TObject); var page: integer; begin if rgVariants.ItemIndex < 0 then exit; answears := nil; page := savePoint.asInteger('PAGE_' + intToStr(rgVariants.ItemIndex + 1)); if(page >= 1) and (page <= UTT_TASK_COUNT) then fTask := page else fTask := 1; taskResultMask := savePoint.asResultMask('MASK_' + intToStr(rgVariants.ItemIndex + 1)); if taskResultMask = nil then begin setLength(taskResultMask, UTT_TASK_COUNT); clearUserResults(); end; loadTask(rgVariants.ItemIndex + 1, fTask); end; procedure TfrmUTT.saveResults; begin if rgVariants.ItemIndex < 0 then exit; savePoint.addResultMask('MASK_' + intToStr(rgVariants.ItemIndex + 1), taskResultMask); savePoint.Save; end; procedure TfrmUTT.ShowUTT; var variant: integer; begin mode := mNormal; fUTTTest := doLoadUTT(); if (fUTTTest = nil) then begin messageBox(self.Handle, 'Не удалось загузить тесты', 'Ошибка', MB_OK or MB_ICONERROR); abort; end; UpdateButtons(false); savePoint := TSavePoint.Create(frmOGE.User.id, self.ClassName); savePoint.Load; variant := savePoint.asInteger('VARIANT'); if (variant >= 1) and (variant <= rgVariants.Items.Count) then rgVariants.ItemIndex := variant - 1; show; end; procedure TfrmUTT.send; var key, value: string; begin key := 'MASK'; value := format('%d;%s;%s;MASK_%d;%s', [frmOGE.User.id, 'n/a', savepoint.Window, rgVariants.ItemIndex + 1, savepoint.asString( 'MASK_' + intToStr(rgVariants.ItemIndex + 1))] ); frmOGE.Sync.send(key, value); end; procedure TfrmUTT.txtAnswerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_RETURN then actAnswearClickExecute(Sender); end; function TfrmUTT.doLoadUTT: TUTTModulesList; var info: string; s: TStringStream; i, id, cnt: integer; root, node: IXMLNode; begin result := nil; info := UTT_DIR + '/info.xml'; s := TStringStream.Create; try if not FindData(dm.DataFile, info, s) then abort; dm.xmlDoc.LoadFromStream(s); id := 1; root := dm.xmlDoc.ChildNodes.FindNode('UTT'); if root = nil then exit; cnt := root.ChildNodes.Count; setLength(result, cnt); for i := 0 to cnt - 1 do begin node := root.ChildNodes.Get(i); with node.ChildNodes do begin result[i].id := id; result[i].level := TUTTLevel(strToInt(FindNode('LEVEL').Text)); result[i].lable := FindNode('DISPLAY_LABEL').Text; result[i].task_from := strToInt(FindNode('TASK_FROM').Text); result[i].task_to := strToInt(FindNode('TASK_TO').Text); result[i].visible := boolean(strToInt(FindNode('VISIBLE').Text)); result[i].color := hexToColor(FindNode('COLOR').Text); inc(id); end; end; finally s.Free; end; end; end.
unit Import; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface uses _FAreas; function ImportArea( ParentArea: PFileArea ) : Boolean; function ImportEcho : Boolean; function ImportLinks: Boolean; { =================================================================== } implementation uses Objects, SysUtils, MyLib, Views, Dialogs, App, _RES, _CFG, _fopen, MsgBox, _LOG, _MapFile, _Working, VpUtils, MsgAPI, HiFiHelp, StdDlg; // WARNING: StdDlg.Pas line #701 should be: // FindFirst(Tmp, Directory shl 8 or AnyFile, S); const STREAM_BUFFER_SIZE = 4096; { --------------------------------------------------------- } { ImportTree } { --------------------------------------------------------- } procedure ImportTree( const Root: String; ParentArea: PFileArea ); var Info: record Accepted: Integer; Rejected: Integer; end; procedure ScanDir( Deep: String ); var R: SysUtils.TSearchRec; DosError : Integer; Area : PFileArea; LevelName: String; LevelPath: String; function TargetOk: Boolean; begin try if FileBase^.GetArea( LevelName ) <> nil then raise Exception.Create( LoadString(_SNameExists) ); if Filebase^.GetAreaByPath( LevelPath ) <> nil then raise Exception.Create( LoadString(_SDLPathExists) ); if not DirExists( LevelPath ) then raise Exception.Create( LoadString(_SDLPathNotExists) ); Result := True; Exit; except on E: Exception do begin Inc( Info.Rejected ); Log^.Write( ll_Warning, Format(LoadString(_SAreaRejected), [LevelName, E.Message]) ); ShowLog; end; end; Result := False; end; { TargetOk } begin DosError := SysUtils.FindFirst( AddBackSlash(AddBackSlash(Root) + Deep) + '*.*', faDirectory shl 8 or faAnyFile, R ); while DosError = 0 do begin if (R.Name <> '.') and (R.Name <> '..') then begin LevelName := AddBackSlash(Deep) + R.Name; LevelPath := AddBackSlash(Root) + LevelName; if TargetOk then begin New( Area, Init( LevelName ) ); if ParentArea <> nil then ParentArea^.Clone( Area ); Area^.DL_Path^.FreeAll; with Area^ do begin DL_Path^.Insert( AllocStr(LevelPath) ); ReplaceStr( FilesBbs, AtPath('files.bbs', LevelPath) ); end; Inc( Info.Accepted ); FileBase^.Insert( Area ); FileBase^.Modified := True; end; ScanDir( LevelName ); end; DosError := SysUtils.FindNext( R ); end; SysUtils.FindClose( R ); end; { ScanDir } begin Info.Accepted := 0; Info.Rejected := 0; OpenWorking( LoadString(_SImportingTree) ); try ScanDir( '' ); finally CloseWorking; end; MessageBox( Format(LoadString(_SImportSummary), [Info.Accepted, Info.Rejected]), nil, mfInformation + mfOkButton ); end; { ImportTree } { --------------------------------------------------------- } { Import_DirTree } { --------------------------------------------------------- } procedure Import_DirTree( ParentArea: PFileArea ); var D: PDialog; SaveDir: String; Root: String; begin SaveDir := GetCurrentDir; D := New( PChDirDialog, Init( cdNormal, 100 ) ); if Application^.ExecuteDialog( D, nil ) = cmOk then begin Root := GetCurrentDir; SetCurrentDir( SaveDir ); ImportTree( Root, ParentArea ); end else SetCurrentDir( SaveDir ); end; { Import_DirTree } { --------------------------------------------------------- } { Import_BlstBbs } { --------------------------------------------------------- } procedure Import_BlstBbs; var S: String; Key : String; Val : String; Map : TMappedFile; Area: PFileArea; Info: record NAreas, NEchoes: Integer; end; procedure MakeNewArea( const AreaTag: String ); var Q: Integer; T: String; begin Q := 0; T := AreaTag; Area := FileBase^.GetArea( T ); while Area <> nil do begin Inc(Q); T := Format( '%s (%d)', [AreaTag, Q] ); Area := FileBase^.GetArea( T ); end; Area := New( PFileArea, Init(T) ); FileBase^.Insert( Area ); Inc( Info.NAreas ); FileBase^.Modified := True; end; { MakeNewArea } procedure AttachFileEcho( const EchoTag: String ); var Echo: PFileEcho; begin if FileBase^.GetEcho( EchoTag ) <> nil then Exit; Echo := New( PFileEcho, Init(EchoTag) ); FileBase^.EchoList^.Insert( Echo ); Echo^.Area := Area; Inc( Info.NEchoes ); FileBase^.Modified := True; end; { AttachFileEcho } begin S := '*.dir'; if not ExecFileOpenDlg(LoadString(_SImportBlstCaption), S, S) then Exit; if not FileExists( S ) then begin ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; OpenWorking( Format(LoadString(_SImportingBlst), [S]) ); Log^.Write( ll_Service, Format(LoadString(_SImportingBlst), [S]) ); try Map.Init( S ); OpenProgress( Map.GetSize ); FillChar( Info, SizeOf(Info), #0 ); Area := nil; while Map.GetLine( S ) do begin UpdateProgress( Map.GetPos ); StripComment( S ); if S = '' then Continue; SplitPair( S, Key, Val ); if JustSameText( Key, 'Name' ) then MakeNewArea( Val ) else if Area = nil then Log^.Write( ll_Warning, LoadString(_SLogAreaNameMissing) ) else begin if JustSameText( Key, 'SearchNew' ) then Area^.fScan := TSwitch( StrToBool(Val) ) else if JustSameText( Key, 'SortFiles' ) then Area^.fSorted := TSwitch( StrToBool(Val) ) else if JustSameText( Key, 'EraseFiles' ) then Continue else if JustSameText( Key, 'TicArea' ) then AttachFileEcho( Val ) else if JustSameText( Key, 'FilesID' ) then ReplaceStr( Area^.FilesBbs, Val ) else if JustSameText( Key, 'Exclude' ) then Continue else if JustSameText( Key, 'Level' ) then Continue else if JustSameText( Key, 'Path' ) then begin Area^.DL_Path^.AtInsert( 0, AllocStr(Val) ); if (Area^.FilesBbs = nil) or (Area^.FilesBbs^ = '') then ReplaceStr( Area^.FilesBbs, AtPath( FILES_BBS, Val ) ); end else if JustSameText( Key, 'Add' ) then Area^.DL_Path^.Insert( AllocStr(ExtractWord( 1, Val, [','] ) )) else Log^.Write( ll_Warning, Format(LoadString(_SBadLineIgnored), [S] )); end; end finally Map.Done; CloseWorking; end; MessageBox( Format(LoadString(_SBlstBbsSummary), [Info.NAreas, Info.NEchoes]), nil, mfInformation + mfOkButton ); end; { Import_BlstBbs } { --------------------------------------------------------- } { ImportArea } { --------------------------------------------------------- } function ImportArea( ParentArea: PFileArea ) : Boolean; const bDirTree = 0; bBlstBbs = 1; var D: PDialog; Data: Longint; begin Result := False; D := PDialog( Res^.Get('IMP_AREA') ); D^.HelpCtx := hcImportAreas; Data := bDirTree; if Application^.ExecuteDialog( D, @Data ) = cmOk then begin case Data of bDirTree : Import_DirTree( ParentArea ); bBLstBbs : Import_BlstBbs; else MessageBox( 'Under construction ;-)', nil, mfInformation + mfOkButton ); end; Result := True; end; if Log^.HasWarnings then ShowLog; end; { ImportArea } { --------------------------------------------------------- } { Import_HiFiles } { --------------------------------------------------------- } procedure Import_HiFiles; var S: String; A: TAddress; j: Integer; Key : String; Value: String; Map : TMappedFile; Echo : PFileEcho; Area : PFileArea; EchoTag : String; EchoDir : String; Info : record Created: Integer; Reused : Integer; end; begin S := '*.Ctl'; if not ExecFileOpenDlg(LoadString(_SImportHiFiCaption), S, S) then Exit; if not FileExists( S ) then begin ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; OpenWorking( Format(LoadString(_SImportingHiFi), [S]) ); Log^.Write( ll_Service, Format(LoadString(_SImportingHiFi), [S]) ); try Map.Init( S ); OpenProgress( Map.GetSize ); Echo := nil; FillChar( Info, SizeOf(Info), 0 ); while Map.GetLine( S ) do begin UpdateProgress( Map.GetPos ); StripComment( S ); if S = '' then Continue; SplitPair( S, Key, Value ); if JustSameText( Key, 'Area' ) then begin FileBase^.Modified := True; EchoTag := ExtractWord( 1, Value, BLANK ); EchoDir := ExtractWord( 2, Value, BLANK ); Echo := FileBase^.GetEcho( EchoTag ); if Echo <> nil then begin Log^.Write( ll_Warning, Format(LoadString(_SLogJustAddLinks), [EchoTag] )); Inc( Info.Reused ); end else begin Log^.Write( ll_Protocol, Format(LoadString(_SLogEchoCreated), [EchoTag] )); Inc( Info.Created ); Echo := New( PFileEcho, Init( EchoTag ) ); if EchoDir = '' then Log^.Write( ll_Expand, LoadString(_SLogPassthrough) ) else begin Log^.Write( ll_Expand, Format(LoadString(_SLogParking), [EchoDir])); Area := FileBase^.GetAreaByPath( EchoDir ); if Area = nil then begin Area := New( PFileArea, Init( 'FileEcho: ' + EchoTag ) ); Log^.Write( ll_Protocol, Format(LoadString(_SLogNewHostCreated), [Area^.Name^])); Area^.DL_Path^.Insert( AllocStr( EchoDir ) ); ReplaceStr( Area^.FilesBbs, AtPath( FILES_BBS, EchoDir ) ); ReplaceStr( Area^.Group, FILE_ECHO_GROUP ); FileBase^.Insert( Area ); if not DirExists( EchoDir ) and not CreateDirTree( EchoDir ) then Log^.Write( ll_Warning, Format(LoadString(_SMkDirFailed), [EchoDir] )); end; Echo^.Area := Area; end; FileBase^.EchoList^.Insert( Echo ); end; end else if Echo = nil then begin Log^.Write( ll_Warning, LoadString(_SLogAreaNameMissing) ); Continue; end else if JustSameText( Key, 'ReceiveFrom' ) then begin for j := 1 to WordCount( Value, BLANK ) do begin if SafeAddr( ExtractWord( j, Value, BLANK ), A ) then Echo^.Uplinks^.Insert( NewAddr(A) ) else Log^.Write( ll_Warning, Format(LoadString(_SBadULAddr), [Value]) ); end; end else if JustSameText( Key, 'SendTo' ) then begin for j := 1 to WordCount( Key, BLANK ) do begin if SafeAddr( ExtractWord( j, Value, BLANK ), A ) then Echo^.Downlinks^.Insert( NewAddr(A) ) else Log^.Write( ll_Warning, Format(LoadString(_SBadDLAddr), [Value]) ); end; end else if JustSameText( Key, 'Hook' ) then begin Echo^.Hooks^.Add( Value ); end else begin Log^.Write( ll_Warning, Format(LoadString(_SBadLineIgnored), [S] )) end; end; finally Map.Done; CloseWorking; end; MessageBox( Format(LoadString(_SImportEchoSummary), [Info.Created, Info.Reused]), nil, mfInformation + mfOkButton ); end; { Import_HiFiles } { --------------------------------------------------------- } { Import_AllFixBin } { --------------------------------------------------------- } procedure Import_AllFixBin; const // Attribute bits for the fileecho records (attrib) _announce = $0001; _replace = $0002; _convertall = $0004; _passthru = $0008; _dupecheck = $0010; _fileidxxx = $0020; _visible = $0040; _tinysb = $0080; _Security = $0100; _NoTouch = $0200; _SendOrig = $0400; _AddGifSpecs= $0800; _VirusScan = $1000; _UpdateMagic= $2000; _UseFDB = $4000; _TouchAV = $8000; // Attribute bits for the fileecho records (attrib2) _Unique = $0001; _AutoAdded = $0002; _ConvertInc = $0004; _CompUnknown= $0008; // Attribute bits for the systems in the system list _SendTo = $0001; _ReceiveFrom = $0002; _PreRelease = $0004; _Inactive = $0008; _NoneStat = $0010; _HoldStat = $0020; _CrashStat = $0040; _Mandatory = $0080; const TagLength = 40; // Maximum length of a fileecho tag ExportSize = 255; // Size of the systems list type FileEchoTagSTr = String[TagLength]; NetAddress = Packed Record Zone, Net, Node, Point : smallword; end; ExportEntry = Packed Record Address: NetAddress; Status : byte; end; ExportArray = packed Array[1..ExportSize] of ExportEntry; { Systems list } // FAREAS.FIX FileMGRrec = packed Record Name : FileEchoTagStr; Message : String[12]; Comment : String[55]; Group : Byte; Attrib : smallword; KeepLate : Byte; Convert : Byte; UplinkNum : Byte; DestDir : String[60]; TotalFiles, TotalKb : smallword; Byear, Bmonth : Byte; _FBoard : smallWord; UseAka : Byte; LongDesc : Byte; Banner : String[8]; UnitCost : packed array [1..6] of Byte; // Real UnitSize : byte; DivCost : byte; AddPercentage: packed array [1..6] of Byte; // Real IncludeRcost : Byte; Attrib2 : smallword; PurgeSize, PurgeNum, PurgeAge : smallword; BBSmask : smallword; Extra : packed array[1..19] of byte; Export : ExportArray; end; // FAREAS.IDX FileMGRidx = Record Name : FileEchoTagStr; Group : Byte; Offset : smallword; end; var S: String; A: TAddress; P: PAddress; n: Integer; j: Integer; DataStream : TBufStream; IndexStream: TBufStream; DataRec : FileMgrRec; IndexRec : FileMgrIdx; Echo : PFileEcho; Area : PFileArea; Info : record Created: Integer; Reused : Integer; end; begin S := '*.Fix'; if not ExecFileOpenDlg(LoadString(_SImportAllFixCaption), S, S) then Exit; DataStream.Init( S, stOpenRead, STREAM_BUFFER_SIZE ); if DataStream.Status <> stOk then begin DataStream.Done; ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; S := ChangeFileExt( S, '.Idx' ); IndexStream.Init( S, stOpenRead, STREAM_BUFFER_SIZE ); if IndexStream.Status <> stOk then begin IndexStream.Done; DataStream.Done; ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; OpenWorking( Format(LoadString(_SImportingAllfix), [S]) ); OpenProgress( IndexStream.GetSize ); Log^.Write( ll_Service, Format(LoadString(_SImportingAllfix), [S]) ); FillChar( Info, SizeOf(Info), 0 ); try FileBase^.Modified := True; IndexStream.Read( IndexRec, SizeOf(FileMgrIdx) ); while IndexStream.Status = stOk do begin UpdateProgress( IndexStream.GetPos ); DataStream.Seek( IndexRec.Offset * SizeOf(FileMgrRec) ); DataStream.Read( DataRec, SizeOf(FileMgrRec) ); Echo := FileBase^.GetEcho( DataRec.Name ); if Echo <> nil then begin Log^.Write( ll_Warning, Format(LoadString(_SLogJustAddLinks), [DataRec.Name] )); Inc( Info.Reused ); end else begin Log^.Write( ll_Protocol, Format(LoadString(_SLogEchoCreated), [DataRec.Name] )); Inc( Info.Created ); Echo := New( PFileEcho, Init( DataRec.Name ) ); if TestBit( DataRec.Attrib, _passthru ) then begin Echo^.Area := nil; Log^.Write( ll_Expand, LoadString(_SLogPassthrough) ); end else begin Log^.Write( ll_Expand, Format(LoadString(_SLogParking), [DataRec.DestDir])); Area := FileBase^.GetAreaByPath( DataRec.Name ); if Area = nil then begin Area := New( PFileArea, Init( 'FileEcho: ' + DataRec.Name ) ); Log^.Write( ll_Protocol, Format(LoadString(_SLogNewHostCreated), [Area^.Name^])); Area^.DL_Path^.Insert( AllocStr( DataRec.DestDir ) ); ReplaceStr( Area^.FilesBbs, AtPath( FILES_BBS, DataRec.DestDir ) ); ReplaceStr( Area^.Group, FILE_ECHO_GROUP ); FileBase^.Insert( Area ); if not DirExists( DataRec.DestDir ) and not CreateDirTree( DataRec.DestDir ) then Log^.Write( ll_Warning, Format(LoadString(_SMkDirFailed), [DataRec.DestDir] )); end; Echo^.Area := Area; end; FileBase^.EchoList^.Insert( Echo ); end; for n := 1 to ExportSize do begin with DataRec.Export[n], Address do begin if Zone = 0 then Break; A.Zone := Zone; A.Net := Net; A.Node := Node; A.Point := Point; if TestBit( Status, _SendTo ) and not Echo^.Downlinks^.Search( @A, j ) then Echo^.Downlinks^.AtInsert( j, NewAddr(A) ); if TestBit( Status, _ReceiveFrom ) and not Echo^.Uplinks^.Search( @A, j ) then Echo^.Uplinks^.AtInsert( j, NewAddr(A) ); end; end; IndexStream.Read( IndexRec, SizeOf(FileMgrIdx) ); end; finally IndexStream.Done; DataStream.Done; CloseWorking; end; MessageBox( Format(LoadString(_SImportEchoSummary), [Info.Created, Info.Reused]), nil, mfInformation + mfOkButton ); end; { Import_Allfix } { --------------------------------------------------------- } { Import_DMTic } { --------------------------------------------------------- } procedure Import_DMTic; var S: String; A: TAddress; N: Integer; j: Integer; Map : TMappedFile; Echo : PFileEcho; Area : PFileArea; Key : String; Value: String; EchoTag : String; EchoDir : String; Access : (_ReadOnly, _WriteOnly, _ReadWrite); Info : record Created: Integer; Reused : Integer; end; begin S := '*.Ini'; if not ExecFileOpenDlg(LoadString(_SImportDMCaption), S, S) then Exit; if not FileExists( S ) then begin ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; OpenWorking( Format(LoadString(_SImportingDMT), [S]) ); Log^.Write( ll_Service, Format(LoadString(_SImportingDMT), [S]) ); try Map.Init( S ); OpenProgress( Map.GetSize ); Echo := nil; FillChar( Info, SizeOf(Info), 0 ); while Map.GetLine( S ) do begin UpdateProgress( Map.GetPos ); StripComment( S ); if S = '' then Continue; SplitPair( S, Key, Value ); if JustSameText( Key, 'Area' ) then begin N := WordCount( Value, BLANK ); if (N <> 6) and (N <> 7) then begin Log^.Write( ll_Warning, LoadString(_SBadLineIgnored) ); Echo := nil; Continue; end; FileBase^.Modified := True; EchoTag := ExtractWord( 1, Value, BLANK ); EchoDir := ExtractWord( 2, Value, BLANK ); S := JustUpperCase(ExtractWord( 7, Value, BLANK )); // Flags: // P - Passthrough // M - "Magic" disabled // R - "Replaces" disabled // U - Mandatory // D - Dont extract file_id.diz Echo := FileBase^.GetEcho( EchoTag ); if Echo <> nil then begin Log^.Write( ll_Warning, Format(LoadString(_SLogJustAddLinks), [EchoTag] )); Inc( Info.Reused ); end else begin Log^.Write( ll_Protocol, Format(LoadString(_SLogEchoCreated), [EchoTag] )); Inc( Info.Created ); Echo := New( PFileEcho, Init( EchoTag ) ); if Pos('P', S) <> 0 then Log^.Write( ll_Expand, LoadString(_SLogPassthrough) ) else begin Log^.Write( ll_Expand, Format(LoadString(_SLogParking), [EchoDir])); Area := FileBase^.GetAreaByPath( EchoDir ); if Area = nil then begin Area := New( PFileArea, Init( 'FileEcho: ' + EchoTag ) ); Log^.Write( ll_Protocol, Format(LoadString(_SLogNewHostCreated), [Area^.Name^])); Area^.DL_Path^.Insert( AllocStr( EchoDir ) ); ReplaceStr( Area^.FilesBbs, AtPath( FILES_BBS, EchoDir ) ); ReplaceStr( Area^.Group, FILE_ECHO_GROUP ); FileBase^.Insert( Area ); if not DirExists( EchoDir ) and not CreateDirTree( EchoDir ) then Log^.Write( ll_Warning, Format(LoadString(_SMkDirFailed), [EchoDir] )); end; Echo^.Area := Area; end; if Pos('R', S) <> 0 then SetBit( Echo^.Paranoia, bSkipRepl, True ); FileBase^.EchoList^.Insert( Echo ); end; end else if (Echo = nil) or JustSameText(Key, 'Desc') then Continue else if JustSameText( Key, 'Links' ) then begin for j := 1 to WordCount( Value, BLANK ) do begin S := ExtractWord( j, Value, BLANK ); case S[1] of '!': begin System.Delete(S, 1, 1); Access := _ReadOnly; end; '~': begin System.Delete(S, 1, 1); Access := _WriteOnly; end; else Access := _ReadWrite; end; if not SafeAddr(S, A) then begin Log^.Write( ll_Warning, Format(LoadString(_SBadAddr), [S] )); Continue; end; if Access <> _ReadOnly then Echo^.UpLinks^.Insert( NewAddr(A) ); if Access <> _WriteOnly then Echo^.DownLinks^.Insert( NewAddr(A) ); end; end else Log^.Write( ll_Warning, Format(LoadString(_SBadLineIgnored), [S] )) end; finally Map.Done; CloseWorking; end; MessageBox( Format(LoadString(_SImportEchoSummary), [Info.Created, Info.Reused]), nil, mfInformation + mfOkButton ); end; { Import_DMTic} { --------------------------------------------------------- } { ImportEcho } { --------------------------------------------------------- } function ImportEcho: Boolean; const bHiFiles = 0; bAllFixBin = 1; bDMTic = 2; bTFix = 3; bFilin = 4; var D: PDialog; Data: Longint; begin Result := False; D := PDialog( Res^.Get('IMP_ECHO') ); D^.HelpCtx := hcImportEchoes; Data := bHiFiles; if Application^.ExecuteDialog( D, @Data ) = cmOk then begin case Data of bHiFiles : Import_HiFiles; bAllFixBin : Import_AllFixBin; bDMTic : Import_DMTic; else MessageBox( 'Under construction ;-)', nil, mfInformation + mfOkButton ); end; Result := True; end; if Log^.HasWarnings then ShowLog; end; { ImportEcho } { --------------------------------------------------------- } { Import_AllfixLinks } { --------------------------------------------------------- } procedure Import_AllfixLinks; const _stat_none = 0; _stat_hold = 1; _stat_crash = 2; _stat_direct = 3; _stat_hold_direct = 4; _stat_crash_direct = 5; type NetAddress = Packed Record Zone, Net, Node, Point : smallword; end; // Array used to store groups GroupArray = Array[0..31] of byte; // NODEFILE.FIX NodeMGRrec = Packed Record Aka : NetAddress; Sysop : String[35]; Password : String[20]; Groups : GroupArray; Reserved : Byte; Inactive : Boolean; RepNewEchos : Boolean; CopyOther : Boolean; SendTicWFreq : Boolean; FileStat : Byte; AreaMgrStat : Byte; TicFile : Byte; UseAka : Byte; Message : Boolean; Notify : Boolean; Archiver : Byte; Forward : Boolean; AutoAdd : Boolean; MgrPassword : String[20]; Remote : Boolean; PackMode : Byte; ViaNode : NetAddress; Billing : Byte; BillGroups : GroupArray; Credit, WarnLevel, StopLevel : array [1..6] of Byte; // Real SendBill : byte; SendDay : byte; AddPercentage : array [1..6] of Byte; // Real BillSent : smallword; SystemPath : String[60]; MembershipFee : array [1..6] of Byte; // Real Extra2 : array[1..118] of byte; end; // NODEFILE.IDX NodeMGRidx = Record Aka : NetAddress; Offset: smallword; end; var IndexStream: TBufStream; DataStream : TBufStream; IndexRec: NodeMgrIdx; DataRec : NodeMgrRec; S: String; A: TAddress; Link : PEchoLink; Info : record Accepted: Integer; Rejected: Integer; end; begin S := '*.fix'; if not ExecFileOpenDlg(LoadString(_SImpLnkAfixCaption), S, S) then Exit; DataStream.Init( S, stOpenRead, STREAM_BUFFER_SIZE ); if DataStream.Status <> stOk then begin DataStream.Done; ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; S := ChangeFileExt( S, '.Idx' ); IndexStream.Init( S, stOpenRead, STREAM_BUFFER_SIZE ); if IndexStream.Status <> stOk then begin IndexStream.Done; DataStream.Done; ShowError( Format(LoadString(_SFileNotFound), [S]) ); Exit; end; OpenWorking( LoadString(_SImportingAfixLnk) ); OpenProgress( IndexStream.GetSize ); Log^.Write( ll_Service, Format(LoadString(_SImportingAllfix), [S]) ); FillChar( Info, SizeOf(Info), 0 ); try IndexStream.Read( IndexRec, SizeOf(NodeMGRidx) ); while IndexStream.Status = stOk do begin UpdateProgress( IndexStream.GetPos ); DataStream.Seek( IndexRec.Offset * SizeOf(NodeMgrRec) ); DataStream.Read( DataRec, SizeOf(NodeMgrRec) ); with DataRec.Aka do begin A.Zone := Zone; A.Net := Net; A.Node := Node; A.Point := Point; end; Link := CFG^.Links^.Find( A ); if Link = nil then begin Inc( Info.Accepted ); Log^.Write( ll_Protocol, Format( LoadString(_SLogAddLink), [AddrToStr(A), DataRec.Sysop] )); New( Link, Init(A) ); ReplaceStr( Link^.Password, DataRec.Password ); if DataRec.RepNewEchos or DataRec.Notify then Include( Link^.Opt, elo_Notify ); if DataRec.AutoAdd then Include( Link^.Opt, elo_AutoCreate ); case DataRec.FileStat of _stat_hold : Link^.Flavor := fl_Hold; _stat_crash : Link^.Flavor := fl_Crash; _stat_direct : Link^.Flavor := fl_Dir; _stat_hold_direct : Link^.Flavor := fl_Hold; _stat_crash_direct : Link^.Flavor := fl_Dir; else Link^.Flavor := fl_Hold; end; CFG^.Links^.Insert( Link ); CFG^.Modified := True; end else Inc( Info.Rejected ); IndexStream.Read( IndexRec, SizeOf(NodeMGRidx) ); end; finally IndexStream.Done; DataStream.Done; CloseWorking; end; MessageBox( Format(LoadString(_SImportLinkSummary), [Info.Accepted, Info.Rejected]), nil, mfInformation + mfOkButton ); end; { Import_AllfixLinks } { --------------------------------------------------------- } { ImportLinks } { --------------------------------------------------------- } function ImportLinks: Boolean; const bAllfix = 0; var D: PDialog; Data: Longint; begin Result := False; D := PDialog( Res^.Get('IMP_LINKS') ); D^.HelpCtx := hcImportLinks; Data := bAllFix; if Application^.ExecuteDialog( D, @Data ) = cmOk then begin case Data of bAllfix: Import_AllfixLinks; else MessageBox( 'Under construction ;-)', nil, mfInformation + mfOkButton ); end; Result := True; end; if Log^.HasWarnings then ShowLog; end; { ImportLinks } end.
unit Aurelius.Schema.Utils; {$I Aurelius.Inc} interface uses Generics.Collections, Aurelius.Sql.Metadata; type TSchemaUtils = class public class function GetReferencingForeignKeys(Database: TDatabaseMetadata; ReferencedTable: TTableMetadata): TArray<TForeignKeyMetadata>; class function FindTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; class function GetTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; class function FindSequence(Database: TDatabaseMetadata; const SequenceName: string): TSequenceMetadata; class function FindColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; class function GetColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; class function FindForeignKey(Table: TTableMetadata; const ForeignKeyName: string): TForeignKeyMetadata; class function FindUniqueKey(Table: TTableMetadata; const UniqueKeyName: string): TUniqueKeyMetadata; end; implementation uses SysUtils, Aurelius.Schema.Exceptions; { TSchemaUtils } class function TSchemaUtils.FindColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; var Column: TColumnMetadata; begin for Column in Table.Columns do if SameText(Column.Name, ColumnName) then Exit(Column); Result := nil; end; class function TSchemaUtils.FindForeignKey(Table: TTableMetadata; const ForeignKeyName: string): TForeignKeyMetadata; var ForeignKey: TForeignKeyMetadata; begin for ForeignKey in Table.ForeignKeys do if SameText(ForeignKey.Name, ForeignKeyName) then Exit(ForeignKey); Result := nil; end; class function TSchemaUtils.FindSequence(Database: TDatabaseMetadata; const SequenceName: string): TSequenceMetadata; var Sequence: TSequenceMetadata; begin for Sequence in Database.Sequences do if SameText(Sequence.Name, SequenceName) then Exit(Sequence); Result := nil; end; class function TSchemaUtils.FindTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; var Table: TTableMetadata; begin for Table in Database.Tables do if SameText(Table.Name, TableName) and SameText(Table.Schema, TableSchema) then Exit(Table); Result := nil; end; class function TSchemaUtils.FindUniqueKey(Table: TTableMetadata; const UniqueKeyName: string): TUniqueKeyMetadata; var UniqueKey: TUniqueKeyMetadata; begin for UniqueKey in Table.UniqueKeys do if SameText(UniqueKey.Name, UniqueKeyName) then Exit(UniqueKey); Result := nil; end; class function TSchemaUtils.GetColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; begin Result := FindColumn(Table, ColumnName); if Result = nil then raise EColumnMetadataNotFound.Create(ColumnName, Table.Name); end; class function TSchemaUtils.GetReferencingForeignKeys(Database: TDatabaseMetadata; ReferencedTable: TTableMetadata): TArray<TForeignKeyMetadata>; var Table: TTableMetadata; ForeignKey: TForeignKeyMetadata; ForeignKeys: TList<TForeignKeyMetadata>; {$IFNDEF DELPHIXE_LVL} I: integer; {$ENDIF} begin ForeignKeys := TList<TForeignKeyMetadata>.Create; try for Table in Database.Tables do for ForeignKey in Table.ForeignKeys do begin if SameText(ForeignKey.ToTable.Name, ReferencedTable.Name) and SameText(ForeignKey.ToTable.Schema, ReferencedTable.Schema) then ForeignKeys.Add(ForeignKey); end; {$IFDEF DELPHIXE_LVL} Result := ForeignKeys.ToArray; {$ELSE} SetLength(Result, ForeignKeys.Count); for I := 0 to ForeignKeys.Count - 1 do Result[I] := ForeignKeys[I]; {$ENDIF} finally ForeignKeys.Free; end; end; class function TSchemaUtils.GetTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; begin Result := FindTable(Database, TableName, TableSchema); if Result = nil then raise ETableMetadataNotFound.Create(TableName, TableSchema); end; end.
unit FileCache; interface uses classes ,System.Types ,ExtCtrls ; type TFileCacheObject = class(TObject) Filename :string; FileData :TByteDynArray; Cached :TDateTime; //when the item was added to the cache LastAccessed :TDateTime; //when the item was last accessed end; TFileCache = class(TList) private FExpiryTimer :TTimer; FExpiryTimeOut :integer; //expiry timeout in minutes since last access procedure DecDynArrayRefCount(const ADynArray); function GetDynArrayRefCnt(const ADynArray): Longword; procedure IncDynArrayRefCount(const ADynArray); procedure TimerExpired(Sender: TObject); procedure RemoveCachedItem(Index: integer); procedure SetExpiryTimeout(Value :integer); public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure EmptyCache; function IndexOf(const FileName :string) :integer; procedure AddFile(const Filename :string; FileData :TByteDynArray); function GetFileData(const Index :integer) :TByteDynArray; property ExpiryTimeOut :integer read FExpiryTimeOut write SetExpiryTimeOut; end; implementation uses System.SysUtils, System.DateUtils; { TFileCache } procedure TFileCache.IncDynArrayRefCount(const ADynArray); begin PLongword(Longword(ADynArray) - 8)^ := PLongword(Longword(ADynArray) - 8)^ + 1; end; procedure TFileCache.AfterConstruction; begin inherited; FExpiryTimer:= TTimer.Create(nil); FExpiryTimer.OnTimer := TimerExpired; SetExpiryTimeout(15); end; procedure TFileCache.BeforeDestruction; begin FExpiryTimer.Free; inherited; end; procedure TFileCache.TimerExpired(Sender :TObject); //traverse all objects and release ones that have expired var I: Integer; TimeOfScan :TDateTime; anItem :TFileCacheObject; begin TimeOfScan := Now; for I := Count - 1 downto 0 do begin anItem := TFileCacheObject(Self[I]); if (MinutesBetween(anItem.LastAccessed,TimeOfScan) > 0) then RemoveCachedItem(I); end; end; procedure TFileCache.RemoveCachedItem(Index :integer); var anItem :TFileCacheObject; begin anItem := TFileCacheObject(Self[Index]); DecDynArrayRefCount(anItem.FileData); //enable release of file data Delete(Index); //remove the item from the list anItem.Free; //free the item end; procedure TFileCache.SetExpiryTimeout(Value: integer); begin FExpiryTimer.Enabled := False; FExpiryTimer.Interval := Value * SecsPerMin * MSecsPerSec; FExpiryTimer.Enabled := True; end; procedure TFileCache.DecDynArrayRefCount(const ADynArray); begin PLongword(Longword(ADynArray) - 8)^ := PLongword(Longword(ADynArray) - 8)^ - 1; end; function TFileCache.GetDynArrayRefCnt(const ADynArray): Longword; begin if Pointer(ADynArray) = nil then Result := 1 {or 0, depending what you need} else Result := PLongword(Longword(ADynArray) - 8)^; end; procedure TFileCache.AddFile(const Filename: string; FileData: TByteDynArray); var anItem :TFileCacheObject; begin anItem := TFileCacheObject.Create; anItem.Cached := Now; anItem.Filename := FileName; anItem.FileData := FileData; IncDynArrayRefCount(FileData); Add(anItem); end; procedure TFileCache.EmptyCache; var I :integer; begin for I := Count - 1 downto 0 do RemoveCachedItem(I); end; function TFileCache.GetFileData(const Index: integer): TByteDynArray; var anItem :TFileCacheObject; begin anItem := TFileCacheObject(Self[Index]); anItem.LastAccessed := Now; Result := anItem.FileData; end; function TFileCache.IndexOf(const FileName: string): integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do begin if (TFileCacheObject(Self[I]).Filename = FileName) then begin Result := I; break; end; end; end; end.
Unit AdvSynchronizationRegistries; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses ThreadSupport, MathSupport, StringSupport, DateSupport, AdvExclusiveCriticalSections, AdvObjects, AdvObjectLists, AdvTimeControllers, AdvIntegerMatches; Type TAdvSynchronizationLockEventStatus = (AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite, AdvSynchronizationLockEventStatusLockedForRead, AdvSynchronizationLockEventStatusLockedForWrite); TAdvSynchronizationLockEvent = Class(TAdvObject) Private FEventStatus : TAdvSynchronizationLockEventStatus; FEventTimestamp : TDateTime; FEventSequence : Int64; Public Function Link : TAdvSynchronizationLockEvent; Procedure Assign(oObject : TAdvObject); Override; Function IsWaiting : Boolean; Procedure EventStatusWaitingForRead; Procedure EventStatusWaitingForWrite; Procedure EventStatusLockedForRead; Procedure EventStatusLockedForWrite; Property EventSequence : Int64 Read FEventSequence Write FEventSequence; Property EventTimestamp : TDateTime Read FEventTimestamp Write FEventTimestamp; Property EventStatus : TAdvSynchronizationLockEventStatus Read FEventStatus Write FEventStatus; End; TAdvSynchronizationLockEventList = Class(TAdvObjectList) Private Function GetLockEventByIndex(Const iIndex : Integer) : TAdvSynchronizationLockEvent; Protected Function ItemClass : TAdvObjectClass; Override; Function CompareByEventSequence(pA, pB : Pointer) : Integer; Public Procedure SortedByEventSequence; Property LockEventByIndex[Const iIndex : Integer] : TAdvSynchronizationLockEvent Read GetLockEventByIndex; Default; End; TAdvSynchronizationThreadLock = Class(TAdvObject) Private FThreadIdentifier : TThreadID; FLockIdentifier : Integer; FLockEventList : TAdvSynchronizationLockEventList; Public Constructor Create; Override; Destructor Destroy; Override; Procedure Assign(oObject : TAdvObject); Override; Procedure PushLockEvent(oLockEvent : TAdvSynchronizationLockEvent); Function PeekLockEvent : TAdvSynchronizationLockEvent; Function PopLockEvent : TAdvSynchronizationLockEvent; Property ThreadIdentifier : TThreadID Read FThreadIdentifier Write FThreadIdentifier; Property LockIdentifier : Integer Read FLockIdentifier Write FLockIdentifier; Property LockEventList : TAdvSynchronizationLockEventList Read FLockEventList; End; TAdvSynchronizationThreadLockList = Class(TAdvObjectList) Private Function GetThreadLockByIndex(Const iIndex : Integer) : TAdvSynchronizationThreadLock; Protected Function ItemClass : TAdvObjectClass; Override; Function CompareByThreadIdentifierAndLockIdentifier(pA, pB : Pointer) : Integer; Public Procedure SortedByThreadIdentifierAndLockIdentifier; Function IndexByThreadIdentifierAndLockIdentifier(Const iThreadIdentifier : TThreadID; Const iLockIdentifier : Integer) : Integer; Property ThreadLockByIndex[Const iIndex : Integer] : TAdvSynchronizationThreadLock Read GetThreadLockByIndex; Default; End; TAdvSynchronizationRegistry = Class(TAdvObject) Private FThreadLockListCriticalSection : TAdvExclusiveCriticalSection; FTimeController : TAdvTimeController; FThreadLockList : TAdvSynchronizationThreadLockList; FThreadIdentifierNextEventSequenceMatch : TAdvIntegerMatch; Function GetTimeController : TAdvTimeController; Procedure SetTimeController(Const Value : TAdvTimeController); Protected Procedure RegisterWaitingForLock(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Procedure RegisterNoLongerWaitingForLock(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Procedure RegisterLocked(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Procedure RegisterUnlocked(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Public Constructor Create; Override; Destructor Destroy; Override; Function Link : TAdvSynchronizationRegistry; Function Active : Boolean; Procedure Query(oThreadLockList : TAdvSynchronizationThreadLockList); Procedure RegisterWaitingForRead(Const iLockIdentifier : Integer); Procedure RegisterWaitingForWrite(Const iLockIdentifier : Integer); Procedure RegisterNoLongerWaitingForRead(Const iLockIdentifier : Integer); Procedure RegisterNoLongerWaitingForWrite(Const iLockIdentifier : Integer); Procedure RegisterLockedForRead(Const iLockIdentifier : Integer); Procedure RegisterLockedForWrite(Const iLockIdentifier : Integer); Procedure RegisterUnlockedForRead(Const iLockIdentifier : Integer); Procedure RegisterUnlockedForWrite(Const iLockIdentifier : Integer); Property TimeController : TAdvTimeController Read GetTimeController Write SetTimeController; End; Procedure PrepareSynchronizationRegistry; Procedure TerminateSynchronizationRegistry; Function HasSynchronizationRegistry : Boolean; Function SynchronizationRegistry : TAdvSynchronizationRegistry; Implementation Uses AdvExceptions, AdvParameters; Var gUseSynchronizationRegistry : Boolean; gSynchronizationRegistry : TAdvSynchronizationRegistry; Procedure PrepareSynchronizationRegistry; Var oParameters : TAdvParameters; Begin Assert(Not Assigned(gSynchronizationRegistry), 'gSynchronizationRegistry is already assigned.'); gSynchronizationRegistry := TAdvSynchronizationRegistry.Create; oParameters := TAdvParameters.Create; Try gUseSynchronizationRegistry := Not oParameters.Switched('NoDeadlockDetection'); Finally oParameters.Free; End; End; Procedure TerminateSynchronizationRegistry; Begin Assert(Assigned(gSynchronizationRegistry), 'gSynchronizationRegistry is not assigned.'); gSynchronizationRegistry.Free; gSynchronizationRegistry := Nil; End; Function HasSynchronizationRegistry : Boolean; Begin Result := Assigned(gSynchronizationRegistry) And gSynchronizationRegistry.Active; End; Function SynchronizationRegistry : TAdvSynchronizationRegistry; Begin Assert(Assigned(gSynchronizationRegistry), 'gSynchronizationRegistry was not assigned.'); Result := gSynchronizationRegistry; End; Function TAdvSynchronizationLockEvent.Link : TAdvSynchronizationLockEvent; Begin Result := TAdvSynchronizationLockEvent(Inherited Link); End; Procedure TAdvSynchronizationLockEvent.Assign(oObject : TAdvObject); Begin Inherited; FEventStatus := TAdvSynchronizationLockEvent(oObject).EventStatus; FEventTimestamp := TAdvSynchronizationLockEvent(oObject).EventTimestamp; FEventSequence := TAdvSynchronizationLockEvent(oObject).EventSequence; End; Function TAdvSynchronizationLockEvent.IsWaiting : Boolean; Begin Result := FEventStatus In [AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite]; End; Procedure TAdvSynchronizationLockEvent.EventStatusWaitingForRead; Begin FEventStatus := AdvSynchronizationLockEventStatusWaitingForRead; End; Procedure TAdvSynchronizationLockEvent.EventStatusWaitingForWrite; Begin FEventStatus := AdvSynchronizationLockEventStatusWaitingForWrite; End; Procedure TAdvSynchronizationLockEvent.EventStatusLockedForRead; Begin FEventStatus := AdvSynchronizationLockEventStatusLockedForRead; End; Procedure TAdvSynchronizationLockEvent.EventStatusLockedForWrite; Begin FEventStatus := AdvSynchronizationLockEventStatusLockedForWrite; End; Function TAdvSynchronizationLockEventList.ItemClass : TAdvObjectClass; Begin Result := TAdvSynchronizationLockEvent; End; Function TAdvSynchronizationLockEventList.CompareByEventSequence(pA, pB : Pointer) : Integer; Begin Result := DateTimeCompare(TAdvSynchronizationLockEvent(pA).EventSequence, TAdvSynchronizationLockEvent(pB).EventSequence); End; Procedure TAdvSynchronizationLockEventList.SortedByEventSequence; Begin SortedBy({$IFDEF FPC}@{$ENDIF}CompareByEventSequence); End; Function TAdvSynchronizationLockEventList.GetLockEventByIndex(Const iIndex : Integer) : TAdvSynchronizationLockEvent; Begin Result := TAdvSynchronizationLockEvent(ObjectByIndex[iIndex]); End; Constructor TAdvSynchronizationThreadLock.Create; Begin Inherited; FLockEventList := TAdvSynchronizationLockEventList.Create; FLockEventList.SortedByEventSequence; End; Destructor TAdvSynchronizationThreadLock.Destroy; Begin FLockEventList.Free; Inherited; End; Procedure TAdvSynchronizationThreadLock.Assign(oObject: TAdvObject); Begin Inherited; FThreadIdentifier := TAdvSynchronizationThreadLock(oObject).ThreadIdentifier; FLockIdentifier := TAdvSynchronizationThreadLock(oObject).LockIdentifier; FLockEventList.Assign(TAdvSynchronizationThreadLock(oObject).LockEventList); End; Procedure TAdvSynchronizationThreadLock.PushLockEvent(oLockEvent : TAdvSynchronizationLockEvent); Begin Assert(Invariants('PushLockEvent', oLockEvent, TAdvSynchronizationLockEvent, 'oLockEvent')); FLockEventList.Add(oLockEvent); End; Function TAdvSynchronizationThreadLock.PeekLockEvent : TAdvSynchronizationLockEvent; Begin Assert(CheckCondition(Not FLockEventList.IsEmpty, 'PeekLockEvent', 'Cannot peek last lock event as there are no lock events for this context.')); Result := FLockEventList[FLockEventList.Count - 1]; Assert(Invariants('PeekLockEvent', Result, TAdvSynchronizationLockEvent, 'Result')); End; Function TAdvSynchronizationThreadLock.PopLockEvent : TAdvSynchronizationLockEvent; Begin Result := PeekLockEvent.Link; FLockEventList.DeleteByIndex(FLockEventList.Count - 1); End; Function TAdvSynchronizationThreadLockList.ItemClass : TAdvObjectClass; Begin Result := TAdvSynchronizationThreadLock; End; Function TAdvSynchronizationThreadLockList.CompareByThreadIdentifierAndLockIdentifier(pA, pB : Pointer) : Integer; Begin Result := IntegerCompare(TAdvSynchronizationThreadLock(pA).ThreadIdentifier, TAdvSynchronizationThreadLock(pB).ThreadIdentifier); If Result = 0 Then Result := IntegerCompare(TAdvSynchronizationThreadLock(pA).LockIdentifier, TAdvSynchronizationThreadLock(pB).LockIdentifier); End; Procedure TAdvSynchronizationThreadLockList.SortedByThreadIdentifierAndLockIdentifier; Begin SortedBy({$IFDEF FPC}@{$ENDIF}CompareByThreadIdentifierAndLockIdentifier); End; Function TAdvSynchronizationThreadLockList.IndexByThreadIdentifierAndLockIdentifier(Const iThreadIdentifier : TThreadID; Const iLockIdentifier : Integer) : Integer; Var oThreadLock : TAdvSynchronizationThreadLock; Begin oThreadLock := TAdvSynchronizationThreadLock.Create; Try oThreadLock.ThreadIdentifier := iThreadIdentifier; oThreadLock.LockIdentifier := iLockIdentifier; Result := IndexBy(oThreadLock, {$IFDEF FPC}@{$ENDIF}CompareByThreadIdentifierAndLockIdentifier); Finally oThreadLock.Free; End; End; Function TAdvSynchronizationThreadLockList.GetThreadLockByIndex(Const iIndex : Integer) : TAdvSynchronizationThreadLock; Begin Result := TAdvSynchronizationThreadLock(ObjectByIndex[iIndex]); End; Constructor TAdvSynchronizationRegistry.Create; Begin Inherited; FThreadLockListCriticalSection := TAdvExclusiveCriticalSection.Create; FTimeController := Nil; FThreadLockList := TAdvSynchronizationThreadLockList.Create; FThreadLockList.SortedByThreadIdentifierAndLockIdentifier; FThreadIdentifierNextEventSequenceMatch := TAdvIntegerMatch.Create; FThreadIdentifierNextEventSequenceMatch.SortedByKey; FThreadIdentifierNextEventSequenceMatch.Default := 1; FThreadIdentifierNextEventSequenceMatch.Forced := True; End; Destructor TAdvSynchronizationRegistry.Destroy; Begin FThreadIdentifierNextEventSequenceMatch.Free; FThreadLockList.Free; FTimeController.Free; FThreadLockListCriticalSection.Free; Inherited; End; Function TAdvSynchronizationRegistry.Link : TAdvSynchronizationRegistry; Begin Result := TAdvSynchronizationRegistry(Inherited Link); End; Function TAdvSynchronizationRegistry.Active : Boolean; Begin Result := gUseSynchronizationRegistry; End; Procedure TAdvSynchronizationRegistry.Query(oThreadLockList : TAdvSynchronizationThreadLockList); Begin Assert(Invariants('Query', oThreadLockList, TAdvSynchronizationThreadLockList, 'oThreadLockList')); FThreadLockListCriticalSection.Lock; Try oThreadLockList.Assign(FThreadLockList); Finally FThreadLockListCriticalSection.Unlock; End; End; Procedure TAdvSynchronizationRegistry.RegisterWaitingForLock(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Var iThreadIdentifier : Integer; iThreadLockIndex : Integer; iThreadNextSequenceMatchIndex : Integer; oThreadLock : TAdvSynchronizationThreadLock; oLockEvent : TAdvSynchronizationLockEvent; Begin Assert(CheckCondition(aEventStatus In [AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite], 'RegisterWaitingForLock', 'Invalid waiting for lock event status.')); oLockEvent := TAdvSynchronizationLockEvent.Create; Try iThreadIdentifier := ThreadID; oLockEvent.EventTimestamp := TimeController.UniversalDateTime; oLockEvent.EventStatus := aEventStatus; FThreadLockListCriticalSection.Lock; Try iThreadLockIndex := FThreadLockList.IndexByThreadIdentifierAndLockIdentifier(iThreadIdentifier, iLockIdentifier); If Not FThreadLockList.ExistsByIndex(iThreadLockIndex) Then Begin oThreadLock := TAdvSynchronizationThreadLock.Create; oThreadLock.ThreadIdentifier := iThreadIdentifier; oThreadLock.LockIdentifier := iLockIdentifier; FThreadLockList.Add(oThreadLock); End Else Begin oThreadLock := FThreadLockList[iThreadLockIndex]; End; Assert(Invariants('RegisterWaitingForLock', oThreadLock, TAdvSynchronizationThreadLock, 'oThreadLock')); iThreadNextSequenceMatchIndex := FThreadIdentifierNextEventSequenceMatch.IndexByKey(iThreadIdentifier); If FThreadIdentifierNextEventSequenceMatch.ExistsByIndex(iThreadNextSequenceMatchIndex) Then Begin oLockEvent.EventSequence := FThreadIdentifierNextEventSequenceMatch.ValueByIndex[iThreadNextSequenceMatchIndex]; FThreadIdentifierNextEventSequenceMatch.ValueByIndex[iThreadNextSequenceMatchIndex] := oLockEvent.EventSequence + 1; End Else Begin oLockEvent.EventSequence := 1; FThreadIdentifierNextEventSequenceMatch.Add(iThreadIdentifier, 2); End; oThreadLock.PushLockEvent(oLockEvent.Link); Finally FThreadLockListCriticalSection.Unlock; End; Finally oLockEvent.Free; End; End; Procedure TAdvSynchronizationRegistry.RegisterNoLongerWaitingForLock(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Const AdvSynchronizationLockEventStatusRelevantWaitingForLockStatusArray : Array [TAdvSynchronizationLockEventStatus] Of TAdvSynchronizationLockEventStatus = (AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite, AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite); Var iThreadIdentifier : TThreadID; iThreadLockIndex : Integer; oLastLockEvent : TAdvSynchronizationLockEvent; oThreadLock : TAdvSynchronizationThreadLock; Begin Assert(CheckCondition(aEventStatus In [AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite], 'RegisterNoLongerWaitingForLock', 'Invalid locked event status.')); iThreadIdentifier := ThreadID; FThreadLockListCriticalSection.Lock; Try iThreadLockIndex := FThreadLockList.IndexByThreadIdentifierAndLockIdentifier(iThreadIdentifier, iLockIdentifier); If Not FThreadLockList.ExistsByIndex(iThreadLockIndex) Then RaiseError('RegisterNoLongerWaitingForLock', 'Thread lock for thread ''' + IntegerToString(iThreadIdentifier) + ''' does not exist.'); oThreadLock := FThreadLockList[iThreadLockIndex]; oLastLockEvent := oThreadLock.PopLockEvent; Try If oLastLockEvent.EventStatus <> AdvSynchronizationLockEventStatusRelevantWaitingForLockStatusArray[aEventStatus] Then RaiseError('RegisterNoLongerWaitingForLock', 'Last lock event should be relevant waiting for lock status.'); Finally oLastLockEvent.Free; End; // Destroy the thread lock if it has no active lock events so that there is no way we can get // conflicting object references in the lifetime of the server. If oThreadLock.LockEventList.IsEmpty Then FThreadLockList.DeleteByIndex(iThreadLockIndex); Finally FThreadLockListCriticalSection.Unlock; End; End; Procedure TAdvSynchronizationRegistry.RegisterLocked(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Const AdvSynchronizationLockEventStatusRelevantWaitingForLockStatusArray : Array [TAdvSynchronizationLockEventStatus] Of TAdvSynchronizationLockEventStatus = (AdvSynchronizationLockEventStatusLockedForRead, AdvSynchronizationLockEventStatusLockedForRead, AdvSynchronizationLockEventStatusWaitingForRead, AdvSynchronizationLockEventStatusWaitingForWrite); Var iThreadIdentifier : TThreadID; iThreadLockIndex : Integer; oLastLockEvent : TAdvSynchronizationLockEvent; oLockEvent : TAdvSynchronizationLockEvent; oThreadLock : TAdvSynchronizationThreadLock; Begin Assert(CheckCondition(aEventStatus In [AdvSynchronizationLockEventStatusLockedForRead, AdvSynchronizationLockEventStatusLockedForWrite], 'RegisterLocked', 'Invalid locked event status.')); oLockEvent := TAdvSynchronizationLockEvent.Create; Try iThreadIdentifier := ThreadID; oLockEvent.EventTimestamp := TimeController.UniversalDateTime; oLockEvent.EventStatus := aEventStatus; FThreadLockListCriticalSection.Lock; Try iThreadLockIndex := FThreadLockList.IndexByThreadIdentifierAndLockIdentifier(iThreadIdentifier, iLockIdentifier); If Not FThreadLockList.ExistsByIndex(iThreadLockIndex) Then RaiseError('RegisterLocked', 'Thread lock for thread ''' + IntegerToString(iThreadIdentifier) + ''' does not exist.'); oThreadLock := FThreadLockList[iThreadLockIndex]; oLastLockEvent := oThreadLock.PopLockEvent; Try If oLastLockEvent.EventStatus <> AdvSynchronizationLockEventStatusRelevantWaitingForLockStatusArray[aEventStatus] Then RaiseError('RegisterLocked', 'Last lock event should be relevant waiting for lock status.'); oLockEvent.EventSequence := oLastLockEvent.EventSequence; oThreadLock.PushLockEvent(oLockEvent.Link); Finally oLastLockEvent.Free; End; Finally FThreadLockListCriticalSection.Unlock; End; Finally oLockEvent.Free; End; End; Procedure TAdvSynchronizationRegistry.RegisterWaitingForRead(Const iLockIdentifier : Integer); Begin RegisterWaitingForLock(iLockIdentifier, AdvSynchronizationLockEventStatusWaitingForRead); End; Procedure TAdvSynchronizationRegistry.RegisterWaitingForWrite(Const iLockIdentifier : Integer); Begin RegisterWaitingForLock(iLockIdentifier, AdvSynchronizationLockEventStatusWaitingForWrite); End; Procedure TAdvSynchronizationRegistry.RegisterNoLongerWaitingForRead(Const iLockIdentifier : Integer); Begin RegisterNoLongerWaitingForLock(iLockIdentifier, AdvSynchronizationLockEventStatusWaitingForRead); End; Procedure TAdvSynchronizationRegistry.RegisterNoLongerWaitingForWrite(Const iLockIdentifier : Integer); Begin RegisterNoLongerWaitingForLock(iLockIdentifier, AdvSynchronizationLockEventStatusWaitingForWrite); End; Procedure TAdvSynchronizationRegistry.RegisterLockedForRead(Const iLockIdentifier : Integer); Begin RegisterLocked(iLockIdentifier, AdvSynchronizationLockEventStatusLockedForRead); End; Procedure TAdvSynchronizationRegistry.RegisterLockedForWrite(Const iLockIdentifier : Integer); Begin RegisterLocked(iLockIdentifier, AdvSynchronizationLockEventStatusLockedForWrite); End; Procedure TAdvSynchronizationRegistry.RegisterUnlocked(Const iLockIdentifier : Integer; Const aEventStatus : TAdvSynchronizationLockEventStatus); Var iThreadIdentifier : TThreadID; iThreadLockIndex : Integer; iThreadNextSequenceMatchIndex : Integer; oThreadLock : TAdvSynchronizationThreadLock; oLastLockEvent : TAdvSynchronizationLockEvent; Begin iThreadIdentifier := ThreadID; FThreadLockListCriticalSection.Lock; Try iThreadLockIndex := FThreadLockList.IndexByThreadIdentifierAndLockIdentifier(iThreadIdentifier, iLockIdentifier); If Not FThreadLockList.ExistsByIndex(iThreadLockIndex) Then RaiseError('RegisterUnlocked', 'Thread lock for thread ''' + IntegerToString(iThreadIdentifier) + ''' does not exist.'); oThreadLock := FThreadLockList[iThreadLockIndex]; oLastLockEvent := oThreadLock.PopLockEvent; Try If oLastLockEvent.EventStatus <> aEventStatus Then RaiseError('RegisterUnlocked', 'Last lock event should have same event status.'); iThreadNextSequenceMatchIndex := FThreadIdentifierNextEventSequenceMatch.IndexByKey(iThreadIdentifier); Assert(CheckCondition(FThreadIdentifierNextEventSequenceMatch.ExistsByIndex(iThreadNextSequenceMatchIndex), 'RegisterUnlocked', 'Could not find thread lock for this combination of thread and lock identifier.')); FThreadIdentifierNextEventSequenceMatch.ValueByIndex[iThreadNextSequenceMatchIndex] := FThreadIdentifierNextEventSequenceMatch.ValueByIndex[iThreadNextSequenceMatchIndex] - 1; Finally oLastLockEvent.Free; End; // Destroy the thread lock if it has no active lock events so that there is no way we can get // conflicting object references in the lifetime of the server. If oThreadLock.LockEventList.IsEmpty Then FThreadLockList.DeleteByIndex(iThreadLockIndex); Finally FThreadLockListCriticalSection.Unlock; End; End; Procedure TAdvSynchronizationRegistry.RegisterUnlockedForRead(Const iLockIdentifier : Integer); Begin RegisterUnlocked(iLockIdentifier, AdvSynchronizationLockEventStatusLockedForRead); End; Procedure TAdvSynchronizationRegistry.RegisterUnlockedForWrite(Const iLockIdentifier : Integer); Begin RegisterUnlocked(iLockIdentifier, AdvSynchronizationLockEventStatusLockedForWrite); End; Function TAdvSynchronizationRegistry.GetTimeController : TAdvTimeController; Begin Assert(Invariants('GetTimeController', FTimeController, TAdvTimeController, 'FTimeController')); Result := FTimeController; End; Procedure TAdvSynchronizationRegistry.SetTimeController(Const Value : TAdvTimeController); Begin Assert(Invariants('SetTimeController', Value, TAdvTimeController, 'Value')); FTimeController.Free; FTimeController := Value; End; End. // AdvSynchronizationRegistries //
unit prosody.main; interface uses Winapi.Windows, System.SysUtils, Winapi.ShlObj, Winapi.ActiveX, dorService, dorSocketStub, dorLua, lua.context, lua.loader; type TProsodyMainThread = class(TDORThread) private FStopping: Boolean; FScriptLoader: TScriptLoader; function LocalAppDataPath: string; function ProgramDataPath: string; protected function Run: Cardinal; override; procedure Stop; override; end; implementation {$IFDEF CONSOLEAPP} type ConsoleString = type AnsiString(850); {$ENDIF} { TProsodyMainThread } function TProsodyMainThread.LocalAppDataPath: string; const SHGFP_TYPE_CURRENT = 0; var path: array [0..MaxChar] of Char; begin SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, @path[0]); Result := IncludeTrailingPathDelimiter(StrPas(path)); end; function TProsodyMainThread.ProgramDataPath: string; var ItemIDList: PItemIDList; Path: array[0..MAX_PATH-1] of Char; begin SHGetSpecialFolderLocation(HInstance, CSIDL_COMMON_APPDATA, ItemIDList); SHGetPathFromIDList(ItemIDList, @Path); CoTaskMemFree(ItemIDList); Result := IncludeTrailingPathDelimiter(Path); end; function TProsodyMainThread.Run: Cardinal; var Context: TScriptContext; root, data: string; I: Integer; begin FStopping := False; FScriptLoader := nil; { Disable Floating Point Exceptions } Set8087CW(Get8087CW or $3F); Context := TScriptContext.Create; try { This loader must be installed in Prosody\bin } root := ExpandFileName(ExtractFilePath(ParamStr(0)) + '..'); (* Data is stored in {commonappdata} then in {userappdata} and if not found in {root} *) data := ProgramDataPath + 'Prosody'; if not DirectoryExists(data) then data := LocalAppDataPath + 'Prosody'; if DirectoryExists(data) then begin Context.Globals.AddOrSetValue('CFG_CONFIGDIR', data); Context.Globals.AddOrSetValue('CFG_DATADIR', data + '\data'); end else begin { Debug mode : data is stored within the installation directory } Context.Globals.AddOrSetValue('CFG_CONFIGDIR', root); Context.Globals.AddOrSetValue('CFG_DATADIR', root + '\data'); end; { Source and plugin directories for Prosody } Context.Globals.AddOrSetValue('CFG_SOURCEDIR', root + '\src\'); Context.Globals.AddOrSetValue('CFG_PLUGINDIR', root + '\plugins\'); { Lua interpreter package.[c]path for loading dependencies } Context.LoadPath := root + '\src\?.lua;' + root + '\lib\?.lua';; Context.LoadCPath := root + '\lib\?.dll'; { We can pass params to prosody so we build a structure to handle these params that will be passed as the "arg" table to the script, the first argument is, by convention, the full path of the prosody main script } Context.Arguments.Add(root + '\src\prosody'); for I := 1 to ParamCount do Context.Arguments.Add(ParamStr(I)); FScriptLoader := TScriptLoader.Create; try FScriptLoader.Run(Context, procedure(Status: Integer; const Error: string) begin {$IFDEF CONSOLEAPP} WriteLn(ConsoleString(Error)); {$ENDIF} end ); finally Free; FScriptLoader := nil; end; finally Context.Free; end; Result := 0; end; { This is an Lua CFunction used to stop the Lua application } procedure lua_stop(L: Plua_State; ar: Plua_Debug); cdecl; begin lua_sethook(L, nil, 0, 0); luaL_error(L, 'interrupted!'); end; procedure TProsodyMainThread.Stop; begin inherited; if not FStopping then begin if Assigned(FScriptLoader) then lua_sethook(FScriptLoader.LuaState, lua_stop, LUA_MASKCALL or LUA_MASKRET or LUA_MASKCOUNT, 1); FStopping := True; end; end; initialization // requests the application to start this thread Application.CreateThread(TProsodyMainThread); end.
unit TableSourceOptions; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ActnList, BCDialogs.Dlg, System.Actions, BCControls.CheckBox, JvExStdCtrls, JvCheckBox; type TTableSourceOptionsDialog = class(TDialog) ActionList: TActionList; CancelButton: TButton; CommentsCheckBox: TBCCheckBox; ConstraintsCheckBox: TBCCheckBox; CreateTableCheckBox: TBCCheckBox; GrantsCheckBox: TBCCheckBox; IndexesCheckBox: TBCCheckBox; OKAction: TAction; OKButton: TButton; Panel1: TPanel; Panel2: TPanel; ParametersCheckBox: TBCCheckBox; Separator1Panel: TPanel; StorageCheckBox: TBCCheckBox; SynonymsCheckBox: TBCCheckBox; TriggersCheckBox: TBCCheckBox; procedure FormDestroy(Sender: TObject); procedure OKActionExecute(Sender: TObject); private { Private declarations } function GetComments: Boolean; function GetConstraints: Boolean; function GetCreateTable: Boolean; function GetGrants: Boolean; function GetIndexes: Boolean; function GetParameters: Boolean; function GetStorage: Boolean; function GetSynonyms: Boolean; function GetTriggers: Boolean; procedure ReadIniFile; procedure WriteIniFile; public { Public declarations } function Open: Boolean; property Comments: Boolean read GetComments; property Constraints: Boolean read GetConstraints; property CreateTable: Boolean read GetCreateTable; property Grants: Boolean read GetGrants; property Indexes: Boolean read GetIndexes; property Parameters: Boolean read GetParameters; property Storage: Boolean read GetStorage; property Synonyms: Boolean read GetSynonyms; property Triggers: Boolean read GetTriggers; end; function TableSourceOptionsDialog: TTableSourceOptionsDialog; implementation {$R *.dfm} uses BigIni, BCCommon.StyleUtils, BCCommon.FileUtils; var FTableSourceOptionsDialog: TTableSourceOptionsDialog; function TableSourceOptionsDialog: TTableSourceOptionsDialog; begin if not Assigned(FTableSourceOptionsDialog) then Application.CreateForm(TTableSourceOptionsDialog, FTableSourceOptionsDialog); Result := FTableSourceOptionsDialog; FTableSourceOptionsDialog.ReadIniFile; SetStyledFormSize(Result); end; procedure TTableSourceOptionsDialog.FormDestroy(Sender: TObject); begin FTableSourceOptionsDialog := nil; end; procedure TTableSourceOptionsDialog.OKActionExecute(Sender: TObject); begin WriteIniFile; ModalResult := mrOk; end; function TTableSourceOptionsDialog.Open: Boolean; begin Result := ShowModal = mrOk; end; procedure TTableSourceOptionsDialog.ReadIniFile; var s: string; begin with TBigIniFile.Create(GetINIFilename) do try s := ReadString('TableSource', 'Options', 'YYYYYYYNN'); CreateTableCheckBox.Checked := s[1] = 'Y'; CommentsCheckBox.Checked := s[2] = 'Y'; IndexesCheckBox.Checked := s[3] = 'Y'; ConstraintsCheckBox.Checked := s[4] = 'Y'; TriggersCheckBox.Checked := s[5] = 'Y'; SynonymsCheckBox.Checked := s[6] = 'Y'; GrantsCheckBox.Checked := s[7] = 'Y'; StorageCheckBox.Checked := s[8] = 'Y'; ParametersCheckBox.Checked := s[9] = 'Y'; finally Free; end; end; function TTableSourceOptionsDialog.GetCreateTable: Boolean; begin Result := CreateTableCheckBox.Checked; end; function TTableSourceOptionsDialog.GetComments: Boolean; begin Result := CommentsCheckBox.Checked; end; function TTableSourceOptionsDialog.GetIndexes: Boolean; begin Result := IndexesCheckBox.Checked; end; function TTableSourceOptionsDialog.GetConstraints: Boolean; begin Result := ConstraintsCheckBox.Checked; end; function TTableSourceOptionsDialog.GetTriggers: Boolean; begin Result := TriggersCheckBox.Checked; end; function TTableSourceOptionsDialog.GetSynonyms: Boolean; begin Result := SynonymsCheckBox.Checked; end; function TTableSourceOptionsDialog.GetGrants: Boolean; begin Result := GrantsCheckBox.Checked; end; function TTableSourceOptionsDialog.GetStorage: Boolean; begin Result := StorageCheckBox.Checked end; function TTableSourceOptionsDialog.GetParameters: Boolean; begin Result := ParametersCheckBox.Checked end; procedure TTableSourceOptionsDialog.WriteIniFile; var s: string; begin with TBigIniFile.Create(GetINIFilename) do try s := 'YYYYYYYYY'; if CreateTableCheckBox.Checked then s[1] := 'Y' else s[1] := 'N'; if CommentsCheckBox.Checked then s[2] := 'Y' else s[2] := 'N'; if IndexesCheckBox.Checked then s[3] := 'Y' else s[3] := 'N'; if ConstraintsCheckBox.Checked then s[4] := 'Y' else s[4] := 'N'; if TriggersCheckBox.Checked then s[5] := 'Y' else s[5] := 'N'; if SynonymsCheckBox.Checked then s[6] := 'Y' else s[6] := 'N'; if GrantsCheckBox.Checked then s[7] := 'Y' else s[7] := 'N'; if StorageCheckBox.Checked then s[8] := 'Y' else s[8] := 'N'; if ParametersCheckBox.Checked then s[9] := 'Y' else s[9] := 'N'; WriteString('TableSource', 'Options', s); finally Free; end; end; end.
unit RestorePoint; interface uses Windows, SysUtils; const { restore point types } APPLICATION_INSTALL = 0; APPLICATION_UNINSTALL = 1; DEVICE_DRIVER_INSTALL = 10; MODIFY_SETTINGS = 12; CANCELLED_OPERATION = 13; { event types } BEGIN_SYSTEM_CHANGE = 100; END_SYSTEM_CHANGE = 101; { other stuff } MAX_DESC = 256; type int64 = comp; { comment this if you are on a Delphi that supports int64 } restoreptinfo = packed record dwEventType: DWord; dwRestorePtType: DWord; llSequenceNumber: int64; szDescription: array[0..max_desc] of widechar; end; prestoreptinfo = ^restoreptinfo; statemgrstatus = packed record nStatus: DWord; llSequenceNumber: int64; end; pstatemgrstatus = ^statemgrstatus; set_func = function(restptinfo: prestoreptinfo; status: pstatemgrstatus): boolean; stdcall; remove_func = function(dwRPNum: DWord): DWord; stdcall; var DLLHandle: THandle; set_restore: set_func; remove_restore: remove_func; function begin_restore(var seqnum: int64; instr: widestring): DWord; function end_restore(seqnum: int64): DWord; function cancel_restore(seqnum: int64): integer; function error_report(inerr: integer): string; implementation function begin_restore(var seqnum: int64; instr: widestring): DWord; { starts a restore point } var r_point: restoreptinfo; smgr: statemgrstatus; fret: boolean; retval: integer; begin retval := 0; fillchar(r_point, sizeof(r_point), 0); fillchar(smgr, sizeof(smgr), 0); r_point.dwEventType := BEGIN_SYSTEM_CHANGE; r_point.dwRestorePtType := APPLICATION_INSTALL; move(instr[1], r_point.szDescription, max_desc); r_point.llSequenceNumber := 0; fret := set_restore(@r_point, @smgr); if fret = false then retval := smgr.nStatus; seqnum := smgr.llSequenceNumber; begin_restore := retval; end; function end_restore(seqnum: int64): DWord; { ends restore point } var r_point: restoreptinfo; smgr: statemgrstatus; fret: boolean; retval: integer; begin retval := 0; fillchar(r_point, sizeof(r_point), 0); fillchar(smgr, sizeof(smgr), 0); r_point.dwEventType := END_SYSTEM_CHANGE; r_point.llSequenceNumber := seqnum; fret := set_restore(@r_point, @smgr); if fret = false then retval := smgr.nStatus; end_restore := retval; end; function cancel_restore(seqnum: int64): integer; { cancels restore point in progress} var r_point: restoreptinfo; smgr: statemgrstatus; retval: integer; fret: boolean; begin retval := 0; r_point.dwEventType := END_SYSTEM_CHANGE; r_point.dwRestorePtType := CANCELLED_OPERATION; r_point.llSequenceNumber := seqnum; fret := set_restore(@r_point, @smgr); if fret = false then retval := smgr.nStatus; cancel_restore := retval; end; function error_report(inerr: integer): string; begin { case inerr of ERROR_SUCCESS: error_report := SERROR_SUCCESS; ERROR_BAD_ENVIRONMENT: error_report := SERROR_BAD_ENVIRONMENT; ERROR_DISK_FULL: error_report := SERROR_DISK_FULL; ERROR_FILE_EXISTS: error_report := SERROR_FILE_EXISTS; ERROR_INTERNAL_ERROR: error_report := SERROR_INTERNAL_ERROR; ERROR_INVALID_DATA: error_report := SERROR_INVALID_DATA; ERROR_SERVICE_DISABLED: error_report := SERROR_SERVICE_DISABLED; ERROR_TIMEOUT: error_report := SERROR_TIMEOUT; else error_report := IntToStr(inerr); end;} end; initialization { find library functions and enable them } DLLHandle := LoadLibraryW('SRCLIENT.DLL'); if DLLHandle <> 0 then begin @set_restore := GetProcAddress(DLLHandle, 'SRSetRestorePointW'); if @set_restore = nil then begin raise Exception.Create('Did not find SRSetRestorePointW'); halt(1); end; @remove_restore := GetProcAddress(DLLHandle, 'SRRemoveRestorePoint'); if @remove_restore = nil then begin raise Exception.Create('Did not find SRRemoveRestorePoint'); halt(1); end; end else begin raise Exception.Create('System Restore Interface Not Present.'); halt(1); end; finalization { release library } FreeLibrary(DLLHandle); end.
unit aOPCProvider; interface uses SysUtils, Classes, //Dialogs, aCustomOPCSource, aOPCSource, uDCObjects; type TDataEvent = (deProviderChange, deProviderListChange, dePropertyChange, deFocusControl, deDisabledStateChange); TCrackOPCLink = class(TaOPCDataLink); TaOPCProviderList = class; { identifies the control value name for TaOPCProvider } [ObservableMember('Value')] TaOPCProvider = class(TaCustomSingleOPCSource) private fDataLink: TaOPCDataLink; FOnChange: TNotifyEvent; function GetOPCSource: TaCustomOPCSource; procedure SetOPCSource(const Value: TaCustomOPCSource); function GetPhysID: TPhysID; procedure SetPhysID(const Value: TPhysID); function GetErrorCode: integer; function GetErrorString: string; function GetValue: string; procedure SetValue(const Value: string); procedure ChangeData(Sender:TObject); function GetStairsOptions: TDCStairsOptionsSet; procedure SetStairsOptions(const Value: TDCStairsOptionsSet); procedure ObserverToggle(const AObserver: IObserver; const Value: Boolean); function GetValueAsFloat: Double; procedure SetValueAsFloat(const Value: Double); protected function CanObserve(const ID: Integer): Boolean; override; procedure ObserverAdded(const ID: Integer; const Observer: IObserver); override; procedure DoActive; override; procedure DoNotActive; override; // procedure DefineProperties(Filer: TFiler); override; public constructor Create(aOwner : TComponent);override; destructor Destroy; override; published property OnChange: TNotifyEvent read FOnChange write FOnChange; property OPCSource : TaCustomOPCSource read GetOPCSource write SetOPCSource; property StairsOptions : TDCStairsOptionsSet read GetStairsOptions write SetStairsOptions default []; property Value : string read GetValue write SetValue; property ValueAsFloat : Double read GetValueAsFloat write SetValueAsFloat; property PhysID : TPhysID read GetPhysID write SetPhysID; property ErrorCode : integer read GetErrorCode; property ErrorString : string read GetErrorString; end; { identifies the control value name for TaOPCProviderItem } [ObservableMember('Value')] [ObservableMember('PhysID')] TaOPCProviderItem = class(TaOPCProvider) private FProviderList: TaOPCProviderList; procedure SetProviderList(const Value: TaOPCProviderList); function GetIndex: Integer; procedure SetIndex(Value: Integer); protected procedure ReadState(Reader: TReader); override; procedure SetParentComponent(AParent: TComponent); override; public destructor Destroy; override; function GetParentComponent: TComponent; override; function HasParent: Boolean; override; property ProviderList: TaOPCProviderList read FProviderList write SetProviderList; published property Index: Integer read GetIndex write SetIndex stored False; end; TaOPCProviderClass = class of TaOPCProvider; TaOPCProviderListDesigner = class; TaOPCProviderList = class(TComponent) private FDesigner : TaOPCProviderListDesigner; FProviders: TList; FOPCSource: TaOPCSource; function GetProvider(Index: Integer): TaOPCProviderItem; function GetProviderCount: Integer; procedure SetProvider(Index: Integer; Value: TaOPCProviderItem); procedure SetOPCSource(const Value: TaOPCSource); protected procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure DataEvent(Event: TDataEvent; Info: Longint); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetChildOrder(Component: TComponent; Order: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddProvider(Provider: TaOPCProviderItem); procedure RemoveProvider(Provider: TaOPCProviderItem); property Designer: TaOPCProviderListDesigner read FDesigner; property Providers[Index: Integer]: TaOPCProviderItem read GetProvider write SetProvider; default; property ProviderCount: Integer read GetProviderCount; published property OPCSource : TaOPCSource read FOPCSource write SetOPCSource; end; TaOPCProviderListDesigner = class(TObject) private FProviderList: TaOPCProviderList; public constructor Create(aProviderList: TaOPCProviderList); destructor Destroy; override; procedure DataEvent(Event: TDataEvent; Info: Longint); virtual; property ProviderList: TaOPCProviderList read FProviderList; end; implementation //uses // Controls; { TaOPCProvider } constructor TaOPCProvider.Create(aOwner: TComponent); begin inherited Create(aOwner); fDataLink := TaOPCDataLink.Create(Self); fDataLink.OnChangeData := ChangeData; fDataLink.StairsOptions := []; end; //procedure TaOPCProvider.DefineProperties(Filer: TFiler); //begin //end; destructor TaOPCProvider.Destroy; begin FOnChange := nil; OPCSource := nil; fDataLink.Free; inherited; end; function TaOPCProvider.GetErrorCode: integer; begin Result := fDataLink.ErrorCode; end; function TaOPCProvider.GetErrorString: string; begin Result := fDataLink.ErrorString; end; function TaOPCProvider.GetPhysID: TPhysID; begin Result := fDataLink.PhysID; end; function TaOPCProvider.GetValue: string; begin Result := fDataLink.Value; end; function TaOPCProvider.GetValueAsFloat: Double; begin Result := fDataLink.FloatValue; end; procedure TaOPCProvider.ObserverAdded(const ID: Integer; const Observer: IObserver); begin if ID = TObserverMapping.EditLinkID then Observer.OnObserverToggle := ObserverToggle; end; // на будущее можно запретить связанным элемента менять Value // например, добавить свойство ReadOnly { All controls that support the EditLink observer should prevent the user from changing the control value. Disabling the control is one way to do it. Some observer implementations ignore certain types of input to prevent the user from changing the control value. } procedure TaOPCProvider.ObserverToggle(const AObserver: IObserver; const Value: Boolean); //var // LEditLinkObserver: IEditLinkObserver; begin // if Value then // begin // if Supports(AObserver, IEditLinkObserver, LEditLinkObserver) then // { disable the trackbar if the associated field does not support editing } // Enabled := not LEditLinkObserver.IsReadOnly; // end else // Enabled := True; end; function TaOPCProvider.GetOPCSource: TaCustomOPCSource; begin Result := fDataLink.OPCSource; end; procedure TaOPCProvider.SetPhysID(const Value: TPhysID); var DataLinkGroup:TOPCDataLinkGroup; i,j: Integer; begin if PhysID<>Value then begin fDataLink.PhysID := Value; for i:=DataLinkGroups.Count - 1 downto 0 do begin DataLinkGroup:=TOPCDataLinkGroup(DataLinkGroups.Items[i]); DataLinkGroup.PhysID:=Value; if DataLinkGroup<>nil then for j := 0 to DataLinkGroup.DataLinks.Count - 1 do TaOPCDataLink(DataLinkGroup.DataLinks.Items[j]).PhysID := Value; end; end; end; procedure TaOPCProvider.SetValue(const Value: string); begin if (csLoading in ComponentState) or (csDestroying in ComponentState) then Exit; if fDataLink.Value <> Value then begin fDataLink.Value := Value; if Assigned(FOnChange) then FOnChange(Self); end; { if Assigned(FOnChange) and (not (csLoading in ComponentState)) then FOnChange(self); } end; procedure TaOPCProvider.SetValueAsFloat(const Value: Double); begin fDataLink.FloatValue := Value; end; procedure TaOPCProvider.SetOPCSource(const Value: TaCustomOPCSource); begin if (fDataLink.OPCSource <> Value) and (Value <> Self) then fDataLink.OPCSource := Value; end; function TaOPCProvider.CanObserve(const ID: Integer): Boolean; { Controls which implement observers always override TComponent.CanObserve(const ID: Integer). } { This method identifies the type of observers supported by TObservableTrackbar. } begin case ID of TObserverMapping.EditLinkID, { EditLinkID is the observer that is used for control-to-field links } TObserverMapping.ControlValueID: Result := True; else Result := False; end; end; procedure TaOPCProvider.ChangeData(Sender: TObject); var i,j: Integer; IsChanged:boolean; DataLinkGroup:TOPCDataLinkGroup; CrackDataLink:TCrackOPCLink; begin if (csLoading in ComponentState) or (csDestroying in ComponentState) then Exit; TLinkObservers.ControlChanged(Self); if Active then begin for i := 0 to FDataLinkGroups.Count - 1 do // Iterate begin DataLinkGroup:=TOPCDataLinkGroup(FDataLinkGroups.Items[i]); if DataLinkGroup<>nil then begin for j := 0 to DataLinkGroup.DataLinks.Count - 1 do begin CrackDataLink := TCrackOPCLink(DataLinkGroup.DataLinks.Items[j]); IsChanged:=(CrackDataLink.fValue<>Value) or (CrackDataLink.fErrorCode<>ErrorCode) or (CrackDataLink.fErrorString<>ErrorString); if IsChanged then begin CrackDataLink.fValue := Value; CrackDataLink.fErrorCode := ErrorCode; CrackDataLink.fErrorString := ErrorString; CrackDataLink.ChangeData; end; end; end; end; end; if Assigned(FOnChange) and (not (csLoading in ComponentState)) and (not (csDestroying in ComponentState)) then FOnChange(Self); { if Assigned(FOnChange) then FOnChange(Self); } end; procedure TaOPCProvider.DoActive; begin fActive:=true; inherited; end; procedure TaOPCProvider.DoNotActive; begin fActive:=False; inherited; end; function TaOPCProvider.GetStairsOptions: TDCStairsOptionsSet; begin Result := fDataLink.StairsOptions; end; procedure TaOPCProvider.SetStairsOptions(const Value: TDCStairsOptionsSet); begin fDataLink.StairsOptions := Value; end; { TCustomProviderList } procedure TaOPCProviderList.AddProvider(Provider: TaOPCProviderItem); begin FProviders.Add(Provider); Provider.FProviderList := Self; Provider.FreeNotification(Self); DataEvent(deProviderListChange,0); end; constructor TaOPCProviderList.Create(AOwner: TComponent); begin inherited Create(AOwner); FProviders := TList.Create; end; procedure TaOPCProviderList.DataEvent(Event: TDataEvent; Info: Integer); begin if FDesigner <> nil then FDesigner.DataEvent(Event, Info); end; destructor TaOPCProviderList.Destroy; begin FreeAndNil(FDesigner); while FProviders.Count > 0 do TaOPCProvider(FProviders.Last).Free; FProviders.Free; inherited Destroy; end; procedure TaOPCProviderList.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; Provider: TaOPCProvider; begin for I := 0 to FProviders.Count - 1 do begin Provider := FProviders.List[I]; if Provider.Owner = Root then Proc(Provider); end; end; function TaOPCProviderList.GetProvider(Index: Integer): TaOPCProviderItem; begin Result := FProviders[Index]; end; function TaOPCProviderList.GetProviderCount: Integer; begin Result := FProviders.Count; end; procedure TaOPCProviderList.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then if (AComponent is TaOPCProviderItem) then RemoveProvider(TaOPCProviderItem(AComponent)); end; procedure TaOPCProviderList.RemoveProvider(Provider: TaOPCProviderItem); begin if FProviders.Remove(Provider) >= 0 then Provider.FProviderList := nil; DataEvent(deProviderListChange,0); end; procedure TaOPCProviderList.SetChildOrder(Component: TComponent; Order: Integer); begin if FProviders.IndexOf(Component) >= 0 then (Component as TaOPCProviderItem).Index := Order; end; procedure TaOPCProviderList.SetOPCSource(const Value: TaOPCSource); begin FOPCSource := Value; end; procedure TaOPCProviderList.SetProvider(Index: Integer; Value: TaOPCProviderItem); begin TaOPCProvider(FProviders[Index]).Assign(Value); DataEvent(deProviderListChange,0); end; { TaOPCProviderListDesigner } constructor TaOPCProviderListDesigner.Create(aProviderList: TaOPCProviderList); begin FProviderList := aProviderList; aProviderList.FDesigner := self; end; procedure TaOPCProviderListDesigner.DataEvent(Event: TDataEvent; Info: Integer); begin end; destructor TaOPCProviderListDesigner.Destroy; begin FProviderList.FDesigner := nil; inherited; end; { TaOPCProviderItem } destructor TaOPCProviderItem.Destroy; begin inherited; if ProviderList <> nil then ProviderList.RemoveProvider(Self); end; function TaOPCProviderItem.GetIndex: Integer; begin if FProviderList <> nil then Result := FProviderList.FProviders.IndexOf(Self) else Result := -1; end; function TaOPCProviderItem.GetParentComponent: TComponent; begin if ProviderList <> nil then begin Result := ProviderList; //ShowMessage(ProviderList.Name); end else Result := inherited GetParentComponent; end; function TaOPCProviderItem.HasParent: Boolean; begin if ProviderList <> nil then Result := True else Result := inherited HasParent; end; procedure TaOPCProviderItem.ReadState(Reader: TReader); begin inherited ReadState(Reader); if Reader.Parent is TaOPCProviderList then ProviderList := TaOPCProviderList(Reader.Parent); end; procedure TaOPCProviderItem.SetIndex(Value: Integer); var CurIndex, Count: Integer; begin CurIndex := GetIndex; if CurIndex >= 0 then begin Count := ProviderList.FProviders.Count; if Value < 0 then Value := 0; if Value >= Count then Value := Count - 1; if Value <> CurIndex then begin ProviderList.FProviders.Delete(CurIndex); ProviderList.FProviders.Insert(Value, Self); end; end; end; procedure TaOPCProviderItem.SetParentComponent(AParent: TComponent); begin if not (csLoading in ComponentState) and (AParent is TaOPCProviderList) then ProviderList := TaOPCProviderList(AParent); end; procedure TaOPCProviderItem.SetProviderList(const Value: TaOPCProviderList); begin if Value <> ProviderList then begin if ProviderList <> nil then ProviderList.RemoveProvider(Self); if Value <> nil then Value.AddProvider(Self); end; end; initialization Classes.RegisterClass(TaOPCProvider); // GroupDescendentsWith(TaOPCProviderList, Controls.TControl); // GroupDescendentsWith(TaCustomSingleOPCSource, Controls.TControl); end.
unit GBJSON.Deserializer; interface uses GBJSON.Interfaces, GBJSON.Base, GBJSON.RTTI, GBJSON.DateTime.Helper, System.Rtti, System.JSON, System.SysUtils, System.Generics.Collections, System.StrUtils, System.Variants, System.TypInfo; type TGBJSONDeserializer<T: class, constructor> = class(TGBJSONBase, IGBJSONDeserializer<T>) private FUseIgnore: Boolean; procedure ProcessOptions(AJsonObject: TJSOnObject); function ObjectToJsonString(AObject: TObject; AType: TRttiType): string; overload; function ValueToJson (AObject: TObject; AProperty: TRttiProperty): string; function ValueListToJson(AObject: TObject; AProperty: TRttiProperty): string; public function ObjectToJsonString(Value: TObject): string; overload; function ObjectToJsonObject(Value: TObject): TJSONObject; function StringToJsonObject(value: string) : TJSONObject; function ListToJSONArray(Value: TObjectList<T>): TJSONArray; class function New(bUseIgnore: Boolean = True): IGBJSONDeserializer<T>; constructor create(bUseIgnore: Boolean = True); reintroduce; destructor Destroy; override; end; implementation { TGBJSONDeserializer } uses GBJSON.Helper; constructor TGBJSONDeserializer<T>.create(bUseIgnore: Boolean = True); begin inherited create; FUseIgnore := bUseIgnore; end; destructor TGBJSONDeserializer<T>.Destroy; begin inherited; end; function TGBJSONDeserializer<T>.StringToJsonObject(value: string): TJSONObject; var json : string; begin json := value.Replace(#$D, EmptyStr) .Replace(#$A, EmptyStr); result := TJSONObject.ParseJSONValue(json) as TJSONObject; if Assigned(Result) then ProcessOptions(Result); end; function TGBJSONDeserializer<T>.ListToJSONArray(Value: TObjectList<T>): TJSONArray; var myObj: T; begin result := TJSONArray.Create; if Assigned(Value) then for myObj in Value do begin result.AddElement(ObjectToJsonObject(myObj)); end; end; class function TGBJSONDeserializer<T>.New(bUseIgnore: Boolean = True): IGBJSONDeserializer<T>; begin result := Self.create(bUseIgnore); end; function TGBJSONDeserializer<T>.ObjectToJsonObject(Value: TObject): TJSONObject; var jsonString: string; begin jsonString := ObjectToJsonString(Value); result := TJSONObject.ParseJSONValue(jsonString) as TJSONObject; ProcessOptions(Result); end; function TGBJSONDeserializer<T>.ObjectToJsonString(Value: TObject): string; var rttiType: TRttiType; begin if not Assigned(Value) then Exit('{}'); rttiType := TGBRTTI.GetInstance.GetType(Value.ClassType); result := ObjectToJsonString(Value, rttiType); end; procedure TGBJSONDeserializer<T>.ProcessOptions(AJsonObject: TJSOnObject); var LPair: TJSONPair; LItem: TObject; i: Integer; begin if not assigned(AJsonObject) then Exit; for i := AJsonObject.Count -1 downto 0 do begin LPair := TJSONPair(AJsonObject.Pairs[i]); if LPair.JsonValue is TJSOnObject then begin ProcessOptions(TJSOnObject(LPair.JsonValue)); if LPair.JsonValue.ToString.Equals('{}') then begin AJsonObject.RemovePair(LPair.JsonString.Value).DisposeOf; Continue; end; end else if LPair.JsonValue is TJSONArray then begin if (TJSONArray(LPair.JsonValue).Count = 0) then begin AJsonObject.RemovePair(LPair.JsonString.Value).DisposeOf; end else for LItem in TJSONArray(LPair.JsonValue) do begin if LItem is TJSOnObject then ProcessOptions(TJSOnObject(LItem)); end; end else begin if (LPair.JsonValue.value = '') or (LPair.JsonValue.ToJSON = '0') then begin AJsonObject.RemovePair(LPair.JsonString.Value).DisposeOf; end; end; end; end; function TGBJSONDeserializer<T>.ValueListToJson(AObject: TObject; AProperty: TRttiProperty): string; var rttiType: TRttiType; method : TRttiMethod; value : TValue; i : Integer; begin value := AProperty.GetValue(AObject); if value.AsObject = nil then Exit('[]'); rttiType := TGBRTTI.GetInstance.GetType(value.AsObject.ClassType); method := rttiType.GetMethod('ToArray'); value := method.Invoke(value.AsObject, []); if value.GetArrayLength = 0 then Exit('[]'); result := '['; for i := 0 to value.GetArrayLength - 1 do begin if value.GetArrayElement(i).IsObject then result := Result + ObjectToJsonString(value.GetArrayElement(i).AsObject) + ',' else result := Result + '"' + (value.GetArrayElement(i).AsString) + '"' + ','; end; result[Length(Result)] := ']'; end; function TGBJSONDeserializer<T>.ValueToJson(AObject: TObject; AProperty: TRttiProperty): string; var value : TValue; data : TDateTime; begin value := AProperty.GetValue(AObject); if AProperty.IsString then Exit('"' + Value.AsString.Replace('\', '\\') + '"'); if AProperty.IsInteger then Exit(value.AsInteger.ToString); if AProperty.IsEnum then Exit('"' + GetEnumName(AProperty.GetValue(AObject).TypeInfo, AProperty.GetValue(AObject).AsOrdinal) + '"'); if AProperty.IsFloat then Exit(value.AsExtended.ToString.Replace(',', '.')); if AProperty.IsBoolean then Exit(IfThen(value.AsBoolean, 'true', 'false')); if AProperty.IsDateTime then begin data := value.AsExtended; if data = 0 then Exit('""'); result := IfThen(FDateTimeFormat.IsEmpty, data.DateTimeToIso8601, data.Format(FDateTimeFormat)); result := '"' + result + '"'; Exit; end; if AProperty.IsObject then Exit(ObjectToJsonString(value.AsObject)); if AProperty.IsList then Exit(ValueListToJson(AObject, AProperty)); if AProperty.IsVariant then begin if VarType(value.AsVariant) = varDate then begin data := value.AsVariant; if data = 0 then Exit('""'); result := IfThen(FDateTimeFormat.IsEmpty, data.DateTimeToIso8601, data.Format(FDateTimeFormat)); result := '"' + result + '"'; Exit; end; Exit('"' + VartoStrDef(value.AsVariant, '') + '"') end; end; function TGBJSONDeserializer<T>.ObjectToJsonString(AObject: TObject; AType: TRttiType): string; var rttiProperty: TRttiProperty; begin result := '{'; for rttiProperty in AType.GetProperties do begin if ( (not FUseIgnore) or (not rttiProperty.IsIgnore(AObject.ClassType))) and (not rttiProperty.IsEmpty(AObject)) then begin result := result + Format('"%s":', [rttiProperty.Name]); result := result + ValueToJson(AObject, rttiProperty) + ','; end; end; if Result.EndsWith(',') then Result[Length(Result)] := '}' else Result := Result + '}'; end; end.
unit TextEditor.LeftMargin.Colors; interface uses System.Classes, System.UITypes, TextEditor.Consts; type TTextEditorLeftMarginColors = class(TPersistent) strict private FActiveLineBackground: TColor; FActiveLineBackgroundUnfocused: TColor; FActiveLineNumber: TColor; FBackground: TColor; FBookmarkBackground: TColor; FBookmarkPanelBackground: TColor; FBorder: TColor; FLineNumberLine: TColor; FLineStateModified: TColor; FLineStateNormal: TColor; FMarkDefaultBackground: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property ActiveLineBackground: TColor read FActiveLineBackground write FActiveLineBackground default TDefaultColors.ActiveLineBackground; property ActiveLineBackgroundUnfocused: TColor read FActiveLineBackgroundUnfocused write FActiveLineBackgroundUnfocused default TDefaultColors.ActiveLineBackgroundUnfocused; property ActiveLineNumber: TColor read FActiveLineNumber write FActiveLineNumber default TColors.SysNone; property Background: TColor read FBackground write FBackground default TDefaultColors.LeftMarginBackground; property BookmarkBackground: TColor read FBookmarkBackground write FBookmarkBackground default TColors.SysNone; property BookmarkPanelBackground: TColor read FBookmarkPanelBackground write FBookmarkPanelBackground default TDefaultColors.LeftMarginBackground; property Border: TColor read FBorder write FBorder default TDefaultColors.LeftMarginBackground; property LineNumberLine: TColor read FLineNumberLine write FLineNumberLine default TDefaultColors.LeftMarginFontForeground; property LineStateModified: TColor read FLineStateModified write FLineStateModified default TColors.Yellow; property LineStateNormal: TColor read FLineStateNormal write FLineStateNormal default TColors.Lime; property MarkDefaultBackground: TColor read FMarkDefaultBackground write FMarkDefaultBackground default TColors.SysNone; end; implementation constructor TTextEditorLeftMarginColors.Create; begin inherited; FActiveLineBackground := TDefaultColors.ActiveLineBackground; FActiveLineBackgroundUnfocused := TDefaultColors.ActiveLineBackgroundUnfocused; FActiveLineNumber := TColors.SysNone; FBackground := TDefaultColors.LeftMarginBackground; FBookmarkBackground := TColors.SysNone; FBookmarkPanelBackground := TDefaultColors.LeftMarginBackground; FBorder := TDefaultColors.LeftMarginBackground; FLineNumberLine := TDefaultColors.LeftMarginFontForeground; FLineStateModified := TColors.Yellow; FLineStateNormal := TColors.Lime; FMarkDefaultBackground := TColors.SysNone; end; procedure TTextEditorLeftMarginColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorLeftMarginColors) then with ASource as TTextEditorLeftMarginColors do begin Self.FActiveLineBackground := FActiveLineBackground; Self.FActiveLineBackgroundUnfocused := FActiveLineBackgroundUnfocused; Self.FBackground := FBackground; Self.FBookmarkPanelBackground := FBookmarkPanelBackground; Self.FBorder := FBorder; Self.FLineNumberLine := FLineNumberLine; Self.FLineStateModified := FLineStateModified; Self.FLineStateNormal := FLineStateNormal; Self.FMarkDefaultBackground := FMarkDefaultBackground; end else inherited Assign(ASource); end; end.
unit FreeOTFEfmeOptions_Advanced; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Spin64, FreeOTFESettings, SDUStdCtrls, CommonfmeOptions_Base, FreeOTFEfmeOptions_Base; type TfmeOptions_FreeOTFEAdvanced = class(TfmeFreeOTFEOptions_Base) gbAdvanced: TGroupBox; lblDragDrop: TLabel; ckAllowMultipleInstances: TSDUCheckBox; cbDragDrop: TComboBox; ckAutoStartPortable: TSDUCheckBox; ckAdvancedMountDlg: TSDUCheckBox; ckRevertVolTimestamps: TSDUCheckBox; pnlVertSplit: TPanel; seMRUMaxItemCount: TSpinEdit64; lblMRUMaxItemCountInst: TLabel; lblMRUMaxItemCount: TLabel; ckWarnBeforeForcedDismount: TSDUCheckBox; lblOnNormalDismountFail: TLabel; cbOnNormalDismountFail: TComboBox; cbDefaultMountAs: TComboBox; lblDefaultMountAs: TLabel; cbOnExitWhenMounted: TComboBox; lblOnExitWhenMounted: TLabel; cbOnExitWhenPortableMode: TComboBox; lblOnExitWhenPortableMode: TLabel; ckAllowNewlinesInPasswords: TSDUCheckBox; ckAllowTabsInPasswords: TSDUCheckBox; procedure ControlChanged(Sender: TObject); private protected procedure _ReadSettings(config: TFreeOTFESettings); override; procedure _WriteSettings(config: TFreeOTFESettings); override; public procedure Initialize(); override; procedure EnableDisableControls(); override; end; implementation {$R *.dfm} uses SDUi18n, SDUGeneral, SDUDialogs, CommonSettings, CommonfrmOptions, OTFEFreeOTFEBase_U; const CONTROL_MARGIN_LBL_TO_CONTROL = 5; resourcestring USE_DEFAULT = 'Use default'; procedure TfmeOptions_FreeOTFEAdvanced.ControlChanged(Sender: TObject); begin inherited; EnableDisableControls(); end; procedure TfmeOptions_FreeOTFEAdvanced.EnableDisableControls(); begin inherited; // Do nothing end; procedure TfmeOptions_FreeOTFEAdvanced.Initialize(); const // Vertical spacing between checkboxes, and min horizontal spacing between // checkbox label and the vertical separator line // Set to 6 for now as that looks reasonable. 10 is excessive, 5 is a bit // cramped CHKBOX_CONTROL_MARGIN = 6; // Min horizontal spacing between label and control to the right of it LABEL_CONTROL_MARGIN = 10; // This adjusts the width of a checkbox, and resets it caption so it // autosizes. If it autosizes such that it's too wide, it'll drop the width // and repeat procedure NudgeCheckbox(chkBox: TCheckBox); var tmpCaption: string; maxWidth: integer; useWidth: integer; lastTriedWidth: integer; begin tmpCaption := chkBox.Caption; maxWidth := (pnlVertSplit.left - CHKBOX_CONTROL_MARGIN) - chkBox.Left; useWidth := maxWidth; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; while ( (chkBox.Width > maxWidth) and (lastTriedWidth > 0) ) do begin // 5 used here; just needs to be something sensible to reduce the // width by; 1 would do pretty much just as well useWidth := useWidth - 5; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; end; end; procedure NudgeFocusControl(lbl: TLabel); begin if (lbl.FocusControl <> nil) then begin lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL; end; end; procedure NudgeLabel(lbl: TLabel); var maxWidth: integer; begin if (pnlVertSplit.left > lbl.left) then begin maxWidth := (pnlVertSplit.left - LABEL_CONTROL_MARGIN) - lbl.left; end else begin maxWidth := (lbl.Parent.Width - LABEL_CONTROL_MARGIN) - lbl.left; end; lbl.Width := maxWidth; end; var stlChkBoxOrder: TStringList; YPos: integer; i: integer; currChkBox: TCheckBox; groupboxMargin: integer; begin inherited; SDUCenterControl(gbAdvanced, ccHorizontal); SDUCenterControl(gbAdvanced, ccVertical, 25); // Re-jig label size to take cater for differences in translation lengths // Size so the max. right is flush with the max right of pbLangDetails // lblDragDrop.width := (pbLangDetails.left + pbLangDetails.width) - lblDragDrop.left; // lblMRUMaxItemCount.width := (pbLangDetails.left + pbLangDetails.width) - lblMRUMaxItemCount.left; groupboxMargin := ckAutoStartPortable.left; lblDragDrop.width := (gbAdvanced.width - groupboxMargin) - lblDragDrop.left; lblMRUMaxItemCount.width := (gbAdvanced.width - groupboxMargin) - lblMRUMaxItemCount.left; pnlVertSplit.caption := ''; pnlVertSplit.bevelouter := bvLowered; pnlVertSplit.width := 3; // Here we re-jig the checkboxes so that they are nicely spaced vertically. // This is needed as some language translation require the checkboxes to have // more than one line of text // // !! IMPORTANT !! // When adding a checkbox: // 1) Add it to stlChkBoxOrder below (doesn't matter in which order these // are added) // 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi // TCheckBox // 3) Make sure it's autosize property is TRUE // stlChkBoxOrder:= TStringList.Create(); try // stlChkBoxOrder is used to order the checkboxes in their vertical order; // this allows checkboxes to be added into the list below in *any* order, // and it'll still work stlChkBoxOrder.Sorted := TRUE; stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowMultipleInstances.Top]), ckAllowMultipleInstances); stlChkBoxOrder.AddObject(Format('%.5d', [ckAutoStartPortable.Top]), ckAutoStartPortable); stlChkBoxOrder.AddObject(Format('%.5d', [ckAdvancedMountDlg.Top]), ckAdvancedMountDlg); stlChkBoxOrder.AddObject(Format('%.5d', [ckRevertVolTimestamps.Top]), ckRevertVolTimestamps); stlChkBoxOrder.AddObject(Format('%.5d', [ckWarnBeforeForcedDismount.Top]), ckWarnBeforeForcedDismount); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowNewlinesInPasswords.Top]), ckAllowNewlinesInPasswords); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowTabsInPasswords.Top]), ckAllowTabsInPasswords); currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; for i:=1 to (stlChkBoxOrder.count - 1) do begin currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]); currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN; // Sort out the checkbox's height NudgeCheckbox(currChkBox); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; end; finally stlChkBoxOrder.Free(); end; // Nudge labels so they're as wide as can be allowed NudgeLabel(lblOnExitWhenMounted); NudgeLabel(lblOnExitWhenPortableMode); NudgeLabel(lblOnNormalDismountFail); NudgeLabel(lblDragDrop); NudgeLabel(lblMRUMaxItemCount); NudgeLabel(lblMRUMaxItemCountInst); NudgeLabel(lblDefaultMountAs); // Here we move controls associated with labels, such that they appear // underneath the label // NudgeFocusControl(lblLanguage); NudgeFocusControl(lblDragDrop); // NudgeFocusControl(lblDefaultDriveLetter); // NudgeFocusControl(lblMRUMaxItemCount); end; procedure TfmeOptions_FreeOTFEAdvanced._ReadSettings(config: TFreeOTFESettings); var owem: TOnExitWhenMounted; owrp: TOnExitWhenPortableMode; ondf: TOnNormalDismountFail; ma: TFreeOTFEMountAs; ft: TDragDropFileType; idx: integer; useIdx: integer; begin // Advanced... ckAllowMultipleInstances.checked := config.OptAllowMultipleInstances; ckAutoStartPortable.checked := config.OptAutoStartPortable; ckAdvancedMountDlg.checked := config.OptAdvancedMountDlg; ckRevertVolTimestamps.checked := config.OptRevertVolTimestamps; ckWarnBeforeForcedDismount.checked := config.OptWarnBeforeForcedDismount; ckAllowNewlinesInPasswords.checked := config.OptAllowNewlinesInPasswords; ckAllowTabsInPasswords.checked := config.OptAllowTabsInPasswords; // Populate and set action on exiting when volumes mounted cbOnExitWhenMounted.Items.Clear(); idx := -1; useIdx := -1; for owem:=low(owem) to high(owem) do begin inc(idx); cbOnExitWhenMounted.Items.Add(OnExitWhenMountedTitle(owem)); if (config.OptOnExitWhenMounted = owem) then begin useIdx := idx; end; end; cbOnExitWhenMounted.ItemIndex := useIdx; // Populate and set action on exiting when in portable mode cbOnExitWhenPortableMode.Items.Clear(); idx := -1; useIdx := -1; for owrp:=low(owrp) to high(owrp) do begin inc(idx); cbOnExitWhenPortableMode.Items.Add(OnExitWhenPortableModeTitle(owrp)); if (config.OptOnExitWhenPortableMode = owrp) then begin useIdx := idx; end; end; cbOnExitWhenPortableMode.ItemIndex := useIdx; // Populate and set action when normal dismount fails cbOnNormalDismountFail.Items.Clear(); idx := -1; useIdx := -1; for ondf:=low(ondf) to high(ondf) do begin inc(idx); cbOnNormalDismountFail.Items.Add(OnNormalDismountFailTitle(ondf)); if (config.OptOnNormalDismountFail = ondf) then begin useIdx := idx; end; end; cbOnNormalDismountFail.ItemIndex := useIdx; // Populate and set default mount type cbDefaultMountAs.Items.Clear(); idx := -1; useIdx := -1; for ma:=low(ma) to high(ma) do begin if (ma = fomaUnknown) then begin continue; end; inc(idx); cbDefaultMountAs.Items.Add(FreeOTFEMountAsTitle(ma)); if (config.OptDefaultMountAs = ma) then begin useIdx := idx; end; end; cbDefaultMountAs.ItemIndex := useIdx; // Populate and set drag drop filetype dropdown cbDragDrop.Items.Clear(); idx := -1; useIdx := -1; for ft:=low(ft) to high(ft) do begin inc(idx); cbDragDrop.Items.Add(DragDropFileTypeTitle(ft)); if (config.OptDragDropFileType = ft) then begin useIdx := idx; end; end; cbDragDrop.ItemIndex := useIdx; seMRUMaxItemCount.Value := config.OptMRUList.MaxItems; end; procedure TfmeOptions_FreeOTFEAdvanced._WriteSettings(config: TFreeOTFESettings); var owem: TOnExitWhenMounted; owrp: TOnExitWhenPortableMode; ondf: TOnNormalDismountFail; ma: TFreeOTFEMountAs; ft: TDragDropFileType; begin // Advanced... config.OptAllowMultipleInstances := ckAllowMultipleInstances.checked; config.OptAutoStartPortable := ckAutoStartPortable.checked; config.OptAdvancedMountDlg := ckAdvancedMountDlg.checked; config.OptRevertVolTimestamps := ckRevertVolTimestamps.checked; config.OptWarnBeforeForcedDismount := ckWarnBeforeForcedDismount.checked; config.OptAllowNewlinesInPasswords := ckAllowNewlinesInPasswords.checked; config.OptAllowTabsInPasswords := ckAllowTabsInPasswords.checked; // Decode action on exiting when volumes mounted config.OptOnExitWhenMounted := oewmPromptUser; for owem:=low(owem) to high(owem) do begin if (OnExitWhenMountedTitle(owem) = cbOnExitWhenMounted.Items[cbOnExitWhenMounted.ItemIndex]) then begin config.OptOnExitWhenMounted := owem; break; end; end; // Decode action on exiting when in portable mode config.OptOnExitWhenPortableMode := oewpPromptUser; for owrp:=low(owrp) to high(owrp) do begin if (OnExitWhenPortableModeTitle(owrp) = cbOnExitWhenPortableMode.Items[cbOnExitWhenPortableMode.ItemIndex]) then begin config.OptOnExitWhenPortableMode := owrp; break; end; end; // Decode action when normal dismount fails config.OptOnNormalDismountFail := ondfPromptUser; for ondf:=low(ondf) to high(ondf) do begin if (OnNormalDismountFailTitle(ondf) = cbOnNormalDismountFail.Items[cbOnNormalDismountFail.ItemIndex]) then begin config.OptOnNormalDismountFail := ondf; break; end; end; // Decode default mount type config.OptDefaultMountAs := fomaFixedDisk; for ma:=low(ma) to high(ma) do begin if (FreeOTFEMountAsTitle(ma) = cbDefaultMountAs.Items[cbDefaultMountAs.ItemIndex]) then begin config.OptDefaultMountAs := ma; break; end; end; // Decode drag drop filetype config.OptDragDropFileType := ftPrompt; for ft:=low(ft) to high(ft) do begin if (DragDropFileTypeTitle(ft) = cbDragDrop.Items[cbDragDrop.ItemIndex]) then begin config.OptDragDropFileType := ft; break; end; end; config.OptMRUList.MaxItems := seMRUMaxItemCount.Value; end; END.
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Casbin.Resolve; interface uses Casbin.Types, Casbin.Resolve.Types, System.Generics.Collections, Casbin.Effect.Types, Casbin.Functions.Types; function resolve (const aResolve: TList<string>; const aResolveType: TResolveType; const aAssertions: TList<string>): TDictionary<string, string>; overload; {$REGION 'This function decides whether a policy is relevant to the request. It returnsone of the two options erAllow (means the policy is relevant) or erDeny (the policy is not relevant)'} /// <summary> /// <para> /// This function decides whether a policy is relevant to the request. /// </para> /// <para> /// It returns one of the two options erAllow (means the policy is /// relevant) or erDeny (the policy is not relevant) /// </para> /// </summary> {$ENDREGION} function resolve(const aResolvedRequest, aResolvedPolicy: TDictionary<string, string>; const aFunctions: IFunctions; const aMatcher: string): TEffectResult; overload; implementation uses Casbin.Exception.Types, System.SysUtils, Casbin.Matcher.Types, Casbin.Matcher, Casbin.Core.Utilities, Classes; function resolve (const aResolve: TList<string>; const aResolveType: TResolveType; const aAssertions: TList<string>): TDictionary<string, string>; var i: Integer; index: Integer; request: TEnforceParameters; begin if not Assigned(aAssertions) then raise ECasbinException.Create('Assertions list is nil'); Result:=TDictionary<string, string>.Create; case aResolveType of rtRequest, rtPolicy: begin SetLength(request, aResolve.Count); for i:=0 to aResolve.Count-1 do request[i]:=UpperCase(Trim(aResolve.Items[i])); if (aResolveType=rtRequest) and (Length(request)<>aAssertions.Count) then raise ECasbinException.Create ('The resolve param has more fields than the definition'); for index:=0 to aAssertions.Count-1 do Result.Add(UpperCase(aAssertions.Items[index]), UpperCase(aResolve[index])); end; else raise ECasbinException.Create('Resolve Type not correct'); end; end; function resolve(const aResolvedRequest, aResolvedPolicy: TDictionary<string, string>; const aFunctions: IFunctions; const aMatcher: string): TEffectResult; var matcher: IMatcher; resolvedMatcher: string; item: string; args: string; argsArray: TArray<string>; endArgsPos: Integer; startArgsPos: Integer; startFunPos: Integer; funcResult: Boolean; replaceStr: string; boolReplaceStr: string; i: Integer; begin if not Assigned(aResolvedRequest) then raise ECasbinException.Create('Resolved Request is nil'); if not Assigned(aResolvedPolicy) then raise ECasbinException.Create('Policy Request is nil'); if not Assigned(aFunctions) then raise ECasbinException.Create('Functions are nil'); resolvedMatcher:=UpperCase(Trim(aMatcher)); matcher:=TMatcher.Create; // We replace first the ABAC related terms because a simple call to Replace // does not respect whole words // This assumes ABAC attributes are modeled with two 'dots'. e.g r.obj.owner for item in aResolvedRequest.Keys do begin if item.CountChar('.')=2 then resolvedMatcher:=resolvedMatcher.Replace (UpperCase(item), UpperCase(aResolvedRequest.Items[item]), [rfIgnoreCase, rfReplaceAll]); matcher.addIdentifier(UpperCase(aResolvedRequest.Items[item])); end; for item in aResolvedRequest.Keys do begin if item.CountChar('.')=1 then resolvedMatcher:=resolvedMatcher.Replace (UpperCase(item), UpperCase(aResolvedRequest.Items[item]), [rfIgnoreCase, rfReplaceAll]); matcher.addIdentifier(UpperCase(aResolvedRequest.Items[item])); end; for item in aResolvedPolicy.Keys do begin resolvedMatcher:=resolvedMatcher.Replace (UpperCase(item), UpperCase(aResolvedPolicy.Items[item]), [rfReplaceAll]); matcher.addIdentifier(UpperCase(aResolvedPolicy.Items[item])); end; //Functions for item in aFunctions.list do begin // We need to match individual words // This is a workaround to avoid matching individual characters (eg. 'g') if resolvedMatcher.Contains(UpperCase(item+'(')) or resolvedMatcher.Contains(UpperCase(item+' (')) then begin //We need to find the arguments startFunPos:=resolvedMatcher.IndexOf(UpperCase(item)); startArgsPos:=startFunPos+Length(item)+1; endArgsPos:=resolvedMatcher.IndexOfAny([')'], startArgsPos); args:= Copy(resolvedMatcher, startArgsPos, endArgsPos-startArgsPos+1); argsArray:=args.Split([',']); for i:=0 to Length(argsArray)-1 do begin argsArray[i]:=Trim(argsArray[i]); if argsArray[i][findStartPos]='(' then argsArray[i]:=trim(Copy(argsArray[i],findStartPos+1, Length(argsArray[i]))); if argsArray[i][findEndPos(argsArray[i])]=')' then argsArray[i]:=trim(Copy(argsArray[i], findStartPos, Length(argsArray[i])-1)); end; if (UpperCase(item)='G') or (UpperCase(item)='G2') then funcResult:=aFunctions.retrieveObjFunction(item)(argsArray) else funcResult:=aFunctions.retrieveFunction(item)(argsArray); replaceStr:=UpperCase(item); if args[findStartPos]<>'(' then replaceStr:=replaceStr+'('; replaceStr:=replaceStr+args; if args[findEndPos(args)]<>')' then replaceStr:=replaceStr+')'; if funcResult then boolReplaceStr:='100 = 100' else boolReplaceStr:='100 = 90'; resolvedMatcher:=resolvedMatcher.Replace(replaceStr, boolReplaceStr, [rfReplaceAll]); end; end; // Evaluation Result:=matcher.evaluateMatcher(resolvedMatcher); end; end.
unit ImageForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, PNGImage, PicFile, Head, Menus; type TImageEditor = class(TForm) Panel1: TPanel; Panel2: TPanel; ScrollBar: TScrollBar; Image: TImage; OpenDialog: TOpenDialog; PopupMenu: TPopupMenu; InsertItem: TMenuItem; EditItem: TMenuItem; DeleteItem: TMenuItem; AddItem: TMenuItem; FileNameLabel: TLabel; FileNameEdit: TEdit; OpenBtn: TButton; SaveBtn: TButton; DirectionEdit: TEdit; IntervalEdit: TEdit; IntervalLabel: TLabel; DirectionLabel: TLabel; Panel3: TPanel; DynamicImage: TImage; DynamicCheckBox: TCheckBox; Timer: TTimer; procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OpenBtnClick(Sender: TObject); procedure ScrollBarChange(Sender: TObject); procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SaveBtnClick(Sender: TObject); procedure ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DeleteItemClick(Sender: TObject); procedure InsertItemClick(Sender: TObject); procedure AddItemClick(Sender: TObject); procedure EditItemClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure DynamicCheckBoxClick(Sender: TObject); procedure IntervalEditChange(Sender: TObject); procedure DirectionEditChange(Sender: TObject); private { Private declarations } FBuffer: TBitmap; FNowFirstPicNum: Integer; FIMPImageFile: TIMPImageFile; FLineNum: Integer; FLineWidth: Integer; FSelectedIndex: Integer; PopupSelectedIndex: Integer; TimerCount: Integer; procedure DrawBuffer(); procedure BufferPresent(); procedure DrawSquare(x, y: Integer); procedure ReDraw(); function InsertFrame(idx: Integer): Boolean; function EditFrame(idx: Integer): Boolean; const FLinePicNum: Integer = 10; FLineHeight: Integer = 150; public { Public declarations } Col: Cardinal; BGCol: Cardinal; function GetNowFirstPicNum(): Integer; property nowFirstPicNum: Integer read GetNowFirstPicNum; function GetPicCount(): Integer; property picCount: Integer read GetPicCount; end; implementation uses ImageEdit; {$R *.dfm} procedure TImageEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin FBuffer.Free(); FBuffer := nil; Action := caFree; CImageEditor := False; FIMPImageFile.Free(); FIMPImageFile := nil; Timer.Enabled := False; end; procedure TImageEditor.FormCreate(Sender: TObject); begin FBuffer := TBitmap.Create; FIMPImageFile := TIMPImageFile.Create; Col := clRed; BGCol := clWhite; TimerCount := 0; end; procedure TImageEditor.FormResize(Sender: TObject); begin if FBuffer = nil then exit; Image.Picture.Bitmap.Width := Image.Width; Image.Picture.Bitmap.Height := Image.Height; FBuffer.Width := Image.Width; FBuffer.Height := Image.Height; FLineNum := Image.Height div FLineHeight + 1; FLineWidth := Image.Width div FLinePicNum; ReDraw(); end; procedure TImageEditor.DeleteItemClick(Sender: TObject); begin FIMPImageFile.DeleteFrame(PopupSelectedIndex); ReDraw(); end; procedure TImageEditor.DirectionEditChange(Sender: TObject); begin try FIMPImageFile.directions := StrToInt(DirectionEdit.Text); except end; end; procedure TImageEditor.DrawBuffer(); var I, ix, iy, totalNum: Integer; rect: TRect; const titleHeight = 15; begin ix := 0; iy := 0; totalNum := FLinePicNum * FLineNum + FNowFirstPicNum; if picCount < totalNum then begin totalNum := picCount; end; if FBuffer = nil then exit; FBuffer.Canvas.Brush.Color := BGCol; FBuffer.Canvas.FillRect(FBuffer.Canvas.ClipRect); FBuffer.Canvas.Brush.Style := bsClear; FBuffer.Canvas.Font.Color := Col; FBuffer.Canvas.Font.Size := 10; for I := FNowFirstPicNum to totalNum - 1 do begin rect.Left := ix * FLineWidth; rect.Top := iy * FLineHeight + titleHeight; rect.Right := FLineWidth + rect.Left; rect.Bottom := FLineHeight + rect.Top - titleHeight; FBuffer.Canvas.TextOut(rect.Left, rect.Top - titleHeight, inttostr(I + 1)); FIMPImageFile.StretchDrawFrame(@FBuffer, I, rect); inc(ix); if ix = FLinePicNum then begin ix := 0; inc(iy); end; end; end; procedure TImageEditor.AddItemClick(Sender: TObject); begin if InsertFrame(picCount) then ReDraw(); end; procedure TImageEditor.BufferPresent(); begin if FBuffer = nil then exit; Image.Canvas.CopyRect(Image.Canvas.ClipRect, FBuffer.Canvas, FBuffer.Canvas.ClipRect); end; procedure TImageEditor.DrawSquare(x, y: Integer); var i: Integer; begin for i := 0 to FLineWidth - 1 do begin Image.Canvas.Pixels[x + i, y] := clRed; Image.Canvas.Pixels[x + i, y + FLineHeight] := Col; end; for i := 1 to FLineHeight - 2 do begin Image.Canvas.Pixels[x, y + i] := clRed; Image.Canvas.Pixels[x + FLineWidth, y + i] := Col; end; end; procedure TImageEditor.DynamicCheckBoxClick(Sender: TObject); begin Timer.Enabled := DynamicCheckBox.Checked and (FIMPImageFile.interval > 0); Timer.Interval := FIMPImageFile.interval; end; procedure TImageEditor.EditItemClick(Sender: TObject); begin if EditFrame(PopupSelectedIndex) then ReDraw(); end; procedure TImageEditor.ReDraw; begin DrawBuffer(); BufferPresent(); FSelectedIndex := -1; end; function TImageEditor.InsertFrame(idx: Integer): Boolean; var data: array of Byte; len, count, i: Integer; FH: Cardinal; begin Result := false; OpenDialog.Filter := 'PNG files (*.png)|*.png|All files (*.*)|*.*'; if OpenDialog.Execute() then begin count := 0; for i := 0 to OpenDialog.Files.Count - 1 do begin if FileExists(OpenDialog.Files[i]) then begin FH := FileOpen(OpenDialog.Files[i], fmOpenRead); len := FileSeek(FH, 0, 2); FileSeek(FH, 0, 0); if len <= 0 then begin FIMPImageFile.InsertFrame(idx + count, nil, 0, 0, 0); end else begin SetLength(data, len); FileRead(FH, data[0], len); FIMPImageFile.InsertFrame(idx + count, @data[0], len, 0, 0); end; SetLength(data, 0); FileClose(FH); Inc(count); Result := true; end; end; end; end; function TImageEditor.EditFrame(idx: Integer): Boolean; var ImageEditForm: TImageEditForm; begin ImageEditForm := TImageEditForm.Create(Self); Result := ImageEditForm.doEdit(idx, @FIMPImageFile); ImageEditForm.Free(); end; function TImageEditor.GetNowFirstPicNum(): Integer; begin result := FNowFirstPicNum; end; function TImageEditor.GetPicCount(): Integer; begin if FIMPImageFile <> nil then result := FIMPImageFile.imageCount else result := 0; end; procedure TImageEditor.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var temp: Integer; begin if x >= FLinePicNum * FLineWidth then begin temp := -1; end else begin temp := x div FLineWidth + (y div FLineHeight) * FLinePicNum; if (FIMPImageFile <> nil) and (temp + FNowFirstPicNum >= FIMPImageFile.imageCount) then temp := -1; end; if temp <> FSelectedIndex then begin FSelectedIndex := temp; BufferPresent(); if FSelectedIndex >= 0 then DrawSquare(FSelectedIndex mod FLinePicNum * FLineWidth, FSelectedIndex div FLinePicNum * FLineHeight); end; end; procedure TImageEditor.ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pt: TPoint; begin GetCursorPos(pt); if (FSelectedIndex >= 0) and (Button = mbRight) then begin PopupSelectedIndex := FSelectedIndex + FNowFirstPicNum; PopupMenu.Popup(pt.X, pt.Y); end; end; procedure TImageEditor.InsertItemClick(Sender: TObject); begin if InsertFrame(PopupSelectedIndex) then ReDraw(); end; procedure TImageEditor.IntervalEditChange(Sender: TObject); begin try FIMPImageFile.interval := StrToInt(IntervalEdit.Text); except end; Timer.Enabled := DynamicCheckBox.Checked and (FIMPImageFile.interval > 0); Timer.Interval := FIMPImageFile.interval; end; procedure TImageEditor.OpenBtnClick(Sender: TObject); begin if OpenDialog.Execute() then begin OpenDialog.Filter := 'All files (*.*)|*.*'; if FIMPImageFile.Load(OpenDialog.FileName) then begin FileNameEdit.Text := OpenDialog.FileName; ScrollBar.Max := FIMPImageFile.imageCount div FLinePicNum; ScrollBar.Position := 0; FNowFirstPicNum := 0; DirectionEdit.Text := IntToStr(FIMPImageFile.directions); IntervalEdit.Text := IntToStr(FIMPImageFile.interval); ReDraw(); end; end; end; procedure TImageEditor.SaveBtnClick(Sender: TObject); begin FIMPImageFile.directions := StrToInt(DirectionEdit.Text); FIMPImageFile.interval := StrToInt(IntervalEdit.Text); FIMPImageFile.Save(FileNameEdit.Text); end; procedure TImageEditor.ScrollBarChange(Sender: TObject); begin FNowFirstPicNum := ScrollBar.Position * FLinePicNum; ReDraw(); end; procedure TImageEditor.TimerTimer(Sender: TObject); var bmp: TBitmap; begin if (FIMPImageFile = nil) or (FIMPImageFile.imageCount <= 0) then exit; if TimerCount >= FIMPImageFile.imageCount then TimerCount := 0; bmp := TBitmap.Create(); bmp.Width := DynamicImage.Width; bmp.Height := DynamicImage.Height; bmp.Canvas.Brush.Color := BGCol; bmp.Canvas.Brush.Style := bsSolid; bmp.Canvas.FillRect(bmp.Canvas.ClipRect); FIMPImageFile.DrawFrameWithOffset(@bmp, TimerCount, bmp.Width div 2, bmp.Height div 2); DynamicImage.Canvas.CopyRect(DynamicImage.Canvas.ClipRect, bmp.Canvas, bmp.Canvas.ClipRect); bmp.Free; Inc(TimerCount); end; end.
unit CellFormats; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses SysUtils, Classes, Graphics, BIFFRecsII, ExcelMaskII, Dialogs, XLSFonts, XLSRWIIResourceStrings; const UNFORMATTED = -1; const NUMFORMAT_DATE = 14; const NUMFORMAT_TIME = 20; var TInternalNumberFormats: array[0..49] of string; type TCellProtection = (cpLocked,cpHidden); TCellProtections = set of TCellProtection; type TCellHorizAlignment = (chaGeneral,chaLeft,chaCenter,chaRight,chaFill,chaJustify,chaCenterAcross); type TCellVertAlignment = (cvaTop,cvaCenter,cvaBottom,cvaJustify); type TCellBorderStyle = (cbsNone,cbsThin,cbsMedium,cbsDashed,cbsDotted,cbsThick, cbsDouble,cbsHair,cbsMediumDashed,cbsDashDot,cbsMediumDashDot, cbsDashDotDot,cbsMediumDashDotDot,cbsSlantedDashDot); type TDiagLines = (dlNone,dlDown,dlUp,dlBoth); type TFormatOption = (foWrapText,foShrinkToFit); TFormatOptions = set of TFormatOption; type TCellFormat = class(TCollectionItem) private FName: string; FFontIndex: integer; FNumberFormatIndex: integer; FData1: word; FData2: word; FData3: word; FData4: word; FData5: word; FData6: longword; FData7: word; // The only purpose of this variable is to prevent from corrupt DFM files // on the FillPatternBackColor property. FBackColor: integer; procedure SetIndent(const Value: byte); procedure SetRotation(const Value: smallint); function GetRotation: smallint; function GetFormatOptions: TFormatOptions; function GetHorizAlignment: TCellHorizAlignment; function GetIndent: byte; function GetProtection: TCellProtections; function GetVertAlignment: TCellVertAlignment; procedure SetFFormatOptions(const Value: TFormatOptions); procedure SetHorizAlignment(const Value: TCellHorizAlignment); procedure SetProtection(const Value: TCellProtections); procedure SetVertAlignment(const Value: TCellVertAlignment); function GetMerged: boolean; procedure SetMerged(const Value: boolean); function GetBorderBottomColor: TExcelColor; function GetBorderBottomStyle: TCellBorderStyle; function GetBorderDiagColor: TExcelColor; function GetBorderDiagLines: TDiagLines; function GetBorderDiagStyle: TCellBorderStyle; function GetBorderLeftColor: TExcelColor; function GetBorderLeftStyle: TCellBorderStyle; function GetBorderRightColor: TExcelColor; function GetBorderRightStyle: TCellBorderStyle; function GetBorderTopColor: TExcelColor; function GetBorderTopStyle: TCellBorderStyle; function GetFillPatternBackColor: TExcelColor; function GetFillPatternForeColor: TExcelColor; function GetFillPatternPattern: byte; procedure SetBorderBottomColor(const Value: TExcelColor); procedure SetBorderBottomStyle(const Value: TCellBorderStyle); procedure SetBorderDiagColor(const Value: TExcelColor); procedure SetBorderDiagLines(const Value: TDiagLines); procedure SetBorderDiagStyle(const Value: TCellBorderStyle); procedure SetBorderLeftColor(const Value: TExcelColor); procedure SetBorderLeftStyle(const Value: TCellBorderStyle); procedure SetBorderRightColor(const Value: TExcelColor); procedure SetBorderRightStyle(const Value: TCellBorderStyle); procedure SetBorderTopColor(const Value: TExcelColor); procedure SetBorderTopStyle(const Value: TCellBorderStyle); procedure SetFillPatternBackColor(const Value: TExcelColor); procedure SetFillPatternForeColor(const Value: TExcelColor); procedure SetFillPatternPattern(const Value: byte); function GetWideNumberFormat: WideString; procedure SetWideNumberFormat(const Value: WideString); protected procedure SetName(Value: string); function GetDisplayName: string; override; function GetNumberFormat: string; procedure SetNumberFormat(Value: string); // function GetFont: TXFont; // procedure SetFont(Value: TXFont); procedure ReadFontIndex(Reader: TReader); procedure WriteFontIndex(Writer: TWriter); procedure DefineProperties(Filer: TFiler); override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function FormatIsDateTime: boolean; function Equal(F: TCellFormat): boolean; // ********************************************** // *********** For internal use only. *********** // ********************************************** procedure FromXF8(P: PByteArray); procedure FromXF7(P: PByteArray); procedure FromXF4(P: PByteArray); procedure ToXF8(var P: PByteArray); procedure ToXF7(var P: PByteArray); procedure ToXF4(var P: PByteArray); function GetFontManager: TXFonts; property Merged: boolean read GetMerged write SetMerged; property NumberFormatIndex: integer read FNumberFormatIndex; // ********************************************** // *********** End internal use only. *********** // ********************************************** property WideNumberFormat: WideString read GetWideNumberFormat write SetWideNumberFormat; published property Name: string read FName write SetName; property Protection: TCellProtections read GetProtection write SetProtection; property HorizAlignment: TCellHorizAlignment read GetHorizAlignment write SetHorizAlignment; property VertAlignment: TCellVertAlignment read GetVertAlignment write SetVertAlignment; property Indent: byte read GetIndent write SetIndent; property Rotation: smallint read GetRotation write SetRotation; property FormatOptions: TFormatOptions read GetFormatOptions write SetFFormatOptions; // property Font: TXFont read GetFont write SetFont; property FontIndex: integer read FFontIndex write FFontIndex; property FillPatternForeColor: TExcelColor read GetFillPatternForeColor write SetFillPatternForeColor; property FillPatternBackColor: TExcelColor read GetFillPatternBackColor write SetFillPatternBackColor; property FillPatternPattern: byte read GetFillPatternPattern write SetFillPatternPattern; property NumberFormat: string read GetNumberFormat write SetNumberFormat; property BorderTopColor: TExcelColor read GetBorderTopColor write SetBorderTopColor; property BorderTopStyle: TCellBorderStyle read GetBorderTopStyle write SetBorderTopStyle; property BorderLeftColor: TExcelColor read GetBorderLeftColor write SetBorderLeftColor; property BorderLeftStyle: TCellBorderStyle read GetBorderLeftStyle write SetBorderLeftStyle; property BorderRightColor: TExcelColor read GetBorderRightColor write SetBorderRightColor; property BorderRightStyle: TCellBorderStyle read GetBorderRightStyle write SetBorderRightStyle; property BorderBottomColor: TExcelColor read GetBorderBottomColor write SetBorderBottomColor; property BorderBottomStyle: TCellBorderStyle read GetBorderBottomStyle write SetBorderBottomStyle; property BorderDiagColor: TExcelColor read GetBorderDiagColor write SetBorderDiagColor; property BorderDiagStyle: TCellBorderStyle read GetBorderDiagStyle write SetBorderDiagStyle; property BorderDiagLines: TDiagLines read GetBorderDiagLines write SetBorderDiagLines; end; type TCellFormats = class(TCollection) private function GetFormat(Index: integer): TCellFormat; protected FOwner: TPersistent; FFontManager: TXFonts; FNumberFormats: TStringList; function GetOwner: TPersistent; override; procedure AddStdFormats; public constructor Create(AOwner: TPersistent; FontManager: TXFonts); destructor Destroy; override; procedure Clear; procedure ClearAll; procedure Delete(Index: integer); function Add: TCellFormat; function IndexByName(Name: string): integer; procedure AddNumberFormat(Format: string; Index: integer); procedure AddWideNumberFormat(Format: string; Index: integer); procedure AddNumberFormat40(Format: string); property Items[Index: integer]: TCellFormat read GetFormat; default; property NumberFormats: TStringList read FNumberFormats; end; type TColumnFormat = class(TCollectionItem) private FCol1,FCol2: integer; FWidth: integer; FFormatIndex: integer; FHidden: boolean; FOutlineLevel: integer; FCollapsedOutline: boolean; FUnknownOptionsFlag: boolean; procedure SetCol1(Value: integer); procedure SetCol2(Value: integer); procedure SetWidth(Value: integer); procedure SetFormatIndex(Value: integer); procedure SetOutlineLevel(Value: integer); public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published property Col1: integer read FCol1 write SetCol1; property Col2: integer read FCol2 write SetCol2; property CollapsedOutline: boolean read FCollapsedOutline write FCollapsedOutline; property FormatIndex: integer read FFormatIndex write SetFormatIndex; property Hidden: boolean read FHidden write FHidden; property OutlineLevel: integer read FOutlineLevel write SetOutlineLevel; property Width: integer read FWidth write SetWidth; property UnknownOptionsFlag: boolean read FUnknownOptionsFlag write FUnknownOptionsFlag; end; type TColumnFormats = class(TCollection) private function GetColumnFormat(Index: integer): TColumnFormat; protected FOwner: TPersistent; function GetOwner: TPersistent; override; public constructor Create(AOwner: TPersistent); function Add: TColumnFormat; overload; function Add(Col1,Col2,FormatIndex: integer): TColumnFormat; overload; function ByColumn(Col: integer): TColumnFormat; function ColWidth(Col: integer): integer; property Items[Index: integer]: TColumnFormat read GetColumnFormat; default; end; implementation const DefaultData1 = $0001; DefaultData2 = $0020; DefaultData3 = $0000; DefaultData4 = $0000; DefaultData5 = $2040; DefaultData6 = $00102040; DefaultData7 = $20C0; constructor TCellFormat.Create; begin inherited Create(Collection); FData1 := $0001; FData2 := $0020; FData3 := $0000; FData4 := $0000; FData5 := $2040; FData6 := $00102040; FData7 := $20C0; FNumberFormatIndex := -1; FBackColor := Integer(xcAutomatic); SetName('Format ' + IntToStr(Collection.Count - 1)); end; destructor TCellFormat.Destroy; begin TCellFormats(Collection).FFontManager.RemoveFont(FFontIndex); inherited Destroy; end; { function TCellFormat.GetFont: TXFont; begin FFontIndex := TCellFormats(Collection).FFontManager.GetEditFont(FFontIndex); Result := TCellFormats(Collection).FFontManager[FFontIndex]; end; procedure TCellFormat.SetFont(Value: TXFont); begin FFontIndex := TCellFormats(Collection).FFontManager.GetIndex(Value); end; } function TCellFormat.GetNumberFormat: string; begin if FNumberFormatIndex < 0 then Result := '' else begin Result := TCellFormats(Collection).FNumberFormats[FNumberFormatIndex]; if Result <> '' then begin if Result[1] = #0 then Result := Copy(Result,2,MAXINT) else Result := WideCharLenToString(PWideChar(Copy(Result,2,MAXINT)),(Length(Result)) div 2) end; end end; procedure TCellFormat.SetNumberFormat(Value: string); var Mask: TExcelMask; function XIndexOf(List: TStringList; Value: string): integer; begin for Result := 0 to List.Count - 1 do begin if Length(Value) = Length(List[Result]) then begin if CompareMem(Pointer(List[Result]),Pointer(Value),Length(Value)) then Exit; end; end; Result := -1; end; begin if Value = '' then FNumberFormatIndex := -1 else begin Mask := TExcelMask.Create; try Mask.Mask := Value; finally Mask.Free; end; FNumberFormatIndex := XIndexOf(TCellFormats(Collection).FNumberFormats,#0 + Value); if FNumberFormatIndex < 0 then begin TCellFormats(Collection).FNumberFormats.Add(#0 + Value); FNumberFormatIndex := TCellFormats(Collection).FNumberFormats.Count - 1; end; end; end; function TCellFormat.GetWideNumberFormat: WideString; var S: string; i: integer; begin if FNumberFormatIndex < 0 then Result := '' else begin S := TCellFormats(Collection).FNumberFormats[FNumberFormatIndex]; if S <> '' then begin if S[1] = #0 then begin SetLength(Result,Length(S) - 1); for i := 1 to Length(S) - 1 do Result[i] := WideChar(S[i]); end else Result := Copy(S,2,MAXINT); end else Result := S; end end; procedure TCellFormat.SetWideNumberFormat(const Value: WideString); var S: string; Mask: TExcelMask; begin if Value = '' then FNumberFormatIndex := -1 else begin Mask := TExcelMask.Create; try S := WideCharLenToString(PWideChar(Value),Length(Value)); Mask.Mask := S; finally Mask.Free; end; SetLength(S,Length(Value) * 2); Move(Pointer(Value)^,Pointer(S)^,Length(S)); FNumberFormatIndex := TCellFormats(Collection).FNumberFormats.IndexOf(S); if FNumberFormatIndex < 0 then begin TCellFormats(Collection).FNumberFormats.Add(#1 + S); FNumberFormatIndex := TCellFormats(Collection).FNumberFormats.Count - 1; end; end; end; function TCellFormat.GetDisplayName: string; begin inherited GetDisplayName; Result := FName; end; procedure TCellFormat.SetName(Value: string); begin FName := Value; end; function TCellFormat.FormatIsDateTime: boolean; begin Result := FNumberFormatIndex in [$0E,$14]; end; constructor TCellFormats.Create(AOwner: TPersistent; FontManager: TXFonts); begin inherited Create(TCellFormat); FOwner := AOwner; FFontManager := FontManager; FNumberFormats := TstringList.Create; AddStdFormats; end; destructor TCellFormats.Destroy; begin FNumberFormats.Free; inherited Destroy; end; procedure TCellFormats.AddStdFormats; var i: integer; begin for i := 0 to High(TInternalNumberFormats) do FNumberFormats.Add(#0 + TInternalNumberFormats[i]); end; procedure TCellFormats.Clear; begin ClearAll; Add; end; procedure TCellFormats.ClearAll; begin inherited Clear; FNumberFormats.Clear; AddStdFormats; end; procedure TCellFormats.Delete(Index: integer); begin {$ifndef ver120} inherited Delete(Index); {$endif} if Count < 1 then Add; end; procedure TCellFormats.AddNumberFormat(Format: string; Index: integer); var i: integer; begin for i := FNumberFormats.Count to Index do FNumberFormats.Add(''); FNumberFormats[Index] := #0 + Format; end; procedure TCellFormats.AddWideNumberFormat(Format: string; Index: integer); var i: integer; begin for i := FNumberFormats.Count to Index do FNumberFormats.Add(''); FNumberFormats[Index] := Format; end; procedure TCellFormats.AddNumberFormat40(Format: string); begin if Format = 'General' then Format := '@'; FNumberFormats.Add(#0 + Format); end; function TCellFormats.GetFormat(Index: integer): TCellFormat; begin Result := TCellFormat(inherited Items[Index]); end; function TCellFormats.IndexByName(Name: string): integer; begin Name := Uppercase(Name); for Result := 0 to Count - 1 do begin if Name = Uppercase(TCellFormat(Items[Result]).Name) then Exit; end; Result := -1; end; function TCellFormats.Add: TCellFormat; begin Result := TCellFormat(inherited Add); end; function TCellFormats.GetOwner: TPersistent; begin Result := FOwner; end; procedure TCellFormat.ReadFontIndex(Reader: TReader); begin FFontIndex := Reader.ReadInteger; end; procedure TCellFormat.WriteFontIndex(Writer: TWriter); begin Writer.WriteInteger(FFontIndex); end; procedure TCellFormat.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineProperty('FontIndex', ReadFontIndex, WriteFontIndex,FFontIndex > 0); end; { TColumnFormat } procedure TColumnFormat.Assign(Source: TPersistent); begin if not (Source is TColumnFormat) then raise Exception.Create('Can only assign TColumnFormat'); FCol1 := TColumnFormat(Source).FCol1; FCol2 := TColumnFormat(Source).FCol2; FWidth := TColumnFormat(Source).FWidth; FFormatIndex := TColumnFormat(Source).FFormatIndex; FHidden := TColumnFormat(Source).FHidden; FOutlineLevel := TColumnFormat(Source).FOutlineLevel; FCollapsedOutline := TColumnFormat(Source).FCollapsedOutline; FUnknownOptionsFlag := TColumnFormat(Source).FUnknownOptionsFlag; end; constructor TColumnFormat.Create(Collection: TCollection); begin inherited; FWidth := 2500; end; procedure TColumnFormat.SetCol1(Value: integer); begin if (Value < 0) or (Value > $FFFF) then raise Exception.Create(ersInvalidValue); FCol1 := Value; end; procedure TColumnFormat.SetCol2(Value: integer); begin if (Value < 0) or (Value > $FFFF) then raise Exception.Create(ersInvalidValue); FCol2 := Value; end; procedure TColumnFormat.SetFormatIndex(Value: integer); begin if (Value < 0) or (Value > $FFFF) then raise Exception.Create(ersInvalidValue); FFormatIndex := Value; end; procedure TColumnFormat.SetOutlineLevel(Value: integer); begin if (Value < 0) or (Value > $10) then raise Exception.Create(ersInvalidValue); FOutlineLevel := Value; end; procedure TColumnFormat.SetWidth(Value: integer); begin if (Value < 0) or (Value > $FFFF) then raise Exception.Create(ersInvalidValue); FWidth := Value; end; { TColumnFormats } function TColumnFormats.Add: TColumnFormat; begin Result := TColumnFormat(inherited Add); end; function TColumnFormats.Add(Col1, Col2, FormatIndex: integer): TColumnFormat; begin if (Col1 < 0) or (Col1 > $FFFF) or (Col2 < 0) or (Col2 > $FFFF) or (FormatIndex < 0) or (FormatIndex > $FFFF) then raise Exception.Create(ersInvalidValue); Result := TColumnFormat(inherited Add); Result.Col1 := Col1; Result.Col2 := Col2; Result.FormatIndex := FormatIndex; end; function TColumnFormats.ByColumn(Col: integer): TColumnFormat; var i: integer; begin for i := 0 to Count - 1 do begin if (TColumnFormat(Items[i]).Col1 = Col) and (TColumnFormat(Items[i]).Col2 = Col) then begin Result := TColumnFormat(Items[i]); Exit; end; end; Result := Nil; end; function TColumnFormats.ColWidth(Col: integer): integer; var i: integer; begin for i := 0 to Count - 1 do begin if (Col >= TColumnFormat(Items[i]).Col1) and (Col <= TColumnFormat(Items[i]).Col2) then begin Result := TColumnFormat(Items[i]).Width; Exit; end; end; Result := -1; end; constructor TColumnFormats.Create(AOwner: TPersistent); begin inherited Create(TColumnFormat); FOwner := AOwner; end; function TColumnFormats.GetColumnFormat(Index: integer): TColumnFormat; begin Result := TColumnFormat(inherited Items[Index]); end; function TColumnFormats.GetOwner: TPersistent; begin Result := FOwner; end; function TCellFormat.GetBorderBottomColor: TExcelColor; begin Result := TExcelColor((FData6 and $00003F80) shr 7); end; function TCellFormat.GetBorderBottomStyle: TCellBorderStyle; begin Result := TCellBorderStyle((FData4 and $F000) shr 12); end; function TCellFormat.GetBorderDiagColor: TExcelColor; begin Result := TExcelColor((FData6 and $001FC000) shr 14); end; function TCellFormat.GetBorderDiagLines: TDiagLines; begin Result := TDiagLines((FData5 and $C000) shr 14); end; function TCellFormat.GetBorderDiagStyle: TCellBorderStyle; begin Result := TCellBorderStyle((FData6 and $01E00000) shr 21); end; function TCellFormat.GetBorderLeftColor: TExcelColor; begin Result := TExcelColor((FData5 and $007F) shr 0); end; function TCellFormat.GetBorderLeftStyle: TCellBorderStyle; begin Result := TCellBorderStyle((FData4 and $000F) shr 0); end; function TCellFormat.GetBorderRightColor: TExcelColor; begin Result := TExcelColor((FData5 and $3F80) shr 7); end; function TCellFormat.GetBorderRightStyle: TCellBorderStyle; begin Result := TCellBorderStyle((FData4 and $00F0) shr 4); end; function TCellFormat.GetBorderTopColor: TExcelColor; begin Result := TExcelColor((FData6 and $0000007F) shr 0); end; function TCellFormat.GetBorderTopStyle: TCellBorderStyle; begin Result := TCellBorderStyle((FData4 and $0F00) shr 8); end; function TCellFormat.GetFillPatternBackColor: TExcelColor; begin Result := TExcelColor(FBackColor); if Result > xcAutomatic then Result := xcAutomatic; // Result := TExcelColor(((FData7 and $3F80) shr 7) and $007F); end; function TCellFormat.GetFillPatternForeColor: TExcelColor; begin Result := TExcelColor((FData7 and $007F) shr 0); end; function TCellFormat.GetFillPatternPattern: byte; begin Result := (FData6 and $FC000000) shr 26; end; function TCellFormat.GetFormatOptions: TFormatOptions; begin Result := []; if ((FData2 and $0008) shr 3) > 0 then Result := [foWrapText]; if ((FData3 and $0010) shr 4) > 0 then Result := Result + [foShrinkToFit]; end; function TCellFormat.GetHorizAlignment: TCellHorizAlignment; begin Result := TCellHorizAlignment(FData2 and $0007); end; function TCellFormat.GetIndent: byte; begin Result := FData3 and $000F; end; function TCellFormat.GetMerged: boolean; begin Result := (FData3 and $0020) = $0020; end; function TCellFormat.GetProtection: TCellProtections; begin Result := TCellProtections(Byte(FData1 and $0003)); end; function TCellFormat.GetRotation: smallint; begin Result := FData2 shr 8; if (Result > 90) and (Result <> 255) then Result := -(Result - 90) end; function TCellFormat.GetVertAlignment: TCellVertAlignment; begin Result := TCellVertAlignment((FData2 and $0070) shr 4); end; procedure TCellFormat.SetBorderBottomColor(const Value: TExcelColor); begin FData6 := FData6 and (not $00003F80); FData6 := FData6 + (Longword(Value) shl 7); end; procedure TCellFormat.SetBorderBottomStyle(const Value: TCellBorderStyle); begin FData4 := FData4 and (not $F000); FData4 := FData4 + (Word(Value) shl 12); if (FData4 <> 0) or ((FData6 and $01E00000) <> 0) then FData3 := FData3 or $2000 else FData3 := FData3 and (not $2000); end; procedure TCellFormat.SetBorderDiagColor(const Value: TExcelColor); begin FData6 := FData6 and (not $001FC000); FData6 := FData6 + (Longword(Value) shl 14); end; procedure TCellFormat.SetBorderDiagLines(const Value: TDiagLines); begin FData5 := FData5 and (not $C000); FData5 := FData5 + (Word(Value) shl 14); end; procedure TCellFormat.SetBorderDiagStyle(const Value: TCellBorderStyle); begin FData6 := FData6 and (not $01E00000); FData6 := FData6 + (Longword(Value) shl 21); if (FData4 <> 0) or ((FData6 and $01E00000) <> 0) then FData3 := FData3 or $2000 else FData3 := FData3 and (not $2000); end; procedure TCellFormat.SetBorderLeftColor(const Value: TExcelColor); begin FData5 := FData5 and (not $007F); FData5 := FData5 + (Word(Value) shl 0); end; procedure TCellFormat.SetBorderLeftStyle(const Value: TCellBorderStyle); begin FData4 := FData4 and (not $000F); FData4 := FData4 + (Word(Value) shl 0); if (FData4 <> 0) or ((FData6 and $01E00000) <> 0) then FData3 := FData3 or $2000 else FData3 := FData3 and (not $2000); end; procedure TCellFormat.SetBorderRightColor(const Value: TExcelColor); begin FData5 := FData5 and (not $3F80); FData5 := FData5 + (Word(Value) shl 7); end; procedure TCellFormat.SetBorderRightStyle(const Value: TCellBorderStyle); begin FData4 := FData4 and (not $00F0); FData4 := FData4 + (Word(Value) shl 4); if (FData4 <> 0) or ((FData6 and $01E00000) <> 0) then FData3 := FData3 or $2000 else FData3 := FData3 and (not $2000); end; procedure TCellFormat.SetBorderTopColor(const Value: TExcelColor); begin FData6 := FData6 and (not $0000007F); FData6 := FData6 + (Longword(Value) shl 0); end; procedure TCellFormat.SetBorderTopStyle(const Value: TCellBorderStyle); begin FData4 := FData4 and (not $0F00); FData4 := FData4 + (Word(Value) shl 8); if (FData4 <> 0) or ((FData6 and $01E00000) <> 0) then FData3 := FData3 or $2000 else FData3 := FData3 and (not $2000); end; procedure TCellFormat.SetFFormatOptions(const Value: TFormatOptions); begin FData2 := FData2 and (not ($0008 + $0010 + $0070)); if foWrapText in Value then FData2 := FData2 + $0008; if foShrinkToFit in Value then FData3 := FData3 + $0010; if ((FData2 and $0008) <> 0) or ((FData2 and $0007) <> 0) then FData3 := FData3 or $1000 else FData3 := FData3 and (not $1000); end; procedure TCellFormat.SetFillPatternBackColor(const Value: TExcelColor); begin FBackColor := Integer(Value); FData7 := FData7 and (not $3F80); FData7 := FData7 + (Word(Value) shl 7); if (FData7 and ($007F + $3F80)) <> $2040 then FData3 := FData3 or $4000 else FData3 := FData3 and (not $4000); end; procedure TCellFormat.SetFillPatternForeColor(const Value: TExcelColor); begin FData7 := FData7 and (not $007F); FData7 := FData7 + (Word(Value) shl 0); if (FData7 and ($007F + $3F80)) <> $2040 then FData3 := FData3 or $4000 else FData3 := FData3 and (not $4000); if Value <> xcAutomatic then begin SetFillPatternPattern(1); SetFillPatternBackColor(xcWhite); end; end; procedure TCellFormat.SetFillPatternPattern(const Value: byte); begin FData6 := FData6 and (not $FC000000); FData6 := FData6 + ((Longword(Value) shl 26) and $FC000000); if Value <> 0 then FData3 := FData3 or $4000 else FData3 := FData3 and (not $4000); end; procedure TCellFormat.SetHorizAlignment(const Value: TCellHorizAlignment); begin FData2 := FData2 and (not $0007); FData2 := FData2 + (Word(Value) shl 0); if ((FData2 and $0008) <> 0) or ((FData2 and $0007) <> 0) or ((FData2 and $0070) <> 0) then FData3 := FData3 or $1000 else FData3 := FData3 and (not $1000); end; procedure TCellFormat.SetIndent(const Value: byte); begin FData3 := FData3 and (not $000F); FData3 := FData3 + (Word(Value and $0F) and $000F); end; procedure TCellFormat.SetMerged(const Value: boolean); begin FData3 := FData3 and (not $0020); if Value then FData3 := FData3 + $0020; end; procedure TCellFormat.SetProtection(const Value: TCellProtections); begin FData1 := FData1 and (not $0003); if cpLocked in Value then FData1 := FData1 + $0001; if cpHidden in Value then FData1 := FData1 + $0002; end; procedure TCellFormat.SetRotation(const Value: smallint); var V: byte; begin if Value >= 255 then V := 255 else if Value > 90 then V := 90 else if Value < -90 then V := 180 else if Value < 0 then V := -Value + 90 else V := Value; FData2 := (FData2 and $00FF) + (V shl 8); end; procedure TCellFormat.SetVertAlignment(const Value: TCellVertAlignment); begin FData2 := FData2 and (not $0070); FData2 := FData2 + (Word(Value) shl 4); if ((FData2 and $0008) <> 0) or ((FData2 and $0007) <> 0) or ((FData2 and $0070) <> 0) then FData3 := FData3 or $1000 else FData3 := FData3 and (not $1000); end; procedure TCellFormat.FromXF4(P: PByteArray); function Get4BorderStyle(Value: byte): TCellBorderStyle; begin case Value of 0: Result := cbsNone; 1: Result := cbsThin; 2: Result := cbsMedium; 3: Result := cbsDashed; 4: Result := cbsDotted; 5: Result := cbsThick; 6: Result := cbsDouble; 7: Result := cbsHair; else Result := cbsNone; end; end; begin FData1 := DefaultData1; FData2 := DefaultData2; FData3 := DefaultData3; FData4 := DefaultData4; FData5 := DefaultData5; FData6 := DefaultData6; FData7 := DefaultData7; FFontIndex := PRecXF4(P).FontIndex; if TCellFormats(Collection).FNumberFormats.Count > Length(TInternalNumberFormats) then FNumberFormatIndex := PRecXF4(P).FormatIndex + Length(TInternalNumberFormats) else FNumberFormatIndex := PRecXF4(P).FormatIndex; Protection := []; if (PRecXF4(P).Data1 and $01) = $01 then Protection := Protection + [cpLocked]; if (PRecXF4(P).Data1 and $02) = $02 then Protection := Protection + [cpHidden]; case PRecXF4(P).Data2 and $07 of 0: HorizAlignment := chaGeneral; 1: HorizAlignment := chaLeft; 2: HorizAlignment := chaCenter; 3: HorizAlignment := chaRight; 4: HorizAlignment := chaFill; 5: HorizAlignment := chaJustify; 6: HorizAlignment := chaCenterAcross; end; FormatOptions := []; if (PRecXF4(P).Data2 and $08) = $08 then FormatOptions := [foWrapText]; case (PRecXF4(P).Data2 and $30) shr 4 of 0: VertAlignment := cvaTop; 1: VertAlignment := cvaCenter; 2: VertAlignment := cvaBottom; end; if (PRecXF4(P).UsedAttributes and $20) = $20 then begin FillPatternPattern := PRecXF4(P).CellColor and $003F; FillPatternForeColor := TExcelColor((PRecXF4(P).CellColor and $07C0) shr 6); FillPatternBackColor := TExcelColor((PRecXF4(P).CellColor and $F800) shr 11); end; BorderTopStyle := Get4BorderStyle(PRecXF4(P).TopBorder and $07); BorderLeftStyle := Get4BorderStyle(PRecXF4(P).LeftBorder and $07); BorderBottomStyle := Get4BorderStyle(PRecXF4(P).BottomBorder and $07); BorderRightStyle := Get4BorderStyle(PRecXF4(P).RightBorder and $07); end; procedure TCellFormat.FromXF7(P: PByteArray); begin FData1 := 0; FData2 := 0; FData3 := 0; FData4 := 0; FData5 := 0; FData6 := 0; FData7 := 0; FFontIndex := PRecXF7(P).FontIndex; FNumberFormatIndex := PRecXF7(P).FormatIndex; FData1 := PRecXF7(P).Data1; FData2 := PRecXF7(P).Data2 and $00FF; case (PRecXF7(P).Data2 and $0300) shr 8 of 1: FData2 := FData2 + $FF00; 2: FData2 := FData2 + (90 shl 8); 3: FData2 := FData2 + (180 shl 8); end; FData3 := PRecXF7(P).Data2 and $FC00; FData4 := FData4 + ((PRecXF7(P).Data5 and $0038) shr 3); // Left FData4 := FData4 + ((PRecXF7(P).Data5 and $01C0) shr 2); // Right FData4 := FData4 + ((PRecXF7(P).Data5 and $0007) shl 8); // Top FData4 := FData4 + ((PRecXF7(P).Data4 and $01C0) shl 6); // Bottom FData5 := FData5 + (PRecXF7(P).Data6 and ($007F + $3F80)); FData6 := FData6 + ((PRecXF7(P).Data5 and $FE00) shr 9); FData6 := FData6 + ((PRecXF7(P).Data4 and $FE00) shr 2); FData6 := FData6 + ((PRecXF7(P).Data4 and $003F) shl 26); // Fill pattern FData7 := FData7 + (PRecXF7(P).Data3 and $007F); FData7 := FData7 + (PRecXF7(P).Data3 and $1F80); FData7 := FData7 + ((PRecXF7(P).Data3 and $2000) shl 1); end; procedure TCellFormat.FromXF8(P: PByteArray); begin FFontIndex := PRecXF8(P).FontIndex; FNumberFormatIndex := PRecXF8(P).FormatIndex; FData1 := PRecXF8(P).Data1; FData2 := PRecXF8(P).Data2; FData3 := PRecXF8(P).Data3; FData4 := PRecXF8(P).Data4; FData5 := PRecXF8(P).Data5; FData6 := PRecXF8(P).Data6; FData7 := PRecXF8(P).Data7; FBackColor := ((FData7 and $3F80) shr 7) and $007F; end; procedure TCellFormat.ToXF4(var P: PByteArray); function Get4BorderValue(Value: TCellBorderStyle): byte; begin case Value of cbsNone: Result := 0; cbsThin: Result := 1; cbsMedium: Result := 2; cbsDashed: Result := 3; cbsDotted: Result := 4; cbsThick: Result := 5; cbsDouble: Result := 6; cbsHair: Result := 7; else Result := 0; end; end; begin PRecXF4(P).FontIndex := FFontIndex; if FNumberFormatIndex >= 0 then PRecXF4(P).FormatIndex := FNumberFormatIndex - Length(TInternalNumberFormats) else PRecXF4(P).FormatIndex := 0; PRecXF4(P).Data1 := $0000; if cpLocked in Protection then PRecXF4(P).Data1 := PRecXF4(P).Data1 or $0001; if cpHidden in Protection then PRecXF4(P).Data1 := PRecXF4(P).Data1 or $0002; case HorizAlignment of chaGeneral: PRecXF4(P).Data2 := 0; chaLeft: PRecXF4(P).Data2 := 1; chaCenter: PRecXF4(P).Data2 := 2; chaRight: PRecXF4(P).Data2 := 3; chaFill: PRecXF4(P).Data2 := 4; chaJustify: PRecXF4(P).Data2 := 5; chaCenterAcross: PRecXF4(P).Data2 := 6; else PRecXF4(P).Data2 := 0; end; if foWrapText in FormatOptions then PRecXF4(P).Data2 := PRecXF4(P).Data2 or $0008; case VertAlignment of cvaCenter: PRecXF4(P).Data2 := PRecXF4(P).Data2 or (1 shl 4); cvaBottom: PRecXF4(P).Data2 := PRecXF4(P).Data2 or (2 shl 4); end; PRecXF4(P).UsedAttributes := 0; if FNumberFormatIndex > 0 then PRecXF4(P).UsedAttributes := PRecXF4(P).UsedAttributes or $04; if FFontIndex > 0 then PRecXF4(P).UsedAttributes := PRecXF4(P).UsedAttributes or $08; if (HorizAlignment <> chaGeneral) or (foWrapText in FormatOptions) or (VertAlignment <> cvaBottom) then PRecXF4(P).UsedAttributes := PRecXF4(P).UsedAttributes or $10; if (BorderTopStyle <> cbsNone) or (BorderLeftStyle <> cbsNone) or (BorderBottomStyle <> cbsNone) or (BorderRightStyle <> cbsNone) then PRecXF4(P).UsedAttributes := PRecXF4(P).UsedAttributes or $20; if Protection <> [cpLocked] then PRecXF4(P).UsedAttributes := PRecXF4(P).UsedAttributes or $80; PRecXF4(P).CellColor := $0000; PRecXF4(P).CellColor := FillPatternPattern and $003F; PRecXF4(P).CellColor := (PRecXF4(P).CellColor and $07C0) shl 6; PRecXF4(P).CellColor := (PRecXF4(P).CellColor and $F80) shl 11; PRecXF4(P).TopBorder := Get4BorderValue(BorderTopStyle); PRecXF4(P).LeftBorder := Get4BorderValue(BorderLeftStyle); PRecXF4(P).BottomBorder := Get4BorderValue(BorderBottomStyle); PRecXF4(P).RightBorder := Get4BorderValue(BorderRightStyle); if PRecXF4(P).TopBorder <> 0 then PRecXF4(P).TopBorder := PRecXF4(P).TopBorder or $C0; if PRecXF4(P).LeftBorder <> 0 then PRecXF4(P).LeftBorder := PRecXF4(P).LeftBorder or $C0; if PRecXF4(P).BottomBorder <> 0 then PRecXF4(P).BottomBorder := PRecXF4(P).BottomBorder or $C0; if PRecXF4(P).RightBorder <> 0 then PRecXF4(P).RightBorder := PRecXF4(P).RightBorder or $C0; end; procedure TCellFormat.ToXF7(var P: PByteArray); var V: word; begin FillChar(P^,SizeOf(TRecXF7),#0); with PRecXF7(P)^ do begin FontIndex := FFontIndex; if FNumberFormatIndex >= 0 then FormatIndex := FNumberFormatIndex else FormatIndex := 0; Data1 := FData1; Data2 := FData2 and $00FF; V := FData2 shr 8; if V = $00FF then Data2 := Data2 + $0100 else if V > 135 then Data2 := Data2 + $0300 else if V > 45 then Data2 := Data2 + $0200; Data2 := Data2 + FData3 and $FC00; Data5 := Data5 + ((FData4 shl 3) and $0038); Data5 := Data5 + ((FData4 shl 2) and $01C0); Data5 := Data5 + ((FData4 shr 8) and $0007); Data4 := Data4 + ((FData4 shr 6) and $01C0); Data6 := FData5 and ($007F + $3F80); Data5 := Data5 + ((FData6 shl 9) and $FE00); Data4 := Data4 + ((FData6 shl 2) and $FE00); Data4 := Data4 + ((FData6 shr 26) and $003F); Data3 := Data3 + (FData7 and $007F); Data3 := Data3 + (FData7 and $1F80); Data3 := Data3 + ((FData7 shr 1) and $2000); end; end; procedure TCellFormat.ToXF8(var P: PByteArray); begin PRecXF8(P).FontIndex := FFontIndex; if FNumberFormatIndex >= 0 then PRecXF8(P).FormatIndex := FNumberFormatIndex else PRecXF8(P).FormatIndex := 0; PRecXF8(P).Data1 := FData1; PRecXF8(P).Data2 := FData2; PRecXF8(P).Data3 := FData3; PRecXF8(P).Data4 := FData4; PRecXF8(P).Data5 := FData5; PRecXF8(P).Data6 := FData6; PRecXF8(P).Data7 := FData7; end; function TCellFormat.Equal(F: TCellFormat): boolean; begin Result := (FFontIndex = F.FFontIndex) and (FNumberFormatIndex = F.FNumberFormatIndex) and (FData1 = F.FData1) and (FData2 = F.FData2) and (FData3 = F.FData3) and (FData4 = F.FData4) and (FData5 = F.FData5) and (FData6 = F.FData6) and (FData7 = F.FData7); end; function TCellFormat.GetFontManager: TXFonts; begin Result := TCellFormats(Collection).FFontManager; end; const ExcelStandardFormats: array[0..49] of string = ( {00} '', {01} '0', {02} '0.00', {03} '#,##0', {04} '#,##0.00', {05} '_($#,##0_);($#,##0)', {06} '_($#,##0_);[Red]($#,##0)', {07} '_($#,##0.00_);($#,##0.00)', {08} '_($#,##0.00_);[Red]($#,##0.00)', {09} '0%', {0A} '0.00%', {0B} '0.00E+00', {0C} '# ?/?', {0D} '# ??/??', {0E} 'm/d/yy', // Localized date format in Excel. {0F} 'd-mmm-y', {10} 'd-mmm', {11} 'mmmm-yy', {12} 'h:mm AM/PM', {13} 'h:mm:ss AM/PM', {14} 'h:mm', // Localized time format in Excel. {15} 'h:mm:SS', {16} 'm/d/yy h:mm', {17} // Format $17 - $24 are undocumented. TBD can these formats be stored in the XLS file? {18} '', {19} '', {1A} '', {1B} '', {1C} '', {1D} '', {1E} '', {1F} '', {20} '', {21} '', {22} '', {23} '', {24} '', {25} '', {26} '#,##0_);(#,##0)', {27} '#,##0_);[Red](#,##0)', {28} '#,##0.00_);(#,##0.00)', {29} '#,##0.00_);[Red](#,##0.00)', {2A} '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)', {2B} '_($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)', {2C} '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)', {2D} '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)', {2E} 'mm:ss', {2F} '[h]:mm:ss', {30} 'mm:ss.0', {31} '# #0.0E+0', {32} '@'); var i: integer; initialization for i := 0 to High(ExcelStandardFormats) do TInternalNumberFormats[i] := ExcelStandardFormats[i]; end.
unit ClassDataSet; interface uses System.SysUtils, System.Classes, Datasnap.DBClient, Data.DB, Data.SqlExpr, System.DateUtils, System.Variants, Data.FMTBcd, Vcl.ExtCtrls, Vcl.Graphics, System.JSON.Writers, System.StrUtils; type TFieldTek = class helper for TField public function CampoTipoData: Boolean; function CampoTipoFloat: Boolean; function CampoTipoInteiro: Boolean; function CampoTipoNumerico: Boolean; function CampoTipoString: Boolean; function CampoBoolean: Boolean; end; TDataSetTek = class helper for TDataSet private public // Verificação function EstaEditando: Boolean; // Manipulação procedure EditarDataSet; procedure PostarDataSet; procedure AdicionarCampos(const bVerificarSeJaExiste: Boolean = True); procedure RemoverCampos; procedure ConfigurarProviderFlags(const aChavePrimaria: array of const); end; TSQLDataSetSetTek = class helper for TSQLDataSet public end; TClientDataSetTek = class helper for TClientDataSet private public // Manipulação da estrutura procedure RemoverCampos; overload; procedure CriarCampoFloat(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); deprecated; procedure CriarCampoCurrency(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); procedure CriarCampoFmtBCD(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); procedure CriarCampoData(const sFieldName, sDisplayLabel: string; const iTag: Integer); procedure CriarCampoDataHora(const sFieldName, sDisplayLabel: string; const iTag: Integer); procedure CriarCampoInteiro(const sFieldName, sDisplayLabel: string; const iTag: Integer); procedure CriarCampoString(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); procedure CriarCampoMemo(const sFieldName, sDisplayLabel: string; const iTag: Integer); end; TFuncoesClientDataSet = class public end; implementation uses Constantes; {$region 'TFieldTek'} function TFieldTek.CampoTipoData: Boolean; begin Result := (DataType in [ftDate, ftDateTime, ftTimeStamp]); end; function TFieldTek.CampoTipoFloat: Boolean; begin Result := (DataType in [ftExtended, ftFloat, ftCurrency, ftBCD, ftFMTBcd]); end; function TFieldTek.CampoTipoInteiro: Boolean; begin Result := (DataType in [ftSmallint, ftInteger, ftLargeint, ftAutoInc, ftShortint, ftLongWord, ftWord]); end; function TFieldTek.CampoTipoNumerico: Boolean; begin Result := CampoTipoInteiro or CampoTipoFloat; end; function TFieldTek.CampoTipoString: Boolean; begin Result := (DataType in [ftString, ftWideString, ftMemo, ftWideMemo, ftFixedWideChar, ftFmtMemo]); end; function TFieldTek.CampoBoolean: Boolean; begin Result := (CustomConstraint = sCC_ValueSimNao); end; {$endregion} {$region 'TDataSetTek'} function TDataSetTek.EstaEditando: Boolean; begin Result := (State in [dsInsert, dsEdit]); end; procedure TDataSetTek.EditarDataSet; begin if not Active then Exit; if not(State in [dsInsert, dsEdit]) then Edit; end; procedure TDataSetTek.PostarDataSet; begin if (State in [dsInsert, dsEdit]) then Post; end; procedure TDataSetTek.AdicionarCampos(const bVerificarSeJaExiste: Boolean = True); var X: Integer; begin // Atualizando os tipos dos TFields, conforme tipos dos campos definidos no banco de dados Active := False; FieldDefs.Update; // Criar os TFields inserindo-os no DataSet. for X := 0 to FieldDefs.Count - 1 do if (not bVerificarSeJaExiste) or (FindField(FieldDefs[x].Name) = nil) then FieldDefs.Items[X].CreateField(Self); end; procedure TDataSetTek.RemoverCampos; begin Close; if (FieldCount > 0) then Fields.Clear; if (FieldDefs.Count > 0) then FieldDefs.Clear; end; procedure TDataSetTek.ConfigurarProviderFlags(const aChavePrimaria: array of const); var x, Y: integer; begin for x := 0 to FieldDefList.Count - 1 do begin // Para todos os campos Fields[x].ProviderFlags := [pfInUpdate]; Fields[x].Required := False; // Para as Chaves Primárias for Y := Low(aChavePrimaria) to High(aChavePrimaria) do if (AnsiUpperCase(FieldDefList[x].Name) = AnsiUpperCase(aChavePrimaria[Y].{$IFDEF VER185} VPChar {$ELSE} VPWideChar {$endif})) then begin Fields[x].ProviderFlags := [pfInUpdate, pfInWhere, pfInKey]; Break; end; end; end; {$endregion} {$region 'TClientDataSetTek'} procedure TClientDataSetTek.CriarCampoFmtBCD(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); var Campo: TField; begin Campo := TFMTBCDField.Create(Self); with TFMTBCDField(Campo) do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Precision := 15; Size := iTamanho; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoFloat(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); var Campo: TField; begin Campo := TFloatField.Create(Self); with TFloatField(Campo) do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Precision := iTamanho; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoCurrency(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); var Campo: TField; begin Campo := TCurrencyField.Create(Self); with TCurrencyField(Campo) do begin DisplayLabel := sDisplayLabel; Currency := False; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Precision := iTamanho; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoData(const sFieldName, sDisplayLabel: string; const iTag: Integer); var Campo: TField; begin Campo := TDateField.Create(Self); with Campo do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoDataHora(const sFieldName, sDisplayLabel: string; const iTag: Integer); var Campo: TField; begin Campo := TDateTimeField.Create(Self); with Campo do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoInteiro(const sFieldName, sDisplayLabel: string; const iTag: Integer); var Campo: TField; begin Campo := TIntegerField.Create(Self); with Campo do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoString(const sFieldName, sDisplayLabel: string; const iTamanho, iTag: Integer); var Campo: TField; begin Campo := TStringField.Create(Self); with Campo do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Size := iTamanho; Required := False; Tag := iTag; end; end; procedure TClientDataSetTek.CriarCampoMemo(const sFieldName, sDisplayLabel: string; const iTag: Integer); var Campo: TField; begin Campo := TMemoField.Create(Self); with Campo do begin DisplayLabel := sDisplayLabel; Name := sFieldName; FieldName := sFieldName; FieldKind := fkData; Index := Self.FieldCount; DataSet := Self; Required := False; Tag := iTag; end; end; procedure TClientDataSetTek.RemoverCampos; begin Close; if (FieldCount > 0) then Fields.Clear; if (FieldDefs.Count > 0) then FieldDefs.Clear; end; {$endregion} end.
unit MsXmlBuilder; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses SysUtils, Classes, StringSupport, EncodeSupport, TextUtilities, AdvStreams, AdvVCLStreams, AdvObjects, AdvGenerics, MXML, XmlBuilder, ParserSupport; Type TMsXmlBuilder = class (TXmlBuilder) private FExternal : Boolean; FStack : TAdvList<TMXmlElement>; FDoc : TMXmlDocument; FAttributes : TAdvMap<TMXmlAttribute>; FSourceLocation : TSourceLocation; Function Pad(offset : integer = 0) : String; function ReadTextLength(s : string):String; function ReadTextLengthWithEscapes(pfx, s, sfx : string):String; // procedure WriteMsXml(iElement: IXMLDomElement); // procedure WriteMsXmlNode(iDoc: IXMLDOMNode); // procedure WriteXmlDocument(iDoc: IXMLDocument); // procedure WriteXmlNode(iDoc: IXMLNode; first: boolean); Public Constructor Create; Override; Destructor Destroy; override; Procedure Start(oNode : TMXmlElement); overload; Procedure Start(); overload; override; Procedure StartFragment; override; Procedure Finish; override; Procedure Build(oStream: TStream); Overload; override; Procedure Build(oStream: TAdvStream); Overload; override; Function Build : String; Overload; override; Function SourceLocation : TSourceLocation; override; Procedure Comment(Const sContent : String); override; Procedure AddAttribute(Const sName, sValue : String); override; Procedure AddAttributeNS(Const sNamespace, sName, sValue : String); override; function Tag(Const sName : String) : TSourceLocation; override; function Open(Const sName : String) : TSourceLocation; override; Procedure Close(Const sName : String); override; function Text(Const sValue : String) : TSourceLocation; override; function Entity(Const sValue : String) : TSourceLocation; override; function TagText(Const sName, sValue : String) : TSourceLocation; override; Procedure WriteXml(iElement : TMXmlElement); override; procedure ProcessingInstruction(sName, sText : String); override; procedure DocType(sText : String); override; procedure inject(const bytes : TBytes); override; End; Implementation Uses MsXmlParser, ActiveX, ComObj; { TMsXmlBuilder } function TMsXmlBuilder.SourceLocation: TSourceLocation; begin result.line := 0; result.col := 0; end; procedure TMsXmlBuilder.Start(oNode : TMXmlElement); begin if oNode = nil Then Begin FDoc := TMXmlDocument.create; if CharEncoding <> '' Then FDoc.addC(TMXmlElement.createProcessingInstruction(CharEncoding)); FStack.Add(FDoc.Link); End else FStack.Add(oNode.Link); FSourceLocation.line := 0; FSourceLocation.col := 0; end; procedure TMsXmlBuilder.Build(oStream: TAdvStream); var oVCL : TVCLStream; Begin oVCL := TVCLStream.Create; Try oVCL.Stream := oStream.Link; Build(oVCL); Finally oVCL.Free; End; End; procedure TMsXmlBuilder.Finish; Begin if FStack.Count > 1 Then RaiseError('Close', 'Document is not finished'); FDoc.Free; End; procedure TMsXmlBuilder.inject(const bytes: TBytes); begin raise Exception.Create('Inject is not supported on the MSXml Builder'); end; procedure TMsXmlBuilder.Build(oStream: TStream); Var vAdapter : Variant; b : TBytes; begin assert(FAttributes = nil); assert(not FExternal); b := TEncoding.UTF8.GetBytes(FStack[0].ToXml(true)); oStream.Write(b[0], length(b)); end; {function HasElements(oElem : IXMLDOMElement) : Boolean; var oChild : IXMLDOMNode; Begin Result := False; oChild := oElem.firstChild; While Not result and (oChild <> nil) Do Begin result := oChild.nodeType = NODE_ELEMENT; oChild := oChild.nextSibling; End; End; } function TMsXmlBuilder.Open(const sName: String) : TSourceLocation; var oElem : TMXmlElement; oParent : TMXmlElement; iLoop : integer; len : integer; begin oElem := nil; try if CurrentNamespaces.DefaultNS <> '' Then begin oElem := TMXmlElement.Create(ntElement, sName, CurrentNamespaces.DefaultNS); len := length(sName)+3 end Else begin oElem := TMXmlElement.Create(ntElement, sName); len := length(sName); end; oParent := FStack.Last; if IsPretty and (oParent.NodeType = ntElement) Then oParent.addC(TMXmlElement.createText(ReadTextLength(#13#10+pad))); oParent.addC(oElem); inc(FSourceLocation.col, len+2); for iLoop := 0 to FAttributes.Count - 1 Do oElem.attributes.addAll(FAttributes); FAttributes.Clear; FStack.Add(oElem.Link); result.line := FSourceLocation.line; result.col := FSourceLocation.col; finally oElem.Free; end; end; procedure TMsXmlBuilder.Close(const sName: String); begin if IsPretty Then Begin If FStack.Last.HasChildren Then FStack.Last.addC(TMXmlElement.createText(readTextLength(#13#10+pad(-1)))); End; FStack.Delete(FStack.Count - 1) end; procedure TMsXmlBuilder.AddAttribute(const sName, sValue: String); begin FAttributes.AddOrSetValue(sName, TMXmlAttribute.Create(sValue)); ReadTextLengthWithEscapes(sName+'="', sValue, '"'); end; function TMsXmlBuilder.Text(const sValue: String) : TSourceLocation; begin FStack.Last.addC(TMXmlElement.createText(ReadTextLengthWithEscapes('', sValue, ''))); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; procedure TMsXmlBuilder.WriteXml(iElement: TMXmlElement); begin raise Exception.Create('TMsXmlBuilder.WriteXml not Done Yet'); end; function TMsXmlBuilder.Entity(const sValue: String) : TSourceLocation; begin FStack.Last.addC(TMXmlElement.createText('&'+sValue+';')); inc(FSourceLocation.col, length(sValue)+2); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; function TMsXmlBuilder.Tag(const sName: String) : TSourceLocation; begin Open(sName); Close(sName); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; function TMsXmlBuilder.TagText(const sName, sValue: String) : TSourceLocation; begin result := Open(sName); if (sValue <> '') Then Text(sValue); Close(sName); end; function TMsXmlBuilder.Pad(offset : integer = 0): String; var iLoop : integer; begin Setlength(result, ((FStack.Count - 1) + offset) * 2); For iLoop := 1 to Length(Result) Do result[iLoop] := ' '; end; procedure TMsXmlBuilder.ProcessingInstruction(sName, sText: String); begin raise Exception.Create('Not supported yet'); end; function TMsXmlBuilder.ReadTextLength(s: string): String; var i : integer; begin i := 1; while i <= length(s) do begin if CharInSet(s[i], [#10, #13]) then begin inc(FSourceLocation.line); FSourceLocation.col := 0; if (i < length(s)) and (s[i+1] <> s[i]) and CharInSet(s[i+1], [#10, #13]) then inc(i); end else inc(FSourceLocation.col); inc(i); end; end; function TMsXmlBuilder.ReadTextLengthWithEscapes(pfx, s, sfx: string): String; begin ReadTextLength(pfx); ReadTextLength(EncodeXml(s, xmlText)); ReadTextLength(sfx); end; Procedure TMsXmlBuilder.Comment(Const sContent : String); begin if IsPretty and (FStack.Last.nodeType = ntElement) Then FStack.Last.addC(TMXmlElement.createText(ReadTextLength(#13#10+pad))); FStack.Last.addC(TMXmlElement.createComment(sContent)); ReadTextLength('<!--'+sContent+'-->'); End; function TMsXmlBuilder.Build: String; var oStream : TStringStream; begin oStream := TStringStream.Create(''); Try Build(oStream); Result := oStream.DataString; Finally oStream.Free; End; end; constructor TMsXmlBuilder.Create; begin inherited; CurrentNamespaces.DefaultNS := 'urn:hl7-org:v3'; CharEncoding := 'UTF-8'; FStack := TAdvList<TMXmlElement>.Create; FAttributes := TAdvMap<TMXmlAttribute>.Create; end; destructor TMsXmlBuilder.Destroy; begin FStack.Free; FStack := nil; FAttributes.Free; FAttributes := nil; inherited; end; procedure TMsXmlBuilder.DocType(sText: String); begin raise Exception.Create('Not supported yet'); end; {procedure TMsXmlBuilder.WriteMsXml(iElement: IXMLDomElement); var i : integer; oElem : IXMLDOMElement; begin oElem := FStack[FStack.Count - 1] as IXMLDOMElement; For i := 0 to iELement.childNodes.length - 1 do if (iElement.childNodes[i].nodeType <> NODE_TEXT) or not StringIsWhitespace(iElement.childNodes[i].text) Then oElem.appendChild(iElement.childNodes[i].CloneNode(true)); end; } procedure TMsXmlBuilder.AddAttributeNS(const sNamespace, sName, sValue: String); var attr : TMXmlAttribute; begin attr := TMXmlAttribute.Create(sValue); try attr.NamespaceURI := sNamespace; attr.LocalName := sName; FAttributes.AddOrSetValue(sName, attr.link); finally attr.free; end; ReadTextLengthWithEscapes(sName+'="', sValue, '"'); end; procedure TMsXmlBuilder.Start; begin Start(nil); end; procedure TMsXmlBuilder.StartFragment; begin Start(nil); end; {procedure TMsXmlBuilder.WriteXml(iElement: IXMLNode; first : boolean); begin raise Exception.Create('Not supported yet'); end; procedure TMsXmlBuilder.WriteXmlDocument(iDoc: IXMLDocument); begin raise Exception.Create('Not supported yet'); end; procedure TMsXmlBuilder.WriteMsXmlNode(iDoc: IXMLDOMNode); begin raise Exception.Create('Not supported yet'); end; procedure TMsXmlBuilder.WriteXmlNode(iDoc: IXMLNode; first : boolean); begin raise Exception.Create('Not supported yet'); end; } End.
unit SmtpConfigurationUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SmtpModuleUnit, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls; type TConfigurationForm = class(TForm) GroupBox1: TGroupBox; ServerPortUpDown: TUpDown; ServerPort: TLabeledEdit; ServerSslMode: TComboBox; GroupBox2: TGroupBox; ClientHost: TLabeledEdit; ClientPassword: TLabeledEdit; ClientUserName: TLabeledEdit; ClientPort: TLabeledEdit; ClientPortUpDown: TUpDown; ServerIp: TLabeledEdit; PageControl1: TPageControl; TabSheet1: TTabSheet; ButtonClose: TButton; ButtonApply: TButton; ClientSslMode: TComboBox; TabSheet2: TTabSheet; ServerName: TLabeledEdit; ClientTest: TButton; ServerUserName: TLabeledEdit; ServerPassword: TLabeledEdit; GroupBox3: TGroupBox; GroupBox4: TGroupBox; GroupBox5: TGroupBox; QueueDirectory: TLabeledEdit; SelectFolder: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ButtonApplyClick(Sender: TObject); procedure ClientTestClick(Sender: TObject); procedure TestConnectionClick(Sender: TObject); procedure OnConfigurationChange(Sender: TObject); procedure FormShow(Sender: TObject); private _Modified : Boolean; procedure SetModified(v: Boolean); protected property Modified : Boolean read _Modified write SetModified; procedure LoadSettings(); procedure SaveSettings(); public { Public declarations } end; var ConfigurationForm: TConfigurationForm; implementation uses SmtpTestMailUnit; {$R *.dfm} procedure TConfigurationForm.ButtonApplyClick(Sender: TObject); begin SaveSettings(); end; procedure TConfigurationForm.ClientTestClick(Sender: TObject); var testResult : string; begin with TSmtpTestForm.Create(Self) do try if ShowModal() = mrOk then begin testResult := SmtpModule.TestClient( ClientHost.Text, StrToInt(ClientPort.Text), ClientSslMode.ItemIndex = 1, ClientUserName.Text, ClientPassword.Text, MailFrom.Text, MailTo.Text); if (testResult = 'OK') then begin ShowMessage('Client connection is successful!'); end else begin ShowMessage('Client connection is failed!'); end; end; finally Free; end; end; procedure TConfigurationForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TConfigurationForm.FormShow(Sender: TObject); begin if Visible then LoadSettings(); end; procedure TConfigurationForm.OnConfigurationChange(Sender: TObject); begin Modified := true; end; procedure TConfigurationForm.SetModified(v: Boolean); begin _Modified := v; ButtonApply.Enabled := _Modified; end; procedure TConfigurationForm.TestConnectionClick(Sender: TObject); begin end; // Loads settings to UI procedure TConfigurationForm.LoadSettings(); var s : TSmtpSettings; begin try s := SmtpModule.SmtpSettings; // Read listening server settings ServerName.Text := s.ServiceName; ServerIp.Text := s.ListenIp; ServerPort.Text := IntToStr(s.ListenPort); if s.SslRequired then ServerSslMode.ItemIndex := 1 else ServerSslMode.ItemIndex := 0; ServerUserName.Text := s.Username; ServerPassword.Text := S.Password; // Read remote server settings ClientHost.Text := s.RemoteHost; ClientPort.Text := IntToStr(s.RemotePort); if s.RemoteSslRequired then ClientSslMode.ItemIndex := 1 else ClientSslMode.ItemIndex := 0; ClientUserName.Text := s.RemoteUserName; ClientPassword.Text := s.RemotePassword; finally Modified := false; end; end; // Saves settings from UI procedure TConfigurationForm.SaveSettings(); var s : TSmtpSettings; begin s := TSmtpSettings.Create(); try // Get listening server settings s.SslRequired := ServerSslMode.ItemIndex = 1; s.ListenIp := ServerIp.Text; s.ListenPort := StrToInt(ServerPort.Text); s.Username := ServerUserName.Text; s.Password := ServerPassword.Text; // Get remote server settings s.RemoteSslRequired := ClientSslMode.ItemIndex = 1; s.RemoteHost := ClientHost.Text; s.RemotePort := StrToInt(ClientPort.Text); s.RemoteUserName := ClientUserName.Text; s.RemotePassword := ClientPassword.Text; s.ServiceName := ServerName.Text; // Write settings SmtpModule.SmtpSettings := s; Modified := false; finally s.Free; end; end; end.
{.$include LoadMetadataDemo.inc} unit gmSQLEditor; interface uses Forms, RemoteDB.Client.Dataset, RemoteDB.Client.Database, gmClientDataset, acAST, acUniversalSynProvider, acQBEventMetaProvider, acQBBase, acSQLBuilderPlainText, Vcl.StdCtrls, Vcl.Controls, Vcl.ExtCtrls, System.Classes, Data.DB, System.Contnrs; type TfrmSQLEditor = class(TForm) acSQLBuilderPlainText1: TacSQLBuilderPlainText; MemoSQL: TMemo; acLoadObjectMetadataEventMetadataProvider: TacEventMetadataProvider; Splitter1: TSplitter; Panel1: TPanel; acUniversalSyntaxProvider1: TacUniversalSyntaxProvider; gmDatabase: TgmDatabase; acQueryBuilder1: TacQueryBuilder; Panel2: TPanel; btnConferma: TButton; btnAnnulla: TButton; qTemp: TgmClientDataset; procedure MemoSQLExit(Sender: TObject); procedure acSQLBuilderPlainText1SQLUpdated(Sender: TObject); // 2nd way procedure acLoadObjectMetadataEventMetadataProviderGetTables( Sender: TacBaseMetadataProvider; DatabaseObjects: TSQLDatabaseObjectsList); procedure acLoadObjectMetadataEventMetadataProviderGetTableRelations( Sender: TacBaseMetadataProvider; TableName: TSQLQualifiedName; Relations: TObjectList); procedure acLoadObjectMetadataEventMetadataProviderLoadObjectMetadata( Sender: TacBaseMetadataProvider; ASQLContext: TacBaseSQLContext; AMetadataObject: TacMetadataObject); procedure acLoadObjectMetadataEventMetadataProviderGetSQLFieldNames( Sender: TacBaseMetadataProvider; const ASQL: WideString; AFields: TacFieldsList); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure acQueryBuilder1ObjectMetadataLoading(Sender: TacMetadataContainer; AMetadataObject: TacMetadataObject); procedure btnConfermaClick(Sender: TObject); private procedure DoAddFields(DataSet: TgmClientDataset); procedure CreateFields(Dataset: TgmClientDataset; FieldsList: TStringList); function DoCreateField(Dataset: TgmClientDataset; const FieldName: WideString; Origin: string): TField; procedure VerificaDataset( ds: TgmClientDataset ); public // ADO helpers procedure GetTablesListFromConnection(AConnection: TgmDatabase; ADatabaseObjects: TSQLDatabaseObjectsList); procedure GetObjectFieldsListFromConnection(AConnection: TgmDatabase; AMetadataObject: TacMetadataObject); procedure GetSQLFieldsListFromConnection(AConnection: TgmDatabase; const ASQL: WIdeString; AFieldsList: TacFieldsList); procedure GetTableRelationsFromConnection(AConnection: TgmDatabase; TableName: TSQLQualifiedName; Relations: TObjectList); procedure AggiornaDataset( ds: TgmClientDataset ); end; procedure gmSQLDesignPopulate(ds: TgmClientDataSet; showit:Boolean); implementation {$R *.dfm} uses System.SysUtils, System.Character, Vcl.Dialogs, System.Variants; // Find the name of the owner of a subcomponent function DataSetName(ADataSet: TComponent): string; begin if csSubComponent in ADataSet.ComponentStyle then Result := DataSetName(ADataSet.Owner) else Result := ADataSet.Name; end; // Find the owner of a subcomponent function DataSetOwner(ADataSet: TComponent): TComponent; begin Result := ADataSet.Owner; if csSubComponent in ADataSet.ComponentStyle then Result := DataSetOwner(Result); end; function GenerateName(Dataset: TDataset; FieldName: string; FieldClass: TFieldClass; Number: Integer): string; var Fmt: string; function Alpha(C: Char): Boolean; inline; begin Result := TCharacter.IsLetter(C) or (C = '_'); end; function AlphaNumeric(C: Char): Boolean; inline; begin Result := TCharacter.IsLetterOrDigit(C) or (C = '_'); end; procedure CrunchFieldName; var I: Integer; begin I := 1; while I <= Length(FieldName) do begin if AlphaNumeric(FieldName[I]) then Inc(I) else Delete(FieldName, I, 1); end; end; begin CrunchFieldName; if (FieldName = '') or not Alpha(FieldName[1]) then begin if FieldClass <> nil then FieldName := FieldClass.ClassName + FieldName else FieldName := 'Field' + FieldName; if FieldName[1] = 'T' then Delete(FieldName, 1, 1); CrunchFieldName; end; Fmt := '%s%s%d'; if Number < 2 then Fmt := '%s%s'; Result := Format(Fmt, [DatasetName(DataSet), FieldName, Number]); end; function CreateUniqueName(Dataset: TDataset; const FieldName: string; FieldClass: TFieldClass; Component: TComponent): string; var I: Integer; function IsUnique(const AName: string): Boolean; var I: Integer; begin Result := False; with DataSetOwner(DataSet) do for I := 0 to ComponentCount - 1 do if (Component <> Components[i]) and (CompareText(AName, Components[I].Name) = 0) then Exit; Result := True; end; begin for I := 1 to MaxInt do begin Result := GenerateName(Dataset, FieldName, FieldClass, I); if IsUnique(Result) then Exit; end; end; procedure gmSQLDesignPopulate(ds: TgmClientDataSet; showit:Boolean); var frmSQLEditor: TfrmSQLEditor; res: integer; begin if ds.Database=nil then begin ShowMessage(format('%s: Database non definito!',[ds.Name])); exit; end; frmSQLEditor := TfrmSQLEditor.Create(nil); try // if ds <> nil then frmSQLEditor.Setup(ds, TADNone); frmSQLEditor.gmDatabase.ServerUri := TgmDatabase(ds.Database).ServerUri; frmSQLEditor.MemoSQL.Text := ds.SQL.Text; if showit then res := frmSQLEditor.ShowModal else res := mrCancel; if res=mrOk then begin frmSQLEditor.AggiornaDataset( ds ); // Designer.Modified; end; finally frmSQLEditor.Free; end; end; // ============================================================================= // common part of all methods // ============================================================================= Type TMyDataset = class(TgmClientDataset); procedure TfrmSQLEditor.DoAddFields(DataSet: TgmClientDataset); var I: Integer; FieldName: String; Field: TField; FieldsList: TStringList; oldInDesigning: boolean; begin // CheckFieldAdd; oldInDesigning := (csDesigning in DataSet.ComponentState); if not oldInDesigning then TMyDataset(DataSet).SetDesigning(True); try // DSDesigner.BeginUpdateFieldDefs; DataSet.FieldDefs.Update; finally if not oldInDesigning then TMyDataset(DataSet).SetDesigning(False); // DSDesigner.EndUpdateFieldDefs; end; FieldsList := TStringList.Create; try { Add physical fields not already represented by TField components to the list of available fields } for I := 0 to DataSet.FieldDefList.Count - 1 do with Dataset.FieldDefList[I] do if (FieldClass <> nil) and not (faHiddenCol in Attributes) then begin FieldName := DataSet.FieldDefList.Strings[I]; Field := DataSet.FindField(FieldName); if (Field = nil) or (Field.Owner <> DataSetOwner(DataSet)) then FieldsList.Add(FieldName); end; CreateFields(Dataset,FieldsList); finally FieldsList.Free; end; end; procedure TfrmSQLEditor.CreateFields(Dataset: TgmClientDataset; FieldsList: TStringList); var i: Integer; begin for i := 0 to FieldsList.Count - 1 do DoCreateField(Dataset,FieldsList[I], ''); end; function TfrmSQLEditor.DoCreateField(Dataset: TgmClientDataset; const FieldName: WideString; Origin: string): TField; var FieldDef: TFieldDef; ParentField: TField; SubScript, ShortName, ParentFullName: String; begin FieldDef := Dataset.FieldDefList.FieldByName(FieldName); ParentField := nil; if Dataset.ObjectView then begin if FieldDef.ParentDef <> nil then begin if FieldDef.ParentDef.DataType = ftArray then begin { Strip off the subscript to determine the parent's full name } SubScript := Copy(FieldName, Pos('[', FieldName), MaxInt); ParentFullName := Copy(FieldName, 1, Length(FieldName) - Length(SubScript)); ShortName := FieldDef.ParentDef.Name + SubScript; end else begin if faUnNamed in FieldDef.ParentDef.Attributes then ParentFullName := FieldDef.ParentDef.Name else ParentFullName := ChangeFileExt(FieldName, ''); ShortName := FieldDef.Name; end; ParentField := Dataset.FieldList.Find(ParentFullName); if ParentField = nil then ParentField := DoCreateField(Dataset,ParentFullName, Origin); end else ShortName := FieldDef.Name; end else ShortName := FieldName; Result := FieldDef.CreateField(DataSetOwner(DataSet), ParentField as TObjectField, ShortName, False); try Result.Origin := Origin; Result.Name := CreateUniqueName(Dataset, FieldName, TFieldClass(Result.ClassType), nil); except Result.Free; raise; end; end; procedure TfrmSQLEditor.AggiornaDataset( ds: TgmClientDataset ); var s: TField; begin if MemoSQL.Text<>'' then begin qTemp.UpdateSQL( MemoSQL.Text ); try qTemp.GetAll('1=2'); except on E: Exception do MessageDlg(E.Message,mtWarning,[mbOk],0); end; // -- cancello i TFields del dataset originario che non trovo più nel nuovo // (solo field di dati, no Calculated) for s in ds.Fields do begin if (s.FieldKind=fkData) and (qTemp.FindField(s.FieldName)=nil) then ds.Fields.Remove(s); end; ds.UpdateSQL( MemoSQL.Text ); // ds.GetAll('1=2'); DoAddFields(ds); // -- verifico la chiave primaria sui TFields VerificaDataset(ds); end else begin for s in ds.Fields do ds.Fields.Remove(s); ds.UpdateSQL( MemoSQL.Text ); end; end; procedure TfrmSQLEditor.btnConfermaClick(Sender: TObject); begin // -- ModalResult := mrOk; end; procedure TfrmSQLEditor.VerificaDataset( ds: TgmClientDataset ); var // availableFields:TStringList; // usq:TacUnionSubQuery; // datasourceList:TObjectList; i:integer; // datasource:TacDatasource; // datasourceNameInQuery:WideString; FirstdatasourceNameInQuery:WideString; fieldName:WideString; field:TacMetadataField; qs: TacQueryStatistics; x: integer; begin { usq := acQueryBuilder1.ActiveSubQuery.ActiveUnionSubquery; availableFields := TStringList.Create; datasourceList := TObjectList.Create(false); try } qs := acQueryBuilder1.QueryStatistics; // -- cerco di assegare il tipo di dato ai parametri for i:=0 to ds.Params.Count-1 do begin if ds.Params[i].DataType=ftUnknown then begin for x:=0 to qs.OutputColumns.Count-1 do if qs.OutputColumns[x].ExpressionAlias=ds.Params[i].Name then begin ds.Params[i].DataType := qs.OutputColumns[x].FieldType; end; end; end; for i := 0 to qs.OutputColumns.Count - 1 do begin // -- la tabella della prima colonna è quella aggiornabile !! if i=0 then FirstdatasourceNameInQuery := qs.OutputColumns[i].ObjectName; ds.UpdateTableName := FirstdatasourceNameInQuery; if qs.OutputColumns[i].ExpressionAlias<>'' then fieldName := qs.OutputColumns[i].ExpressionAlias else fieldName := qs.OutputColumns[i].ColumnName; field := qs.OutputColumns[i].MetadataField; if ds.FindField(fieldName)<>nil then begin if (qs.OutputColumns[i].ObjectName=FirstdatasourceNameInQuery) then begin ds.FieldByName(fieldName).Origin := ''; if field.PrimaryKey then ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags + [pfInKey] else ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags - [pfInKey]; if field.IsAutoInc then ds.FieldByName(fieldName).AutoGenerateValue := arAutoInc else ds.FieldByName(fieldName).AutoGenerateValue := arNone; ds.FieldByName(fieldName).Required := not field.Nullable and not field.IsAutoInc; end else begin ds.FieldByName(fieldName).Origin := qs.OutputColumns[i].ObjectName; ds.FieldByName(fieldName).Required := false; ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags - [pfInKey]; ds.FieldByName(fieldName).AutoGenerateValue := arNone; end; end else MessageDlg(format('Colonna %s non trovata nei Fields',[fieldName]),mtWarning,[mbOk],0); end; (* // get list of all datasources usq.FromClause.GetDatasources(datasourceList); for i:=0 to datasourceList.Count-1 do begin datasource:=TacDatasource(datasourceList[i]); datasourceNameInQuery := datasource.DataSourceName; // datasource.NameInQuery; // -- la tabella del primo Datasource è la tabella aggiornabile !! if i=0 then FirstdatasourceNameInQuery := datasourceNameInQuery; for j:=0 to datasource.Fields.Count-1 do begin field:=datasource.Fields[j]; fieldName:=''; { if acQueryBuilder1.UseAltNames and (field.AltName<>'') then fieldName := field.AltNameId.SimpleSQL(acQueryBuilder1.SQLContext.SQLBuilderExpression); } if fieldName='' then fieldName:=field.Name.QualifiedName; availableFields.Add(datasourceNameInQuery+'.'+fieldName); if ds.FindField(fieldName)<>nil then begin if (datasourceNameInQuery=FirstdatasourceNameInQuery) then begin ds.FieldByName(fieldName).Origin := ''; ds.FieldByName(fieldName).Required := not field.Nullable; if field.PrimaryKey then ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags + [pfInKey] else ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags - [pfInKey]; if field.IsAutoInc then ds.FieldByName(fieldName).AutoGenerateValue := arAutoInc else ds.FieldByName(fieldName).AutoGenerateValue := arNone; end else begin ds.FieldByName(fieldName).Origin := datasourceNameInQuery; ds.FieldByName(fieldName).Required := false; ds.FieldByName(fieldName).ProviderFlags := ds.FieldByName(fieldName).ProviderFlags - [pfInKey]; ds.FieldByName(fieldName).AutoGenerateValue := arNone; end; end; end; end; *) // ShowMessage(availableFields.Text); { finally datasourceList.Free; availableFields.Free; end; } end; // parse and load sql into QueryBuilder procedure TfrmSQLEditor.MemoSQLExit(Sender: TObject); begin acQueryBuilder1.SQL := MemoSQL.Text; end; // print generated SQL procedure TfrmSQLEditor.acSQLBuilderPlainText1SQLUpdated(Sender: TObject); begin MemoSQL.Text := acSQLBuilderPlainText1.SQL; end; // helper - loads fields list for given object procedure TfrmSQLEditor.GetObjectFieldsListFromConnection( AConnection: TgmDatabase; AMetadataObject: TacMetadataObject); var DataSet: TgmClientDataSet; // v: Variant; tname: string; pField: TacMetadataField; procedure GetFieldDefinition(Column: TacMetadataField; ADataType: String; ASize, APrecision, AScale: Integer); const vNoSizeTypes : array[0..22] of string = ('bigint', 'bit', 'date', 'datetime', 'float', 'image', 'int', 'money', 'ntext', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'sql_variant', 'sysname', 'text', 'timestamp', 'tinyint', 'uniqueidentifier', 'xml', 'geometry', 'hierarchyid', 'geography'); function NeedSize: Boolean; var I: Integer; begin for i := 0 to high(vNoSizeTypes) do if vNoSizeTypes[I] = ADataType then Exit(false); Result := true; end; begin Column.FieldTypeName := ADataType; ADataType := LowerCase(ADataType); if NeedSize then begin if (ASize = -1) and ( (ADatatype = 'nvarchar') or (ADatatype = 'varbinary') or (ADatatype = 'varchar') ) then begin Column.FieldTypeName := Column.FieldTypeName + '(MAX)'; end else if (ADataType = 'decimal') or (ADataType = 'numeric') then begin Column.FieldTypeName := 'numeric'; Column.Precision := APrecision; Column.Scale := AScale; end else if (ADataType = 'nchar') or (ADataType = 'nvarchar') then begin // Column.Length := APrecision; end else if (ADataType = 'datetime2') or (ADataType = 'datetimeoffset') or (ADataType = 'time') then begin // Just keep the size 0 end else // Column.Length := ASize; end; end; begin // process only tables if AMetadataObject is TacMetadataTable then begin DataSet := TgmClientDataSet.Create(nil); DataSet.Database := AConnection; try tname := AMetadataObject.NameStrNotQuoted; DataSet.UpdateSQL( AConnection.SQLGetColumns ); DataSet.ParamByName('tname').AsString := tname; DataSet.Open; while not DataSet.Eof do begin pField := AMetadataObject.Fields.AddField(DataSet.FieldByName('COLUMN_NAME').AsString); GetFieldDefinition(pField,DataSet.FieldByName('TYPE_NAME').AsString, DataSet.FieldByName('DATA_SIZE').AsInteger, DataSet.FieldByName('DATA_PRECISION').AsInteger, DataSet.FieldByName('SCALE').AsInteger); pField.PrimaryKey := (DataSet.FieldByName('PK').AsString='Y'); pField.Nullable := (DataSet.FieldByName('IS_NULLABLE').AsString='Y'); // (DataSet.FieldByName('IS_NULLABLE').AsInteger=1); pField.IsAutoInc := (DataSet.FieldByName('IS_IDENTITY').AsString='Y'); // (DataSet.FieldByName('IS_IDENTITY').AsInteger=1); DataSet.Next; end; finally DataSet.Free; end; end; end; // helper - loads fields list for given SQL procedure TfrmSQLEditor.GetSQLFieldsListFromConnection(AConnection: TgmDatabase; const ASQL: WIdeString; AFieldsList: TacFieldsList); var DataSet: TgmClientDataSet; i: integer; begin AFieldsList.Clear; DataSet := TgmClientDataSet.Create(nil); DataSet.Database := AConnection; try DataSet.UpdateSQL( ASQL ); // DataSet.MaxRecords := 1; DataSet.FieldDefs.Update; for i := 0 to DataSet.FieldDefs.Count - 1 do begin AFieldsList.Add(DataSet.FieldDefs.Items[i].Name) end; finally DataSet.Free; end; end; procedure TfrmSQLEditor.GetTableRelationsFromConnection( AConnection: TgmDatabase; TableName: TSQLQualifiedName; Relations: TObjectList); var ds: TgmClientDataSet; r: TSQLMetadataRelation; // prevOrd: integer; v: Variant; begin try ds := TgmClientDataSet.Create(nil); ds.Database := AConnection; try ds.UpdateSQL( AConnection.SQLGetRelations ); ds.ParamByName('tname').AsString := TableName.Items[0].Token; ds.Open; for v in ds do begin // creating new relation r := TSQLMetadataRelation.Create(TableName.SQLContext); Relations.Add(r); r.KeyTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.KeyTable.AddName(v.referenced_table); (* if not VarIsNull(v.schema_name) then begin r.KeyTable.AddPrefix(v.schema_name) end; *) r.ChildTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.ChildTable.AddName(v.table_name); (* if not VarIsNull(v.schema_name) then begin r.ChildTable.AddPrefix(v.schema_name); end; *) r.KeyFields.Add(v.referenced_column); r.ChildFields.Add(v.column_name); end; (* if TableName.Count = 1 then begin ADOConnection1.OpenSchema(siForeignKeys, VarArrayOf([Null, Null, TableName.Items[0].Token, Null, Null, Null]), EmptyParam, ds) end else begin ADOConnection1.OpenSchema(siForeignKeys, VarArrayOf([Null, TableName.Items[1].Token, TableName.Items[0].Token, Null, Null, Null]), EmptyParam, ds) end; if not ds.IsEmpty then begin r := nil; prevOrd := MaxInt; ds.Sort := 'FK_TABLE_SCHEMA, FK_TABLE_NAME, FK_NAME, ORDINAL'; ds.First; while not ds.Eof do begin if ds.FieldByName('ORDINAL').AsInteger <= prevOrd then begin // creating new relation r := TSQLMetadataRelation.Create(TableName.SQLContext); Relations.Add(r); r.KeyTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.KeyTable.AddName(ds.FieldByName('PK_TABLE_NAME').AsString); if ds.FieldByName('PK_TABLE_SCHEMA').AsString <> '' then begin r.KeyTable.AddPrefix(ds.FieldByName('PK_TABLE_SCHEMA').AsString) end; r.ChildTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.ChildTable.AddName(ds.FieldByName('FK_TABLE_NAME').AsString); if ds.FieldByName('FK_TABLE_SCHEMA').AsString <> '' then begin r.ChildTable.AddPrefix( ds.FieldByName('FK_TABLE_SCHEMA').AsString) end; end; r.KeyFields.Add(ds.FieldByName('PK_COLUMN_NAME').AsString); r.ChildFields.Add(ds.FieldByName('FK_COLUMN_NAME').AsString); prevOrd := ds.FieldByName('ORDINAL').AsInteger; ds.Next; end; end; if TableName.Count = 1 then begin ADOConnection1.OpenSchema(siForeignKeys, VarArrayOf([Null, Null, Null, Null, Null, TableName.Items[0].Token]), EmptyParam, ds) end else begin ADOConnection1.OpenSchema(siForeignKeys, VarArrayOf([Null, Null, Null, Null, TableName.Items[1].Token, TableName.Items[0].Token]), EmptyParam, ds) end; if not ds.IsEmpty then begin r := nil; prevOrd := MaxInt; ds.Sort := 'FK_TABLE_SCHEMA, PK_TABLE_NAME, FK_NAME, ORDINAL'; ds.First; while not ds.Eof do begin if ds.FieldByName('ORDINAL').AsInteger <= prevOrd then begin // creating new relation r := TSQLMetadataRelation.Create(TableName.SQLContext); Relations.Add(r); r.KeyTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.KeyTable.AddName(ds.FieldByName('PK_TABLE_NAME').AsString); if ds.FieldByName('PK_TABLE_SCHEMA').AsString <> '' then begin r.KeyTable.AddPrefix(ds.FieldByName('PK_TABLE_SCHEMA').AsString) end; r.ChildTable := TSQLDatabaseObject.Create(TableName.SQLContext); r.ChildTable.AddName(ds.FieldByName('FK_TABLE_NAME').AsString); if ds.FieldByName('FK_TABLE_SCHEMA').AsString <> '' then begin r.ChildTable.AddPrefix( ds.FieldByName('FK_TABLE_SCHEMA').AsString) end end; r.KeyFields.Add(ds.FieldByName('PK_COLUMN_NAME').AsString); r.ChildFields.Add(ds.FieldByName('FK_COLUMN_NAME').AsString); prevOrd := ds.FieldByName('ORDINAL').AsInteger; ds.Next; end; *) finally ds.Free; end; except raise; end; end; // helper - loads tables list from connection procedure TfrmSQLEditor.GetTablesListFromConnection(AConnection: TgmDatabase; ADatabaseObjects: TSQLDatabaseObjectsList); var DataSet: TgmClientDataSet; dbobj: TSQLQualifiedName; v: Variant; begin ADatabaseObjects.Clear; DataSet := TgmClientDataSet.Create(nil); DataSet.Database := AConnection; try DataSet.UpdateSQL( AConnection.SQLGetTables ); DataSet.Open; for v in DataSet do // if v.Table_Type='U' then begin dbobj := ADatabaseObjects.CreateSQLDatabaseObject; dbobj.AddName(v.Table_Name); (* if not VarIsNull(v.Table_Schema) then dbobj.AddPrefix(v.Table_Schema); *) end; finally DataSet.Free; end; end; // ============================================================================= // 2nd way with ADO connection // ============================================================================= procedure TfrmSQLEditor.acLoadObjectMetadataEventMetadataProviderGetTables( Sender: TacBaseMetadataProvider; DatabaseObjects: TSQLDatabaseObjectsList); begin DatabaseObjects.Clear; GetTablesListFromConnection(gmDatabase, DatabaseObjects); end; procedure TfrmSQLEditor.acLoadObjectMetadataEventMetadataProviderLoadObjectMetadata( Sender: TacBaseMetadataProvider; ASQLContext: TacBaseSQLContext; AMetadataObject: TacMetadataObject); begin AMetadataObject.Fields.Clear; GetObjectFieldsListFromConnection(gmDatabase, AMetadataObject); end; procedure TfrmSQLEditor.acQueryBuilder1ObjectMetadataLoading( Sender: TacMetadataContainer; AMetadataObject: TacMetadataObject); //var // DataSet: TgmClientDataSet; // v: Variant; // tname: string; begin (* if (AMetadataObject.Name = 'Orders') MetadataFieldList fields = metadataObject.Fields; fields.AddField("Field 1").FieldTypeName = "nvarchar"; fields.AddField("Field 2").FieldTypeName = "int"; fields.Loaded = true; FieldTypeNames[MetadataField.FieldType]; // process only tables if AMetadataObject is TacMetadataTable then begin DataSet := TgmClientDataSet.Create(nil); DataSet.Database := gmDatabase; try tname := AMetadataObject.NameStrNotQuoted; DataSet.UpdateSQL( gmDatabase.SQLGetColumns ); DataSet.ParamByName('tname').AsString := tname; DataSet.Open; for v in DataSet do begin AMetadataObject.Fields.AddField(v.COLUMN_NAME); end; finally DataSet.Free; end; end; *) end; procedure TfrmSQLEditor.acLoadObjectMetadataEventMetadataProviderGetSQLFieldNames( Sender: TacBaseMetadataProvider; const ASQL: WideString; AFields: TacFieldsList); begin // GetSQLFieldsListFromConnection(gmDatabase, ASQL, AFields ); end; procedure TfrmSQLEditor.acLoadObjectMetadataEventMetadataProviderGetTableRelations( Sender: TacBaseMetadataProvider; TableName: TSQLQualifiedName; Relations: TObjectList); begin GetTableRelationsFromConnection(gmDatabase, TableName, Relations); end; procedure TfrmSQLEditor.FormCreate(Sender: TObject); begin // you should also set the offline mode when working without database connection // to prevent retrieval of additional metadata information from the database // acQueryBuilder1.WorkOffline := True; // load metadata container container from XML file or from URL // acQueryBuilder1.MetadataContainer.LoadFromXMLFile('C:\Apps\GestioneFS\Documenti\AQB Schema.xml'); end; procedure TfrmSQLEditor.FormShow(Sender: TObject); begin // valid connection is required for this way gmDatabase.Connected := True; // allow QueryBuilder to make metadata requests acQueryBuilder1.WorkOffline := false; acQueryBuilder1.MetadataProvider := acLoadObjectMetadataEventMetadataProvider; acQueryBuilder1.RefreshMetadata; acQueryBuilder1.SQL := MemoSQL.Text; end; end.
unit UTodasCombinacoesLotoFacil; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, UAposta, UCombinacao, UNumeros, USorteio, UCombinacao.Geracao, UNumerosOcorrencias; type TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Button2: TButton; Button3: TButton; Button4: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private FCombinacoes: TCombinacoes; FSorteios: TSorteios; procedure AssociarSorteio(AGeracao: TCombinacaoGeracao); procedure AssociarCombinacao(AGeracao: TCombinacaoGeracao); published public property Combinacoes: TCombinacoes read FCombinacoes write FCombinacoes; property Sorteios: TSorteios read FSorteios write FSorteios; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AssociarSorteio(AGeracao: TCombinacaoGeracao); var I: Integer; LSorteio: TSorteio; begin for I := 0 to Pred(AGeracao.Combinacoes.Count) do begin if (I < 2000) then begin LSorteio := TSorteio.Create; LSorteio.NumerosSorteio.Assign(AGeracao.Combinacoes[I].NumerosCombinacao); FSorteios.Add(LSorteio); end; end; end; procedure TForm1.AssociarCombinacao(AGeracao: TCombinacaoGeracao); var I: Integer; LCombinacao: TCombinacao; begin for I := 0 to Pred(AGeracao.Combinacoes.Count) do begin LCombinacao := TCombinacao.Create; LCombinacao.NumerosCombinacao.Assign(AGeracao.Combinacoes[I].NumerosCombinacao); FCombinacoes.Add(LCombinacao); end; end; procedure TForm1.Button1Click(Sender: TObject); var LGeracao: TCombinacaoGeracao; begin LGeracao := TCombinacaoGeracao.Create; try LGeracao.Gerar(15); AssociarSorteio(LGeracao); LGeracao.Clear; LGeracao.Gerar(08); AssociarCombinacao(LGeracao); finally FreeAndNil(LGeracao); end; end; procedure TForm1.Button2Click(Sender: TObject); var LOcorrencias: TNumerosOcorrencias; I: Integer; begin LOcorrencias := TNumerosOcorrencias.Create; try for I := 0 to Pred(FSorteios.Count) do LOcorrencias.Ocorrencias(FSorteios[I].NumerosSorteio); ShowMessageFmt('Ocorrencia 01 = %D', [LOcorrencias.Numero01]); finally FreeAndNil(LOcorrencias); end; end; procedure TForm1.Button3Click(Sender: TObject); var I, Y: Integer; begin for I := 0 to Pred(FCombinacoes.Count) do begin for Y := 0 to Pred(FSorteios.Count) do FCombinacoes[I].VerificaOcorrencias(08, FSorteios[Y].NumerosSorteio); end; ShowMessageFmt('%S - %d', [FCombinacoes[0].NumerosCombinacao.ToStr, FCombinacoes[0].Ocorrencias]); end; procedure TForm1.FormCreate(Sender: TObject); begin FCombinacoes := TCombinacoes.Create(); FSorteios := TSorteios.Create(); end; procedure TForm1.FormDestroy(Sender: TObject); begin FreeAndNil(FCombinacoes); FreeAndNil(FSorteios); end; end.
{ ID: a_zaky01 PROG: subset LANG: PASCAL } var n,sum:integer; arr:array[0..39,0..390] of int64; fin,fout:text; function subset(n,sum:integer):int64; begin if sum=0 then subset:=1 else if (sum<0) or (sum>(n*(n+1)) div 2) or (n=0) then subset:=0 else if arr[n,sum]=0 then begin arr[n,sum]:=subset(n-1,sum)+subset(n-1,sum-n); subset:=arr[n,sum]; end else subset:=arr[n,sum]; end; begin assign(fin,'subset.in'); assign(fout,'subset.out'); reset(fin); rewrite(fout); readln(fin,n); sum:=(n*(n+1)) div 2; if sum mod 2=1 then writeln(fout,0) else writeln(fout,subset(n-1,sum div 2)); close(fin); close(fout); end.
{$include kode.inc} unit kode_voice; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_array, kode_list;//, //syn_s2_const; //const // // voice states // voice_state_off = 0; // voice_state_playing = 1; // voice_state_released = 2; type KVoice = class(KListNode) protected FVoiceManager : Pointer; FState : LongInt; public property state : LongInt read FState write FState; property voicemanager : Pointer read FVoiceManager; public constructor create(AManager:Pointer); destructor destroy; override; procedure on_setSampleRate(ARate:Single); virtual; procedure on_noteOn(ANote,AVel:Single); virtual; procedure on_noteOff(ANote,AVel:Single); virtual; procedure on_pitchBend(ABend:Single); virtual; procedure on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); virtual; procedure on_process(outs:PSingle); virtual; end; //--- KVoices = specialize KArray<KVoice>; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses math, kode_const, kode_debug, kode_flags; //---------- constructor KVoice.create(AManager:Pointer); begin inherited create; FVoiceManager := AManager; FState := kvs_off; end; //---------- destructor KVoice.destroy; begin inherited; end; //---------- procedure KVoice.on_setSampleRate(ARate:Single); begin end; procedure KVoice.on_noteOn(ANote,AVel:Single); begin end; procedure KVoice.on_noteOff(ANote,AVel:Single); begin end; procedure KVoice.on_pitchBend(ABend:Single); begin end; procedure KVoice.on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); begin end; procedure KVoice.on_process(outs:PSingle); begin end; //---------------------------------------------------------------------- end.
// Copyright 2018 The Casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Tests.Model; interface uses DUnitX.TestFramework, Casbin.Model.Types, Casbin.Model.Sections.Types; type [TestFixture] TTestModel = class(TObject) private fModel: IModel; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] [TestCase ('Request', 'stRequestDefinition')] [TestCase ('Policy_Definition', 'stPolicyDefinition')] [TestCase ('Effect', 'stPolicyEffect')] [TestCase ('Matcher', 'stMatchers')] procedure testSections (const aSection: TSectionType); [Test] [TestCase ('Request', 'stRequestDefinition')] [TestCase ('Policy_Definition', 'stPolicyDefinition')] [TestCase ('Effect', 'stPolicyEffect')] [TestCase ('Matcher', 'stMatchers')] procedure testAssertions (const aSection: TSectionType); [Test] procedure testEffect; [Test] [TestCase ('Request','r=sub,obj,act#true', '#')] [TestCase ('Policy','p=sub,obj,act#true', '#')] [TestCase ('Effect','e = some(where (p.eft == allow))', '#')] [TestCase ('Matchers','m=r.sub == p.sub && r.obj == p.obj && r.act == p.act#true', '#')] procedure testAssertionExists(const aAssertion: string; const aResult: boolean); [Test] [TestCase ('Request','stRequestDefinition#r#a,b,c', '#')] procedure testAddDefinitionFull(const aSection: TSectionType; const aTag: string; const aAssertion: string); [Test] [TestCase ('Request','stRequestDefinition#r=a,b,c', '#')] procedure testAddDefinitionCompact(const aSection: TSectionType; const aAssertion: string); [Test] procedure testAddWrongAssertionType; [Test] procedure testAddEmptyAssertion; [Test] procedure testAddAssertionString; [Test] procedure testToOutputString; end; implementation uses Casbin.Adapter.Filesystem, Casbin.Model, System.SysUtils, System.Generics.Collections, System.Classes, Casbin.Effect.Types; procedure TTestModel.testAddAssertionString; begin fModel.addDefinition(stRoleDefinition,'g','_,_'); Assert.AreEqual('[request_definition]'+sLineBreak+ 'r=sub,obj,act'+sLineBreak+sLineBreak+ '[policy_definition]'+sLineBreak+ 'p=sub,obj,act'+sLineBreak+sLineBreak+ '[role_definition]'+sLineBreak+ 'g=_,_'+sLineBreak+sLineBreak+ '[policy_effect]'+sLineBreak+ 'e=some(where(p.eft==allow))'+sLineBreak+sLineBreak+ '[matchers]'+sLineBreak+ 'm=r.sub == p.sub && r.obj == p.obj && r.act == p.act', Trim(fModel.toOutputString)); end; procedure TTestModel.testAddDefinitionCompact(const aSection: TSectionType; const aAssertion: string); begin fModel.addDefinition(aSection, aAssertion); Assert.IsTrue(fModel.assertionExists(Trim(aAssertion))); end; procedure TTestModel.testAddDefinitionFull(const aSection: TSectionType; const aTag: string; const aAssertion: string); begin fModel.addDefinition(aSection, aTag, aAssertion); Assert.IsTrue(fModel.assertionExists(Trim(aTag)+'='+Trim(aAssertion))); end; procedure TTestModel.testAddEmptyAssertion; var proc: TProc; begin proc:=procedure begin fModel.addDefinition(stRequestDefinition, ''); end; Assert.WillRaise(proc); end; procedure TTestModel.testAddWrongAssertionType; var proc: TProc; begin proc:=procedure begin fModel.addDefinition(stUnknown, ''); end; Assert.WillRaise(proc); end; procedure TTestModel.Setup; begin fModel:=TModel.Create('..\..\..\Examples\Default\basic_model.conf'); end; procedure TTestModel.TearDown; begin end; procedure TTestModel.testAssertionExists(const aAssertion: string; const aResult: boolean); begin Assert.AreEqual(aResult, fModel.assertionExists(aAssertion)); end; procedure TTestModel.testAssertions(const aSection: TSectionType); var list: TList<string>; begin list:=fModel.assertions(aSection); case aSection of stRequestDefinition: begin Assert.AreEqual(3, list.Count); Assert.AreEqual('r.sub', Trim(list.Items[0])); Assert.AreEqual('r.obj', Trim(list.Items[1])); Assert.AreEqual('r.act', Trim(list.Items[2])); end; stPolicyDefinition: begin Assert.AreEqual(3, list.Count); Assert.AreEqual('p.sub', Trim(list.Items[0])); Assert.AreEqual('p.obj', Trim(list.Items[1])); Assert.AreEqual('p.act', Trim(list.Items[2])); end; stPolicyEffect: begin Assert.AreEqual(1, list.Count); Assert.AreEqual('some(where(p.eft==allow))', Trim(list.Items[0])); end; stMatchers: begin Assert.AreEqual(1, list.Count); Assert.AreEqual('r.sub == p.sub && r.obj == p.obj && r.act == p.act', Trim(list.Items[0])); end; end; end; procedure TTestModel.testEffect; begin Assert.AreEqual(ecSomeAllow, fModel.effectCondition); end; procedure TTestModel.testSections(const aSection: TSectionType); var expected: string; begin case aSection of stRequestDefinition: expected:= 'r=sub,obj,act'; stPolicyDefinition: expected:= 'p=sub,obj,act'; stPolicyEffect: expected:= 'e=some(where(p.eft==allow))'; stMatchers: expected:= 'm=r.sub == p.sub && r.obj == p.obj && r.act == p.act'; end; Assert.AreEqual(trim(expected), Trim(fModel.Section(aSection))); end; procedure TTestModel.testToOutputString; begin Assert.AreEqual('[request_definition]'+sLineBreak+ 'r=sub,obj,act'+sLineBreak+sLineBreak+ '[policy_definition]'+sLineBreak+ 'p=sub,obj,act'+sLineBreak+sLineBreak+ '[policy_effect]'+sLineBreak+ 'e=some(where(p.eft==allow))'+sLineBreak+sLineBreak+ '[matchers]'+sLineBreak+ 'm=r.sub == p.sub && r.obj == p.obj && r.act == p.act', Trim(fModel.toOutputString)); end; initialization TDUnitX.RegisterTestFixture(TTestModel); end.
unit tpAbout; (* Permission is hereby granted, on 1-Nov-2003, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author of original version of this file: Michael Ax *) (* using the about box in tpmenu: you need to manually 'poke' the address of your aboutbox method into tpmenu.aboutbox. see the unit ToolProc.pas which does that, and include it in your project to get the default tpaboutbox when using a tpmenu. *) interface uses SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Windows, UpdateOk, tpAction, utForm, IniLink, UserWin; type TtPackAboutBox = class(TTpAction) private protected public constructor Create(aOwner:TComponent); override; procedure Execute; Override; published end; TtPackAboutBoxForm = class(TtpFitForm) Panel2: TPanel; BitBtn1: TBitBtn; Panel1: TPanel; Panel3: TPanel; ProgramIcon: TImage; ProductName: TLabel; Version: TLabel; Copyright: TLabel; procedure FormCreate(Sender: TObject); private public end; {------------------------------------------------------------------------------} procedure AboutBox; //procedure Register; implementation {------------------------------------------------------------------------------} uses tpmenu; {$R *.DFM} const cShipTime='7/01/96 3:25:00 AM'; // mm/dd/yy {------------------------------------------------------------------------------} procedure TtPackAboutBoxForm.FormCreate(Sender: TObject); begin Version.Caption:='Version '+cShipTime; end; constructor TtPackAboutBox.Create(aOwner:TComponent); begin inherited create(aOwner); end; procedure AboutBox; begin try with TtPackAboutBoxForm.Create(Application) do try ShowHint:=True; ShowModal; finally Free; end; except end; end; procedure TtPackAboutBox.Execute; begin { Create dialog in memory } AboutBox; end; //---------------------------------------------------------------------- //procedure Register; //begin // RegisterComponents('TPACK', [TtPackAboutBox]); //end; //---------------------------------------------------------------------- initialization tpmenu.AboutBoxProc:=AboutBox; finalization // if tpmenu.AboutBoxProc=AboutBox then // tpmenu.AboutBoxProc:=nil; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, Sugar.TestFramework; type QueueTest = public class (Testcase) private Data: Queue<Message>; public method Setup; override; method Contains; method Clear; method Peek; method Enqueue; method Dequeue; method ToArray; method Count; method Enumerator; method ForEach; end; Message = public class public constructor(aData: String; aCode: Integer); method {$IF NOUGAT}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean; override; property Data: String read write; property Code: Integer read write; end; implementation { Message } constructor Message(aData: String; aCode: Integer); begin Data := aData; Code := aCode; end; method Message.{$IF NOUGAT}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean; begin if obj = nil then exit false; if not (obj is Message) then exit false; var Msg := (obj as Message); exit (Data = Msg.Data) and (Code = Msg.Code); end; { QueueTest } method QueueTest.Setup; begin Data := new Queue<Message>; Data.Enqueue(new Message("One", 1)); Data.Enqueue(new Message("Two", 2)); Data.Enqueue(new Message("Three", 3)); end; method QueueTest.Contains; begin Assert.CheckBool(true, Data.Contains(Data.Peek)); Assert.CheckBool(true, Data.Contains(new Message("Two", 2))); Assert.CheckBool(false, Data.Contains(new Message("Two", 3))); Assert.CheckBool(false, Data.Contains(nil)); end; method QueueTest.Clear; begin Assert.CheckInt(3, Data.Count); Data.Clear; Assert.CheckInt(0, Data.Count); end; method QueueTest.Peek; begin Assert.CheckInt(3, Data.Count); var Actual := Data.Peek; Assert.CheckInt(3, Data.Count); Assert.CheckBool(true, new Message("One", 1).Equals(Actual)); Data.Clear; Assert.IsException(->Data.Peek); end; method QueueTest.Enqueue; begin Assert.CheckInt(3, Data.Count); var Msg := new Message("Four", 4); Data.Enqueue(Msg); Assert.CheckInt(4, Data.Count); Assert.CheckBool(true, Data.Contains(Msg)); //must be last Data.Dequeue; Data.Dequeue; Data.Dequeue; Assert.CheckBool(true, Data.Peek.Equals(Msg)); //allow duplicates Data.Enqueue(Msg); Data.Enqueue(Msg); Assert.CheckInt(3, Data.Count); Data.Enqueue(nil); Assert.CheckInt(4, Data.Count); end; method QueueTest.Dequeue; begin var Actual := Data.Dequeue; Assert.IsNotNull(Actual); Assert.CheckBool(true, Actual.Equals(new Message("One", 1))); Assert.CheckInt(2, Data.Count); Actual := Data.Dequeue; Assert.IsNotNull(Actual); Assert.CheckInt(1, Data.Count); Assert.CheckBool(true, Actual.Equals(new Message("Two", 2))); Actual := Data.Dequeue; Assert.IsNotNull(Actual); Assert.CheckInt(0, Data.Count); Assert.CheckBool(true, Actual.Equals(new Message("Three", 3))); Assert.IsException(->Data.Dequeue); Data.Enqueue(nil); Assert.CheckInt(1, Data.Count); Actual := Data.Dequeue; Assert.IsNull(Actual); Assert.CheckInt(0, Data.Count); end; method QueueTest.Count; begin Assert.CheckInt(3, Data.Count); Data.Dequeue; Assert.CheckInt(2, Data.Count); Data.Enqueue(new Message("", 0)); Assert.CheckInt(3, Data.Count); Data.Clear; Assert.CheckInt(0, Data.Count); end; method QueueTest.ToArray; begin var Expected: array of Message := [new Message("One", 1), new Message("Two", 2), new Message("Three", 3)]; var Actual: array of Message := Data.ToArray; Assert.CheckInt(3, length(Actual)); for i: Integer := 0 to length(Expected) - 1 do Assert.CheckBool(true, Expected[i].Equals(Actual[i])); end; method QueueTest.Enumerator; begin var Expected: array of Message := [new Message("One", 1), new Message("Two", 2), new Message("Three", 3)]; var &Index: Integer := 0; for Item: Message in Data do begin Assert.CheckBool(true, Expected[&Index].Equals(Item)); inc(&Index); end; Assert.CheckInt(3, &Index); end; method QueueTest.ForEach; begin var Expected: array of Message := [new Message("One", 1), new Message("Two", 2), new Message("Three", 3)]; var &Index: Integer := 0; Data.ForEach(x -> begin Assert.CheckBool(true, Expected[&Index].Equals(x)); &Index := &Index + 1; end); Assert.CheckInt(3, &Index); end; end.
program test_atomiclevelwidth; {$APPTYPE CONSOLE} {$IFDEF FPC} {$linklib libxrl} {$ENDIF} {$mode objfpc} {$h+} uses xraylib, xrltest, Classes, SysUtils, fpcunit, testreport, testregistry; type TestAtomicLevelWidth = class(TTestCase) private procedure _Test_bad_Z; procedure _Test_bad_shell; procedure _Test_invalid_shell; published procedure Test_Fe_K; procedure Test_U_N7; procedure Test_bad_Z; procedure Test_bad_shell; procedure Test_invalid_shell; end; procedure TestAtomicLevelWidth.Test_Fe_K; var width: double; begin width := AtomicLevelWidth(26, K_SHELL); AssertEquals(1.19E-3, width, 1E-6); end; procedure TestAtomicLevelWidth.Test_U_N7; var width: double; begin width := AtomicLevelWidth(92, N7_SHELL); AssertEquals(0.31E-3, width, 1E-6); end; procedure TestAtomicLevelWidth._Test_bad_Z; var width: double; begin width := AtomicLevelWidth(185, N7_SHELL); end; procedure TestAtomicLevelWidth._Test_bad_shell; var width: double; begin width := AtomicLevelWidth(185, -5); end; procedure TestAtomicLevelWidth._Test_invalid_shell; var width: double; begin width := AtomicLevelWidth(23, N3_SHELL); end; procedure TestAtomicLevelWidth.Test_bad_Z; begin AssertException(EArgumentException, @_Test_bad_Z); end; procedure TestAtomicLevelWidth.Test_bad_shell; begin AssertException(EArgumentException, @_Test_bad_shell); end; procedure TestAtomicLevelWidth.Test_invalid_shell; begin AssertException(EArgumentException, @_Test_invalid_shell); end; var App: TestRunner; begin RegisterTest(TestAtomicLevelWidth); App := TestRunner.Create(nil); App.Initialize; App.Run; App.Free; end.
unit xxmPReg; interface uses Windows, SysUtils, xxm; type TXxmProjectCacheEntry=class(TObject) private FName,FFilePath,FCookiePath:WideString; FProject:IXxmProject; FHandle:THandle; FSignature,FUserName:string; FCookies:array of record Name,Value:WideString; //TODO: expiry, domain, path... end; FContextCount:integer; procedure GetRegisteredPath; function GetModulePath:WideString; function GetProject:IXxmProject; procedure SetSignature(const Value: string); published constructor Create(Name:WideString); public LastCheck:cardinal; procedure Release; destructor Destroy; override; procedure OpenContext; procedure CloseContext; procedure GetFilePath(Address:WideString;var Path,MimeType:WideString); function GetSessionCookie(Name: WideString): WideString; procedure SetSessionCookie(Name: WideString; Value: WideString); property Name:WideString read FName; property Project:IXxmProject read GetProject; property ModulePath:WideString read GetModulePath; property Signature:string read FSignature write SetSignature; function CookieFile(Name:string):string; end; TXxmProjectCache=class(TObject) private FLock:TRTLCriticalSection; ProjectCacheSize:integer; ProjectCache:array of TXxmProjectCacheEntry; procedure ClearAll; function Grow:integer; function FindProject(Name:WideString):integer; public constructor Create; destructor Destroy; override; function GetProject(Name:WideString):TXxmProjectCacheEntry; procedure ReleaseProject(Name:WideString); end; TXxmAutoBuildHandler=function(pce:TXxmProjectCacheEntry; Context:IXxmContext; ProjectName:WideString):boolean; EXxmProjectNotFound=class(Exception); EXxmModuleNotFound=class(Exception); EXxmProjectLoadFailed=class(Exception); var XxmProjectCache:TXxmProjectCache; XxmAutoBuildHandler:TXxmAutoBuildHandler; procedure XxmProjectRegister( hwnd:HWND; // handle to owner window hinst:cardinal; // instance handle for the DLL lpCmdLine:LPTSTR; // string the DLL will parse nCmdShow:integer // show state ); stdcall; exports XxmProjectRegister; implementation uses Registry; const //resourcestring? SXxmProjectNotFound='xxm Project "__" not defined.'; SXxmModuleNotFound='xxm Module "__" does not exist.'; SXxmProjectLoadFailed='xxm Project load "__" failed.'; procedure XxmProjectRegister( hwnd:HWND; // handle to owner window hinst:cardinal; // instance handle for the DLL lpCmdLine:LPTSTR; // string the DLL will parse nCmdShow:integer // show state ); stdcall; var r:TRegistry; s,t:string; i,j:integer; begin s:=lpCmdLine; i:=Length(s); while not(i=0) and not(s[i]='.') do dec(i); j:=i; while not(j=0) and not(s[j]='\') do dec(j); inc(j); t:=Copy(s,j,i-j); r:=TRegistry.Create; try //r.RootKey:=HKEY_LOCAL_MACHINE;//setting? r.RootKey:=HKEY_CURRENT_USER; r.OpenKey('\Software\xxm\local\'+t,true); r.WriteString('',s); //TODO: default settings? finally r.Free; end; MessageBox(GetDesktopWindow,PChar('Project "'+t+'" registered.'), 'xxm Local Handler',MB_OK or MB_ICONINFORMATION); end; { TXxmProjectCacheEntry } constructor TXxmProjectCacheEntry.Create(Name: WideString); begin inherited Create; FName:=LowerCase(Name);//lowercase here! FFilePath:=''; FProject:=nil; FHandle:=0; FUserName:=''; LastCheck:=GetTickCount-100000; FContextCount:=0; end; destructor TXxmProjectCacheEntry.Destroy; begin Release; inherited; end; function TXxmProjectCacheEntry.GetProject: IXxmProject; var lp:TXxmProjectLoadProc; begin if FProject=nil then begin if (FFilePath='') or (FileExists(FFilePath)) then GetRegisteredPath;//refresh if not(FileExists(FFilePath)) then raise EXxmModuleNotFound.Create(StringReplace( SXxmModuleNotFound,'__',FFilePath,[])); FHandle:=LoadLibraryW(PWideChar(FFilePath)); //TODO: see if DisableThreadLibraryCalls applies if FHandle=0 then RaiseLastOSError; @lp:=GetProcAddress(FHandle,'XxmProjectLoad'); if @lp=nil then RaiseLastOSError; FProject:=lp(Name);//try? if FProject=nil then begin FFilePath:='';//force refresh next time raise EXxmProjectLoadFailed.Create(StringReplace( SXxmProjectLoadFailed,'__',FFilePath,[])); end; end; Result:=FProject; end; procedure TXxmProjectCacheEntry.Release; begin //attention: deadlock danger, use OpenContext,CloseContext //XxmAutoBuildHandler should lock new requests while (FContextCount>0) do Sleep(1); //finalization gets called on last loaded libraries first, //so FProject release may fail on finalization try FProject:=nil; except pointer(FProject):=nil; end; if not(FHandle=0) then begin FreeLibrary(FHandle); FHandle:=0; FContextCount:=0; end; end; procedure TXxmProjectCacheEntry.GetFilePath(Address:WideString; var Path, MimeType: WideString); var rf,sf,s:string; i,j,l:integer; r:TRegistry; begin //TODO: widestring all the way? //TODO: virtual directories? rf:=FFilePath; i:=Length(rf); while not(i=0) and not(rf[i]=PathDelim) do dec(i); SetLength(rf,i); sf:=''; i:=1; l:=Length(Address); while (i<=l) do begin j:=i; while (j<=l) and not(char(Address[j]) in ['/','\']) do inc(j); s:=Copy(Address,i,j-i); i:=j+1; if (s='') or (s='.') then begin //nothing end else if (s='..') then begin //try to go back, but not into rf (raise?) j:=Length(sf)-1; while (j>0) and not(sf[j]=PathDelim) do dec(j); SetLength(sf,j); end else begin sf:=sf+s+PathDelim; //DirectoryExists()?? end; end; Path:=rf+Copy(sf,1,Length(sf)-1); i:=Length(sf)-1; while (i>0) and not(sf[i]='.') do dec(i); s:=LowerCase(copy(sf,i,Length(sf)-i)); //TODO: get from settings or list? or project? r:=TRegistry.Create; try r.RootKey:=HKEY_CLASSES_ROOT; if r.OpenKeyReadOnly(s) and r.ValueExists('Content Type') then MimeType:=r.ReadString('Content Type') else if (s='.log') then //override default for a few known types MimeType:='text/plain' else MimeType:='application/octet-stream'; finally r.Free; end; end; function TXxmProjectCacheEntry.GetSessionCookie(Name: WideString): WideString; var i:integer; begin i:=0; while (i<Length(FCookies)) and not(FCookies[i].Name=Name) do inc(i);//case? if (i<Length(FCookies)) then Result:=FCookies[i].Value else Result:=''; end; procedure TXxmProjectCacheEntry.SetSessionCookie(Name, Value: WideString); var i:integer; begin i:=0; while (i<Length(FCookies)) and not(FCookies[i].Name=Name) do inc(i);//case? if (i<Length(FCookies)) then FCookies[i].Value:=Value else begin SetLength(FCookies,i+1); FCookies[i].Name:=Name; FCookies[i].Value:=Value; end; end; function TXxmProjectCacheEntry.CookieFile(Name: string): string; var l:cardinal; begin if FUserName='' then begin l:=1024; SetLength(FUserName,l); if GetUserName(PChar(FUserName),l) then SetLength(FUserName,l-1) else FUserName:=GetEnvironmentVariable('USERNAME'); end; //TODO: filenamesafe? Result:=FCookiePath+FUserName+'_'+Name+'.txt'; end; procedure TXxmProjectCacheEntry.SetSignature(const Value: string); var r:TRegistry; k:string; begin FSignature:=Value; k:='\Software\xxm\local\'+FName; r:=TRegistry.Create; try r.RootKey:=HKEY_CURRENT_USER; if not(r.OpenKey(k,false)) then begin r.RootKey:=HKEY_LOCAL_MACHINE; if not(r.OpenKey(k,false)) then raise EXxmProjectNotFound.Create(StringReplace( SXxmProjectNotFound,'__',FName,[])); end; r.WriteString('Signature',FSignature); finally r.Free; end; end; procedure TXxmProjectCacheEntry.GetRegisteredPath; var r:TRegistry; k:string; i:integer; begin k:='\Software\xxm\local\'+FName; r:=TRegistry.Create; try r.RootKey:=HKEY_CURRENT_USER; if r.OpenKeyReadOnly(k) then FFilePath:=r.ReadString('') else begin r.RootKey:=HKEY_LOCAL_MACHINE; if r.OpenKeyReadOnly(k) then FFilePath:=r.ReadString('') else FFilePath:=''; end; if FFilePath='' then raise EXxmProjectNotFound.Create(StringReplace( SXxmProjectNotFound,'__',FName,[])); //TODO: alias? (see xxm.xml) //TODO: extra flags,settings? //TODO: from setting? i:=Length(FFilePath); while not(i=0) and not(FFilePath[i]=PathDelim) do dec(i); FCookiePath:=Copy(FFilePath,1,i); if r.ValueExists('Signature') then FSignature:=r.ReadString('Signature') else FSignature:=''; finally r.Free; end; end; function TXxmProjectCacheEntry.GetModulePath: WideString; begin if FFilePath='' then GetRegisteredPath; Result:=FFilePath; end; procedure TXxmProjectCacheEntry.OpenContext; begin InterlockedIncrement(FContextCount); end; procedure TXxmProjectCacheEntry.CloseContext; begin InterlockedDecrement(FContextCount); end; { TXxmProjectCache } constructor TXxmProjectCache.Create; begin inherited; ProjectCacheSize:=0; InitializeCriticalSection(FLock); end; destructor TXxmProjectCache.Destroy; begin ClearAll; DeleteCriticalSection(FLock); inherited; end; function TXxmProjectCache.Grow: integer; var i:integer; begin i:=ProjectCacheSize; Result:=i; inc(ProjectCacheSize,16);//const growstep SetLength(ProjectCache,ProjectCacheSize); while (i<ProjectCacheSize) do begin ProjectCache[i]:=nil; inc(i); end; end; function TXxmProjectCache.FindProject(Name: WideString): integer; var l:string; begin Result:=0; l:=LowerCase(Name); //assert cache stores ProjectName already LowerCase! while (Result<ProjectCacheSize) and ( (ProjectCache[Result]=nil) or not(ProjectCache[Result].Name=l)) do inc(Result); if Result=ProjectCacheSize then Result:=-1; end; function TXxmProjectCache.GetProject(Name: WideString): TXxmProjectCacheEntry; var i:integer; begin EnterCriticalSection(FLock); try i:=FindProject(Name); if i=-1 then begin Result:=TXxmProjectCacheEntry.Create(Name); //add to cache i:=0; while (i<ProjectCacheSize) and not(ProjectCache[i]=nil) do inc(i); if (i=ProjectCacheSize) then i:=Grow; ProjectCache[i]:=Result; end else Result:=ProjectCache[i]; finally LeaveCriticalSection(FLock); end; end; procedure TXxmProjectCache.ReleaseProject(Name: WideString); var i:integer; begin i:=FindProject(Name); //if i=-1 then raise? if not(i=-1) then FreeAndNil(ProjectCache[i]); end; procedure TXxmProjectCache.ClearAll; var i:integer; begin for i:=0 to ProjectCacheSize-1 do try FreeAndNil(ProjectCache[i]); except //silent end; SetLength(ProjectCache,0); ProjectCacheSize:=0; end; initialization XxmProjectCache:=nil;//TXxmProjectCache.Create;//see Handler.Start finalization FreeAndNil(XxmProjectCache); end.
{ Realizar un programa que lea información de 200 productos de un supermercado. De cada producto se lee código y precio (cada código es un número entre 1 y 200). Informar en pantalla: ? Los códigos de los dos productos más baratos. ? La cantidad de productos de más de 16 pesos con código par. ? El precio promedio. } program punto5; var codigo, codBarato1, codBarato2, cantProdMas16, i, cantProductos: integer; precio, precioBarato1, precioBarato2, promedio, sumaPrecios: real; begin cantProductos:= 0; cantProdMas16:= 0; precioBarato1:= 9999; precioBarato2:= 9999; sumaPrecios:= 0; for i:= 1 to 5 do begin write('Ingrese el codigo del producto: '); readln(codigo); write('Ingrese el precio del codigo ', codigo, ': '); readln(precio); writeln(); sumaPrecios:= sumaPrecios + precio; cantProductos:= cantProductos + 1; if(precio < precioBarato1) then begin codBarato2:= codBarato1; precioBarato2:= precioBarato1; codBarato1:= codigo; precioBarato1:= precio; end else if(precio < precioBarato2) then begin codBarato2:= codigo; precioBarato2:= precio; end; if( (precio > 16) and ((codigo mod 2) = 0) ) then cantProdMas16:= cantProdMas16 + 1; end; writeln(); writeln('Los codigos de los dos productos mas baratos son: ', codBarato1, ' y ', codBarato2); writeln('La cantidad de productos de mas de 16 pesos con cadigo par es: ', cantProdMas16); promedio:= sumaPrecios / cantProductos; writeln('El precio promedio de los productos es: ', promedio:2:2); readln(); end.