Ali Keshavarz's Website
RSS icon Home icon
  • Boolean and BOOL

    Posted on November 5th, 2011 Ali Keshavarz 2 comments

    It took me an hour to fix an Access Violation in one of my source codes tonight. The AV caught my eyes when I thought everything was done correctly, and it is ready for committing changes and hit the bed!

    It was a vague AV, giving me just a few NT OS functions in call stack trace, and stopping on any line containing Result (as the return value for a property getter). I reviewed the code several times, everything seemed OK, and I had only changed tens of lines of code, so I was really confused where the hell this AV came from; I mean, I knew which property getter method was causing the error, and the method was not lengthy or complicated, but I had no clue how come it was causing such an AV >-(

    Eventually while I was reviewing the changed codes again and again, I noticed something; there was a Windows API call which required a PBOOL parameter, and I had called it twice in the function code. One call was written a while ago, and the other was written tonight. The problem was, for the second call I had defined the parameter as Boolean rather than defining it as BOOL (passing its address using @ operator). That’s a shame!

    So here’s a personal note for myself: Do not code at 2 AM, specially when you are kinda sleepy. If you did, make sure your eyes can distinguish between BOOL, and Boolean :)

  • Enumerating Windows services

    Posted on September 13th, 2011 Ali Keshavarz 3 comments

    A while ago, I had to enumerate all Windows services for a project. I was browsing the source code today, and thought maybe it would be a good idea to talk about this matter in a blog post, and publish a sample source code to achieve this.

    The easiest way to enumerate Windows services is using WMI. Of course using WMI requires some basic knowledge of MS COM technology which is tricky, but thanks to the great tool. Delphi WMI Class Generator by Rodrigo Ruz, you can have a ready Delphi class for obtaining information about installed services on a Windows machine without even writing a single line of code. All you have to know is that WMI class for Windows services is Win32_Service under root\CIMV2 namespace. Delphi WMI Class Generator will generate a unit named uWin32_Service.pas which contains a class named TWin32_Service. This class returns info about a single service for you. If you need to enumerate all installed services, you need to write a couple of codes to call its GetCollectionCount to retrieve number of available services, and SetCollectionIndex to set current item index for the class. Here is a sample code to retrieve names of all installed services on the local machine using TWin32_Service class:

    var
      i: Integer;
    begin
      with TWin32_Service.Create do
      try
        for i := 0 to GetCollectionCount - 1 do
        begin
          Writeln(DisplayName);
          SetCollectionIndex(i);
        end;
      finally
        Free;
      end;
    end;
    

    However, WMI is slow, and it relays on WMI service. If you need a faster way to enumerate Windows services, or if for whatever reason WMI service is disabled or not working on your target machine; then you have to relay on Windows API. Using Windows API for this purpose is not as easy as using the automatically generated TWin32_Service class. I am not aware of a single Windows API function that can enumerate Windows services for you and give you all the detailed information which WMI returns for each service. You have to call roughly a dozen of API functions to enumerate Windows services and retrieve some nice information for each service.

    First you need to open a handle to service manager on the target machine by calling OpenSCManager function, then you should call EnumServicesStatusEx function to enumerate available services, and retrieve their names and status. If you just need service names and status, you are done, but if you need to retrieve description and configuration for each service too, then you should open a handle for each service using OpenService function by giving it service name which you obtain through EnumServicesStatusEx call , and then call QueryServiceConfig and QueryServiceConfig2 functions to get the required configurations. At the end you should make sure you free all the allocated buffers, and close all handles. Delphi installation does not provide header translation for some of these API functions (particularly EnumServicesStatusEx and QueryServiceConfig2), but they are translated and available for Delphi by well-known Project JEDI, and their JEDI Windows API Headers which contain the majority of Windows headers. If you are a Delphi developer and have not heard about them yet (That would be weird!!), you can download the package from this link.

    Anyways, in the source code below, I wrapped all of those API calls into a class named TAkServices. This class holds an internal list containing information for each Windows service installed on a given machine. I tested it on both Delphi 2010 (Win32) and Delphi XE2 (Win64):

    Read the rest of this entry »

  • Implementing Singleton pattern in Delphi

    Posted on June 4th, 2011 Ali Keshavarz 11 comments

    There are several ways to implement Singleton pattern in Delphi. Most of the publicly available source codes that I saw use old techniques to keep backward compatibility with older versions of Delphi (e.g. Delphi 7). In such techniques usually a global variable or a writable const is used to keep a reference to the singleton instance; because in those old versions of Delphi, there were no way to define a class variable.

    Also many of them try to hide the constructor under protected visibility, assuming it would prohibit users from instantiating the class, and forcing them to use the defined method for accessing the singleton instance. I can’t realize what was the rationale behind hiding the constructor, because all Delphi classes are inherited from TObject, and it already has a default Create constructor defined as public, so a user can always call that Create method to instantiate a new object and getting around your singleton implementation.

    A few months ago when I was looking for a singleton implementation in Delphi which does not use old writable consts or global variables; I found a blog post by Yanniel Alvarez Alfonso, implementing Singleton pattern using class variables, but there was still the problem of hiding constructors, so I wrote a comment there, telling him that hiding the constructor is not a good idea; and instead of that, he should override TObject.NewInstance method. He appreciated the note, and changed his code to reflect that.

    Today I needed to implement Singleton again, but I was too lazy to write it, so I searched for it in my source codes, but didn’t find my own code! I tried my favorite modeling tool; ModelMaker, but their Singleton pattern implementation was the same old-style writable const technique (even in the new ModelMaker 11). Eventually I decided to write it again, and save it as a code template in ModelMaker to use it later when I need it and I am not in the mood of writing it again and again Smile

    Read the rest of this entry »

  • دانلود از مارکت آمازون برای اندروید

    Posted on April 13th, 2011 Ali Keshavarz 1 comment

    در این نوشته قصد دارم درباره چگونگی دانلود از مارکت آمازون برای اندروید بنویسم…

    حدود یک ماهی میشه که شرکت آمازون یک فروشگاه آنلاین برای نرم افزارهای سیستم عامل اندروید افتتاح کرده. هر چند این فروشگاه به اندازه فروشگاه اندروید مارکت گوگل نرم افزار نداره، و به اندازه اون هم همه گیر نیست، اما با توجه به عظمت شرکت آمازون، و تخصص آن در فروشگاه های آنلاین، و محتوای متنوعی که این شرکت ارائه میکنه، و توجه روز افزون این شرکت به تبلت ها؛ میشه امیدوار بود که این فروشگاه به زودی به عنوان رقیبی برای اندروید مارکت شرکت گوگل تبدیل بشه، و مانعی بر سر راه انحصار طلبی تدریجی گوگل در بازار اندروید بشه. در حال حاضر، آمازون هر روز یک نرم افزار تجاری را به طور رایگان در اختیار کاربرانش قرار میده، که همین خودش تبلیغ خوبی برای این سرویس هست.

    مارکت آمازون از دو طریق وب سای و همچنین از طریق نرم افزار اختصاصی این شرکت در دسترس هست. کاربر میتونه از طریق وب سایت آمازون یا نرم افزار مارکت آمازون لیست نرم افزارها را مرور کنه، و نرم افزار دلخواه اش را خریداری کنه. در این حالت، نرم افزار مربوطه به لیست آنلاین نرم افزارهای کاربر در سایت آمازون افزوده میشه، و کاربر میتونه از طریق نرم افزار مارکت آمازون بر روی دستگاه اندروید خود، نرم افزار های خود را دانلود کرده و بر روی دستگاه نصب کنه. مارکت فعلی امکان جستجو در لیست نرم افزارها، مشاهده دسته بندی نرم افزار، مشاهده صد نرم افزار رایگان و تجاری برتر، ایجاد Wish List، و ارائه لیست نرم افزارهای پیشنهادی بر اساس علایق شما را فراهم میکنه. البته متاسفانه نرم افزار مارکت آمازون که بر روی دستگاه نصب میشه، امکان شناسایی نرم افزارهای نصب شده فعلی را نداره، و اگر بخواید نسخه جدیدی از یکی از نرم افزارهای فعلی تان را نصب کنید، آمازون قبل از نصب نسخه جدید، نسخه قبلی را حذف میکنه، اما بعد از اینکه یک بار نرم افزار مربوطه با مارکت آمازون نصب شد، دفعات بعد، می تونید بدون مشکل آن نرم افزار را توسط مارکت آمازون آپدیت کنید.

    Read the rest of this entry »

  • How to use TProcessInfo #2

    Posted on July 26th, 2010 Ali Keshavarz No comments

    I had a few e-mails and comments about using TProcessInfo, so I decided to answer those questions in new blog posts.

    Q1: How can we find a module which is running a specific thread, giving a thread ID:

    A: First of all, Threads are not assigned to modules, they are assigned to processes. You can find a process which is running the thread, by searching in the list of threads owned by each running process. Here is a sample code:

    function FindProcessByThreadID(ID: Cardinal): TProcessItem;
    var
      ProcessInfo : TProcessInfo;
      AProcess : TProcessItem;
    begin
      Result := nil;
      ProcessInfo := TProcessInfo.Create(nil);
      try
        for AProcess in ProcessInfo.RunningProcesses do
        begin
          if Assigned(AProcess.Threads.FindByID(ID)) then
          begin
            Result := AProcess;
            Exit;
          end;
        end;
      finally
        ProcessInfo.Free;
      end;
    end;
    

    FindProcessByThreadID iterates over all running processes, and checks which of them has a thread with the given ID. If a process owns a thread with that ID, it will return that process as a TProcessItem object.

    Once you have the process object, you can get more information about the process or the specific thread, or you can kill the process, or suspend the thread. For example:

    var
      Process : TProcessItem;
    begin
      Process := FindProcessByThreadID(StrToInt(3444));
      if Assigned(Process) then
        ShowMessage(Process.FullPath);
    end;
    

    The above code looks for a thread with its ID = 3444, and if it is found, it provides full path of the EXE file for that process.

    Q2: How can we get memory consumption for a given process?

    A: You can read memory info for a given process using TProcessItem.MemoryInfo. It provides different info about the memory the process is consuming. Here is an example for reading memory info of Google Chrome process while it is running :

    var
      ProcessInfo : TProcessInfo;
      AProcess : TProcessItem;
    begin
      ProcessInfo := TProcessInfo.Create(nil);
      try
        AProcess := ProcessInfo.RunningProcesses.FindByName('Chrome.exe');
        if Assigned(AProcess) then
          ShowMessage(Format('WorkingSet Size = %d, Peak WorkingSet Size = %d',
                             [AProcess.MemoryInfo.WorkingSetSize,
                              AProcess.MemoryInfo.PeakWorkingSetSize]));
      finally
        ProcessInfo.Free;
      end;
    end;
    

    First we search for Chrome.exe process among running processes. Once the process is found, we read its current working set size, and pick working set size through MemoryInfo property, and show them in a message box. The values returned are in Bytes.

    Q3: How can we get process base priority class or change it?

    A: You can access base priority class for a given process or modify it (added in version 1.3), using TProcessItem.

    PriorityClassBase. Be careful, adjusting a base priority class of a given process inappropriately might make other processes unresponsive! Here is a example code:

    var
      ProcessInfo : TProcessInfo;
      AProcess : TProcessItem;
    begin
      ProcessInfo := TProcessInfo.Create(nil);
      try
        AProcess := ProcessInfo.RunningProcesses.FindByName('firefox.exe');
        if Assigned(AProcess) then
          AProcess.PriorityClassBase := BELOW_NORMAL_PRIORITY_CLASS;
      finally
        ProcessInfo.Free;
      end;
    end;
    

    You can also change each priority of  each thread within a process by setting BasePriority property of that TThreadItem instace.

    Q4: How can I check if a process is 64-bit?

    A: You can check this by reading TProcessItem.Is64Bits property.

    Q5: How can I get CPU usage for a given process?

    A: You can get CPU usage by reading TProcessItem.CPUUsage property.

    I hope these few answers and sample source codes can help you use Process Info. For other examples of using Process Info, please refer to this post: How to use TProcessInfo

    If there is any question regarding using Process Info, or anything about Delphi that you think worth being mentioned in Tips & Tricks section of this website, please contact me, and let me know about it.

    Have Fun!

  • Component Toolbar slows down RAD Studio 2010

    Posted on January 2nd, 2010 Ali Keshavarz 4 comments

    In RAD Studio 2010 there is a new IDE feature called Component Toolbar. This feature provides a component palette similar to the old Delphi component palette.

    Component Toolbar
    Component Toolbar in RAD Studio 2010

    This toolbar provides a nice search box which is able to filter components in the palette based on the search phrase. This toolbar is disabled by default, and is shown when Classic Layout is selected. Here you can see a snapshot of Classic Layout in RAD Studio 2010:

    Classic Layout in Delphi 2010

    A few weeks ago while I was working with Delphi 2010, I noticed a delay when switching from code view to form designer. The delay was there not only in the complex forms, but also in simple empty forms! It was not a big delay (about 1 second), but since I had to switch between code and form designer view many times, it was really annoying, so I decided to investigate it and find out what is causing this delay.

    Read the rest of this entry »

  • How to use TProcessInfo

    Posted on September 11th, 2009 Ali Keshavarz 5 comments

    The other day I published Process Info component pack which contains TProcessInfo and TAppInfo. A sample task manager was also published as demo.

    I thought maybe it is a good idea to talk about these components and some of their usages by providing some sample source codes. So I will start with TProcessInfo.

    Read the rest of this entry »