Setting Unit Defaults? - delphi

Not a programming question as such, but..
..Is there a way from the Delphi IDE to define information that will be applied to newly created Units?
For example, suppose I wanted each new Unit to add some commented information to the top, like so:
I like to add such information to Units so that anyone else who may need access to it has some brief information. Obviously I am not expecting the IDE to fill in the Overview information.
I noticed some OpenSource Components include the License Information at the top of Units, I assume they were just Copy and Pasted in there, but wouldnt it be handy if there was a way to Automate such IDE behaviour?
Additionally, I have a few external Units added to my Library Path, which I add to the Uses Clause of a Form/Unit when needed. There is one paticular Unit I always find myself using, It would also be handy to Automatically include X Unit to the Uses Clause of New Units.
Is there a trick to doing something like this, or should Copy and Paste be enough?
Thanks.

You can consider using a Delphi live template too.

The closest you can get is to use GExperts or CNPack. These are great IDE enhancements and they can be used to paste configurable pieces of code using a simple hotkey. In GExperts this is called Code Librarian, CNPack has a similar feature. They contain a lot of other valuable tools so it might be worth to check these out.

Like Marjan already mentioned using an expert for a new custom unit, you can also make an IDE expert rewriting Delphi's default unit code for maximum customizability. But since this answer likely implies the most required work of all, I shall not go in detail or sample code. It's just a possibility.

You'll have to stick to copy/paste. If there was a slick way to do this then every single Delphi programmer on the planet would have used it to turn this
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
into this
type
TForm1 = class(TForm)
end;

Related

Implement Global interfaces

