File: ApplicationDataModule.pas

package info (click to toggle)
mysql-gui-tools 5.0r12-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 105,540 kB
  • ctags: 50,897
  • sloc: sql: 348,439; pascal: 285,780; cpp: 94,578; ansic: 90,768; objc: 33,761; sh: 25,629; xml: 10,924; yacc: 10,755; java: 9,986; php: 2,806; python: 2,068; makefile: 1,945; perl: 3
file content (989 lines) | stat: -rw-r--r-- 36,315 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
unit ApplicationDataModule;

interface

uses
  gnugettext, SysUtils, Classes, TntClasses, ComCtrls, ImgList,
  Controls, Forms, Contnrs, Windows,
  ExtCtrls, AuxFuncs, PNGImage, StdCtrls, StrUtils,
  myx_util_public_interface,
  myx_public_interface, myx_admin_public_interface,
  Options, MyxError, MySQLConnection, AdminService,
  TntForms, TntSysUtils;

type
  TMYXAdminOptions = class;

  TApplicationDM = class(TDataModule)
    ServiceStatusImageList: TImageList;
    AdminTree16ImageList: TImageList;
    AdminTree24ImageList: TImageList;
    Admin48ImageList: TImageList;
    CatalogImageList: TImageList;
    SectionImageList: TImageList;
    ItemSelectImageList: TImageList;
    procedure DataModuleCreate(Sender: TObject);
    procedure DataModuleDestroy(Sender: TObject);
  private
    FOptionProvider: IOptionProvider;
    FCommonOptions: IOptionProvider;
    FFreeService: Boolean;  // True if the DM has created a local service class. This must be freed on DM desctruction.
    FCurrentService: TMySQLService;

    function GetConfigValue(const Key: WideString): WideString;
    function GetDataDir: WideString;
    function GetOptionProvider: IOptionProvider;
    procedure SetCurrentService(const Value: TMySQLService);
  public
    ApplicationIsTerminating: Boolean;

    Options: TMYXAdminOptions;
    CurrentConnection: TMySQLConn;

    procedure CheckCommandlineParameter;
    function CheckFiles: Boolean;
    function GetLastFileDialogPaths(DlgName: WideString): WideString;
    function GetPathFromConfig(const Key: WideString): WideString;
    procedure LoadOptions;
    procedure OnApplicationException(Sender: TObject; E: Exception);
    procedure SetLastFileDialogPaths(DlgName: WideString; Path: WideString);
    procedure MakeBackup;
    function PrepareConnection: Integer;

    property ConfigValue[const S: WideString]: WideString read GetConfigValue;
    property CurrentService: TMySQLService read FCurrentService write SetCurrentService;
    property DataDir: WideString read GetDataDir;
    property OptionProvider: IOptionProvider read GetOptionProvider;
  end;

  TMYXAdminOptions = class(TMyxOptions)
  private
    FCommonOptions: IOptionProvider;
  public
    constructor Create(const ApplicationID: string); override;
    destructor Destroy; override;

    procedure LoadOptions; override;
    procedure StoreOptions; override;
  public
    ShowOnlyServiceSections: Boolean;
    MySQLInstance: WideString;
    MySQLInstallPath: WideString;
    MySQLVersion: WideString;

    ShowUserGlobalPrivileges: Boolean;
    ShowUserTableColumnPrivileges: Boolean;

    StartSection: Integer;
    SectionSidebarWidth: Integer;
    SectionSidebarHidden: Boolean;

    UsePeakLevel: Boolean;
    ResetPeakLevel: Boolean;
    PeakLevelResetTicks: Integer;

    LastFileDialogPaths: TTntStringList;

    BackupProfile: WideString;
    BackupTargetPath: WideString;
    BackupPrefix: WideString;

    AddDateTimeToBackupFiles: Boolean;
    WriteBackupLog: Boolean;
    BackupLogDir: WideString;
    BackupLogEntryAfterRows: Integer;
  end;

  EMyxAdminLibError = class(EMyxLibraryError)
  protected
    function GetFormattedMessage: WideString; override;
  end;

var
  ApplicationDM: TApplicationDM;

//----------------------------------------------------------------------------------------------------------------------

implementation

uses
  Main, ConnectToInstance, AuxAdminBackupRestore;

{$R *.dfm}

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.DataModuleCreate(Sender: TObject);

var
  S: WideString;
  
