Delphi roaming folder, registry access - delphi

I developed an application and I want to deploy it on one machine of my client network.
this machine turns under win7 64 bits and needs an admin authorization (they use active directory, GPO,...) so far no problem.
i am using the roaming folder to store some files.
the problem is when I launch the application it seems that it doesn't find the correct current user roaming folder path, I think that's redirected to the admin roaming folder.
my code is as follow
Function GetRoamingFolderPath():String;
var
OsVersion: integer;
Path: String;
begin
OsVersion:=(TOSVersion.Major);
if OsVersion < 6 then
Path:= GetSpecialFolderPath(CSIDL_COMMON_APPDATA)
else
path:= GetSpecialFolderPath(CSIDL_APPDATA);
end;
where GetSpecialFolderPath is defined as :
function GetSpecialFolderPath(folder : integer) : string;
const SHGFP_TYPE_CURRENT = 0;
var path: array [0..MAX_PATH] of char;
begin
if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,#path[0]))
then Result := path
else
Result := '';
end;
also I need to register some values on registry under HKEY_CURRENT_USER , it's done but my application can't access them !
any idea on how to resolve this 2 issues.
thanks.

Function GetRoamingFolderPath():String;
var
OsVersion: integer;
Path: String;
begin
OsVersion:=(TOSVersion.Major);
if OsVersion < 6 then
Path:= GetSpecialFolderPath(CSIDL_COMMON_APPDATA)
else
path:= GetSpecialFolderPath(CSIDL_APPDATA);
end;
This function assigns to the local variable path, but not the return value. Hence its return value is undefined. Remove the variable path and assign to Result instead.
function GetRoamingFolderPath: string;
begin
if TOSVersion.Major < 6 then
Result := GetSpecialFolderPath(CSIDL_COMMON_APPDATA)
else
Result := GetSpecialFolderPath(CSIDL_APPDATA);
end;
This would have been obvious had you stepped through the code under the debugger and inspected the intermediate values. You would have observed that GetSpecialFolderPath returned the desired value, but that it got lost in GetRoamingFolderPath. Once you had made that observation, it would have become obvious what the fault was. I urge you to debug like this in future when you encounter such problems.

Related

How to fix "No more files" error in Delphi application with Paradox tables on Windows 10 1803?

