unit ana_unite;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons,
  IniFiles, DB, DBTables, ADODB, ComCtrls, Base64, ExtCtrls, Menus, ADOInt,

  Tanimlamalar, gzMain, gzIO, BrowseDialog, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP,

  IdAuthentication, IdURI,

  MsMultiPartFormData, ShlObj, ShellApi, AppEvnts, CoolTrayIcon;


type
  TAnaForm = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    TabSheet3: TTabSheet;
    TabSheet4: TTabSheet;
    PreviousStageSpeedButton: TSpeedButton;
    NextStageSpeedButton: TSpeedButton;
    SpeedButton8: TSpeedButton;
    TabSheet5: TTabSheet;
    AboutSpeedButton: TSpeedButton;
    SettingsSpeedButton: TSpeedButton;
    GroupBox4: TGroupBox;
    Label8: TLabel;
    ConvertStatusLabel: TLabel;
    ConvertProgressBar: TProgressBar;
    Memo5: TMemo;
    GroupBox5: TGroupBox;
    UploadStatusLabel: TLabel;
    Label10: TLabel;
    UploadProgressBar: TProgressBar;
    Memo6: TMemo;
    Bevel1: TBevel;
    IdHTTP1: TIdHTTP;
    GroupBox1: TGroupBox;
    ServerAddressEdit: TEdit;
    Label7: TLabel;
    Label9: TLabel;
    UserNameEdit: TEdit;
    PasswordEdit: TEdit;
    Label12: TLabel;
    ShowPWCheckBox: TCheckBox;
    GroupBox2: TGroupBox;
    AutoUpdateCheckBox: TCheckBox;
    TimeEdit: TEdit;
    VTTimer: TTimer;
    Label13: TLabel;
    Label14: TLabel;
    TabSheet6: TTabSheet;
    Label15: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    ApplicationEvents1: TApplicationEvents;
    AutoStartCheckBox: TCheckBox;
    SaveDialog1: TSaveDialog;
    HelpPanel: TPanel;
    Label1: TLabel;
    SpeedButton1: TSpeedButton;
    Label18: TLabel;
    RootDirectoryEdit: TEdit;
    EducationYearEdit: TComboBox;
    Memo2: TMemo;
    Label2: TLabel;
    SpeedButton3: TSpeedButton;
    SpeedButton4: TSpeedButton;
    SpeedButton5: TSpeedButton;
    SpeedButton6: TSpeedButton;
    Label3: TLabel;
    LocalTablesListBox: TListBox;
    RemoteTablesListBox: TListBox;
    Memo4: TMemo;
    ReportMemo: TMemo;
    SpeedButton2: TSpeedButton;
    Panel2: TPanel;
    HelpMemo: TMemo;
    TrayPopupMenu: TPopupMenu;
    Programgster1: TMenuItem;
    ProgramGizle1: TMenuItem;
    N1: TMenuItem;
    k1: TMenuItem;
    AutoUpdateTimer: TTimer;
    PercentLabel: TLabel;
    Label4: TLabel;
    VersionNumberComboBox: TComboBox;
    Memo3: TMemo;
    Memo1: TMemo;
    TrayIcon1: TCoolTrayIcon;
    procedure FormCreate(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure SpeedButton8Click(Sender: TObject);
    procedure NextStageSpeedButtonClick(Sender: TObject);
    procedure PreviousStageSpeedButtonClick(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure SpeedButton6Click(Sender: TObject);
    procedure SpeedButton4Click(Sender: TObject);
    procedure SpeedButton5Click(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer);
    procedure IdHTTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode; const AWorkCountMax: Integer);
    procedure VTTimerTimer(Sender: TObject);
    procedure SettingsSpeedButtonClick(Sender: TObject);
    procedure ShowPWCheckBoxClick(Sender: TObject);
    procedure AboutSpeedButtonClick(Sender: TObject);
    procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
    procedure SpeedButton2Click(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure Programgster1Click(Sender: TObject);
    procedure ProgramGizle1Click(Sender: TObject);
    procedure k1Click(Sender: TObject);
    procedure AutoUpdateTimerTimer(Sender: TObject);
    procedure TimeEditKeyPress(Sender: TObject; var Key: Char);

  private
    { Private declarations }
    FConnection: _Connection;
    FRecordset: _Recordset;
  public
    { Public declarations }
    procedure WMEndSession(var Msg : TWMEndSession); message WM_ENDSESSION;
  end;

  // tanimlamalar.pas dosyasinda kullaniliyor
  function GetKarmaVersion:String;

type
  SchoolValues = Record
  SchoolName: string;
  SchoolCode: string;
  DirectorName: string;
end;

const
  MaxSchoolCount = 50;

type
  SchoolsArr = Array of SchoolValues;

const
  PROGRAMLAYAN = 'eOkul Temmuz 2004, Yazan Okoca';
  SUNUCU_VT_YAZ = 'Sunucu veri tabanına yazılıyor';
  YUKLEME_TAMAM = 'Yükleme başarıyla tamamlandı.';
  YUKLEME_BASARISIZ = 'Yükleme başarısız!';
  SUNUCUYA_KOPYALANIYOR = 'Veri dosyası sunucuya kopyalanıyor...';
  LOCAL_MDB_PASSWORD = 'MAUEDGSDUUIRTN';
  PREV_BUTTON = 0;
  NEXT_BUTTON = 1;
  ABOUT_BUTTON = 2;
  SETTINGS_BUTTON = 3;
  CR_LF = #13+#10;


var
  AnaForm: TAnaForm;
  Noktalar, SuccessCode, UploadedTables, ServerTableNames: String;
  SQLFileSize, GZFileSize, LinesCount: Integer;
  StartTime, EndTime: TDateTime;
  ProccessedDatabases : string;
  TotalRecordsCount : Integer;
  ErrorCount, LastPageIndex : Integer;
  Thread_Handle: Integer;
  PROGRAM_KAPANMASIN: Boolean = False;
  InUploadProgress: Boolean = False;
  ResponseStream: TMemoryStream;
  ResponseData: TStringList;
  Notice: String;


implementation

uses Math;

{$R *.dfm}

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

// Güncelleme işlemine başlamadan önce sunucu bağlantısını kontrol et
function TestConnectionBeforeUpload: boolean;
var
  TestString, Address: String;
  MultiPartFormDataStream: TMsMultiPartFormDataStream;
  
begin

  try
    Address := AnaForm.ServerAddressEdit.Text;
    AnaForm.UploadStatusLabel.Caption := 'Sunucu bağlantısı kontrol ediliyor...';
    if Address[Length(Address)] = '/' then
    Address := Address +'update/connection_test.php'
    else Address := Address +'/update/connection_test.php';

    MultiPartFormDataStream := TMsMultiPartFormDataStream.Create;
    ResponseStream := TMemoryStream.Create;  
    ResponseData := TStringList.Create;
    
    TestString := Encode64(IntToStr(Random(2004))+PROGRAMLAYAN);
    AnaForm.IdHttp1.Request.ContentType := MultiPartFormDataStream.RequestContentType;
    MultiPartFormDataStream.AddFormField('test', TestString);
    MultiPartFormDataStream.PrepareStreamForDispatch;
    AnaForm.IdHTTP1.Post(Address, MultiPartFormDataStream, ResponseStream);

  finally
    ResponseStream.SaveToFile('swap.dat');
    ResponseData.LoadFromFile('swap.dat');
    DeleteFile('swap.dat');
    MultiPartFormDataStream.Free;
    ResponseStream.Free;

    if Pos(TestString, ResponseData.Text) > 0 then
    result := True
    else
    begin
      result := False;
      MessageDlg(HelpMessages[8], mtWarning, [mbOK], 0);
    end;

    AnaForm.UploadStatusLabel.Caption := '';
    AnaForm.UploadProgressBar.Position := AnaForm.UploadProgressBar.Min;
  end;

end;

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

function GetKarmaVersion:String;
var
  MyIniFile: TIniFile;
  FileName: string;
  i: Byte;
  Supported: Boolean;
begin
  result := '0';
  FileName := AnaForm.RootDirectoryEdit.Text+'\KARMA.INI';
  if not FileExists(FileName) then exit;
  
  MyIniFile := TIniFile.Create(FileName);
  result := MyIniFile.ReadString('DATA', 'VERSIYON', '500');
  MyIniFile.Free;

  Supported := False;
  for i := 0 to AnaForm.VersionNumberComboBox.Items.Count - 1 do
  if AnaForm.VersionNumberComboBox.Items[i] = result then
  begin
    AnaForm.VersionNumberComboBox.ItemIndex := i;
    Supported := True;
    Break;
  end;

  if not Supported then
  MessageDlg(HelpMessages[7], mtWarning, [mbOK], 0);
end;

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

procedure LoadTableNames;
var
  ConnectionString : String;
  AConnection : TADOConnection;
  ADataset : TADODataset;
  AQuery : TADOQuery;

begin
  ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;'+
  'Data Source='+AnaForm.RootDirectoryEdit.Text+'\1\2003-2004\OGRENCI.MDB;'+
  'Mode=Share Deny None;'+
  'Persist Security Info=false;'+
  'Jet OLEDB:Database Password='+ LOCAL_MDB_PASSWORD +';';
  AConnection := TADOConnection.Create(nil);
  AConnection.ConnectionString := ConnectionString;
  AConnection.Open;
  if AnaForm.RemoteTablesListBox.Items.Text = '' then
  AConnection.GetTableNames(AnaForm.LocalTablesListBox.Items);
  AConnection.Close;
end;

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

procedure TAnaForm.WMEndSession(var Msg : TWMEndSession);
begin
  PROGRAM_KAPANMASIN := False;
  AnaForm.Close;
  inherited;
end;

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

procedure CopyFileWithProgressBar(Source, Destination: string);
var 
  FromF, ToF: file of byte; 
  Buffer: array[0..32768] of char;
  NumRead: integer; 
  FileLength: longint; 
begin 
  AssignFile(FromF, Source); 
  reset(FromF); 
  AssignFile(ToF, Destination); 
  rewrite(ToF); 
  FileLength := FileSize(FromF);
  with AnaForm.ConvertProgressbar do
  begin
    AnaForm.ConvertStatusLabel.Caption := Source + ' kopyalanıyor.';
    Min := 0;
    Max := FileLength;
    while FileLength > 0 do
    begin
      Application.ProcessMessages;
      BlockRead(FromF, Buffer[0], SizeOf(Buffer), NumRead); 
      FileLength := FileLength - NumRead; 
      BlockWrite(ToF, Buffer[0], NumRead); 
      Position := Position + NumRead; 
    end; 
    CloseFile(FromF); 
    CloseFile(ToF); 
  end; 
end;

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

function StripHTMLTags(HTML: string):String;
var
  ClearText: string;
  Index:integer;
  Tag:Boolean;
begin
  Index := 1;
  repeat
    if HTML[Index] = '<' then Tag := true;
    if not (HTML[Index] in [#13, #10, #9]) then
    if not Tag then ClearText := ClearText + HTML[Index];
    if HTML[Index] = '>' then Tag := False;
    Inc(Index);
  until Index = Length(HTML);
  result := ClearText;
end;

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

function FileSize(Patika: string):integer;
var
  SearchRec: TSearchRec;
begin
  if FindFirst(ExpandFileName(Patika), faAnyFile, SearchRec) = 0 then
    Result := SearchRec.Size
  else Result := -1;
end;

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

procedure Save_Settings;
var
  Ini: TIniFile;
begin
  Ini := TIniFile.Create( ChangeFileExt( Application.ExeName, '.INI' ) );
  Ini.WriteString('General','db_path',Encode64(AnaForm.RootDirectoryEdit.Text));
  Ini.WriteString('General','value',Encode64(LOCAL_MDB_PASSWORD));
  Ini.WriteString('General','local_tables',Encode64(AnaForm.LocalTablesListBox.Items.Text));
  Ini.WriteString('General','remote_tables',Encode64(AnaForm.RemoteTablesListBox.Items.Text));
  Ini.WriteString('General','server_address',Encode64(AnaForm.ServerAddressEdit.Text));
  Ini.WriteString('General','username',Encode64(AnaForm.UsernameEdit.Text));
  Ini.WriteString('General','password',Encode64(AnaForm.PasswordEdit.Text));
  Ini.WriteBool('General','autoupdate',AnaForm.AutoUpdateCheckBox.Checked);
  Ini.WriteBool('General','autostart',AnaForm.AutoStartCheckBox.Checked);
  Ini.WriteString('General','eduyear',Encode64(IntToStr(AnaForm.EducationYearEdit.ItemIndex)));

  AnaForm.TimeEdit.Text := Trim(AnaForm.TimeEdit.Text);
  if AnaForm.TimeEdit.Text = '' then AnaForm.TimeEdit.Text := '0';
  AnaForm.TimeEdit.Text := IntToStr(StrToInt(Trim(AnaForm.TimeEdit.Text)));
  Ini.WriteString('General','time',Encode64(AnaForm.TimeEdit.Text));
  Ini.Free;
end;

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

procedure Load_Settings;
var
  Ini: TIniFile;
begin              
  Ini := TIniFile.Create( ChangeFileExt( Application.ExeName, '.INI' ) );
  AnaForm.RootDirectoryEdit.Text := Decode64(Ini.ReadString('General','db_path',''));
  AnaForm.LocalTablesListBox.Items.Text := Decode64(Ini.ReadString('General','local_tables',''));
  AnaForm.RemoteTablesListBox.Items.Text := Decode64(Ini.ReadString('General','remote_tables',''));
  AnaForm.ServerAddressEdit.Text := Decode64(Ini.ReadString('General','server_address',''));
  AnaForm.UsernameEdit.Text := Decode64(Ini.ReadString('General','username',''));
  AnaForm.PasswordEdit.Text := Decode64(Ini.ReadString('General','password',''));
  AnaForm.TimeEdit.Text := Decode64(Ini.ReadString('General','time',''));
  AnaForm.AutoUpdateCheckBox.Checked := Ini.ReadBool('General','autoupdate',true);
  AnaForm.AutoStartCheckBox.Checked := Ini.ReadBool('General','autostart',true);
  AnaForm.EducationYearEdit.ItemIndex := StrToInt(Decode64(Ini.ReadString('General','eduyear', '-1')));
  if not AnaForm.AutoUpdateCheckBox.Checked then
  begin
    AnaForm.TimeEdit.Enabled := False;
    AnaForm.AutoStartCheckBox.Enabled := False;
  end;
  Ini.Free;

  // Versiyonu tespit et ve veri tabanı yapısını yükle
  LoadDBStructure;
end;

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

procedure TAnaForm.FormCreate(Sender: TObject);
begin
  PROGRAM_KAPANMASIN := True;
  AnaForm.HelpMemo.Text := HelpMessages[AnaForm.PageControl1.ActivePageIndex+1];
end;

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

procedure TAnaForm.SpeedButton1Click(Sender: TObject);
var sFolder : string;
begin
  sFolder := Browse_Dialog('B. karma programının kurulu olduğu dizini seçin.', BIF_RETURNONLYFSDIRS);
  if sFolder <> '' then RootDirectoryEdit.Text := sFolder;
  GetKarmaVersion;
end;

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

procedure TAnaForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Save_Settings;
end;

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

procedure TAnaForm.SpeedButton8Click(Sender: TObject);
begin
  Close;
end;

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

procedure CompressFile(SQLFile: String);
var
  FromF: file;
  ToF:gzFile;
begin
  ToF := GZOpenZ (SQLFile, 'w9 ', 0);
  AssignFile(FromF, SQLFile);
  Reset(FromF, 1);
  GZ_Compress(FromF, ToF);
end;

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

procedure TAnaForm.VTTimerTimer(Sender: TObject);
begin
  // Kopyalama sonlandıysa ve VT ye yazma başladıysa
  if (Pos(SUNUCU_VT_YAZ, UploadStatusLabel.Caption) > 0) and
  (UploadProgressBar.Position = UploadProgressBar.Max) then
  begin
    if Length(Noktalar) > 10 then Noktalar := '.'
    else
    Noktalar := Noktalar + '.';
    UploadStatusLabel.Caption := SUNUCU_VT_YAZ + Noktalar;
    Application.ProcessMessages;
  end;
end;

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

procedure Log(Rec: String);
var
  LogList: TStringList;
  FilePath: string;
begin
  FilePath := ChangeFileExt(Application.ExeName, '.log');
  LogList := TStringList.Create;
  if FileExists(FilePath) then
  LogList.LoadFromFile(FilePath);
  LogList.Add(DateTimeToStr(Now)+' - '+Rec);
  LogList.SaveToFile(FilePath);
  LogList.Free;
end;

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

procedure ShowReport;
begin
    AnaForm.PageControl1.ActivePageIndex := 4;

    AnaForm.ReportMemo.Text :=
    'e-Okul Güncelleyici Görev Raporu' + CR_LF + CR_LF +
    'Tarih              : ' + DateToStr(Now) + CR_LF +
    'Ogrenci Veritabanı : ' + ProccessedDatabases + CR_LF +
    'Geçen Zaman        : ' + TimeToStr(Now-StartTime)+ CR_LF +
    'Sunucu Oturum Kodu : ' + SuccessCode + CR_LF +
    'Sunucu Adresi      : ' + AnaForm.ServerAddressEdit.Text + CR_LF +
    'Kullanıcı Adı      : ' + AnaForm.UserNameEdit.Text + CR_LF +
    'Hata Sayısı        : ' + IntToStr(ErrorCount) + ' (Açıklamalar .log dosyasındadır).'+ CR_LF + CR_LF +

    'Sunucuya Gönderilen; ' + CR_LF +
    'Dosya Boyutu  : ' + IntToStr(Round(SQLFileSize/1024)) + ' KB' + CR_LF +
    'Sıkıştırılmış : ' + IntToStr(Round(GZFileSize/1024)) + ' KB' + CR_LF +
    'Kayıt Sayısı  : ' + IntToStr(LinesCount) + CR_LF +
    'Tablolar      : ' + CR_LF + CR_LF + AnaForm.RemoteTablesListBox.Items.Text + CR_LF + CR_LF +
    'Diğer         : ' + Notice +
    'İşlem tamamlandı.';
end;

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

function GetSchools(var Vals: SchoolsArr): Boolean;
var
  SourceStartupDB, DestStartupDB : string;
  ConnectionString0  : string;
  AConnection0       : TADOConnection;
  ADataset0          : TADODataset;
  AQuery0            : TADOQuery;
  j,k                : Integer;
  FieldValues0       : string;
  DBFilePath         : string;

begin

  // Bilsa okul veri tabanları getirilecek
  // Okulun bünyesindeki müdürlükler ve kodları getirilecek
  result := False;
  SourceStartupDB := AnaForm.RootDirectoryEdit.Text + '\STARTUP.MDB';
  DestStartupDB := ExtractFileDir(Application.ExeName) + '\DATA\STARTUP.MDB';
  if not DirectoryExists(ExtractFileDir(DestStartupDB)) then ForceDirectories(ExtractFileDir(DestStartupDB));
  CopyFile(PChar(SourceStartupDB), PChar(DestStartupDB), False);

  if FileExists(DestStartupDB) then
  begin
    ConnectionString0 :='Provider=Microsoft.Jet.OLEDB.4.0;'+
    'Data Source='+DestStartupDB+';'+
    'Mode=Share Deny None;'+
    'Persist Security Info=false;'+
    'Jet OLEDB:Database Password='+ LOCAL_MDB_PASSWORD +';';
    AConnection0 := TADOConnection.Create(nil);
    AConnection0.ConnectionString := ConnectionString0;
    AConnection0.Open;

    // Sorgulama nesnesi oluşturuluyor
    AQuery0 := TADOQuery.Create(nil);
    AQuery0.Connection := AConnection0;

    // Okul da bulunan müdürlüklerin sadece isimleri getiriliyor
    AQuery0.Close;
    AQuery0.SQL.Text := 'select distinct SB_OKUL_ADI from sabitbilgiler';
    AQuery0.Open;
    AQuery0.Recordset.MoveFirst;
    FieldValues0 := '';
    for j := 1 to AQuery0.Recordset.RecordCount do
    begin
      for k := 0 to AQuery0.Recordset.Fields.Count - 1 do
      FieldValues0 := FieldValues0 + '(SB_OKUL_ADI='''+ VarToStr(AQuery0.Recordset.Fields[k].Value) + ''')' + ' or ';
      AQuery0.Next;
    end;

    // Müdürlüklerin diğer bilgileri getiriliyor
    SetLength(FieldValues0, Length(FieldValues0)-4);
    AQuery0.Close;
    AQuery0.SQL.Text := 'select distinct SB_OKUL_ADI, SB_Okul_Kodu, SB_Mudur_Adi from sabitbilgiler where (' + FieldValues0 + ') and (SB_OKUL_ADI <> '''') and (SB_Okul_Kodu <> '''') and (SB_Mudur_Adi <> '''')';
    AQuery0.Open;
    AQuery0.Recordset.MoveFirst;

    // Dizinin boyutu ayarlanıyor
    SetLength(Vals, AQuery0.Recordset.RecordCount);

    for j := 0 to High(Vals) do
    begin
      Vals[j].SchoolName := VarToStr(AQuery0.Recordset.Fields[0].Value);
      Vals[j].SchoolCode := VarToStr(AQuery0.Recordset.Fields[1].Value);
      Vals[j].DirectorName := VarToStr(AQuery0.Recordset.Fields[2].Value);
      AQuery0.Next;
    end;

    AQuery0.Free;
    AConnection0.Free;
    result := True;
  end
  else
    MessageDlg('Veri tabanı dosyalarına ulaşılamadı. Belirtilen B.Karma ana dizini '+#13+#10+'yanlış olabilir.'+#13+#10+'Belirttiğiniz B.Karma ana dizinini kontrol edin. '+#13+#10+'Gerekirse yardım dosyasını inceleyin.', mtWarning, [mbOK], 0);
end;

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

procedure Convert_Student_Database(DB_Path, School_Code, School_Name: string);
var
  ConnectionString  : string;
  AConnection       : TADOConnection;
  ADataset          : TADODataset;
  AQuery            : TADOQuery;
  i,j,k             : Integer;
  TableName         : string;
  FieldNames        : string;
  RecordsCount      : Integer;
  FieldValues       : string;
  ServerTableName   : string;
  ServerFieldNames  : string;
  SQLFileName       : string;
  SQLList, SQLListOld : TStringList;
  SchoolNumberPos   : Integer;

begin

  try
  try
  ServerTableNames := '';

  // Seçilen tablolardaki kayıtlar SQL dosyasına yazılacak.
  ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;'+
  'Data Source='+DB_Path+';'+
  'Mode=Share Deny None;'+
  'Persist Security Info=false;'+
  'Jet OLEDB:Database Password='+ LOCAL_MDB_PASSWORD +';';
  AConnection := TADOConnection.Create(nil);
  AConnection.ConnectionString := ConnectionString;
  AConnection.Open;

  SQLList := TStringList.Create;
  AQuery := TADOQuery.Create(nil);
  AQuery.Connection := AConnection;

  for i := 0 to AnaForm.RemoteTablesListBox.Items.Count - 1 do
  begin

    AnaForm.ConvertStatusLabel.Caption := 'Dönüştürülen Veri Tabanı: '+School_Name+' Tablo: '
    + IntToStr(i+1) + ' / ' + IntToStr(AnaForm.RemoteTablesListBox.Items.Count);

    // İşlem yapılacak tablo ve alanlar hazırlanıyor
    TableName := AnaForm.RemoteTablesListBox.Items[i];
    FieldNames := '';
    ServerFieldNames := '';
    for k := 1 to FieldCount do
    if TableName = TablesAndFields[k][1] then
    begin
      // Sunucudaki tablonun ismi
      ServerTableName := TablesAndFields[k][2];
      // Lokal veritabanındaki alanların isimleri
      FieldNames := FieldNames + TablesAndFields[k][3] + ',';
      // Sunucudaki alanların isimleri
      ServerFieldNames := ServerFieldNames + TablesAndFields[k][4] + ',';
    end;

    // Alan isimleri listesinin sonundaki virgul cıkartılıyor
    SetLength(FieldNames, Length(FieldNames)-1);
    SetLength(ServerFieldNames, Length(ServerFieldNames)-1);

    // eOkul veri tablolarinin isimleri buyuk harfle baslar
    TableName[1] := UpCase(TableName[1]);
    ServerTableName[1] := UpCase(ServerTableName[1]);

    // SQL dosyasinda hangi tablolarin oldugu belirtilecek
    ServerTableNames := ServerTableNames + ServerTableName + '#';

    // Tüm kayıtlar veri tabanından çekiliyor
    AQuery.Close;
    AQuery.SQL.Text := 'Select ' + FieldNames + ' from ' + TableName;
    AQuery.Open;


    // SQL dosyası oluşturuluyor
    RecordsCount := AQuery.Recordset.RecordCount;
    AnaForm.ConvertProgressBar.Max := RecordsCount;

    if RecordsCount > 0 then
    begin
    AQuery.Recordset.MoveFirst;

      for j := 1 to RecordsCount do
      begin

        FieldValues := '';
        for k := 0 to AQuery.Recordset.Fields.Count - 1 do

        // Okul numarasının başına okul kodu ekleniyor
        if Pos('Ogr_Numarasi', AQuery.Recordset.Fields[k].Name) > 0 then
          FieldValues := FieldValues + '''' +School_Code+VarToStr(AQuery.Recordset.Fields[k].Value) + ''','
        else
          FieldValues := FieldValues + '''' + VarToStr(AQuery.Recordset.Fields[k].Value) + ''',';

        // Virgülle ayrılmış veri listesinin sonundaki virgül çıkartılıyor
        SetLength(FieldValues, Length(FieldValues)-1);

        // INSERT cümlesi oluşturuluyor
        // Bu cümle sunucuda çalıştırılacak
        SQLList.Add('insert into ' + ServerTableName + ' (' + ServerFieldNames + ') values (' + FieldValues + ')');

        AnaForm.ConvertProgressBar.Position := j;
        Application.ProcessMessages;
        Inc(TotalRecordsCount);

        // Sonraki kayıda konumlan
        AQuery.Recordset.MoveNext;
    end;

      AQuery.Recordset.Close;
      end;
    end;

  except
  on E: Exception do
    begin
      Log('Hata oluştu. Oluşan hatanın kaynağı ve açıklaması: ClassName='+E.ClassName+', Message='+E.Message);
      Inc(ErrorCount);
    end;
  end;

  finally
  
  // Bağlantılar kapatılıyor ve nesneler hafızadan kaldırılıyor
  if RecordsCount > 0 then
  AQuery.Close;
  AQuery.Free;
  AConnection.Close;
  AConnection.Free;

  SetLength(ServerTableNames, Length(ServerTableNames) - 1);

  // SQL cümleleri SQL dosyasına ekleniyor
  SQLListOld := TStringList.Create;
  SQLFileName := ChangeFileExt(Application.ExeName, '.sql');

  if FileExists( SQLFileName ) then
  SQLListOld.LoadFromFile(SQLFileName);

  SQLListOld.Text := SQLListOld.Text + SQLList.Text;
  SQLListOld.SaveToFile(SQLFileName);

  SQLFileSize := FileSize(SQLFileName);
  SQLListOld.Free;
  SQLList.Free;
  end;
end;

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

procedure Convert_Teacher_Database(DB_Path:String);
var
  ConnectionString  : string;
  AConnection       : TADOConnection;
  ADataset          : TADODataset;
  AQuery            : TADOQuery;
  SQLFileName       : string;
  i                 : Integer;
  Username, Password: string;
  SQLList, SQLListOld : TStringList;

begin

  try
    // ÖĞRETMEN, YÖNETİCİ KULLANICI ADLARI VE ŞİFRELERİ VERİTABANINA YAZILACAK
    ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;'+
    'Data Source='+DB_Path+';'+
    'Mode=Share Deny None;'+
    'Persist Security Info=false;'+
    'Jet OLEDB:Database Password='+ LOCAL_MDB_PASSWORD +';';
    AConnection := TADOConnection.Create(nil);
    AConnection.ConnectionString := ConnectionString;
    AConnection.Open;

    SQLList := TStringList.Create;
    AQuery := TADOQuery.Create(nil);
    AQuery.Connection := AConnection;

     // Tüm kayıtlar veri tabanından çekiliyor
    AQuery.Close;
    AQuery.SQL.Text := 'select Ogretmen_Adi, Ogretmen_Sifresi from Ogretmenler';
    AQuery.Open;
    AQuery.Recordset.MoveFirst;
    AnaForm.ConvertProgressBar.Max := AQuery.RecordSet.RecordCount;

    for i := 1 to AQuery.RecordSet.RecordCount do
    begin
      AnaForm.ConvertStatusLabel.Caption := 'Dönüştürülen Veri Tabanı: OGRSIFRE Tablo: Ogretmenler';
      Username := AQuery.Recordset.Fields[0].Value;
      Password := AQuery.Recordset.Fields[1].Value;
      SQLList.Add('insert into Teachers (UID, Password) values ('''+Username+''', '''+Password+''')');

      AnaForm.ConvertProgressBar.Position := i;
      Application.ProcessMessages;
      Inc(TotalRecordsCount);
      AQuery.Recordset.MoveNext;
    end;

  finally

    // Bağlantılar kapatılıyor ve nesneler hafızadan kaldırılıyor
    AQuery.Recordset.Close;
    AQuery.Close;
    AQuery.Free;
    AConnection.Close;
    AConnection.Free;

    // SQL cümleleri SQL dosyasına ekleniyor
    SQLListOld := TStringList.Create;
    SQLFileName := ChangeFileExt(Application.ExeName, '.sql');

    if FileExists( SQLFileName ) then
    SQLListOld.LoadFromFile(SQLFileName);

    SQLListOld.Text := SQLListOld.Text + SQLList.Text;
    SQLListOld.SaveToFile(SQLFileName);

    SQLFileSize := FileSize(SQLFileName);
    SQLListOld.Free;
    SQLList.Free;
  end;

end;

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

procedure Convert_Databases(Directory: string);
var
  Schools : SchoolsArr;
  EduYear : string;
  RootFolder : string;
  SchoolList : TStringList;
  DBFilePath : string;
  FieldValues : string;
  SQLList : TStringList;
  SQLFileName : string;
  DBDestDir, DBDestFilePath, DBSourceFilePath : string;
  i : Integer;

begin

  if GetSchools(Schools) then
  begin
    
  try
    SchoolList := TStringList.Create;
    EduYear := AnaForm.EducationYearEdit.Text;
    RootFolder := AnaForm.RootDirectoryEdit.Text;
    TotalRecordsCount := 0;
    ErrorCount := 0;
    SQLFileName := ChangeFileExt(Application.ExeName, '.sql');
    DeleteFile(SQLFileName);

    //---------------------------------------------------------
    // Öğrenci veritabanı dosyaları eOkul konumuma kopyalanıyor
    //---------------------------------------------------------
    for i := 0 to High(Schools) do
    begin
      DBSourceFilePath := RootFolder+'\'+Schools[i].SchoolCode+'\'+EduYear+'\OGRENCI.MDB';
      DBDestDir := ExtractFileDir(Application.ExeName)+'\Data\'+Schools[i].SchoolCode+'\'+EduYear;
      DBDestFilePath := DBDestDir+'\OGRENCI.MDB';
      if not DirectoryExists(DBDestDir) then ForceDirectories(DBDestDir);
      CopyFileWithProgressBar(DBSourceFilePath, DBDestFilePath);
    end;
    // Öğrenci veri tabanları SQL biçimine çevriliyor
    for i := 0 to High(Schools) do
    begin
      DBFilePath := ExtractFileDir(Application.ExeName)+'\Data\'+Schools[i].SchoolCode+'\'+EduYear+'\OGRENCI.MDB';
      if FileExists(DBFilePath) then
      begin
        // Veri tabanı SQL dosyası formatına çevriliyor
        try
          Convert_Student_Database(DBFilePath, Schools[i].SchoolCode, Schools[i].SchoolName);
        finally
          ProccessedDatabases := ProccessedDatabases + Trim(Schools[i].SchoolName) +', ';
          FieldValues :=
          ''''+Trim(Schools[i].SchoolName)+''','''+Trim(Schools[i].SchoolCode)+''','''+Trim(Schools[i].DirectorName)+'''';
          SchoolList.Add('insert into Schools (SchoolName, SchoolCode, DirectorName) Values('+FieldValues+')');
        end;
      end;
    end;

    //----------------------------------------------------------
    // Öğretmen şifreleri veritabanı eOkul konumuma kopyalanıyor
    //----------------------------------------------------------
    DBSourceFilePath := RootFolder+'\OGRSIFRE.MDB';
    if FileExists(DBSourceFilePath) then
    begin
      DBDestDir := ExtractFileDir(Application.ExeName)+'\Data';
      DBDestFilePath := DBDestDir+'\OGRSIFRE.MDB';
      if not DirectoryExists(DBDestDir) then ForceDirectories(DBDestDir);
      CopyFileWithProgressBar(DBSourceFilePath, DBDestFilePath);
      // Öğretmen şifreleri veri tabanı SQL dosyası formatına çevriliyor
      Convert_Teacher_Database(DBDestFilePath);
    end
    else
      Notice := Notice + 'Öğretmen şifreleri OGRSIFRE.MDB olmadığından yüklenemedi.' + CR_LF;
    
  finally
    // Durum bilgisi ekrana basılıyor
    AnaForm.ConvertStatusLabel.Caption := IntTostr(TotalRecordsCount) + ' adet kayıt dönüştürüldü.';
    SetLength(ProccessedDatabases, Length(ProccessedDatabases)-2);
    // Okul müdürlüklerine ait cümleler SQL dosyasına ekleniyor
    if FileExists(SQLFileName) then
    begin
      SQLList := TStringList.Create;
      SQLList.LoadFromFile(SQLFileName);
      SQLList.Text := SQLList.Text + SchoolList.Text;
      SQLList.SaveToFile(SQLFileName);
      SQLList.Free;
    end;
    SchoolList.Free;
  end;
  end;
  
end;

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

procedure Upload_DB;
var
  MultiPartFormDataStream: TMsMultiPartFormDataStream;
  SQLFile, CompressedFile, Address: String;
  StrList: TStringList;

begin
  try
  Randomize;
  MultiPartFormDataStream := TMsMultiPartFormDataStream.Create;
  ResponseStream := TMemoryStream.Create;
  StrList := TStringList.Create;
  ResponseData := TStringList.Create;

  Address := AnaForm.ServerAddressEdit.Text;
  if Address[Length(Address)] <> '/' then Address := Address + '/';
  Address := Address + 'update/upload.php';

  // SQL veri dosyasının konumu
  // SQLFile := 'E:\Windows\Desktop\d2.sql';
  SQLFile := ChangeFileExt(Application.ExeName, '.sql');

  // SQL veri dosyasındaki kayıt sayısı getiriliyor
  // SQL dosyasındaki satır sayısı kayıt sayısından 1 fazladır
  // SaveToFile metodu dosya sonuna fazladan bir satır ekliyor
  StrList.LoadFromFile(SQLFile);
  LinesCount := StrList.Count + 1;

  // SQL veri dosyası sıkıştırılıyor
  AnaForm.UploadStatusLabel.Caption := 'Veri dosyası sıkıştırılıyor...';
  CompressFile(SQLFile);

  // Sıkışmış SQL dosyasının yolu
  CompressedFile := SQLFile+'.gz';
  GZFileSize := FileSize(CompressedFile);

  with AnaForm do
  try
    // Kayıtların tamamının sunucuya ulaştığından emin olmak için
    SuccessCode := Encode64(IntToStr(Random(LinesCount))+PROGRAMLAYAN);
    IdHttp1.Request.ContentType := MultiPartFormDataStream.RequestContentType;
    // Upload formu hazırlanıyor.
    MultiPartFormDataStream.AddFormField('username', UserNameEdit.Text);
    MultiPartFormDataStream.AddFormField('password', PasswordEdit.Text);
    MultiPartFormDataStream.AddFormField('success_code', SuccessCode);
    MultiPartFormDataStream.AddFormField('lines_count', IntTosTr(LinesCount));
    MultiPartFormDataStream.AddFormField('file_size', IntTosTr(FileSize(SQLFile)));
    MultiPartFormDataStream.AddFormField('tables', ServerTableNames);
    MultiPartFormDataStream.AddFile('sqlfile', CompressedFile, 'multipart/form-data');
    // Yükleme işlemine başlanıyor
    MultiPartFormDataStream.PrepareStreamForDispatch;
    MultiPartFormDataStream.Position := 0;
    AnaForm.UploadStatusLabel.Caption := SUNUCUYA_KOPYALANIYOR;
    AnaForm.VTTimer.Enabled := True;
    IdHTTP1.Post(Address, MultiPartFormDataStream, ResponseStream);
    AnaForm.VTTimer.Enabled := False;

  finally
    Application.ProcessMessages;
    ResponseStream.SaveToFile('swap.dat');
    ResponseData.LoadFromFile('swap.dat');
    DeleteFile('swap.dat');
    MultiPartFormDataStream.Free;
    ResponseStream.Free;
  end;

  if Pos(SuccessCode, ResponseData.Text) > 0 then
  begin
    AnaForm.UploadStatusLabel.Caption := YUKLEME_TAMAM;
    AnaForm.NextStageSpeedButton.Enabled := True;
    AnaForm.PreviousStageSpeedButton.Enabled := False;
    AnaForm.NextStageSpeedButton.Caption := 'Raporu Göster';

    Log('Yükleme başarıyla tamamlandı. Kayıt Sayısı:'+IntToStr(LinesCount)+
    ' Dosya Boyutu:'+IntToStr(FileSize(CompressedFile))+
    ' Oturum Kodu:'+SuccessCode);
    DeleteFile(SQLFile);
    DeleteFile(CompressedFile);
  end
  else
  begin
    AnaForm.UploadStatusLabel.Caption := YUKLEME_BASARISIZ;
    AnaForm.NextStageSpeedButton.Enabled := True;
    AnaForm.NextStageSpeedButton.Caption := 'Yeniden Dene';

    Log('Yükleme başarısız! Kayıt Sayısı:'+IntToStr(LinesCount)+
    ' Dosya Boyutu:'+IntToStr(FileSize(CompressedFile))+
    ' Oturum Kodu:'+SuccessCode+
    ' Açıklama :'+StripHTMLTags(ResponseData.Text));
  end;

  finally
  AnaForm.NextStageSpeedButton.Caption := 'Rapor';

  // Program kanalını sonlandır
  InUploadProgress := False;
  EndThread(0);
  end;
end;

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

procedure ConvertAndUpload;
var
  Thread_ID: LongWord;
begin
  AnaForm.NextStageSpeedButton.Enabled := False;
  StartTime := Now;
  InUploadProgress := True;
  // Veritabanını SQL veri dosyası formatına çevirir
  Convert_Databases(AnaForm.RootDirectoryEdit.Text);
  // SQL veri dosyasını sunucuya kopyala ve veritabanına yaz
  Thread_Handle := BeginThread(nil, 0, Addr(Upload_DB), 0, 0, Thread_ID);
  CloseHandle(Thread_Handle);
end;

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

procedure ResetStages;
begin
  with AnaForm do
  begin
    // İLERİ DÜĞMESİ
    NextStageSpeedButton.Caption := 'İleri  >';
    NextStageSpeedButton.Enabled := True;
    NextStageSpeedButton.Visible := True;

    // GERİ DÜĞMESİ
    PreviousStageSpeedButton.Enabled := False;
    PreviousStageSpeedButton.Caption := '<  Geri';
    PreviousStageSpeedButton.Visible := True;

    // HAKKINDA DÜĞMESİ
    AboutSpeedButton.Caption := 'Hakkında';
    AboutSpeedButton.Enabled := True;
    AboutSpeedButton.Visible := True;

    // AYARLAR DÜĞMESİ
    SettingsSpeedButton.Caption := 'Ayarlar';
    SettingsSpeedButton.Enabled := True;
    SettingsSpeedButton.Visible := True;

    // ETİKETLERİ TEMİZLE VE AKTİF SAYFAYI BAŞA AL
    ConvertProgressBar.Position := ConvertProgressBar.Min;
    UploadProgressBar.Position := UploadProgressBar.Min;
    UploadStatusLabel.Caption := '';
    ConvertStatusLabel.Caption := '';
    PageControl1.ActivePageIndex := 0;
  end;
end;

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

procedure LoadLocalTableListBox;
var
  i: Byte;
  TableName: String;
  
begin
  with AnaForm do
  begin
    RemoteTablesListBox.Items.Text := '';
    LocalTablesListBox.Items.Text := '';
    TableName := '';
    for i := 1 to FieldCount do
    if TableName <> TablesAndFields[i,1] then
    begin
      TableName := TablesAndFields[i,1];
      LocalTablesListBox.Items.Add(TableName);
    end;
  end;
end;

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

procedure SwitchStage(PageIndex, WichButton: Integer);
begin
  with AnaForm do
  case WichButton of

  NEXT_BUTTON:

	  case PageIndex of

	       // Dizin belirleme sayfasından ileri
	    0: begin
	         PageControl1.ActivePageIndex := 1;
	         PreviousStageSpeedButton.Enabled := True;
           LoadDBStructure;
           LoadLocalTableListBox;
	       end;

	       // Tablo belirleme sayfasından ileri
	    1: begin
	         PageControl1.ActivePageIndex := 2;
	         NextStageSpeedButton.Caption := 'Başla';
	       end;

	       // Başla... işlemi veya Rapor sayfasına gidiş
	    2: begin
	         if NextStageSpeedButton.Caption = 'Rapor' then
	         begin
	           ShowReport;
	           NextStageSpeedButton.Caption := 'İleri  >';
	           NextStageSpeedButton.Enabled := False;
	           NextStageSpeedButton.Visible := False;
	           PreviousStageSpeedButton.Enabled := True;
	           PreviousStageSpeedButton.Caption := 'Başa Dön';
	         end
	         else
	         begin
	           PreviousStageSpeedButton.Enabled := False;
	           NextStageSpeedButton.Enabled := False;
             // Sunucu ile bağlantı varsa gönderme işlemine başla
             if TestConnectionBeforeUpload then
	           ConvertAndUpload else ShowReport;
	         end;
	       end;
	    3: begin
	       end;
	    4: begin
	       end;
	    end;


    PREV_BUTTON:

	    case PageIndex of
	    0: begin
	       end;

	       // Tablo seçme sayfasında geri gelirken
	    1: begin
	         PreviousStageSpeedButton.Caption := '<  Geri';
	         NextStageSpeedButton.Caption := 'İleri  >';
	         PreviousStageSpeedButton.Enabled := False;
	         PageControl1.ActivePageIndex := 0;
	       end;

	    2: begin
	         PreviousStageSpeedButton.Caption := '<  Geri';
	         NextStageSpeedButton.Caption := 'İleri >';
	         PageControl1.ActivePageIndex := 1;
	       end;

	    3: begin
	       end;

	       // Ilk sahneye geri dön
	    4: begin
	         if PreviousStageSpeedButton.Caption = 'Başa Dön' then
           ResetStages;
	       end;
	    end;


    ABOUT_BUTTON:

        begin
          if AboutSpeedButton.Caption = 'Hakkında' then
          begin
            AboutSpeedButton.Caption := 'Geri';
            PreviousStageSpeedButton.Enabled := False;
            NextStageSpeedButton.Enabled := False;
            SettingsSpeedButton.Enabled := False;
            LastPageIndex := PageControl1.ActivePageIndex;
            PageControl1.ActivePageIndex := 5;
          end
          else
          begin
            AboutSpeedButton.Caption := 'Hakkında';
            PreviousStageSpeedButton.Enabled := True;
            NextStageSpeedButton.Enabled := True;
            SettingsSpeedButton.Enabled := True;
            PageControl1.ActivePageIndex := LastPageIndex;
          end;
        end;

    SETTINGS_BUTTON:

        begin
          if SettingsSpeedButton.Caption = 'Ayarlar' then
          begin
            SettingsSpeedButton.Caption := 'Geri';
            PreviousStageSpeedButton.Enabled := False;
            NextStageSpeedButton.Enabled := False;
            AboutSpeedButton.Enabled := False;
            LastPageIndex := PageControl1.ActivePageIndex;
            PageControl1.ActivePageIndex := 3;
          end
          else
          begin
            SettingsSpeedButton.Caption := 'Ayarlar';
            if LastPageIndex > 0 then
            PreviousStageSpeedButton.Enabled := True
            else PreviousStageSpeedButton.Enabled := False;
            NextStageSpeedButton.Enabled := True;
            AboutSpeedButton.Enabled := True;
            PageControl1.ActivePageIndex := LastPageIndex;
          end;
        end;
  end;

  AnaForm.HelpMemo.Text := HelpMessages[AnaForm.PageControl1.ActivePageIndex+1];
end;

procedure TAnaForm.NextStageSpeedButtonClick(Sender: TObject);
begin
  SwitchStage(PageControl1.ActivePageIndex, NEXT_BUTTON);
end;

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

procedure TAnaForm.PreviousStageSpeedButtonClick(Sender: TObject);
begin
  SwitchStage(PageControl1.ActivePageIndex, PREV_BUTTON);
end;

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

function IsPrivate(str_:String):Boolean;
var i: Byte;
begin
  result := false;
  for i := 1 to FieldCount do
  if TablesAndFields[i,1] = str_ then
  result := true;
end;

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

procedure TAnaForm.SpeedButton3Click(Sender: TObject);
var
  i : byte;
begin
  if LocalTablesListBox.Items.Text <> '' then
    for i := LocalTablesListBox.Items.Count-1 downto 0 do
      if IsPrivate(LocalTablesListBox.Items[i])  then
      begin
        RemoteTablesListBox.Items.Add(LocalTablesListBox.Items[i]);
        LocalTablesListBox.Items.Delete(i);
        Application.ProcessMessages;
        Sleep(1);
      end;
end;

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

procedure TAnaForm.SpeedButton6Click(Sender: TObject);
var
  i : byte;
begin
  if RemoteTablesListBox.Items.Text <> '' then
    for i := RemoteTablesListBox.Items.Count-1 downto 0 do
      if IsPrivate(RemoteTablesListBox.Items[i])  then
      begin
        LocalTablesListBox.Items.Add(RemoteTablesListBox.Items[i]);
        RemoteTablesListBox.Items.Delete(i);
        Application.ProcessMessages;
        Sleep(1);
      end;
end;

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

procedure TAnaForm.SpeedButton4Click(Sender: TObject);
begin
  if LocalTablesListBox.ItemIndex <> -1 then
  if IsPrivate(LocalTablesListBox.Items[LocalTablesListBox.ItemIndex]) then
  begin
  RemoteTablesListBox.Items.Add(
  LocalTablesListBox.Items[LocalTablesListBox.ItemIndex]);
  LocalTablesListBox.Items.Delete(LocalTablesListBox.ItemIndex);
  end;
end;

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

procedure TAnaForm.SpeedButton5Click(Sender: TObject);
begin
  if RemoteTablesListBox.ItemIndex <> -1 then
  if IsPrivate(RemoteTablesListBox.Items[RemoteTablesListBox.ItemIndex]) then
  begin
  LocalTablesListBox.Items.Add(
  RemoteTablesListBox.Items[RemoteTablesListBox.ItemIndex]);
  RemoteTablesListBox.Items.Delete(RemoteTablesListBox.ItemIndex);
  end;
end;

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

procedure TAnaForm.FormShow(Sender: TObject);
begin
  Load_Settings;
end;

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

procedure TAnaForm.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
  UploadProgressBar.Position := AWorkCount;
  PercentLabel.Caption := 'Tamamlanan %'+
  IntToStr(Round((UploadProgressBar.Position*100)/(UploadProgressBar.Max+1)));

  if UploadProgressBar.Position = UploadProgressBar.Max then
  begin
    AnaForm.UploadStatusLabel.Caption := SUNUCU_VT_YAZ;
    PercentLabel.Caption := '';
  end;
  Application.ProcessMessages;
end;

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

procedure TAnaForm.IdHTTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCountMax: Integer);
begin
  UploadProgressBar.Max := AWorkCountMax;
  UploadProgressBar.Position := 0;
end;

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

procedure TAnaForm.SettingsSpeedButtonClick(Sender: TObject);
begin
  SwitchStage(PageControl1.ActivePageIndex, SETTINGS_BUTTON);
end;

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

procedure TAnaForm.ShowPWCheckBoxClick(Sender: TObject);
begin
  if ShowPWCheckBox.Checked then PasswordEdit.PasswordChar := #0
  else PasswordEdit.PasswordChar := '*';
end;

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

procedure TAnaForm.AboutSpeedButtonClick(Sender: TObject);
begin
  SwitchStage(PageControl1.ActivePageIndex, ABOUT_BUTTON);
end;

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

procedure TAnaForm.ApplicationEvents1Exception(Sender: TObject; E: Exception);
begin
  // Bir hata oluştu.
  Log('Hata: ClassName='+E.ClassName+', Message='+E.Message);
  Inc(ErrorCount);
  MessageDlg(HelpMessages[9], mtWarning, [mbOK], 0);
  ResetStages;
end;

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

procedure TAnaForm.SpeedButton2Click(Sender: TObject);
begin
  If SaveDialog1.Execute then
  if SaveDialog1.FileName <> '' then
  ReportMemo.Lines.SaveToFile(SaveDialog1.FileName);
end;

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

procedure TAnaForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if PROGRAM_KAPANMASIN then
  begin
    Application.Minimize;
    TrayIcon1.HideMainForm;
    Abort;
  end;
end;

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

procedure TAnaForm.Programgster1Click(Sender: TObject);
begin
  TrayIcon1.ShowMainForm;
end;

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

procedure TAnaForm.ProgramGizle1Click(Sender: TObject);
begin
  Application.Minimize;
  TrayIcon1.HideMainForm;
end;

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

procedure TAnaForm.k1Click(Sender: TObject);
begin
  PROGRAM_KAPANMASIN := False;
  AnaForm.Close;
end;

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

procedure TAnaForm.AutoUpdateTimerTimer(Sender: TObject);
begin
  if (FormatDateTime('hh',now) = TimeEdit.Text) and
  (FormatDateTime('mm',now) = '00') then
  begin
    ConvertAndUpload;
    Sleep(50000);
  end;
end;

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

procedure TAnaForm.TimeEditKeyPress(Sender: TObject; var Key: Char);
begin
  if not (Key in ['0'..'9']) then Key := #0;
end;

end.


