using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.ComponentModel; using HeuristicLab.BackgroundProcessing; using HeuristicLab.OKB.Client; using HeuristicLab.OKB.Cockpit.Admin.OKBData; namespace HeuristicLab.OKB.Cockpit.Admin { public class DataClientHelper { BackgroundWorker host; public Action ReportProgress { get; set; } System.ComponentModel.DoWorkEventArgs args; public DataClientHelper(BackgroundWorker host, DoWorkEventArgs args) { this.host = host; this.args = args; if (host.WorkerReportsProgress) ReportProgress = i => host.ReportProgress(i); else ReportProgress = new Action(i => { }); } public byte[] Load(OKBData.EntityType type, int id) { DataServiceClient dataClient = ClientFactory.Create(); int size = dataClient.Request(type, id); using (MemoryStream dataStream = new MemoryStream()) { int chunkSize = Math.Max(100, Math.Min(1024 * 1024, size / 100)); while (!host.CancellationPending && dataStream.Position < size) { byte[] chunk = dataClient.GetNextChunk(chunkSize); dataStream.Write(chunk, 0, chunk.Length); ReportProgress(100 * (int)dataStream.Position / size); } if (host.CancellationPending) { args.Cancel = true; dataClient.AbortTransfer(); dataClient.Close(); return null; } else { dataClient.TransferDone(); dataClient.Close(); ReportProgress(100); return dataStream.ToArray(); } } } public void Save(OKBData.EntityType type, int id, byte[] data) { DataServiceClient dataClient = ClientFactory.Create(); dataClient.Submit(type, id); using (MemoryStream dataStream = new MemoryStream(data)) { int size = Math.Max(100, Math.Min(1024 * 1024, (int)dataStream.Length / 100)); for (int i = 0; i < dataStream.Length && !host.CancellationPending; i += size) { byte[] chunk = new byte[Math.Min(size, dataStream.Length - dataStream.Position)]; dataStream.Read(chunk, 0, chunk.Length); dataClient.SetNextChunk(chunk); ReportProgress(100 * (int)dataStream.Position / (int)dataStream.Length); } if (host.CancellationPending) { args.Cancel = true; dataClient.AbortTransfer(); } else { dataClient.TransferDone(); } dataClient.Close(); } } } }