I'm currently struggling with the following:
I need to create two different DLL's, which do exactly the same but are looking to a different DB. The two DB's are nothing alike.
My dll's should be handling the communication with those different DB's.
So that the main program chooses which dll he wants to use.
I want to be sure each dll has exactly the same procudes/functions/...
I was thinking of using interfaces.
But I can't figure out how to create global interfaces. the dll's belong to the same projectgroup.
I do believe you're making a "mountain out of a molehill" thinking you need 2 different DLLs. But if you choose the last of my suggested options, you should find it fairly easy to switch between a 2 DLL solution and 1 DLL solution.
Option 1
This is the most straightforward:
Create a new unit.
Add your DLL interface (the exports).
Include the unit in both projects.
unit DllExportIntf;
interface
uses
DllExportImpl;
exports DoX;
implementation
end.
Note that this unit uses DllExportImpl which will also have to be included in both projects. However, you'll need 2 different files with the same name in 2 different locations in your file system. So each DLL project will have different implementations.
Now whenever you make a change to your interface, your projects won't compile until you've updated each of the DllExportImpl units.
What I don't particularly like about this solution is the need for units with the same name but different behaviour. Since you intend having both DLLs in the same project group: I should warn you that I've experienced the IDE getting confused by duplicate unit names.
Option 2
Place the exports into a shared include file.
library DllSharedExportsImpl1;
uses
DllExportImpl1 in 'DllExportImpl1.pas';
{$I ..\Common\DllExports.inc}
The DllExports.inc file will only include your exports clauses. E.g.
exports DoX;
This has the advantage that now each DLL can use different unit names for the different implementations. And if you change your include file, neither project will compile until you've updated its implementation unit to accommodate the change.
Note that this does come with its own set of problems. The way includes work: the compiler effectively shoves the contents of the include file into the unit at compile time. So what looks like line 7 to the IDE is entirely different to the compiler. Also editing include files can be a bit of a nuisance because context can only be determined where the file is included making editor support quite impractical.
Option 3
This option is a little more work, but provides much better long-term maintainability.
You do this by implementing your interface via polymorphic objects. In this way, both DllProjects will also share the routines that are actually exported. When each DLL initialises, it sets the concrete implementation to be used.
Your DLL interface could look something like this.
unit DllExportIntf;
interface
type
TAbstractImpl = class(TObject)
public
procedure DoX; virtual; abstract;
end;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
procedure DoX;
exports DoX;
implementation
var
GDllImpl: TAbstractImpl;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
begin
if Assigned(GDllImpl) then
begin
GDllImpl.Free;
end;
GDllImpl := ADllImpl;
end;
procedure DoX;
begin
GDllImpl.DoX;
end;
end.
When you initialise your DLL, you can call:
AssignDllImpl(TDllImpl_1.Create);
A clear advantage of this approach is that if there is any common code between your 2 DLLs, it can be included in your base implementation. Also, if you can change an existing method DLL in such a way that it does not require a change to TAbstractImpl, you possibly will only need to recompile your DLLs.
Furthermore, if you need to change existing virtual abstract methods, you will have to update the overrides in your concrete implementations accordingly.
WARNING If you add a new virtual abstract method, your projects will still compile with warnings that you are creating objects with abstract methods. However, you should always treat warnings as errors. If you do, this caveat won't be a problem.
NOTE: As mentioned earlier, using this approach you should be able to fairly easily switch between single DLL and 2 DLL solutions. The difference basically boils down to which units are included in the project, and how you initialise the global.
It may also be worthwhile mentioning that you could even eliminate the global altogether by implementing a Handle to use with each of your DLL routines. (Similar to Windows.) Bear in mind that there are technical issues when trying to pass objects between DLL and application code. This is why instead of passing objects, you use a "handles" to objects and encapsulate the actual object instances internally.
Considering all that was said, I believe that you would be more successful if you design your solution with packages, not DLLs. A package is a DLL, but rich in symbols, so Delphi can be a better use of it. Particularly, the symbols declared inside the package will more easily be loaded by your application, with a much higher level of abstraction. It´s what the Delphi IDE uses to load components.
So, following this design, this is what you have to do:
Declare your interfaces in units existing in a package named (for instance) DBServices.dpk. Here is an example of such an unit:
unit DBService1;
interface
uses
....;
type
IService1 = interface
[....] // here goes the GUID
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
end.
So, above you created an unit that declares an interface. Your aplication can use that interface anywhere, just reference the package in your application and use it in other units and you will have the access to the symbols declared.
Declare the implementation class for that very same interface in another unit of another package, for instance, dedicated to SQLServer (SQLServerServices.dpk):
unit SQLServerService1;
interface
uses
DBService1, ....;
type
TSQLServerService1 = class(TInterfacedObject, IService1)
protected // IService1
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
procedure TSQLServerService.ServiceMethod1;
begin
// Specific code for SQL Server
end;
procedure TSQLServerService.ServiceMethod2;
begin
// Specific code for SQL Server
end;
...
end.
Above you declared an implementing class for the interface IService1. Now you have two packages, one declaring the interfaces and other implementing those interfaces. Both will be consumed by your application. If you have more implementations for the same interfaces, add other packages dedicated to them.
One important thing is: you have to have a factory system. A factory system is a procedure ou class that will create and return the implementations for your application from each package.
So, in terms of code, in each service package (the ones that implement the interfaces) add a unit named, for instance, xxxServiceFactories, like this:
unit SQLServerServiceFactories;
interface
uses
DBService1;
function NewService1: IService1;
implementation
uses
SQLServerService1;
function NewService1: IService1;
Result := TSQLServerService1.Create;
end;
end.
The code above declares a function that creates the SQL Server implementation and returns it as an interface. Now, if you call a method from the interface returned, you will be actually calling the specific implementation of it for SQL Server.
After loading the package, you will have to link to that function in the very same way you would do if working if a DLL. After you have the pointer for the function, you can call it and you will have the interface in your application's code:
...
var
service1: IService1;
begin
service1 := NewService1;
service1.ServiceMethod1; // here, calling your method!
end;
The model I described in this answer is the one I used in a similar scenario I had to deal with in the past. I presented general ideas that work, but you have to understand the fundamentals of packages and interfaces to really master the technique.
A comprehensive explanation on those matters would be very long for an answer here, but I guess it will be a good starting point for you!
What you want to do is create a COM component project. Define your methods on that & implementations for one DB. Then create a second COM component that uses the same interface.
On the off-chance that your question is more about the fundamentals of Delphi, I've added another answer which may be more helpful to you than the first one. My first answer focused on getting 2 DLLs to expose the same methods (as per the main body of your question). This one focuses on the last 2 sentences of your question:
But I can't figure out how to create global interfaces. The dll's belong to the same project group.
Based on this, it sounds like you're looking for an option to "mark an interface as global so that projects in the same group can use them". Delphi doesn't need a special feature to do this because it's trivially available if you understand certain fundamental principles.
When you create a new unit, it is by default added to the current project. However if you want to share the unit between multiple projects, it's a good idea to save it to a different folder so it's easy to see that it's shared. Your first DLLs project file should look something like this.
library Dll1;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
You can define your "global" interface in the DllSharedIntf unit. E.g.
unit DllSharedIntf;
interface
type
IDllIntf = interface
['{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}']
procedure DoX;
end;
implementation
end.
NOTE: Because the interface type is declared in the interface section of the unit, it is considered "global" because other units are able to use it. But this doesn't automatically make it available to other projects.
You now have to add the shared unit to your other project so it becomes available for use by other units in that project. To do this:
Activate Dll2
Select Project and Add to Project...
Find DllSharedIntf and add it.
Delphi will automatically update your project source file to include the unit.
library Dll2;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
Now in each DLL project you can add a separate implementation unit. E.g. For Dll1:
unit DllImpl1;
interface
uses
//It's very important to indicate that this unit uses the shared unit.
//Otherwise you won't be able to access the "global types" declared
//in the interface-section of that unit.
DllSharedIntf;
type
TDllImpl1 = class(TInterfacedObject,
//Any types defined in the interface-section of any units that
//this unit **uses**, can be accessed as if they were declared
//in this unit.
IDllIntf)
protected
//The fact that this class is marked as implementing the IDllIntf
//means that the compiler will insist on you implementing all
//methods defined in that interface-type.
procedure DoX;
end;
implementation
NOTE This answer only covers sharing an interface between projects. You'll still need to expose the functionality of the DLLs via appropriate exports. You'll need an approach similar to option 3 of my other answer.
Summary
We don't usually talk about "global interfaces" in Delphi. It's generally understood that anything declared in the interface section of a unit is globally accessible. (We do make more of an issue about global variables due to their dangers though; but that's an entirely different topic.)
In Delphi:
Whenever you want one unit (A) to make use of functionality defined in another unit (B), you need to add unit B to the uses clause of unit A.
Whenever you want a project to use a unit created in another project, you need to add the unit to the project. (TIP: It's a good idea to put such units in a separate folder.)
NOTE: When sharing units between projects, the project group is actually irrelevant. Projects don't need to be in the same group to share units. All you need to do is ensure the project can access the unit so that other units in your project can uses it.

How can I get a dataset of in-memory objects?

Does anyone know of a TDataset descendant that works with Generics and RTTI, so that I can write code like this, and make use of data-aware components in the GUI? :
...
ds:TDataset<TPerson>;
...
procedure DoStuff;
begin
ds:=TDataset<TPerson>.create;
ds.add(TPerson.Create('A.','Hitler',77));
ds.add(TPerson.Create('O.','Bin Laden',88));
end;
This should be possible. The fielddefs can be created via RTTI because the exact type of the data is known. Values can also be automatically marshalled back and forth, so you can both view and edit data that's in a class or a record.
I hate having to write a lot of useless marshalling code, while the required information for that is available via RTTI already.
Or maybe somebody once wrote some sort of TEnumerable <-> TDataset adapter?
Does something like that exist, or should I start writing one?
...
The closest thing that I could find is an (excellent!) example by Marco Cantu, from Mastering Delphi 7, but the code itself doesn't make use of new language features like generics, the new RTTI system, or attributes, and it doesn't work with Unicode delphi. TDataset has changed since D7 too.
The TAureliusDataSet included in TMS Aurelius comes very close to that.
Take a look at EverClassy Dataset from Inovativa at www.inovativa.com.br/public.
another one is Snap Object Dataset http://digilander.libero.it/snapobject/
DotNet4Delphi by A-Dato Scheduling Technology from the Netherlands is good for you.
Quotes:
From Torry's Delphi
Hook up any collection to your data aware controls.
DotNet4Delphi implements many .Net collection classes, including
generic types like List<> and Dictionary<>. Different from their
Delphi counterpart is that our generic collections also implement the
non-generic interfaces (IList, IDictionary) allowing you to access
your collections in multiple ways. This opens the door to use any
collection as a data source for data aware controls which is exactly
what the (also included) TListDataset component provides.
It targets Delphi XE and XE2.
It's an open source initiative, Delphi rocks !!!
I have found a more relevant resource and can't help sharing it! So relevant that I think it deserves a separate post rather than a mere update in my first answer.
The Dduce library for Delphi XE2-XE6 makes use of TListDataSet<...> a generic dataset component that can be used to expose a generic list as a TDataSet.
The most relevant units pertaining to the implementation of the generic dataset are:
DDuce.Components.VirtualDataSet.pas (The original SO post is itself cited by the author within the source code as a reference among others!!!)
DDuce.Components.ListDataSet.pas
Class hierarchy:
TDataSet <= TCustomVirtualDataset <= TListDataset <= TListDataset<T>
Yes, it inherits lots of features... my only wish is to have at my disposal a version working with a lessen requirement (Delphi XE without most of the other bells and whistles).
Look and feel:

Delphi 2006 duplicate function names

is there a way to make the Delphi compiler recognize and report duplicated function names (especially defined in different Units that the currently compiled unit uses)?
There isn't. It would sure be nice if there was, though. You can get around this by using the unit name of the function you'd like to invoke:
uses
unit1, unit2;
procedure DoSomethingFromUnit1;
begin
unit1.DoSomething;
end;
Try submitting this to QC as a feature request. It would be a useful thing to have.
From the sight of the compiler, duplicate function names are not duplicate if they reside in different scopes. Finding these ambiguities (in sight of the programmer) is supported quite well by Pascal Analyzer.
This is one of those things that makes "WITH" so dangerous.
CodeHealer does a good job of reporting when a method or identifier is hiding another one with the same name but a different scope.

Separating Interface and Implementation classes in delphi?

Am separating my delphi code into interface and implementation units ie.
EmployeeIntf.pas looks like this
type
// forward declaration
TScheduleList = class;
TDeparment = class;
TEmployee = class(BDObject)
....
function GetSchedules: TScheduleList;
function GetDepartment: TDepartment;
end;
TEmployeeList = class(DBList)
....
end;
TEmployeeDM = class(BDDBobject)
...
end;
Then i have the two units ScheduleIntf.pas & DepartmentIntf.pas which declare the TScheduleList class and TDepartment class.
Then in my main unit which combines all the units looks like this,
Unit BusinessDomain
Interface
uses
classes
{$I Interface\EmployeeIntf.pas}
{$I Interface\DepartmentIntf.pas}
{$I Interface\ScheduleIntf.pas}
Implementation
uses
SysUtils
{$I Implementation\EmployeeImpl.pas}
{$I Implementation\DepartmentImpl.pas}
{$I Implementation\ScheduleImpl.pas}
Initialization
finalization
end.
When i compile this the compiler throws an error;
*Type TScheduleList is not yet completely defined*
How can i have this classes separate in each unit file (.pas) and then do forward declarations without the compiler throwing this error?
The class themselvs are huge and i would prefer to separate them this way.
Gath
My first advice: Skip this $Include thing altogether. As Uwe wrote find a more Delphi-like solution.
If you really want to stay with the $Include style: The error you quote occurs because forward declarations don't work across "type" blocks. You forward declare TScheduleList in one block but define it in a different block. To cure this omit the "type" keyword in your *Intf.pas's and insert it in BusinessDomain.pas before the includes.
I'm afraid, there is no possibility to split a class declaration into multiple files. If the classes are that large, you should consider a redesign.
Another alternative are Interfaces:
type
IEmployee = interface
{ public properties and methods of an employee }
...
end;
type
TEmployee = class(BDObject, IEmployee)
...
end;
The interface and class declaration can now reside in different files.
Ulrich is quite correct (+1) whilst you can manipulate your include files to work approx this way, it's not going to be a very good Dev experience for you.
Think of the $Include directive as a simple text replacement mechanism, the things that make your units, well...units is the scoping mechanisms (uses sections, type sections etc) they will be much more difficult to use in an include file, thats why include files are usually called xxx.inc and not xxxx.pas as they often will not stand up as a source file by themselves. This of course makes them very difficult in a dev environment as they are then effectively just text files not proper debuggable units.
Include files are one of those legacy pascal features which keep rolling forward. There was a point when we didn't have a uses clause, and it was the only way to manage multiple files (of course we all programmed using wordstar commands for code navigation... wait, they are still there too).
Today, the most common use of include files is to include a block of code which must be shared among multiple files and can't be just used from another unit. As Mason pointed out in another comment, that would be the IFDEF-DEFINE blocks for determining things like what compiler options should be turned on, and what defines should be enabled project wide. We are no longer bound by the 64k limit on a source file.
Some other points to consider. Most of the tools for searching your source may not navigate into your include files. Using something as simple as a text search to find that text message that keeps popping up might be difficult. You would be much better served by not putting any code in them at all. When translating a map file to code, I believe your line numbers specified in the map file would be the total file if the include file was merged in place. If you use an automated tool such as MadExcept the error line reported might not be the actual location.
My suggestion would be to use interfaces as Uwe suggested. They are not just for COM, and can solve your desire to separate the "interface" from the "implementation".
Maybe my previous comment was a little presumptuous ... Reading your question again I think you may have misunderstood how to use units and in particular the "uses" directive.
You can declare individual classes both interface and implementation in a single unit file:
unit EmployeeDBCLassesU
uses system, DB, Blah, blah; // Units needed by this unit
interface
type
TEmployeeList = class(DBList)
Procedure DoSomething;
end;
TEmployeeDM = class(BDDBobject)
Procedure DoSomething;
end;
implementation
{TEmployeeList}
Procedure TEmployeeList.DoSomething;
begin
...
end;
{TEmployeeDM }
Procedure TEmployeeDM.DoSomething;
begin
...
end;
Then later to use them elsewehere:
Unit BusinessDomain
interface
uses EmployeeDBCLassesU; // MY units needed by this unit
.
.
.
This brings all the class definition in to BusinessDomain
and you can then do
TBusinessDomain = class(BDDBobject)
EmployeeList: TEmployeeList;
EmployeeDM: TEmployeeDM;
.
.
.;
end;
Hope this helps more as you will gain so much from the correct approach - you will realise this especially when navigating units for editing and Debugging.
If you really like to separate interface and implementation, have a look at Modula2. This is also a pascal like application, but it uses two files for each "unit". One for the interface and one for the implementation.
Another solution, is to split the files or class definitions, and write a custom preprocessor that links these (text wise) together. You then have something like:
unit BusinessDomain
interface
uses
classes;
type
Employment = class from Interface\EmployeeIntf.pas;
Department = class from Interface\DepartmentIntf.pas;
Schedule = class from Interface\ScheduleIntf.pas;
implementation
uses
SysUtils;
external define
Employment = class from Implementation\EmployeeImpl.pas;
Department = class from Implementation\DepartmentImpl.pas;
Schedule = class from Implementation\ScheduleImpl.pas;
end;
end.
With Delphi 2009 you can issue commands before and after the build phase. So technically this is possible.

Is possible to include files (linking) based on a component property?

Delphi 2007/2009 odd question here:
It's possible, based on a component property defined in design-time, to include files in linking or leave them ?
Example: If I leave SomeProperty true, when compiling, the unit SomeUnit will be included into my project. Otherwise it will not be included.
My second approach to this problem is to deploy a second component, which when dropped in the form (or not) will include the unit in uses clause. But if it can be done with a property, that'll be better.
I want to avoid conditional compilation via IFDEF because that forces the component to be built every time the projects are built. Or not?
I am trying to achieve an easy way of including some units in project, and then those units will provide support for specific databases. Having these into an option, at the connection component, will be ideally easy: Check support and that's done. Uncheck, and get some less KBs in your compiled APP.
edit: I'll stay with the component way for instance. I knew the IFDEF method and things, but that forces the component to be built everytime the projects are built. Or not?
I was trying to achieve an easy way of including some units in project, and then that units will provide support for specific databases. Having these into an option, at the connection component, will be ideally easy: Check support and that's done. Uncheck, and get some less KBs in your compiled APP.
No.
What are you trying to solve?
You could add a postcompiling step that would optionally include some resource based on a component property - but you'd have to do some coding to implement such a feature.
You can use the {$IFDEF youridentifier} optional code {$ENDIF} method to conditionally compile data in to your application and then to enable it just go to your project options and enter youridentifier into the appropriate option field. Another method of doing this is to add the following to the top of your unit (or in an include file):
{$DEFINE youridentifier}
which will force youridentifier on. To disable, just place a period right before the $:
{.$DEFINE youridentifier}
Using these techniques its easy to conditionally bring in code or replace code with each compile.
Write an IDE add-in. Handle the "before compile" notification and check whether any forms or data modules in the project have components of the type you're interested in, and then check their properties. Based on what you find there, you can try modifying the contents of a unit to use the other unit of your choice. It certainly doesn't sound easy, but it seems possible.
Your second idea is very easy. It's exactly what the TXPManifest component does, for example. Beware that removing such a component from a form does not "unuse" the associated unit.
To conditionally add support for different databases, you might consider using run-time packages. (That's how the IDE manages to support so many different kinds of components, after all.) Put each database's custom code into a different package. Then, the databases you support are simply whichever ones have packages available at run time. No compile-time or design-time configuration required. The obstacle to this, however, is to manage which packages are available, and determine which of them are the packages that provide database support.
Your second approach will not necessarily work the way you want it to. While Delphi will helpfully add the necessary unit to your uses list when you drop the component onto the form, it will not remove the unit when you delete the component. And even if you don't use the component or any other exported entitiy from that unit, it is possible that the unit will be linked to your application anyway, when there is code in the initialization or finalization part of the unit. This is unfortunately very often the case, even when it would be possible to initialize stuff on-demand.
There is no way to do what you are asking, but something you might not be aware of is that units which are included in your uses list but never referenced will have a minimal impact on the size of your executable. The smart linker that is in Delphi does a very good job of removing code which is never used. If you are careful about your "optional unit" which is referenced by the component, and don't have any code in it which is executed globally (everything is self contained in a class or classes) then it shouldn't matter if it is in the uses clause and not used, or not in the uses clause at all.
This would easily allow you to do what I think your wanting to do, which would be to drop a component on a form which includes a unit that then can be linked to your application. Removing the component would have the effect of not linking in the unit. I believe, however, that any resources (for example forms or other items included by the $R directive) which are in the used unit would still be included in the executable.
You could use DesignIntf.RegisterSelectionEditor to register a selection editor (see comments in Delphi source code about ISelectionEditor), then use the RequiresUnits procedure to include extra units in uses clause.
TMySelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
procedure Register;
implementation
procedure TMySelectionEditor.RequiresUnits(Proc: TGetStrProc);
var
comp: TMyComponent;
I: Integer;
begin
inherited RequiresUnits(Proc);
Proc('ExtraUnit');
// might be a better way of doing the code from here onwards?
if (Designer=nil)or(Designer.Root=nil) then Exit;
for I := 0 to Designer.Root.ComponentCount - 1 do
begin
if (Designer.Root.Components[i] is TMyComponent) then
begin
comp := TMyComponent(Designer.Root.Components[i]);
if comp.SampleProperty = True then
Proc('ExtraUnit2');
Proc(comp.ObjProperty.UnitName);
end;
end;
end;
procedure Register;
begin
RegisterSelectionEditor(TMyComponent, TMySelectionEditor);
end;

Resources