Fórum Converter VB para Delphi #326110

26/07/2006

0

Eu tenho um código em VB que usa DLL para mostrar usuários conectados e possíveis corrupções dos arquivos que quando tento mudar para o Delphi dá erro (Invalid Argument), nem testa se o BD existe. O código em VB é o seguine:


Option Compare Database
Option Explicit

´*************************************************************

´This module is based in part on a VB4 sample that is referenced
´by the white paper "Understanding Jet Locking".  Instructions
´for this and other utilities can be referenced in that paper

´MSLdbUsr.DLL was written and developed by
´Kevin Collins (73760.1047@compuserve.com)
´and Bob Delavan

´This Access for Windows 95 sample was written and developed
´by Michael Kaplan (102363.1726@compuserve.com, or also at
´MichaelK_TSI@msn.com).

´*************************************************************

´You use the following constants with the LDBUser_GetUsers
´function´s "nOptions" parameter below.
Public Const OptAllLDBUsers = &H1
Public Const OptLDBLoggedUsers = &H2
Public Const OptLDBCorruptUsers = &H4
Public Const OptLDBUserCount = &H8
Public Const OptLDBUserAuthor = &HB0B

´Takes a string array buffer, a currently existing database
´filename, and one of the above constants as its parameters.
´When successful it will return the number of people in the
´database or "0" if there are no people in it.  It returns a
´negative number in case of an error, and you can then use
´LDBUser_GetError to retrieve extended error information.
Declare Function LDBUser_GetUsers Lib "MSLDBUSR.DLL" _
  (lpszUserBuffer() As String, ByVal lpszFilename As String, _
  ByVal nOptions As Long) As Integer
  
´Takes the error code returned by another MSLDBUSR.DLL function
´call and returns the error text associated with that error.
Declare Function LDBUser_GetError Lib "MSLDBUSR.DLL" _
  (ByVal nErrorNo As Long) As String _
  

Function GetComputerNames(ByVal strMDB As String, _
                          ByVal lngOptions As Long, _
                          ByRef varArray As Variant) _
                          As Integer

´In:
´   strMDB      Name of MDB file (including MDB file type suffix)
´   lngOptions  The value of the OptMDB constant to be used.
´   varArray    A variant that will hold either the error code
´               and error message OR the array of user names that
´               was requested.
´Out:
´   On Success  The number of users (0-255) that meet the
´               specified criteria.
´   On Failure  The error code. Extended info can be retrieved
´               with LDBUser_GetError.
                
    Dim intReturn As Integer
    
    ReDim astrBuffer(1) As String
    
    strMDB = MDBName(strMDB)
    
    intReturn = LDBUser_GetUsers(astrBuffer, strMDB, lngOptions)
    
    GetComputerNames = intReturn
    
    If intReturn < 0 Then
        varArray = LDBUser_GetError(intReturn)
    Else
        varArray = astrBuffer()
    End If
End Function


Private Function MDBName(strMDB As String)
´Formats the MDB filename string and adds on the file type
´extension, if it does not already exist.
´    If Len(strMDB) <> 0 Then
´        If InStr(UCase(strMDB), ".MDB") = 0 Then
´            strMDB = strMDB & ".MDB"
´        End If
´        strMDB = strMDB + Chr$(0) + Chr$(0)
        MDBName = strMDB
´    End If
End Function



O meu código em Delphi está assim:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    aUserList : array of ansistring;
  end;

var
  Form1: TForm1;

implementation

function LDBUser_GetUsers (var lpszUserBuffer : array of ansistring; const lpszFilename : ansistring; const nOptions : longint) : longint; external ´MSLDBUSR.DLL´;

function LDBUser_GetError (nErrorNo : longint) : shortstring; external ´MSLDBUSR.DLL´;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
const
   cArq : AnsiString = ´C:\DADOS\PRINCIPAL.MDB´;
   nUs : longint = 1;
var
   nUser : longint;