In old Delphi applications which use the old and deprecated but still used BDE database engine with Paradox database files residing on a Windows 10 computer that's updated to the 1803 "Spring Creators Update" version, but the client computers using any older version of Windows like Windows 10 1709 or Windows 7, opening a Paradox table sometimes fails with a "No more files" error, idapi32.dll error code DBIERR_OSENMFILE. This raises a EDBEngineError exception in DBTables.pas / TTable.GetHandle(), which is called by TTable.CreateHandle, called by TBDEDataSet.OpenCursor().
The error seems to be caused by some file-sharing related changes in the Windows 10 1803 update. Removing the 1803 update from the file-sharing Windows 10 computer, or updating all the client computers to Windows 10 + 1803 seems to make the error go away.
People have speculated that the changes have something to do with the SMB protocol, maybe Windows Defender and/or other security related issues. Here's a Google Plus discussion
https://plus.google.com/106831056534874810288/posts/F4nsoTz2pDi
How could the "No more files" error be worked around by some reasonably easily doable changes in the Delphi application, while allowing the file-sharing client and server computers to keep using heterogeneous Windows versions?
Please try to refrain from answering or commenting self-evident things like "the sky is blue" or "BDE is old and deprecated". Keeping BDE is a decision that cannot be changed, certainly not as a "bug fix".
As an emergency fix, we have resorted to simply re-trying DbiOpenTable, when it returns the DBIERR_OSENMFILE error code. I posted an answer with source code to the idapi32.dll hack. So far it seems that if the first DbiOpenTable says "No more files", the second try succeeds, and the application works without noticing anything.
WARNING: what follows is a hack. A kludge. Band-aid, glue, duct tape and chewing gum. BDE is old. You are completely on your own if you use BDE and/or if you try this hack. I accept no responsibility over its use. If it works for you, good for you. If it ruins your business, bad for you.
Since the Paradox tables still mostly worked and the error seemed to be slightly randomly triggered, and since someone suspected Windows Defender having something to do with it, I thought maybe it just needs some kicking around. If DbiOpenTable() suddenly starts sometimes failing over a certain combination of SMB client/server versions, because "No more files" ... then why not just try the file operation again. I put an "if it returns a DBIERR_OSENMFILE error, then Sleep() and try again" logic around the DbiOpenTable function, and guess what - it seemed to work.
Hacking around the BDE's "features" is familiar to anyone who has to maintain BDE based applications. So I made a patching hook around idapi32.dll's DbiOpenTable function, starting from an old routine written by Reinaldo Yañez originally to fix the "insufficient disk space" error with BDE when the free disk space is at a 4 GB boundary. See https://cc.embarcadero.com/Item/21475
To use this, add Fix1803 in a uses clause, and call PatchBDE somewhere before starting to open Paradox tables. Maybe call UnPatchBDE when you're done, though I don't think that's necessary.
But remember, you're on your own, and this is highly experimental code.
unit Fix1803;
// * KLUDGE WARNING *
// Patch (hack) idapi32.dll DbiOpenTable() to try harder, to work with Windows 10 1803 "Spring Creators Update".
//
// The patching routine is an extension of code originally written by Reinaldo Yañez.
// see https://cc.embarcadero.com/Item/21475
//
// Some original Spanish comments are left in place.
interface
procedure PatchBDE;
procedure UnPatchBDE;
implementation
uses
Windows, Db, DbTables, BDE, SysUtils;
// ------------------------------------------- DbiOpenTable hook
var DbiOpenTable_address_plus_9 : Pointer;
function Actual_DbiOpenTable_CallStub(hDb: hDBIDb; pszTableName: PChar; pszDriverType: PChar; pszIndexName: PChar; pszIndexTagName: PChar; iIndexId: Word; eOpenMode: DBIOpenMode; eShareMode: DBIShareMode; exltMode: XLTMode; bUniDirectional: Bool; pOptParams: Pointer; var hCursor: hDBICur): DBIResult stdcall; assembler;
asm
// these two instructions are implicitly contained in the start of the function
// push ebp
// mov ebp, esp
add esp, $fffffee8
jmp dword ptr [DbiOpenTable_address_plus_9]
end;
function LogHook_DbiOpenTable (hDb: hDBIDb; pszTableName: PChar; pszDriverType: PChar; pszIndexName: PChar; pszIndexTagName: PChar; iIndexId: Word; eOpenMode: DBIOpenMode; eShareMode: DBIShareMode; exltMode: XLTMode; bUniDirectional: Bool; pOptParams: Pointer; var hCursor: hDBICur): DBIResult stdcall;
var
i : Integer;
begin
Result := Actual_DbiOpenTable_CallStub(hDb, pszTableName, pszDriverType, pszIndexName, pszIndexTagName, iIndexId, eOpenMode, eShareMode, exltMode, bUniDirectional, pOptParams, hCursor);
// if we got the "No more files" error, try again... and again.
i := 1;
while (Result = DBIERR_OSENMFILE) and (i < 10) do
begin
Windows.Sleep(i);
Result := Actual_DbiOpenTable_CallStub(hDb, pszTableName, pszDriverType, pszIndexName, pszIndexTagName, iIndexId, eOpenMode, eShareMode, exltMode, bUniDirectional, pOptParams, hCursor);
Inc(i);
end;
end;
// ------------------------------------------- Patching routines
const // The size of the jump instruction written over the start of the original routine is 5 bytes
NUM_BYTES_OVERWRITTEN_BY_THE_PATCH = 5;
type
TRYPatch = record
OrgAddr: Pointer;
OrgBytes: array[0..NUM_BYTES_OVERWRITTEN_BY_THE_PATCH-1] of Byte;
end;
procedure TRYPatch_Clear(var ARYPatch : TRYPatch);
begin
FillChar(ARYPatch, SizeOf(TRYPatch), 0);
end;
function RedirectFunction(OldPtr, NewPtr, CallOrigStub : Pointer; var OriginalRoutineAddressPlusN: Pointer; NumBytesInCompleteInstructionsOverwritten : Integer): TRYPatch;
type
PPtr=^pointer;
PPPtr=^PPtr;
TByteArray=array[0..maxint-1] of byte;
PByteArray=^TByteArray;
function SameBytes(Ptr1, Ptr2 : Pointer; NumBytes : Integer) : Boolean;
var
i : Integer;
begin
Result := true;
i := 0;
while (Result) and (i < NumBytes) do
begin
Result := Result and ((PByteArray(Ptr1)^[i] = PByteArray(Ptr2)^[i]));
Inc(i);
end;
end;
var
PatchingAddress : Pointer;
OldProtect,
Protect : DWORD;
p: PByteArray;
i : Integer;
begin
PatchingAddress := OldPtr;
if PWord(PatchingAddress)^ = $25FF then
begin {Es un JMP DWORD PTR [XXXXXXX](=> Esta utilizando Packages)}
p := PatchingAddress;
PatchingAddress := (PPPtr(#p[2])^)^; // PatchingAddress now points to the start of the actual original routine
end;
// Safety check (as if this thing was "safe"). The given replacement routine must start with the same bytes as the replaced routine.
// Otherwise something is wrong, maybe a different version of idapi32.dll or something.
if (CallOrigStub <> nil) and not SameBytes(PatchingAddress, CallOrigStub, NumBytesInCompleteInstructionsOverwritten) then
raise Exception.Create('Will not redirect function, original call stub doesn''t match.');
// Change memory access protection settings, so we can change the contents
VirtualProtect(PatchingAddress, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH, PAGE_READWRITE, #OldProtect);
// Save the old contents of the first N bytes of the routine we're hooking
Result.OrgAddr := PatchingAddress; // Save the address of the code we're patching (which might not be the same as the original OldPtr given as parameter)
for i := 0 to NUM_BYTES_OVERWRITTEN_BY_THE_PATCH-1 do
result.OrgBytes[i] := PByte(Integer(PatchingAddress) + i)^;
// Replace the first bytes of the original function with a relative jump to the new replacement hook function
// First write the instruction opcode, $E9 : JMP rel32
PByte(PatchingAddress)^:= $E9;
// Then write the instruction's operand: the relative address of the new function
PInteger(Integer(PatchingAddress)+1)^ := Integer(NewPtr) - Integer(PatchingAddress) - 5;
// Address to jump to, for the replacement routine's jump instruction
OriginalRoutineAddressPlusN := Pointer(Integer(PatchingAddress) + NumBytesInCompleteInstructionsOverwritten);
// Restore the access protection settings
VirtualProtect(PatchingAddress, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH, OldProtect, #Protect);
FlushInstructionCache(GetCurrentProcess, PatchingAddress, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH);
end;
procedure RestorePatch(RestorePatch: TRYPatch);
var
OldProtect,
Protect : DWORD;
OldPtr: Pointer;
i : Integer;
begin
OldPtr := RestorePatch.OrgAddr;
VirtualProtect(OldPtr, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH, PAGE_READWRITE, #OldProtect);
for i := 0 to NUM_BYTES_OVERWRITTEN_BY_THE_PATCH-1 do
PByte(Integer(OldPtr) + i)^ := RestorePatch.OrgBytes[i];
VirtualProtect(OldPtr, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH, OldProtect, #Protect);
FlushInstructionCache(GetCurrentProcess, OldPtr, NUM_BYTES_OVERWRITTEN_BY_THE_PATCH);
end;
var
idapi32_handle: HMODULE;
Patch_DbiOpenTable : TRYPatch;
procedure PatchBDE;
begin
if idapi32_handle <> 0 then Exit; // already_patched
idapi32_handle := LoadLibrary('idapi32');
if idapi32_handle <> 0 then
begin
Patch_DbiOpenTable := RedirectFunction(GetProcAddress(idapi32_handle, 'DbiOpenTable'), #LogHook_DbiOpenTable, #Actual_DbiOpenTable_CallStub, DbiOpenTable_address_plus_9, 9);
end;
end;
procedure UnPatchBDE;
begin
if idapi32_handle <> 0 then
begin
{Leave everything as before, just in case...}
if Patch_DbiOpenTable.OrgAddr <> nil then
RestorePatch(Patch_DbiOpenTable);
FreeLibrary(idapi32_handle);
idapi32_handle := 0;
end;
end;
initialization
idapi32_handle := 0;
TRYPatch_Clear(Patch_DbiOpenTable);
end.
VMWare, Virtual Box, etc to virtualize an Windows 7. If, as you say, W7 work flawlessly that would solve the problem.

SHDeleteKey Function

I am having one Delphi XE2 Project for Windows Registry Operation. I need to delete all subnodes under **HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000001}** , so I have defined the following codes :
function SHDeleteKey(key: HKEY; SubKey: PWideChar): Integer; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW';
..
..
..
..
..
procedure TMainForm.BitBtn02Click(Sender: TObject);
var
RegistryEntry : TRegistry;
begin
RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
RegistryEntry.RootKey := HKEY_CLASSES_ROOT;
if (RegistryEntry.KeyExists('CLSID\{00000000-0000-0000-0000-000000000001}\')) then
begin
Memo01.Font.Color := 3992580;
Memo01.Lines.Add('Windows Registry Entry Has Been Found In Your System');
RegistryEntry.Access:= KEY_WRITE or KEY_WOW64_64KEY;
SHDeleteKey(HKEY_CLASSES_ROOT, PWideChar('CLSID\{00000000-0000-0000-0000-000000000001}'));
RegistryEntry.CloseKey();
RegistryEntry.Free;
Memo01.Font.Color := 16756480;
Memo01.Lines.Add('Windows Registry Entry Has Been Deleted Successfully');
end
else
begin
Memo01.Font.Color := 7864575;
Memo01.Lines.Add('Windows Registry Entry Has Not Been Found In Your System');
end;
end;
But nothing is happening. Then I have tried
function SHDeleteKey(key: HKEY; SubKey: PChar): Integer; stdcall; external 'shlwapi.dll';
but here is another problem is telling "Entry Point not found".
Your function import is failing because the function is named SHDeleteKeyW where the W specifies that you want to use Unicode characters. So your function declaration should be
function SHDeleteKey(hKey: HKEY; pszSubKey: PWideChar): Integer; stdcall;
external 'shlwapi.dll' name 'SHDeleteKeyW';
Once that is fixed, the two most common failure modes are:
Your process does not have admin rights.
Your process runs in a 32 bit process on a 64 bit system and so cannot see the 64 bit view of the registry.
Based on your earlier question, option 2 seems most likely.
You said "nothing is happening", but I'm sure something is happening. The function is failing and returning an error status to you. But you did not check the return value of the call to SHDeleteKey. Whenever you call a Windows API, check the return value. If it fails, the return value allows you to diagnose that failure.
Assuming the issue is the registry redirector for your 32 bit process, your options include:
Run the code from a 64 bit process.
Use RegDeleteTree.
Empty the key's subkeys first, and then use TRegistry.DeleteKey.
Note that the code where you specify KEY_WOW64_64KEY only has effect when using the TRegistry methods. Since SHDeleteKey is a Windows API function, it is independent from that class.
For your second problem, you may want to try ShDeleteKeyW instead (explicitly selecting the wide string variant).
In both cases, however, you should check the result to see why it failed.
You don't mention what O/S this is on but there appears to be several platform-specific quirks with this function as can be seen in the comments here.

SHGetFolderPath doesn't work for me

I have this function:
function GetProfilePath: string;
const
SHGFP_TYPE_CURRENT = 0;
var
hToken: THandle;
ProfilePath: packed array[ 0..MAX_PATH ] of Char;
begin
ZeroMemory(#ProfilePath[0], SizeOf(ProfilePath));
OpenProcessToken( GetCurrentProcess, TOKEN_QUERY, hToken );
SHGetFolderPath( 0, CSIDL_APPDATA, hToken , SHGFP_TYPE_CURRENT, #ProfilePath[ 0 ] );
CloseHandle( hToken );
Result := ProfilePath;
end;
SHGetFolderPath returns E_FAIL (0x80004005) and an empty ProfilePath buffer. MSDN says that E_FAIL means "The CSIDL in nFolder is valid, but the folder does not exist". But the folder does exist, I'm pretty sure. When I'm creating a simple test application and running the same code, it works well.
What might be wrong with that?
update:
I found that my application doesn't work well when running under Delphi. When I run it separately, all is OK.
Thanks,
Roman
The use of a user token looks needlessly complex. But, having said that, when I ran your code on my machine it worked fine with no error. Perhaps the user token for your process doesn't have sufficient rights to that folder. Or perhaps the folder really does not exist!
For what it's worth I think you would be better off using the simpler off API SHGetSpecialFolderPath. My wrapper for that looks like this:
function GetSpecialFolderPath(const CSIDL: Integer): string;
var
Buffer: TWin32PathBuffer;
begin
if SHGetSpecialFolderPath(Application.Handle, #Buffer[0], CSIDL, False) then begin
Result := Buffer;
end else begin
RaiseLastOSError;
end;
end;
Of course, this may fail in just the same way as your version if the folder really does not exist.
OK, I've just re-read this comment in your question:
When I'm creating a simple test application and running the same code, it works well.
That sounds like you are running the real code in a different context. Perhaps in a service? Or with user impersonation. Maybe that's the clue to solving this. What are you not telling us about the environment/context/setting where the code fails?
And some very minor comments on your code. You've defined ProfilePath with one more element than needed, and packed is superfluous for an array:
ProfilePath: array[ 0..MAX_PATH-1 ] of Char;
Or, even better, re-use the type defined in the Delphi RTL, TWin32PathBuffer.

Check if a directory is readable

How we can check if a directory is readOnly or Not?
you can use the FileGetAttr function and check if the faReadOnly flag is set.
try this code
function DirIsReadOnly(Path:string):Boolean;
var
attrs : Integer;
begin
attrs := FileGetAttr(Path);
Result := (attrs and faReadOnly) > 0;
end;
Testing if the directory's attribute is R/O is only part of the answer. You can easily have a R/W directory that you still can't write to - because of Access Rights.
The best way to check if you can write to a directory or not is - to try it:
FUNCTION WritableDir(CONST Dir : STRING) : BOOLEAN;
VAR
FIL : FILE;
N : STRING;
I : Cardinal;
BEGIN
REPEAT
N:=IncludeTrailingPathDelimiter(Dir);
FOR I:=1 TO 250-LENGTH(N) DO N:=N+CHAR(RANDOM(26)+65)
UNTIL NOT FileExists(N);
Result:=TRUE;
TRY
AssignFile(FIL,N);
REWRITE(FIL,1);
Result:=FileExists(N); // Not sure if this is needed, but AlainD says so :-)
EXCEPT
Result:=FALSE
END;
IF Result THEN BEGIN
CloseFile(FIL);
ERASE(FIL)
END
END;
The version HeartWare has given is nice but contains two bugs. This modified versions works more reliably and has comments to explain what is going on:
function IsPathWriteable(const cszPath: String) : Boolean;
var
fileTest: file;
szFile: String;
nChar: Cardinal;
begin
// Generate a random filename that does NOT exist in the directory
Result := True;
repeat
szFile := IncludeTrailingPathDelimiter(cszPath);
for nChar:=1 to (250 - Length(szFile)) do
szFile := (szFile + char(Random(26) + 65));
until (not FileExists(szFile));
// Attempt to write the file to the directory. This will fail on something like a CD drive or
// if the user does not have permission, but otherwise should work.
try
AssignFile(fileTest, szFile);
Rewrite(fileTest, 1);
// Note: Actually check for the existence of the file. Windows may appear to have created
// the file, but this fails (without an exception) if advanced security attibutes for the
// folder have denied "Create Files / Write Data" access to the logged in user.
if (not FileExists(szFile)) then
Result := False;
except
Result := False;
end;
// If the file was written to the path, delete it
if (Result) then
begin
CloseFile(fileTest);
Erase(fileTest);
end;
end;
In Windows API way, it is:
fa := GetFileAttributes(PChar(FileName))
if (fa and FILE_ATTRIBUTE_DIRECTORY <> 0) and (fa and FILE_ATTRIBUTE_READONLY <> 0) then
ShowMessage('Directory is read-only');
One possible way is to try list the files in that directory and check for the status. This way we can check whether it is readable. this answer is applicable to 2009 or lower. Remember we have to check whether the folder exists and then whether the folder is readable. you can find the implementation here http://simplebasics.net/delphi-how-to-check-if-you-have-read-permission-on-a-directory/

how to quickly verify the case sensitive filename really exists

I have to make a unix compatible windows delphi routine that confirms if a file name exists in filesystem exactly in same CaSe as wanted, e.g. "John.txt" is there, not "john.txt".
If I check "FileExists('john.txt')" its always true for John.txt and JOHN.TXT due windows .
How can I create "FileExistsCaseSensitive(myfile)" function to confirm a file is really what its supposed to be.
DELPHI Sysutils.FileExists uses the following function to see if file is there, how to change it to double check file name is on file system is lowercase and exists:
function FileAge(const FileName: string): Integer;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo) then Exit;
end;
end;
Result := -1;
end;
function FileExistsEx(const FileName: string): Integer;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi, LongRec(Result).Lo) then
if AnsiSameStr(FindData.cFileName, ExtractFileName(FileName)) then Exit;
end;
end;
Result := -1;
end;
Tom, I'm also intrigued by your use case. I tend to agree with Motti that it would be counter intuitive and might strike your users as odd.
On windows file names are not case sensitive so I don't see what you can gain from treating file names as if they were case sensitive.
In any case you can't have two files named "John.txt" and "john.txt" and failing to find "John.txt" when "john.txt" exists will probably result in very puzzled users.
Trying to enforce case sensitivity in this context is un-intuitive and I can't see a viable use-case for it (if you have one I'll be happy to hear what it is).
I dealt with this issue a while back, and even if I'm sure that there are neater solutions out there, I just ended up doing an extra check to see if the given filename was equal to the name of the found file, using the case sensitive string comparer...
I ran into a similar problem using Java. Ultimately I ended up pulling up a list of the directory's contents (which loaded the correct case of filenames for each file) and then doing string compare on the filenames of each of the files.
It's an ugly hack, but it worked.
Edit: I tried doing what Banang describes but in Java at least, if you open up file "a.txt" you'r program will stubbornly report it as "a.txt" even if the underlying file system names it "A.txt".
You can implement the approach mention by Kris using Delphi's FindFirst and FindNext routines.
See this article

Resources