begin
  //Exception Handling
  Application.OnException := OnApplicationException;

  ApplicationIsTerminating := False;

  //DLL Version check
  S := '';
  if (libmysqlx_PUBLIC_INTERFACE_VERSION <> myx_get_public_interface_version) then
    S := Format(_('There is a incompatible version of the ' +
      'library %s installed (Version %s). Please update the library to version %s.'),
      ['libmysqlx.dll', FormatLibraryVersion(myx_get_public_interface_version),
      FormatLibraryVersion(libmysqlx_PUBLIC_INTERFACE_VERSION)]) + #13#10#13#10;

  if (libmysqladmin_PUBLIC_INTERFACE_VERSION <> myx_get_admin_public_interface_version) then
    S := Format(_('There is a incompatible version of the ' +
      'library %s installed (Version %s). Please update the library to version %s.'),
      ['libmysqladmin.dll', FormatLibraryVersion(myx_get_admin_public_interface_version),
      FormatLibraryVersion(libmysqladmin_PUBLIC_INTERFACE_VERSION)]) + #13#10#13#10;

  if (S <> '') then
    if (ShowModalDialog(_('Library version mismatch'),
      Trim(S), myx_mtError, _('Quit') + #13#10 + _('Ignore')) = 1) then
    begin
      ApplicationIsTerminating := True;
      Application.Terminate;
    end;

  // Keep a reference to the global options to make sure it is never freed before the application options are freed.
  FCommonOptions := MYXCommonOptionProvider;

  CurrentConnection := TMySQLConn.Create(nil);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.DataModuleDestroy(Sender: TObject);

begin
  if FFreeService then
    CurrentService.Free;
    
  CurrentConnection.Free;

  // We don't need to free the options class. By setting the option provider to nil the ref count is correctly
  // decremented and the class is freed when the ref count reaches zero.
  Options := nil;
  FOptionProvider := nil;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.CheckCommandlineParameter;

var
  I: Integer;
  S: string;

begin
  for I := 1 to ParamCount do
  begin
    S := ParamStr(I);
    
    //Start in serviceconfig mode
    if (CompareText(S, '-serviceconfig') = 0) then
    begin
      ApplicationDM.Options.ShowOnlyServiceSections := True;

      // Create a dummy service entry just like PrepareConnection does.
      // It is used to do an initial enable/disable call on the  service control page.
      CurrentService := TMySQLService.Create;
      FFreeService := True;
    end;

    //Set MySQL installation path
    if (CompareText(Copy(S, 1, 13), '-installpath=') = 0) then
      ApplicationDM.Options.MySQLInstallPath :=
        IncludeTrailingPathDelimiter(Copy(ParamStr(i), 14, Length(S)));

    //Select the start section
    if (CompareText(Copy(S, 1, 14), '-startsection=') = 0) then
      ApplicationDM.Options.StartSection := StrToIntDef(Copy(S, 15, Length(ParamStr(i))), 1);

    //User settings Data directory
    if (Copy(S, 1, 3) = '-UD') then
    begin
      MYXCommonOptions.UserDataDir := Copy(ParamStr(i), 4, Length(ParamStr(i)));

      MYXCommonOptions.LoadOptions;
      ApplicationDM.LoadOptions;
    end;

    //MySQLInstance
    if (CompareText(Copy(ParamStr(i), 1, 10), '-instance=') = 0) then
      ApplicationDM.Options.MySQLInstance := Copy(S, 11, Length(ParamStr(i)));

    //Backups
    if (Copy(S, 1, 3) = '-bp') then
      ApplicationDM.Options.BackupProfile := Copy(S, 4, Length(ParamStr(i)));
    if (Copy(S, 1, 3) = '-bt') then
      ApplicationDM.Options.BackupTargetPath := Copy(S, 4, Length(ParamStr(i)));
    if (Copy(S, 1, 3) = '-bx') then
      ApplicationDM.Options.BackupPrefix := Copy(S, 4, Length(ParamStr(i)));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.OnApplicationException(Sender: TObject; E: Exception);

begin
  if (not (Application.Terminated)) then
    ShowError(E);
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.PrepareConnection: Integer;

begin
  if CurrentService = nil then
  begin
    CurrentService := TMySQLService.Create;
    FFreeService := True;
  end;

  Result := CurrentConnection.ConnectToServer(True);
  if (Result = 1) and Assigned(CurrentConnection.UserConnection) then
  begin
    Options.MySQLVersion := IntToStr(CurrentConnection.MajorVersion) + '.' + IntToStr(CurrentConnection.MinorVersion);

    if CurrentConnection.IsLocalServer then
    begin
      CurrentService.ServiceName := myx_get_running_service_name(CurrentConnection.UserConnection.port);
      CurrentService.ConfigFile := myx_get_running_service_config_file(CurrentConnection.UserConnection.port);
      if (CurrentService.ServiceName = '') or not FileExists(CurrentService.ConfigFile) then
      begin
        ShowModalDialog(_('Could not find settings'), _('Either the server service or the configuration file could not ' +
          'be found. Startup variables and service section are therefore disabled.'), myx_mtError, _('OK'));
        CurrentConnection.IsLocalServer := False; // Disables the possibility to edit startup vars or the server service.
      end;
    end;
  end
  else
  begin
    if Result = -1 then
      Options.ShowOnlyServiceSections := True;
    CurrentService.ServiceName := '';
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.CheckFiles: Boolean;

var
  MissingFiles: WideString;

begin
  CheckFiles := True;

  MissingFiles := '';

  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqlx_dbm_charsets.xml'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqlx_dbm_charsets.xml' + #13#10;
  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqlx_dbm_datatypes.xml'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqlx_dbm_datatypes.xml' + #13#10;

  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqladmin_startup_variables_description.xml'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqladmin_startup_variables_description.xml' + #13#10;
  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqladmin_status_variables.xml'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqladmin_status_variables.xml' + #13#10;
  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqladmin_system_variables.xml'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqladmin_system_variables.xml' + #13#10;
  if (not (FileExists(MYXCommonOptions.XMLDir + 'mysqladmin_startup_variables_description.dtd'))) then
    MissingFiles := MissingFiles +
      MYXCommonOptions.XMLDir + 'mysqladmin_startup_variables_description.dtd' + #13#10;

  if (MissingFiles <> '') then
  begin
    ShowModalDialog(_('Files missing!'),
      _('Some vital files cannot be found. ') + #13#10 +
      _('Please check the file path and the existence of the following files:') + #13#10#13#10 +
      MissingFiles);

    CheckFiles := False;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.LoadOptions;

begin
  // Load Options
  Options := TMYXAdminOptions.Create('administrator');
  FOptionProvider := Options; // This increases the reference count to 1. Read more in MySQLAdministrator.dpr
                              // why we need that.
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.GetConfigValue(const Key: WideString): WideString;

// Returns the value of the requested entry in the current config file (if there is one).
// If no config file is set or the key does not exist or consists only of its name without an assignment
// the result value is an empty string.

var
  ErrorNumber: MYX_ADMIN_LIB_ERROR;

begin
  Result := '';

  if Assigned(CurrentService) and (CurrentService.ConfigFile <> '') then
    Result := myx_get_cnf_value(CurrentService.ConfigFile, 'mysqld', Key, @ErrorNumber);
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.GetDataDir: WideString;

begin
  Result := ConfigValue['datadir'];

  if (Result = '') and Assigned(CurrentService) then
  begin
    // If no data folder could be found then we might have a corrupted or non-existing ini file.
    // Use the binary folder instead (as is the default in the server).
    Result := CurrentService.PathToBinary + '..\data';
  end;
  Result := WideIncludeTrailingPathDelimiter(Result);
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.GetOptionProvider: IOptionProvider;

begin
  // Return the provider interface implemented in the application option.
  Result := Options;
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.GetLastFileDialogPaths(DlgName: WideString): WideString;

begin
  Result := Options.LastFileDialogPaths.Values['DlgName'];
end;

//----------------------------------------------------------------------------------------------------------------------

function TApplicationDM.GetPathFromConfig(const Key: WideString): WideString;

// Reads the option's value with the given name from the config file as a path.
// If the option does not exist or has no value then an empty string is returned.

begin
  Result := ConfigValue[Key];

  // Check if it is an absolute path. If Result is 'checked' then we have a name only
  // option and pass it along unmodified.
  if not ((Length(Result) > 2) and (Result[2] = ':')) and (Result <> 'checked') then
  begin
    // Add the server's data dir to make it an absolute path.
    // This is how the server interprets relative pathes.
    Result := DataDir + Result;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.SetCurrentService(const Value: TMySQLService);

begin
  if FCurrentService <> Value then
  begin
    if FFreeService then
    begin
      FFreeService := False;
      FCurrentService.Free;
    end;
    FCurrentService := Value;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.SetLastFileDialogPaths(DlgName: WideString; Path: WideString);

begin
  Options.LastFileDialogPaths.Values['DlgName'] := Path;
end;

//----------------------------------------------------------------------------------------------------------------------

function BackupProgress(current_table_name: PChar;
  num_tables: Integer; num_tables_processed: Integer;
  num_rows: Integer; num_rows_processed: Integer; user_data: Pointer): Integer; cdecl;
var
  PSender: ^TApplicationDM;
  BackupLogFilename: WideString;
  S: string;
begin
  PSender := user_data;

  with PSender.Options do
  begin
    BackupLogFilename := IncludeTrailingPathDelimiter(
      BackupLogDir) + 'MySQLAdminBackupLog.txt';

    if (BackupLogEntryAfterRows > 0) then
      S := StringAlignLeft(current_table_name, 30) + ' ' +
        StringAlignLeft(
        '(' + IntToStr(num_tables_processed) + '/' + IntToStr(num_tables) + ')', 11) +
        ' | ' +
        IntToStr(num_rows_processed) + '/' + IntToStr(num_rows) + #13#10
    else
      S := StringAlignLeft(current_table_name, 30) +
        ' (' + IntToStr(num_tables_processed) + '/' + IntToStr(num_tables) + ')' + #13#10;

    AddToFile(BackupLogFilename, S);
  end;

  Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TApplicationDM.MakeBackup;

var
  i: Integer;
  user_conns: PMYX_USER_CONNECTIONS;
  stored_conns: TMYX_USER_CONNECTIONS;
  user_conn: TMYX_USER_CONNECTION;
  error: MYX_LIB_ERROR;
  PMySQL: Pointer;
  BackupError: MYX_BACKUP_ERROR;
  error_code: MYX_ADMIN_LIB_ERROR;
  Profile: PMYX_BACKUP_PROFILE;
  fname, ErrorTxt: WideString;
  BackupLogFilename: WideString;

begin
  try
    SendToEventLog(Format(_('MySQL Administrator is preparing backup for profile %s.'),
      [Options.BackupProfile]), EVENTLOG_INFORMATION_TYPE);
  except
    on Exception do begin end;
  end;

  BackupLogFilename := IncludeTrailingPathDelimiter(
    Options.BackupLogDir) + 'MySQLAdminBackupLog.txt';

  if (Options.WriteBackupLog) then
    AddToFile(BackupLogFilename, StringOfChar('-', 40) + #13#10 +
      Format(_('%s - Backup started.' + #13#10 +
      'Preparing backup for for profile %s.'),
      [FormatDateTime('yyyy-mm-dd hh:nn', Now),
      Options.BackupProfile]) + #13#10);

  //Get connection
  //Fetch connections from library
  user_conns := myx_load_user_connections(
    MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml', @error);
  if (error <> MYX_NO_ERROR) then
  begin
    try
      SendToEventLog(Format(_('Error while loading stored connections from %s. Error Number %d.'),
        [MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml', Ord(error)]), EVENTLOG_ERROR_TYPE);
    except
      on Exception do begin end;
    end;

    if (Options.WriteBackupLog) then
      AddToFile(BackupLogFilename, StringOfChar('-', 40) + #13#10 +
        Format(_('Error while loading stored connections from %s. Error Number %d.'),
        [MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml', Ord(error)]) + #13#10);

    Exit;
  end;

  if (Options.WriteBackupLog) then
    AddToFile(BackupLogFilename,
      Format(_('Connections loaded from file %s.'),
      [MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml']) + #13#10);

  try
    stored_conns := TMYX_USER_CONNECTIONS.create(user_conns);

    try
      user_conn := nil;
      for i := 0 to stored_conns.user_connections.Count - 1 do
      begin
        if (CompareText(stored_conns.user_connections[i].connection_name,
          MYXCommonOptions.ConnectionToUse) = 0) then
        begin
          user_conn := stored_conns.user_connections[i];
          break;
        end;
      end;

      if (Options.WriteBackupLog) then
        AddToFile(BackupLogFilename,
          Format(_('Connection %s selected.'),
          [user_conn.connection_name]) + #13#10);

      if (user_conn = nil) then
      begin
        try
          SendToEventLog(Format(_('Connection %s cannot be found.'),
            [MYXCommonOptions.ConnectionToUse]), EVENTLOG_ERROR_TYPE);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename, StringOfChar('-', 40) + #13#10 +
            Format(_('Connection %s cannot be found.'),
            [MYXCommonOptions.ConnectionToUse]) + #13#10);

        Exit;
      end;

      //Connect to Server
      PMySQL := myx_mysql_init();
      if (PMySQL = nil) then
      begin
        try
          SendToEventLog(_('Error while allocating memory for MySQL Struct.'),
            EVENTLOG_ERROR_TYPE);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename,
            _('Error while allocating memory for MySQL Struct.') + #13#10);

        Exit;
      end;

      if (myx_connect_to_instance(
        user_conn.get_record_pointer, PMySQL) <> 0) then
      begin
        try
          SendToEventLog(Format(_('Cannot connect to MySQL Server. %s (Error Number %d)'),
            [myx_mysql_error(PMySQL), myx_mysql_errno(PMySQL)]),
            EVENTLOG_ERROR_TYPE);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename,
            Format(_('Cannot connect to MySQL Server. %s (Error Number %d)'),
            [myx_mysql_error(PMySQL), myx_mysql_errno(PMySQL)]) + #13#10);

        Exit;
      end;

      if (Options.WriteBackupLog) then
        AddToFile(BackupLogFilename,
          Format(_('Connection to server %s:%d established.'),
          [user_conn.hostname, user_conn.port]) + #13#10);

      if (Pos('.MBP', Uppercase(Options.BackupProfile)) <= 0) then
        Options.BackupProfile := Options.BackupProfile + '.mbp';

      if (Pos(':', Options.BackupProfile) > 0) then
        Profile := myx_load_profile(ExtractFileName(MYXCommonOptions.UserDataDir + Options.BackupProfile),
          ExtractFilePath(Options.BackupProfile), @error_code)
      else
        Profile := myx_load_profile(ExtractFileName(MYXCommonOptions.UserDataDir + Options.BackupProfile),
          ExtractFilePath(MYXCommonOptions.UserDataDir + Options.BackupProfile), @error_code);

      if (error_code <> MYX_ADMIN_NO_ERROR) then
      begin
        try
          SendToEventLog(Format(_('Error while loading profile %s.'),
            [MYXCommonOptions.UserDataDir + Options.BackupProfile]),
            EVENTLOG_ERROR_TYPE);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename,
            Format(_('Error while loading profile %s.'),
            [MYXCommonOptions.UserDataDir + Options.BackupProfile]) + #13#10);

        Exit;
      end;

      if (Options.WriteBackupLog) then
        AddToFile(BackupLogFilename,
          Format(_('Profiled %s loaded.'),
          [MYXCommonOptions.UserDataDir + Options.BackupProfile]) + #13#10);

      if (Options.AddDateTimeToBackupFiles) then
      begin
        if (Copy(Options.BackupPrefix, Length(Options.BackupPrefix), 1) = '_') then
          fname := IncludeTrailingPathDelimiter(Options.BackupTargetPath) +
            Options.BackupPrefix + FormatDateTime('yyyymmdd hhmm', Now) + '.sql'
        else
          fname := IncludeTrailingPathDelimiter(Options.BackupTargetPath) +
            Options.BackupPrefix + ' ' + FormatDateTime('yyyymmdd hhmm', Now) + '.sql';
      end
      else
        fname := IncludeTrailingPathDelimiter(Options.BackupTargetPath) +
          Options.BackupPrefix + '.sql';

      try
        SendToEventLog(Format(_('MySQL Administrator is starting backup for profile %s.'),
          [Options.BackupProfile]), EVENTLOG_INFORMATION_TYPE);
      except
        on Exception do begin end;
      end;

      try
        if (Options.WriteBackupLog) then
        begin
          AddToFile(BackupLogFilename, #13#10 +
            _('Starting backup...') + #13#10#13#10);

          if (Options.BackupLogEntryAfterRows = 0) then
            BackupError := myx_make_backup_with_profile(PMySQL, Profile, fname,
              2000000, BackupProgress, Addr(self))
          else
            BackupError := myx_make_backup_with_profile(PMySQL, Profile, fname,
              Options.BackupLogEntryAfterRows, BackupProgress, Addr(self));
        end
        else
          BackupError := myx_make_backup_with_profile(PMySQL, Profile, fname,
            10000, BackupProgress, Addr(self));

      finally
        myx_free_profile(Profile);
      end;

      if (BackupError <> MYX_BACKUP_NO_ERROR) then
      begin
        ErrorTxt := myx_get_backup_error_string(BackupError);
        case BackupError of
          MYX_BACKUP_SERVER_ERROR:
            ErrorTxt := Format(ErrorTxt, [myx_mysql_errno(PMySQL), myx_mysql_error(PMySQL)]);
          MYX_BACKUP_CANT_OPEN_FILE:
            ErrorTxt := Format(ErrorTxt, [fname]);
          MYX_BACKUP_OUTPUTDEVICE_FULL:
            ErrorTxt := Format(ErrorTxt, [fname]);
        end;

        try
          SendToEventLog(ErrorTxt, EVENTLOG_ERROR_TYPE);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename, #13#10 +
            Format(_('ERROR: %s - The following error occured: ' + #13#10 + '%s'),
            [FormatDateTime('yyyy-mm-dd hh:nn', Now),
            MYXCommonOptions.UserDataDir + Options.BackupProfile]) + #13#10);

        myx_mysql_close(PMySQL);
      end
      else
      begin
        myx_mysql_close(PMySQL);

        try
          SendToEventLog(Format(_('Backup file %s written successfully.'),
            [fname]), EVENTLOG_SUCCESS);
        except
          on Exception do begin end;
        end;

        if (Options.WriteBackupLog) then
          AddToFile(BackupLogFilename, #13#10 +
            Format(_('%s - Backup written successfully.'),
            [FormatDateTime('yyyy-mm-dd hh:nn', Now)]) + #13#10);
      end;
    finally
      stored_conns.Free;
    end;
  finally
    myx_free_user_connections(user_conns);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function EMyxAdminLibError.GetFormattedMessage: WideString;

begin
  case MYX_ADMIN_LIB_ERROR(ErrorNr) of
    MYX_ADMIN_ERROR_CANT_OPEN_FILE:
      Result := Format(_('The File %s cannot be opened.'), [ErrorNrParam]);
    MYX_ADMIN_XML_PARSE_ERROR:
      Result := Format(_('An error occured while parsing the XML file %s.'), [ErrorNrParam]);
    MYX_ADMIN_XML_NO_VALID_DOCUMENT:
      Result := Format(_('An error occured while validating the XML file %s.'), [ErrorNrParam]);
    MYX_ADMIN_XML_EMPTY_DOCUMENT:
      Result := Format(_('The XML file %s is empty.'), [ErrorNrParam]);
    MYX_ADMIN_INI_PARSE_ERROR:
      Result := Format(_('An error occured while parsing the INI file %s.'), [ErrorNrParam]);
    MYX_ADMIN_GENERAL_ERROR:
      Result := _('A general error occured.');
    MYX_ADMIN_SQL_ERROR:
      Result := _('An SQL error occured.');
  else
    Result := _('An error occured.');
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

constructor TMYXAdminOptions.Create(const ApplicationID: string);

begin
  LastFileDialogPaths := TTntStringList.Create;

  // Keep a reference to the global options to avoid that they are released before the application optiones are gone.
  FCommonOptions := MYXCommonOptionProvider;

  inherited Create(ApplicationID);
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TMYXAdminOptions.Destroy;

begin
  inherited Destroy;

  LastFileDialogPaths.Free;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMYXAdminOptions.LoadOptions;

var
  POptions: PMYX_APPLICATION_OPTIONS;
  Options: TMYX_APPLICATION_OPTIONS;
  I, J: Integer;
  error: MYX_LIB_ERROR;
  OptionGroupName, OptionName, OptionValue: WideString;
  ExePath: WideString;
  Provider: IOptionProvider;

begin
  ExePath := ExtractFilePath(Application.ExeName);
  Provider := Self;

  StartSection := 1;
  ShowOnlyServiceSections := False;

  MySQLInstallPath := '';

  if (GetDriveType('D:\') = DRIVE_FIXED) and (DirectoryExists('d:\mysql')) then
    MySQLInstallPath := 'd:\mysql\';

  if MySQLInstallPath = '' then
    MySQLInstallPath := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));

  // Set a default value. When a connection is established this value is reset.
  MySQLVersion := '5.0';

  // Update from 1.0.1a to 1.0.2a.
  if FileExists(MYXCommonOptions.UserDataDir + 'mysqlx_options.xml') then
    RenameFile(MYXCommonOptions.UserDataDir + 'mysqlx_options.xml', MYXCommonOptions.UserDataDir +
      'mysqlx_admin_options.xml');

  // Update from 1.0.3 to 1.0.4.
  if FileExists(MYXCommonOptions.UserDataDir + 'mysqlx_admin_options.xml') then
    RenameFile(MYXCommonOptions.UserDataDir + 'mysqlx_admin_options.xml', MYXCommonOptions.UserDataDir +
      'mysqladmin_options.xml');

  //Initialize Values
  SectionSidebarWidth := 185;
  SectionSidebarHidden := False;
  ShowUserGlobalPrivileges := False;
  ShowUserTableColumnPrivileges := False;

  UsePeakLevel := True;
  ResetPeakLevel := True;
  PeakLevelResetTicks := 30;

  LastFileDialogPaths.Text := '';

  AddDateTimeToBackupFiles := True;
  WriteBackupLog := False;
  BackupLogDir := 'C:\';
  BackupLogEntryAfterRows := 0;

  WindowPosList.Clear;

  // Read options file.
  if (FileExists(MYXCommonOptions.UserDataDir + 'mysqladmin_options.xml')) then
  begin
    POptions := myx_get_application_options(
      MYXCommonOptions.UserDataDir + 'mysqladmin_options.xml',
      @error);
    try
      if (error <> MYX_NO_ERROR) then
      begin
        ShowModalDialog(_('XML Error'), _('Error while loading Options file ''') + MYXCommonOptions.UserDataDir +
          'mysqladmin_options.xml' + ''''#13#10 + _('Error Nr.:' )+ IntToStr(Ord(error)), myx_mtError);
      end
      else
      begin
        Options := TMYX_APPLICATION_OPTIONS.Create(POptions);
        try
          for I := 0 to Options.option_groups.Count - 1 do
            for J := 0 to Options.option_groups[I].name_value_pairs.Count - 1 do
            begin
              OptionGroupName := Options.option_groups[I].name;
              OptionName := Options.option_groups[I].name_value_pairs[J].name;
              OptionValue := Options.option_groups[I].name_value_pairs[J].value;

              Provider.OptionAsString[OptionName] := OptionValue;
              if (CompareText(OptionGroupName, 'General') = 0) then
              begin
                if (CompareText(OptionName, 'LastFileDialogPaths') = 0) then
                  LastFileDialogPaths.Text := AnsiReplaceText(OptionValue, '', #13#10)
                else
                  ;
              end
              else
                if (CompareText(OptionGroupName, 'GUISetup') = 0) then
                begin
                  if (CompareText(OptionName, 'SectionSidebarWidth') = 0) then
                    SectionSidebarWidth := StrToIntDef(OptionValue, 185)
                  else
                    if (CompareText(OptionName, 'SectionSidebarHidden') = 0) then
                      SectionSidebarHidden := (StrToIntDef(OptionValue, 0) = 1);
                end
                else
                  if (CompareText(OptionGroupName, 'AdminUserManagement') = 0) then
                  begin
                    if (CompareText(OptionName, 'ShowUserGlobalPrivileges') = 0) then
                      ShowUserGlobalPrivileges := (StrToIntDef(OptionValue, 0) = 1)
                    else
                      if (CompareText(OptionName, 'ShowUserTableColumnPrivileges') = 0) then
                        ShowUserTableColumnPrivileges := (StrToIntDef(OptionValue, 0) = 1);
                  end
                  else
                    if (CompareText(OptionGroupName, 'AdminHealthGraphs') = 0) then
                    begin
                      if (CompareText(OptionName, 'UsePeakLevel') = 0) then
                        UsePeakLevel := (StrToIntDef(OptionValue, 1) = 1)
                      else
                        if (CompareText(OptionName, 'ResetPeakLevel') = 0) then
                          ResetPeakLevel := (StrToIntDef(OptionValue, 1) = 1)
                        else
                          if (CompareText(OptionName, 'PeakLevelResetTicks') = 0) then
                            PeakLevelResetTicks := StrToIntDef(OptionValue, 30);
                    end
                    else
                      if (CompareText(OptionGroupName, 'AdminBackups') = 0) then
                      begin
                        if (CompareText(OptionName, 'AddDateTimeToBackupFiles') = 0) then
                          AddDateTimeToBackupFiles := (StrToIntDef(OptionValue, 0) = 1)
                        else
                          if (CompareText(OptionName, 'WriteBackupLog') = 0) then
                            WriteBackupLog := (StrToIntDef(OptionValue, 0) = 1)
                          else
                            if (CompareText(OptionName, 'BackupLogDir') = 0) then
                              BackupLogDir := OptionValue
                            else
                              if (CompareText(OptionName, 'BackupLogEntryAfterRows') = 0) then
                                BackupLogEntryAfterRows := StrToIntDef(OptionValue, 0);
                      end
                      else
                        if (CompareText(OptionGroupName, 'WindowPos') = 0) then
                        begin
                          WindowPosList.AddObject(OptionName, TMyxWindowPos.Create(OptionValue));
                        end;
            end;
        finally
          Options.Free;
        end;
      end;
    finally
      myx_free_application_options(POptions);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMYXAdminOptions.StoreOptions;

var
  Options: TMYX_APPLICATION_OPTIONS;
  OptionGroup: TMYX_OPTION_GROUP;
  ExePath: WideString;
  I: Integer;

begin
  if MYXCommonOptions.UserDataDir <> '' then
  begin
    ExePath := ExtractFilePath(Application.ExeName);

    // Create Application Options
    Options := TMYX_APPLICATION_OPTIONS.create;
    try
      StoreListOptions(Options.option_groups);

      OptionGroup := TMYX_OPTION_GROUP.create('General');
      Options.option_groups.Add(OptionGroup);

      AddParam(OptionGroup, 'LastFileDialogPaths', AnsiReplaceText(LastFileDialogPaths.Text, #13#10, ''));

      OptionGroup := TMYX_OPTION_GROUP.create('GUISetup');
      Options.option_groups.Add(OptionGroup);

      AddParam(OptionGroup, 'SectionSidebarWidth', IntToStr(SectionSidebarWidth));
      AddParam(OptionGroup, 'SectionSidebarHidden', IntToStr(Ord(SectionSidebarHidden)));

      OptionGroup := TMYX_OPTION_GROUP.create('AdminUserManagement');
      Options.option_groups.Add(OptionGroup);

      AddParam(OptionGroup, 'ShowUserGlobalPrivileges', IntToStr(Ord(ShowUserGlobalPrivileges)));
      AddParam(OptionGroup, 'ShowUserTableColumnPrivileges', IntToStr(Ord(ShowUserTableColumnPrivileges)));

      OptionGroup := TMYX_OPTION_GROUP.create('AdminHealthGraphs');
      Options.option_groups.Add(OptionGroup);

      AddParam(OptionGroup, 'UsePeakLevel', IntToStr(Ord(UsePeakLevel)));
      AddParam(OptionGroup, 'ResetPeakLevel', IntToStr(Ord(ResetPeakLevel)));
      AddParam(OptionGroup, 'PeakLevelResetTicks', IntToStr(PeakLevelResetTicks));

      OptionGroup := TMYX_OPTION_GROUP.create('AdminBackups');
      Options.option_groups.Add(OptionGroup);

      AddParam(OptionGroup, 'AddDateTimeToBackupFiles', IntToStr(Ord(AddDateTimeToBackupFiles)));
      AddParam(OptionGroup, 'WriteBackupLog', IntToStr(Ord(WriteBackupLog)));
      AddParam(OptionGroup, 'BackupLogDir', BackupLogDir);
      AddParam(OptionGroup, 'BackupLogEntryAfterRows', IntToStr(BackupLogEntryAfterRows));

      OptionGroup := TMYX_OPTION_GROUP.create('WindowPos');
      Options.option_groups.Add(OptionGroup);

      // Store all window positions.
      for I := 0 to WindowPosList.Count - 1 do
        AddParam(OptionGroup, WindowPosList[I],
          TMyxWindowPos(WindowPosList.Objects[I]).AsWideString);

      // Save options to file.
      myx_store_application_options(Options.get_record_pointer, MYXCommonOptions.UserDataDir + 'mysqladmin_options.xml');
    finally
      Options.Free;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

end.