begin
   SetLength(aUserList, 1);

   nUser := LDBUser_GetUsers(aUserList, cArq, nUs);

   if nUser > 0 then
      ShowMessage(aUserList[0])
   else
      ShowMessage(LDBUser_GetError(nUser))
end;

end.


Preciso muito fazer funcionar esta DLL. Ela vem junto com o Access 97, na pasta JetUtls.

Agradeço qualquer ajuda.

Quadrado


Quadrado

Quadrado

Responder

Posts

26/07/2006

Micheus

Achei alguma coisa sobre acesso ao access pelo delphi, e utilização da DLL referida no site [url=http://www.opus.ch/OpenSource/DirectAccess/Versions/Changes3.2.htm#_353]Opus (link)[/url]. Eles declaram as funções de modo um pouco diferente. Veja se adaptando o seu código (chamada às funções) irá funcionar:
unit OpDAOUsers;

{ Delphi interface for MSLDBUSR.DLL
  See basLDB.txt for details.

  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 "Opus DirectAccess".

  The Initial Developer of the Original Code is Opus Software GmbH.
  Portions created by Opus Software GmbH are Copyright (C) 1996,2000
  Opus Software GmbH.  All Rights Reserved.

  Contributor(s):
  Peter Arrenbrecht <arrenbrecht@opus.ch>
  Remo von Ballmoos <ballmoos@opus.ch>

  Last modified:   20.12.2000 11:01:20 by peo 
}

{==============================================================================}
interface

const
  OptAllUsers = $1;
  OptLoggedUsers = $2;
  OptCorruptUsers = $4;
  OptUserCount = $8;
  OptUserAuthor = $b0b;

function GetUsers( const _LDBFileName: string; _opt: integer;
    out _users: array of string ): integer;

function GetError( _result: integer ): string;


{==============================================================================}
implementation
uses
  ActiveX, Windows, SysUtils;

const
  DLLName = ´MSLDBUSR.DLL´;

function LDBUser_GetUsers( lpszUserBufferArray: PSafeArray; const lpszFilename: TBStr;
    nOptions: longint ): longint; stdcall;
  external DLLName;

function LDBUser_GetError( nErrorNo: longint ): TBStr; stdcall;
  external DLLName;


function GetUsers( const _LDBFileName: string; _opt: integer;
    out _users: array of string ): integer;
  var
    pfn: TBStr;
    usr: variant;
    i: integer;
    p: ^pChar;
  begin
    pfn:= SysAllocStringByteLen( nil, Length(_LDBFileName) + 1 );
    try
      StrCopy( pChar(pfn), pChar(_LDBFileName) );
      usr:= VarArrayCreate( [Low(_users), High(_users)], varOleStr );
      result:= LDBUser_GetUsers( @TVarData(usr).vArray, pfn, _opt );
      if result > 0 then begin
        p:= VarArrayLock( usr );
        try
          for i:= 0 to result - 1 do begin
            _users[i]:= StrPas( p^ );
            Inc( p );
          end;
        finally
          VarArrayUnlock( usr );
        end;
      end {if ok};
    finally
      SysFreeString( pfn );
    end;
  end ;


function GetError( _result: integer ): string;
  var
    perr: TBStr;
  begin
    perr:= LDBUser_GetError( _result );
    try
      result:= StrPas( pChar(perr) );
    finally
      SysFreeString( perr );
    end;
  end ;


end .



Responder

Gostei + 0

26/07/2006

Quadrado

Beleza !

Funcionou. Depois achei outro link com um exemplo pronto que também funciona, precisando somente acrescentar a unit Variants na clausula Uses (para D6).

[url]http://www.winsoft.sk/daofaq.htm#Q91[/url]

e o exemplo

[url]http://www.winsoft.sk/download/users.zip[/url]

Com isto, para quem usa access com muitos usuários, é possível monitorar corrupção do arquivo e interromper a gravação de dados.

Obrigado.


Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar