unit ClientUnit_9_1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DBXDataSnap, IPPeerClient, Data.DBXCommon, Vcl.DBCtrls,
  Data.DB, Datasnap.DBClient, Datasnap.DSConnect, Data.SqlExpr, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids,
  ClientMethods_9_1,Contnrs;

type
  TForm3 = class(TForm)
    DBGrid1: TDBGrid;
    bUpload_by_Parts: TButton;
    SQLConnection1: TSQLConnection;
    DSProviderConnection1: TDSProviderConnection;
    ClientDataSet1: TClientDataSet;
    DataSource1: TDataSource;
    DBImage1: TDBImage;
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    procedure bUpload_by_PartsClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;



var
  Form3: TForm3;

 // Objectlist:tobjectlist;
implementation

{$R *.dfm}


procedure NTransfer(ms:tmemorystream;packetsize:int64);
var smc:TServerMethods1Client;
    N:integer;
    i:integer;
    bufferstream:tmemorystream;
    Buffer:Tbytes;

    Objectlist:tobjectlist;

begin
    //Создание


      Objectlist:=tobjectlist.Create;

    N:=(ms.Size div packetsize); // N:=2;
    if N=0 then exit; // Для "Маленьких" файлов меньше packetsize...


   bufferstream:=tmemorystream.Create;

   for i := 0 to N-1 do
     begin
      smc:=TServerMethods1Client.Create(Form3.sqlconnection1.DBXConnection);
      objectlist.Add(smc)
     end;


   ms.Position:=0;


    for I := 1 to N do
      begin
//   smc:=TServerMethods1Client.Create(Form3.sqlconnection1.DBXConnection);


          bufferstream.Clear;
      //    bufferstream.CopyFrom(ms,packetsize);
          SetLength(Buffer, packetsize);
          ms.ReadBuffer(buffer,packetsize); // Прочитали в буфер из потока...



          bufferstream.WriteBuffer(buffer,packetsize); //Записали в другой поток

          bufferstream.Position:=0;

          ms.Position:=packetsize*i; // Передвинули позицию




     //     showmessage('Bufferstream '+inttostr(bufferstream.Size)+#13+'Packetsize '+inttostr(packetsize));

  //        smc.GetstreamByPackets(bufferstream,packetsize);




         SetLength(Buffer, 0);
         // smc:=nil;
     //     if assigned(smc) then showmessage('assigned');
     //    dispose(pointer(smc));

       //   smc:=nil;


       (objectlist[i-1] as tservermethods1client).GetstreamByPackets(bufferstream,packetsize);

         // smc.Free;
     //    smc.FreeInstance;
      //    showmessage(inttostr(TServerMethods1Client.InstanceSize));

        end;
   //    bufferstream.Free;


    //Удаление

  //  objectlist:=nil;
 for i := 0 to N-1 do

  begin

  try
  objectlist.Items[i].Destroy;
  except

  end;

 //  objectlist.Delete(i);
  end;

 // objectlist.Destroy;

 //    pointer(smc):=nil;
  //   smc.Destroy;
//     smc.Free;


end;


procedure dTransfer(ms:tmemorystream;packetsize:int64);
// Передача хвоста...
var smc:TServerMethods1Client;
    N,d:integer;
    bufferstream:tmemorystream;
    Buffer:TBytes;


begin

 //Создание
     bufferstream:=tmemorystream.Create;
     smc:=TServerMethods1Client.Create(Form3.sqlconnection1.DBXConnection);




    N:=(ms.Size div packetsize);
  //  d:=(ms.Size-N*packetsize);
    //  showmessage(inttostr(d));

         bufferstream.Clear;

         SetLength(Buffer, d);

          ms.Position:=N*packetsize;
          bufferstream.CopyFrom(ms,d);
   //      SetLength(Buffer, d);
   //       ms.ReadBuffer(buffer,d); // Прочитали в буфер из потока...

  //        bufferstream.WriteBuffer(buffer,d); //Записали в другой поток

          bufferstream.Position:=0;

           smc.GetstreamByPackets(bufferstream,d);
           SetLength(Buffer, 0);

           smc.FreeInstance;

 //Удаление
    bufferstream.Free;
    smc:=nil;
    smc.Free;

