Jump to content

aehimself

Members
  • Content Count

    1089
  • Joined

  • Last visited

  • Days Won

    23

Posts posted by aehimself


  1. 14 minutes ago, Attila Kovacs said:

    this opens me the file in the running IDE

    How...?! It's the same garbage here, only it appears in the IDE. I thought autoconnecting makes a difference, but that doesn't seem to be the case...

     

    image.thumb.png.67aaa2663d7e97907561c55c416e9e43.png

     

    51 minutes ago, Fr0sT.Brutal said:

    Why not try pure winapi? The functions are quite straightforward AFAICT

    I did not find the needed WinApi calls yet. I might look into it, seems something is broken in TDDEClientConv between XE4 and 11.2...


  2. I remember seeing it on a really old newslist that TDDEClientConv heavily suffers from bad coding and I tend to believe something is not right with it in this case. I already tried with simple casting, StrPCopy, sending @PAnsiString[1] instead of PAnsiChar, even like this:

    Var
     pac: PAnsiChar;
     s: String;
     tb: TBytes;
     len: Integer;
    begin
      s := '[open("' + Edit1.Text + '")]';
      tb := TEncoding.Default.GetBytes(s);
      len := Length(tb);
    
      GetMem(pac, len + 1);
      ZeroMemory(pac, len + 1);
      Move(tb[0], pac^, len);

    ... but BDSLauncher always replies with some Chinese characters what it tried to execute as a command. I can not get more PAnsiChar than this.

     

    I'll try to find a different component to check.


  3. When stepping in .ExecuteMacro, a message box actually pops up but disappears right after the line

     

      hdata := DdeClientTransaction(Pointer(hszCmd), DWORD(-1), FConv, 0, FDdeFmt,
         XTYP_EXECUTE, TIMEOUT_ASYNC, @ddeRslt);
     

    What it said:

    image.png.289e19636ae1234d12f28e6d113302f1.png

     

    So I guess the command is incorrect, Delphi really didn't like the casting. Now attempting to properly build my command, because with

    Var
      pac: PAnsiChar;
      s: AnsiString;
    begin
      s := '[open("' + Edit1.Text + '")]';
      pac := PAnsiChar(s);
    
      If Not DDEClientConv1.ExecuteMacro(pac, False) Then Begin

    my result is:

     

    image.png.6b44a3f9824cbca8eb49612aa2182488.png

     

    🙂


  4. Getting close 🙂 Never worked with DDE so it'll take some attempts to succeed I believe.

     

    So far I have the following code:

     Memo1.Lines.Add(sLineBreak + '----------------------------------------');
     Memo1.Lines.Add('Opening ' + Edit1.Text);
     // DDEClientConv1.ServiceApplication := '"C:\Program Files (x86)\Embarcadero\Studio\22.0\bin\bdsLauncher.exe" "C:\Program Files (x86)\Embarcadero\Studio\22.0\bin\bds.exe" /np';
     DDEClientConv1.ServiceApplication := 'C:\Program Files (x86)\Embarcadero\Studio\22.0\bin\bdsLauncher.exe';
    
     Memo1.Lines.Add('Setting DDE link...');
     If Not DDEClientConv1.SetLink('bdsLauncher', 'system') Then
     Begin
       Memo1.Lines.Add('Setting link failed!');
       Exit;
     End;
    
     Memo1.Lines.Add('Opening DDE link...');
     If Not DDEClientConv1.OpenLink Then
     Begin
       Memo1.Lines.Add('Opening link failed!');
       Exit;
     End;
    
     Try
       Memo1.Lines.Add('Invoking DDE command...');
    
       If Not DDEClientConv1.ExecuteMacro(PAnsiChar('[open("' + Edit1.Text + '")]'), False) Then
       Begin
         Memo1.Lines.Add('Invoking command failed!');
         Exit;
       End;
    
     Finally
       Memo1.Lines.Add('Closing DDE link...');
       DDEClientConv1.CloseLink;
     End;

    No errors are shown but nothing gets executed and I get a ding sound. No popups, no entries in the event log.

    Anyone has experience debugging DDE, where should I look for errors?

     

    I took all the keywords from the registry, HKCU\BDE.pas. ServiceApplication came from Command\Default, SetLink parameters from ddeexec\application\Default and ddeexec\topic\Default, the macro from ddeexec\default.


  5. 4 minutes ago, David Heffernan said:

    Is it possible that DDE is being used? That was how this would have been done in the old days. 

    My guess was on some tricky Windows messages, but DDE is a valid option as well. As I have no source for BDSLauncher I can not say.

    I took a peek at @dummzeuch's dzBdsLauncher but that also is executing a direct bds.exe call, probably resulting in a new IDE.

     

    Finding the method and replicating it would be the goal of this topic.


  6. 11 minutes ago, programmerdelphi2k said:

    sorry, on copy I did wrong ... but the result is the same = WORKS!

    No, it does not 🙂 First, CurrentKey has a zero value after .OpenKeyReadOnly. Second, you are assigning a wrong registry path, not what the API expects:

     

    https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa

     

    hkeyClass

    Type: HKEY

    A handle to the registry key for the file type. The access rights for this registry key should be set to KEY_READ. This member is ignored if fMask does not include SEE_MASK_CLASSKEY.

     

    Edit: wrong parameter copied


  7. 24 minutes ago, programmerdelphi2k said:

    but this works with IDE on memory or not!

    That is really surprising as that's not how you open a registry key with TRegistry AND even if you correct that, reg.CurrentKey won't be changed after a single .OpenReadOnly.

     

    Running the code on a PC with Delphi 10.4 and 11 installed also confirms failure: it opens up the file in Delphi 10.4.


  8. 15 minutes ago, Attila Kovacs said:

    what about bdslauncher.exe bds.exe /np d:\myfile.pas

    ?

     

    with full paths ofc

     

    Tried. Bds.exe never starts, bdslauncher.exe never quits, just hangs. No windows, no errors, nothing.

    Also tried adding the necessary (?) -pDelphi switch, same result. Tried giving these parameters only to Bdslauncher and only the source file. No effect.


  9. I'm building a tool which searches for and opens Delphi source files. Until now execution was a simple ShellExecute call to the .pas file and everything was working just file.

    Now, as a second Delphi version is introduced I had to change the code to support opening said file in a specific Delphi version. My issue is that a simple call to bds.exe will always launch a new Delphi instance, and I need to re-use the one currently running. Basically I need to mimic the IDEs behavior when double-clicking a .pas file in Explorer.

     

    Unfortunately I could not find any documentation about the parameters of BDSLauncher, nor any relevant parameters of Bds.exe which could achieve this. I also built a small program which only lists the parameters it was started with and temporarily replaced BdsLauncher.exe and then bds.exe to see what it received when something is double-clicked, but all I got was the full path of bds.exe.

     

    Can anyone point me to the right direction?

     

    Thanks!


  10. Var
      TokenHandle: THandle;
    Begin
      If LogonUser(PChar(UserEdit.Text), PChar(DomainEdit.Text), PChar(PasswordEdit.Text), LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, TokenHandle) Then
      Try
        // Credentials are valid...
    
        // In case needed:
        If ImpersonateLoggedOnUser(TokenHandle) Then
        Try
          // Do stuff in the context of user
        Finally
          RevertToSelf;
        End;
      Finally
        CloseHandle(TokenHandle);
      End;
    End;

    User must have network login right to the PC, though.


  11. 1 minute ago, Attila Kovacs said:

    As the component itself stores only a reference in both cases, I can't see any benefit.

    The benefit is, that you are not actually storing and handling data in a visual component, e.g.: TTreeNode.Data := TMyClass.Create;

    While it does work it's considered bad practice as you are not separating UI and data / business logic.

     

    Anyway, let's not hijack the topic, shall we. OP might not be interested in this discussion.


  12. 6 minutes ago, direktor05 said:

    DAMN, I just discovered there is also TJsonTreeView component. Delphi 10.4. A nono, its a component I installed. Made by some Polish guy at Embarcadero.

    If you mean https://github.com/pglowack/DelphiJSONComponents/blob/master/JSONTreeView.pas this only visualizes the JSON as far as I can see from the code. You still have to manually append your extra data to each node, or search in each node's children to find your OnClik, URL and Description nodes.

     

    3 minutes ago, Attila Kovacs said:

    You both never worked with treeviews, do you?

    I did, and first I used .Data to actually store data too, it was just too convenient.  Lately I'm keeping my data in a separate store and .Data only points to the data in this store, if needed. This way I don't even need to free up memory when a node is deleted.


  13. We had a custom component which was only a wrapper for a TStringList, you can do something like this. On the other hand I feel like we are wasting memory; to store textual data you simply can use string constants or if you don't want to convert your TXT files into Delphi strings, build a .res file from them and embed it to the compiled application.

     

    In case you wish to convert, I have a method which seemed to work in simple cases and properly splits the input into 255-length chunks while preserving line breaks and escapes apostrophes:

    Function ToDelphiString(Const inString: String): String;
    Const
     ADDITION = #39' + '#39;
     BREAKAT = 80;
    Var
     line, a, max: Integer;
     sb: TStringBuilder;
     strarr: TArray<String>;
    Begin
     sb := TStringBuilder.Create;
     Try
      sb.Append(#39);
    
      strarr := AdjustLineBreaks(inString).Split([sLineBreak]);
    
      For line := Low(strarr) To High(strarr) Do
       Begin
        max := strarr[line].Length Div BREAKAT;
    
        For a := 0 To max Do
         Begin
          sb.Append(strarr[line].Substring(a * BREAKAT, BREAKAT).Replace(#39, #39#39));
    
          sb.Append(#39);
    
          If a <> max Then sb.Append(' +' + sLineBreak + #39);
         End;
    
        If line <> High(strarr) Then sb.Append(' + sLineBreak +' + sLineBreak + #39);
       End;
    
      Result := sb.ToString;
     Finally
      FreeAndNil(sb);
     End;
    End;

     


  14. 8 minutes ago, direktor05 said:

    No I want to make a tool to create HTML menus. So I want a treeview that will be just like a website menu then export to json and read with javascript. The menu must not only have name, but also link url, onclick event description and parent/child id, stored in tTreeview1.items.data pointer.

    TTreeView is basically a wrapper for the old Windows TreeView component, which was created way before JSON. You MIGHT have some success finding JSON export in TVirtualTreeView but I wouldn't be so sure; most probably you'll have to extract that by yourself.

    As @haentschman mentioned storing data in a visual component is a bad practice. What I'd do is...

     

    Have a TJSONObject which stores your node information. By adding childnodes, you will already have the parent / children relationship and since each JSON object has a name, they only now have to store URL, OnClick javascript handler and description.

    For quick access to this information when building your TreeList based on the TJSONObject, you can assign the related object to the TTreeNode's .Data pointer. This way you didn't just separate UI / data, but simply can call TJSonObject(TreeView.Selected.Data).ToString to immediately get the selected node's JSON representation.

    To save the whole tree, call your main TJSONObject.ToString, to rebuild it TJSONObject(TJSONObject.ParseJSONValue).

     

    This is by using the Delphi provided System.JSON unit, but you can use any other library you prefer. The idea behind can stay the same.


  15. If you can detect a malformed packet, you simply can log the input and the output. Once the issue is detected, dump these in a local file so the customer can send it to you.

    Then, it's a matter of running the same byte sequence against your "processor" to see what / why it happens.

     

    You also can do the same if you can't detect the failure, but in this case dumping has to be initiated by a user input.

     

    In unexplainable situations I find it helpful to divide my classes up even further. Have a class ONLY for the COM handling, outputting TBytes. Have one converting these to AnsiSting-based "packets". Have an other one to process these. Usually during coding these tiny classes I'm fixing the issue I had in the beginning.


  16. 1 hour ago, Zazhir said:

     

    
        SetProcessWorkingSetSize(GetCurrentProcess, $FFFFFFFF, $FFFFFFFF);

     

    When I was hired this was the first thing I removed from our legacy application.

    This command only pushes most of the applications data in memory to the swap file, drastically slowing down your application when it tries to access those. It won't decrease your applications memory usage, only relocates it to the hard disk. Avoid it, it does more harm than good.

     

    Btw, at us it was in a Timer's OnTimer event, ran once about every minute...

     

    As for the memory usage, use a tool like DeLeaker. Put a breakpoint in your loop and make a snapshot each time. When you compare those snapshots, you'll see the objects in memory and the callstack which created said objects. It'll point you in the generic direction of what you should .Close or .Free,

     

    WITH THAT SAID

     

    Using Task manager to monitor your application usage is vaguely incorrect. It includes memory areas what your code already released but the OS did not take back yet due to memory allocation speed optimization as far as I know.


  17. On 11/29/2022 at 8:27 AM, Fr0sT.Brutal said:

    Well, you should investigate why the 2-char buffer became insufficient for date sep. What result that WinAPI function returns if you call it directly (or just step into call to it from RTL)?

    And what exactly means " 3rd-party controls handle this incorrectly "?

    It returns a dot, a space and #0 (which makes sense) and DevExpress's date editor started to misbehave... normally it showed correct format but when you clicked in it it showed "____ / " and accepted years only.

    Spent my last day trying to understand how this works and why some hacks were needed at some places. And I think I finally understood.

     

    The issue is NOT with Delphi 11.2 but some random unit changing some properties in the global FormatSettings variable (probably as an attempt to fix the wrongly detected separator). Once I found and got rid of that, VCL controls started to work but some (previously fine) calls to StrToDate started to throw exceptions. The reason is, Emba reworked the logic of date and time parsing, which is more strict in the later. While having a short date format of "yyyy. mm. dd." could parse "2022.11.30" in 10.4.2, Delphi 11.2 actually requires the final separator.

     

    Loads of experiments and this knowledge resulted a custom DateUtils unit to attempt to unify the behavior if the application is compiled with 10.4.2 and 11.2, I'll still have to roll back some local fixes tomorrow and start to use the helper instead... after that we'll see if my idea works.


  18. 41 minutes ago, Fr0sT.Brutal said:

    When function encounters it, it replaces slash to current DateSeparator. This way date format becomes independent from date separator change so user can just modify date separator to get desired format instead of changing whole date format.

    I don't know if I follow you here. Does it mean that I must never use FormatSettings.ShortDateFormat as it is, only FormatSettings.ShortDateFormat.Replace('/', FormatSettings.DateSeparator)?

     

    The reason I'm asking is that 3rd-party controls (like DevExpress) started to show (and save) dates differently just because of compiling under D11. That makes me think that either the above statement is incorrect, or all 3rd-party controls handle this incorrectly.

    To correct this I had to manually correct FormatSettings.ShortDateFormat but that immediately breaks all logic which relies on TFormatSettings.Create and StrToDate - which our tool is using a lot.

     

    54 minutes ago, Fr0sT.Brutal said:

    Regarding the separator itself, probably it couldn't be retrieved from the system (as https://learn.microsoft.com/en-us/windows/win32/intl/locale-sdate says, this constant is deprecated) so it gets value of slash.

    The reason Delphi 10.4.2 could not get it is because Embarcadero didn't provide a buffer big enough. As both versions are calling the same WinApi function, changing the buffer to array[0..1] retrieving will fail on D11 aswell; calling RaiseLastOSError will reveal the reason:

    image.png.66ad55a8e820d3460c36f5cfa655ce41.png

     

    Maybe I should have been more precise. I personally don't care about the date separator alone, only the malformation of ShortDateFormat because of it, which seem to affect appearance and logic.

×