Mega Code Archive

 
Categories / Delphi / Examples
 

Conditionalcomplilation

Some of you may or may not be aware that Delphi allows 'conditional compilation'. I'm currently using this feature to make my MTS objects which can either be run locally as a COM server (with the database connections etc hard-coded) for testing, or remotely on an MTS server (with shared property manager etc). Mr Wilson asked if I'd share this scheme with the rest of the team, so here it is for what it may profit you: 1) Define a condition (eg: LOCALTEST=1) in Project | Options | Directories / Conditionals | Conditional Defines. Conditional compilation in Delphi works through commands like: {$IfDef} {$Else} {$EndIf} {$IfNDef} (yes, they are comments.. look in the Delphi help under 'conditional compilation directives' if you're not sure). 2) Wrap your shared property manager code in your DACs around these {$IfDef} {$Else} {$EndIf} type statements eg: {$IfNDef LOCALTEST} private SharedProp : ISharedProperty; SharedPropGroup : ISharedPropertyGroup; function GetProperty( const PropName : string ) : WideString; {$ENDIF} end; {$IfDef LOCALTEST} const DBConnection = 'Provider=SQLOLEDB; User name=draft3user; Initial Catalog=CMDBDraft3; Data Source=SV-ELISSQL'; DBUsername = 'draft3user'; DBPassword = ''; {$EndIf} {$IfDef LOCALTEST} con.Open( DBConnection, DBUsername, DBPassword, 0 ); {$ELSE} con.Open( GetProperty( 'connectionstring'), GetProperty('username'), GetProperty('password') ,0); {$EndIf} {$IfNDef LOCALTEST} function TEventsDAC.GetProperty(const PropName: string): WideString; var Exists : WordBool; Prop : OleVariant; begin try SharedPropGroup := CreateSharedPropertyGroup( 'Seneca' ); SharedProp := SharedPropGroup.CreateProperty( Trim( PropName ), Exists ); try if Exists then Prop := SharedProp.Value else Prop := EmptyStr; Result := Prop; SetComplete; except SetAbort; raise; end; finally if SharedPropGroup <> nil then SharedPropGroup := nil; if SharedProp <> nil then SharedProp := nil; end; end; {$EndIf} These are just fragments of course, but hopefully you get the idea. So, when I compile with LOCALTEST defined, it will skip out all the shared property manager code, and deal solely with hard-coded database access and therefore usable as a local COM server. To finish testing and put it on MTS, I just remove the LOCALTEST definition from the project options and recompile. Presto. Anyway, if this is crap, or you know all this already, then apologies... but I think it's quite useful. Cheers, Bil Irving ********************************** If you want all the values... look at the Delphi Free Stuff component suite and specifically dfs.inc file. http://www.delphifreestuff.com/ *******************************************