end;


procedure TForm3.bUpload_by_PartsClick(Sender: TObject);
var smc:TServerMethods1Client;
    bmp:tbitmap;
    twic:twicimage;
    ms:tmemorystream;
    i:integer;
 //   const const_packetsize=51200;

begin
  //Создание...
   smc:=TServerMethods1Client.Create(Form3.sqlconnection1.DBXConnection);
   bmp:=tbitmap.Create;
   twic:=twicimage.Create;
   ms:=tmemorystream.Create;

   //Загрузка картинки в память...
   opendialog1.Execute;
   twic.LoadFromFile(opendialog1.FileName);
   bmp.Assign(twic);
   bmp.SaveToStream(ms);

   //Обнулили глоб. переменную
   smc.ZeroGlobalBuffer;

   Ntransfer(ms,51200);
   dtransfer(ms,51200);

   //Залили на СУБД
   smc.GlobalBufferToMySQL;

   //Удаление
   bmp.Free;
   twic.Free;
   ms.Free;

//for i := 0 to objectlist.Count-1 do objectlist.Delete(i);
//        Objectlist.Free;

  //Обновление

//clientdataset1.Close;
//clientdataset1.Open;

  Clientdataset1.Refresh;
  clientdataset1.IndexFieldNames:='Primary_key';
  clientdataset1.Last;

end;

procedure TForm3.Button1Click(Sender: TObject);
var smc:tservermethods1client;
begin
  smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);

  clientdataset1.Delete;
  clientdataset1.ApplyUpdates(-1);
  smc.ApplyUpdates;

  smc.Free;

end;

procedure TForm3.Button2Click(Sender: TObject);
var smc:tservermethods1client; i:integer;
bmp:tbitmap;
    twic:twicimage;
    ms:tmemorystream;
    ss:tstringstream;
    s:string;

begin
   bmp:=tbitmap.Create;
   twic:=twicimage.Create;
   ms:=tmemorystream.Create;
   ss:=tstringstream.Create;

   //Загрузка картинки в память...
   opendialog1.Execute;
   twic.LoadFromFile(opendialog1.FileName);
   bmp.Assign(twic);

   bmp.SaveToStream(ms);
   ss.LoadFromStream(ms);
   s:='';
   s:=ss.DataString;

 //  showmessage('Строка на клиенте '+inttostr(length(s)));

 smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);


 smc.Hello(s);

 clientdataset1.Close;
 clientdataset1.Open;


 smc.Free;
 s:='';
 ss.Free;
 ms.Free;
 bmp.Free;
 twic.Free;

// smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);
// smc.Hello(ms);

// end;



end;





function PackToVarArray(V : AnsiString) : Variant;
var S : String;
    PData : PByteArray;
begin
  S := V;
  if S = '' then begin
    Result := NULL; Exit;
  end;
  Result := VarArrayCreate([0, Length(S)-1], varByte);
  pData := VarArrayLock(Result);
  try
    Move(S[1], pData^, Length(S));
  finally
    VarArrayUnlock(Result);
  end;
end;






procedure TForm3.Button3Click(Sender: TObject);

var smc:tservermethods1client; i:integer;
bmp:tbitmap;
    twic:twicimage;
    ms:tmemorystream;
    ss:tstringstream;
    s:string;

begin
   bmp:=tbitmap.Create;
   twic:=twicimage.Create;
   ms:=tmemorystream.Create;
   ss:=tstringstream.Create;

   //Загрузка картинки в память...
   opendialog1.Execute;
   twic.LoadFromFile(opendialog1.FileName);
   bmp.Assign(twic);

   bmp.SaveToStream(ms);
   ss.LoadFromStream(ms);
   s:='';
   s:=ss.DataString;

   s:='hello';
 // packtovararray(s);

 //  showmessage('Строка на клиенте '+inttostr(length(s)));

 smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);

 smc.DataInsert(PackToVarArray(s));

// smc.Hello(s);

{
 clientdataset1.Close;
 clientdataset1.Open;


 smc.Free;
 s:='';
 ss.Free;
 ms.Free;
 bmp.Free;
 twic.Free;


}

// smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);
// smc.Hello(ms);

// end;



end;




function StringToOleVariant(const Value: string): OleVariant;
  var Data: PByteArray;
      ss: TStringStream;
begin
  Result:=null;
  if Value='' then Exit;
  ss:=TStringStream.Create(Value);
  try
    Result := VarArrayCreate ([0, ss.Size - 1], varByte);
    Data := VarArrayLock(Result);
    try
      ss.Position := 0;
      ss.ReadBuffer(Data^, ss.Size);
    finally
      VarArrayUnlock(Result);
    end;
  finally
    ss.Free;
  end;
end;











procedure TForm3.Button4Click(Sender: TObject);

var smc:tservermethods1client; i:integer;
    bmp:tbitmap;
    twic:twicimage;
    ms:tmemorystream;
    ss:tstringstream;
    s:string; N:integer;

begin

   bmp:=tbitmap.Create;
   twic:=twicimage.Create;

   ss:=tstringstream.Create;

   //Загрузка картинки в память...
   opendialog1.Execute;
   twic.LoadFromFile(opendialog1.FileName);
   bmp.Assign(twic);


   bmp.SaveToStream(ss);


   smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);
   s:=ss.DataString;


   smc.DataInsert(StringToOleVariant(s));

   smc.Free;

   clientdataset1.Refresh;
   bmp.Free;
   twic.Free;
   ss.Free;
   s:='';



end;




procedure TForm3.Button5Click(Sender: TObject);
var smc:tservermethods1client; i:integer;
    bmp:tbitmap;
    twic:twicimage;

    ss:tstringstream;
    s:string;
    tempstring:string; // bufferstring
    N:integer; //Целые части
    d:integer; //Остаток

    const const_packetsize=512000;


begin

   bmp:=tbitmap.Create;
   twic:=twicimage.Create;

   ss:=tstringstream.Create;

   //Загрузка картинки в память...
   opendialog1.Execute;
   twic.LoadFromFile(opendialog1.FileName);
   bmp.Assign(twic);


   bmp.SaveToStream(ss);


   smc:=tservermethods1client.Create(sqlconnection1.DBXConnection);
   s:=ss.DataString;  // Теперь файл в строке...

   // Делим строку на целые части + остаток...
   N:=(length(s) div const_packetsize);// Число целых частей
   d:= (length(s) mod const_packetsize); // Остаток от деления



   smc.ZeroGlobalString; // Обнулили глобальную строку на сервере...

// Обработка целых частей

 if N<>0 then begin

   for i := 0 to N-1 do
    begin
   tempstring:='';
   tempstring:=copy(s,1+i*const_packetsize,const_packetsize);
   smc.BuildGlobalString(Stringtoolevariant(tempstring));
    tempstring:='';
    end;
  end;

  //Обработка остатка
if d<>0 then begin

   tempstring:=copy(s,1+N*const_packetsize,d);
   smc.BuildGlobalString(Stringtoolevariant(tempstring));
 end;

 //Когда глобальная строка сформирована на сервере
 //превращаем её в поток и пишем её в СУБД...
   smc.GlobalStringToMySQL;

 //Обновляем множество
   clientdataset1.Refresh;

 //Чистим память...
   smc.Free;
   bmp.Free;
   twic.Free;
   ss.Free;
   s:='';
   tempstring:='';


end;


procedure TForm3.FormCreate(Sender: TObject);
begin
sqlconnection1.Connected:=true;
clientdataset1.Active:=true;
end;

end.
