示例#1
0
        // TODO: Split to service
        async Task UploadFolder(UploadFolder request, CancellationToken token, Action <ProgressState> progress)
        {
            var auth = new AuthInfo(request.UserName, request.Password);

            const string host       = "staging.sixmirror.com";
            var          folderPath =
                $"{new ShortGuid(request.UserId)}/{new ShortGuid(request.GameId)}/{new ShortGuid(request.ContentId)}";

            Environment.SetEnvironmentVariable("RSYNC_PASSWORD", auth.Password);

            var tp = new TransferProgress();

            using (new Monitor(tp, progress)) {
                var result = await
                             _rsyncLauncher.RunAndProcessAsync(tp,
                                                               request.Folder + "\\.", // "."
                                                               $"rsync://{auth.UserName}@{host}/{folderPath}", token,
                                                               new RsyncOptions {
                    AdditionalArguments =
                    {
                        "-avz",
                        "--exclude=.rsync --exclude=.svn --exclude=.git --exclude=.hg --exclude=.synqinfo"
                    }
                })
                             // , WorkingDirectory = request.Folder
                             .ConfigureAwait(false);

                MainLog.Logger.Debug("Output" + result.StandardOutput + "\nError " + result.StandardError);
                result.ConfirmSuccess();
            }
        }
        public static bool MoveWithProgress(string source, string destination, Action<TransferProgress> progress)
        {
            var startTimestamp = DateTime.Now;

            NativeMethods.CopyProgressRoutine lpProgressRoutine = (size, transferred, streamSize, bytesTransferred, number, reason, file, destinationFile, data) =>
            {
                TransferProgress fileProgress = new TransferProgress(startTimestamp, bytesTransferred)
                {
                    SourcePath = source,
                    Total = size,
                    Transferred = transferred,
                    StreamSize = streamSize,
                    BytesTransferred = bytesTransferred,
                    ProcessedFile = source
                };

                try
                {
                    progress(fileProgress);
                    return NativeMethods.CopyProgressResult.PROGRESS_CONTINUE;
                }
                catch (Exception ex)
                {
                    return NativeMethods.CopyProgressResult.PROGRESS_STOP;
                }
            };


            if (!NativeMethods.MoveFileWithProgress(source, destination, lpProgressRoutine, IntPtr.Zero, NativeMethods.MoveFileFlags.MOVE_FILE_REPLACE_EXISTSING | NativeMethods.MoveFileFlags.MOVE_FILE_COPY_ALLOWED | NativeMethods.MoveFileFlags.MOVE_FILE_WRITE_THROUGH))
                return false;

            return true;
        }
        public async Task DownloadToAsync(Stream fileStream, CancellationToken?cancellationToken = null,
                                          Dictionary <string, object> transferMetadata           = null)
        {
            var downloadQuery        = CreateDownloadQuery();
            var totalBytesToDownload = Item.FileSizeBytes.GetValueOrDefault();
            var progress             = new TransferProgress(totalBytesToDownload, transferMetadata);

            using (var stream = await downloadQuery.ExecuteAsync(cancellationToken))
            {
                if (stream != null)
                {
                    int bytesRead;
                    var buffer = new byte[Config.BufferSize];

                    do
                    {
                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken ?? CancellationToken.None);

                        if (bytesRead > 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);

                            NotifyProgress(progress.UpdateBytesTransferred(bytesRead));

                            await TryPauseAsync(cancellationToken);
                        }
                    } while (bytesRead > 0);
                }
            }

            NotifyProgress(progress.MarkComplete());
        }
示例#4
0
 protected void NotifyProgress(TransferProgress progress)
 {
     if (OnTransferProgress != null)
     {
         OnTransferProgress.Invoke(this, new TransferEventArgs { Progress = progress });
     }
 }
示例#5
0
 private static void RaiseOnTransferProgress(string repository, TransferProgress progress)
 {
     if (OnTransferProgress != null)
     {
         OnTransferProgress(repository, progress);
     }
 }
        public override void Draw()
        {
            if (!this.opened)
            {
                return;
            }
            base.Draw();
            float num1 = 300f;
            float num2 = 60f;
            Vec2  p1_1 = new Vec2((float)((double)this.layer.width / 2.0 - (double)num1 / 2.0), (float)((double)this.layer.height / 2.0 - (double)num2 / 2.0));
            Vec2  p2   = new Vec2((float)((double)this.layer.width / 2.0 + (double)num1 / 2.0), (float)((double)this.layer.height / 2.0 + (double)num2 / 2.0));

            Graphics.DrawRect(p1_1, p2, new Color(70, 70, 70), this.depth, false);
            Graphics.DrawRect(p1_1, p2, new Color(30, 30, 30), this.depth - 1);
            Graphics.DrawRect(p1_1 + new Vec2(4f, 20f), p2 + new Vec2(-4f, -4f), new Color(10, 10, 10), this.depth + 1);
            Graphics.DrawRect(p1_1 + new Vec2(2f, 2f), new Vec2(p2.x - 2f, p1_1.y + 16f), new Color(70, 70, 70), this.depth + 1);
            Graphics.DrawString(this._text, p1_1 + new Vec2(5f, 5f), Color.White, this.depth + 2);
            this._font.scale = new Vec2(1f, 1f);
            Vec2             p1_2           = p1_1 + new Vec2(14f, 38f);
            Vec2             vec2           = new Vec2(270f, 16f);
            TransferProgress uploadProgress = this._item.GetUploadProgress();
            float            x = (float)uploadProgress.bytesDownloaded / (float)uploadProgress.bytesTotal;

            Graphics.DrawRect(p1_2, p1_2 + vec2 * new Vec2(x, 1f), this._hoverOk ? new Color(80, 80, 80) : new Color(30, 30, 30), this.depth + 2);
            if (uploadProgress.bytesTotal == 0UL)
            {
                this._font.Draw("Waiting...", p1_2.x, p1_2.y - 12f, Color.White, this.depth + 3);
            }
            else
            {
                this._font.Draw("Uploading " + (object)uploadProgress.bytesDownloaded + "/" + (object)uploadProgress.bytesTotal + "B", p1_2.x, (float)((double)p1_2.y - 12.0), Color.White, this.depth + 3);
            }
        }
        /// <summary>
        /// Called when [transfer progress].
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <returns></returns>
        private bool OnTransferProgress(TransferProgress progress)
        {
            int percent = progress.ReceivedObjects > 0 ? (progress.ReceivedObjects * 100 / progress.TotalObjects) : 0;

            _onProgress(percent);
            return(true);
        }
示例#8
0
        /// <summary>
        /// This is just a helper method for the git commands in order to have a progress bar display for them.
        /// </summary>
        private bool TransferProgressHandlerMethod(TransferProgress transferProgress)
        {
            // Thank you random issue on the gitlib2sharp repo!!!!
            // Also tldr; rtfm
            if (isGitProcessGettingCancelled)
            {
                return(false);
            }

            // This needs to be in an Invoke, in order to access the variables from the main thread
            // Otherwise this will throw a runtime exception
            Application.Instance.Invoke(() =>
            {
                progressBar.MinValue = 0;
                progressBar.MaxValue = transferProgress.TotalObjects;
                if (currentGitObject >= transferProgress.ReceivedObjects)
                {
                    return;
                }
                progressLabel.Text = Text.ProgressbarProgress + " " + transferProgress.ReceivedObjects + " (" + ((int)transferProgress.ReceivedBytes / 1000000) + "MB) / " + transferProgress.TotalObjects + " objects";
                currentGitObject   = transferProgress.ReceivedObjects;
                progressBar.Value  = transferProgress.ReceivedObjects;
            });

            return(true);
        }
 public void UpdateProgress(TransferProgress progress, Speed <MemSize> speed)
 {
     foreach (var reporter in _reporters)
     {
         reporter.UpdateProgress(progress, speed);
     }
 }
示例#10
0
        public override void DownloadTo(Stream fileStream, Dictionary<string, object> transferMetadata = null)
        {
            var downloadQuery = CreateDownloadQuery();
            var totalBytesToDownload = Item.FileSizeBytes.GetValueOrDefault();
            var progress = new TransferProgress(totalBytesToDownload, transferMetadata);

            using (var stream = downloadQuery.Execute())
            {
                if (stream != null)
                {
                    int bytesRead;
                    var buffer = new byte[Config.BufferSize];

                    do
                    {
                        TryPause();

                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                        if (bytesRead > 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);

                            NotifyProgress(progress.UpdateBytesTransferred(bytesRead));
                        }

                    } while (bytesRead > 0);
                }
            }

            NotifyProgress(progress.MarkComplete());
        }
 public bool FetchTransferProgressHandler(TransferProgress p)
 {
     ProgressBarDialog.MinorThreadSetCount(p.ReceivedObjects);
     ProgressBarDialog.MinorThreadSetTotal(p.TotalObjects);
     ProgressBarDialog.MinorThreadSetBytes(p.ReceivedBytes);
     return(true);
 }
示例#12
0
        public async Task AddFile_WithProgress()
        {
            var path = Path.GetTempFileName();

            File.WriteAllText(path, "hello world");
            try
            {
                var ipfs = TestFixture.Ipfs;
                TransferProgress lastProgress = null;
                var options = new AddFileOptions
                {
                    ChunkSize = 3,
                    Progress  = new Progress <TransferProgress>(t =>
                    {
                        lastProgress = t;
                    })
                };
                var result = await ipfs.FileSystem.AddFileAsync(path, options);

                // Progress reports get posted on another synchronisation context.
                var stop = DateTime.Now.AddSeconds(3);
                while (DateTime.Now < stop && lastProgress == null)
                {
                    await Task.Delay(10);
                }
                Assert.AreEqual(11UL, lastProgress.Bytes);
                Assert.AreEqual(Path.GetFileName(path), lastProgress.Name);
            }
            finally
            {
                File.Delete(path);
            }
        }
示例#13
0
        public void UpdateProgress(TransferProgress progress, Speed <MemSize> speed)
        {
            switch (progress.State)
            {
            case UploadState.NotStarted:
                SetProgressBarStyleLabel(ProgressBarStyle.Marquee);

                SetUploadedBytesLabel("Starting Upload...");
                SetSpeed(string.Empty);
                break;

            case UploadState.Processing:
                SetProgressBarStyleLabel(ProgressBarStyle.Continuous);

                SetSpeed(speed.ToString());
                SetProgressBarValueLabel(progress.ProgressPercentage);
                SetUploadedBytesLabel($"{progress.Current}/{progress.Total}");
                break;

            case UploadState.Paused:
                // TODO / Not needed
                break;

            case UploadState.Finished:
                SetProgressBarStyleLabel(ProgressBarStyle.Marquee);

                SetUploadedBytesLabel("Waiting for server reply...");
                SetSpeed(string.Empty);
                break;

            default:
                Debug.Fail($"Unhandled {nameof(UploadState)}");
                break;
            }
        }
 private bool transferHandler(TransferProgress progress)
 {
     this._repo.isIndetermerminate = false;
     this._repo.progress           = 100.0 / progress.TotalObjects * progress.ReceivedObjects;
     this._repo.taskDescription    = "Cloning repository " + progress.ReceivedObjects + "/" + progress.TotalObjects + " (Received:" + progress.ReceivedBytes / 1024 + "KB)...";
     return(true);
 }
示例#15
0
        public FTP(
//			System.Windows.Forms.Control controlSync,
			TransferProgress tp )
        {
            //			_controlSync = controlSync;
            _tp = tp;
        }
        public void transferDidProgress(Transfer t, TransferProgress tp)
        {
            Progress(tp.getProgress());
            AsyncDelegate d = delegate
            {
                double transferred = _transfer.getTransferred().longValue();
                double size        = _transfer.getSize().longValue();
                if (transferred > 0 && size > 0)
                {
                    View.ProgressIndeterminate = false;
                    // normalize double to int if size is too big
                    if (size > int.MaxValue)
                    {
                        View.ProgressMaximum = int.MaxValue;
                        View.ProgressValue   = Convert.ToInt32(int.MaxValue * transferred / size);
                    }
                    else
                    {
                        View.ProgressMaximum = Convert.ToInt32(size);
                        View.ProgressValue   = Convert.ToInt32(transferred);
                    }
                }
                else
                {
                    View.ProgressIndeterminate = true;
                }
                UpdateOverallProgress();
            };

            invoke(new SimpleDefaultMainAction(this, d));
        }
示例#17
0
 /// <summary>
 /// The constructor
 /// </summary>
 /// <since_tizen> 4 </since_tizen>
 public BluetoothOppServer()
 {
     _impl = BluetoothOppServerImpl.Instance;
     _impl.ConnectionRequested += (s, e) => ConnectionRequested?.Invoke(this, e);
     _impl.TransferProgress    += (s, e) => TransferProgress?.Invoke(this, e);
     _impl.TransferFinished    += (s, e) => TransferFinished?.Invoke(this, e);
 }
        public async virtual Task DownloadToAsync(Stream fileStream, CancellationToken? cancellationToken = null,
            Dictionary<string, object> transferMetadata = null)
        {
            var downloadQuery = CreateDownloadQuery();
            var totalBytesToDownload = Item.FileSizeBytes.GetValueOrDefault();
            var progress = new TransferProgress(totalBytesToDownload, transferMetadata);

            using (var stream = await downloadQuery.ExecuteAsync(cancellationToken))
            {
                if (stream != null)
                {
                    int bytesRead;
                    var buffer = new byte[Config.BufferSize];

                    do
                    {
                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken ?? CancellationToken.None);
                        if (bytesRead > 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);

                            NotifyProgress(progress.UpdateBytesTransferred(bytesRead));

                            await TryPauseAsync(cancellationToken);
                        }

                    } while (bytesRead > 0);
                }
            }

            NotifyProgress(progress.MarkComplete());
        }
示例#19
0
        public override void DownloadTo(Stream fileStream, Dictionary <string, object> transferMetadata = null)
        {
            var downloadQuery        = CreateDownloadQuery();
            var totalBytesToDownload = Item.FileSizeBytes.GetValueOrDefault();
            var progress             = new TransferProgress(totalBytesToDownload, transferMetadata);

            using (var stream = downloadQuery.Execute())
            {
                if (stream != null)
                {
                    int bytesRead;
                    var buffer = new byte[Config.BufferSize];

                    do
                    {
                        TryPause();

                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                        if (bytesRead > 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);

                            NotifyProgress(progress.UpdateBytesTransferred(bytesRead));
                        }
                    } while (bytesRead > 0);
                }
            }

            NotifyProgress(progress.MarkComplete());
        }
示例#20
0
        /// <summary>
        /// Handles transfer of mesh content.
        /// </summary>
        /// <param name="packet">The packet buffer in which to compose the transfer message.</param>
        /// <param name="byteLimit">An advisory byte limit used to restrict how much data should be sent (in bytes).</param>
        /// <param name="progress">The progress value from the last call to this method.</param>
        /// <returns>A new value for <paramref name="progress"/> to use on the next call.</returns>
        /// <remarks>
        /// Supports amortised transfer via the <paramref name="progress"/> argument.
        /// On first call, this is the default initialised structure (zero). On subsequent
        /// calls it is the last returned value unless <c>Failed</c> was true.
        ///
        /// The semantics of this value are entirely dependent on the internal implementation.
        /// </remarks>
        public void Transfer(PacketBuffer packet, int byteLimit, ref TransferProgress progress)
        {
            // Initial call?
            bool phaseComplete = false;

            switch (progress.Phase)
            {
            case (int)Phase.Vertex:
                phaseComplete = Transfer(packet, MeshMessageType.Vertex, Vertices(), byteLimit, ref progress);
                break;

            case (int)Phase.Index:
                if (IndexSize == 2)
                {
                    phaseComplete = Transfer(packet, MeshMessageType.Index, Indices2(), byteLimit, ref progress);
                }
                else if (IndexSize == 4)
                {
                    phaseComplete = Transfer(packet, MeshMessageType.Index, Indices4(), byteLimit, ref progress);
                }
                break;

            case (int)Phase.Normal:
                phaseComplete = Transfer(packet, MeshMessageType.Normal, Normals(), byteLimit, ref progress);
                break;

            case (int)Phase.Colour:
                phaseComplete = Transfer(packet, MeshMessageType.VertexColour, Colours(), byteLimit, ref progress);
                break;

            case (int)Phase.UV:
                phaseComplete = Transfer(packet, MeshMessageType.UV, UVs(), byteLimit, ref progress);
                break;

            case (int)Phase.Finalise:
                MeshFinaliseMessage msg = new MeshFinaliseMessage();
                msg.MeshID = ID;
                msg.Flags  = 0;
                if (CalculateNormals && (Components & MeshComponentFlag.Normal) != MeshComponentFlag.Normal)
                {
                    msg.Flags |= (uint)MeshFinaliseFlag.CalculateNormals;
                }
                packet.Reset((ushort)RoutingID.Mesh, MeshFinaliseMessage.MessageID);
                msg.Write(packet);
                progress.Phase = (int)Phase.End;
                phaseComplete  = true;
                break;
            }

            if (!progress.Failed)
            {
                if (phaseComplete)
                {
                    progress.Phase    = (int)NextPhase((Phase)progress.Phase);
                    progress.Progress = 0;
                    progress.Complete = progress.Phase == (int)Phase.End;
                }
            }
        }
		public OldStandardFileTransferService(IFile source, FileTransferServiceType serviceType)
		{
			m_ServiceType = serviceType;
			m_Source = source;
			m_Destination = m_ServiceType.Destination;

			m_Progress = new TransferProgress(this);
		}
示例#22
0
        public OldStandardFileTransferService(IFile source, FileTransferServiceType serviceType)
        {
            m_ServiceType = serviceType;
            m_Source      = source;
            m_Destination = m_ServiceType.Destination;

            m_Progress = new TransferProgress(this);
        }
示例#23
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            var    pdv = pm.GetValue <IProgress <TransferProgress> >("{Progress}", NullTransferProgress.Instance);
            string url = pm.GetValue <string>(UrlKey);

            if (url == null)
            {
                return(ResultCommand.Error(new ArgumentException("Unspecified Url.")));
            }

            try
            {
                using (var httpClient =
                           pm.ContainsKey(HttpClientKey) && pm[HttpClientKey] is Func <HttpClient>?((Func <HttpClient>)pm[HttpClientKey])() :
                               new HttpClient())
                {
                    var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, pm.CancellationToken);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new WebException(String.Format("{0} when downloading {1}", response.StatusCode, url));
                    }

                    MemoryStream destStream = new MemoryStream();
                    logger.Info(String.Format("{0} = Stream of {1}", DestinationKey, url));
                    using (Stream srcStream = await response.Content.ReadAsStreamAsync())
                    {
                        pdv.Report(TransferProgress.From(url));
                        byte[] buffer         = new byte[1024];
                        ulong  totalBytesRead = 0;
                        ulong  totalBytes     = 0;
                        try { totalBytes = (ulong)srcStream.Length; }
                        catch (NotSupportedException) { }

                        int byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);

                        while (byteRead > 0)
                        {
                            await destStream.WriteAsync(buffer, 0, byteRead, pm.CancellationToken);

                            totalBytesRead = totalBytesRead + (uint)byteRead;
                            short percentCompleted = (short)((float)totalBytesRead / (float)totalBytes * 100.0f);
                            pdv.Report(TransferProgress.UpdateCurrentProgress(percentCompleted));

                            byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);
                        }
                        await destStream.FlushAsync();
                    }

                    pm.SetValue(DestinationKey, destStream.ToByteArray());
                    return(NextCommand);
                }
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
示例#24
0
        protected UploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, int?expirationDays)
        {
            Client = client;
            UploadSpecificationRequest = uploadSpecificationRequest;
            File = file;

            ExpirationDays = expirationDays;
            Progress       = new TransferProgress(uploadSpecificationRequest.FileSize, null, Guid.NewGuid().ToString());
        }
示例#25
0
        protected UploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, int? expirationDays)
        {
            Client = client;
            UploadSpecificationRequest = uploadSpecificationRequest;
            File = file;

            ExpirationDays = expirationDays;
            Progress = new TransferProgress(uploadSpecificationRequest.FileSize, null, Guid.NewGuid().ToString());
        }
        /// <summary>
        /// Called when [transfer progress].
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <returns></returns>
        private bool OnTransferProgress(TransferProgress progress)
        {
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.CursorVisible = false;
            int percent = progress.ReceivedObjects > 0 ? (progress.ReceivedObjects * 100 / progress.TotalObjects) : 0;

            _onProgress(percent);
            return(true);
        }
示例#27
0
 protected void NotifyProgress(TransferProgress progress)
 {
     if (OnTransferProgress != null)
     {
         OnTransferProgress.Invoke(this, new TransferEventArgs {
             Progress = progress
         });
     }
 }
        private void UpdateOverallProgress()
        {
            TransferProgress progress = TransferCollection.defaultCollection().getProgress();

            TransferController.Instance.View.UpdateOverallProgressState(
                TransferCollection.defaultCollection().numberOfRunningTransfers() == 0
                    ? 0
                    : progress.getTransferred().longValue(), progress.getSize().longValue());
        }
        public void TransferProgressCompletedPercentIsCorrect()
        {
            var tested = new TransferProgress();

            tested.Start(1);
            Assert.Equal(0, tested.CompletedPercent);
            tested.ReportProgress();
            Assert.Equal(100, tested.CompletedPercent);
        }
示例#30
0
        private bool OnTransferProgress(TransferProgress progress)
        {
            if (progress.ReceivedObjects % (Math.Max(progress.TotalObjects / 10, 1)) == 0 && !_fetchFinished)
            {
                _logger.Detailed($"{progress.ReceivedObjects} / {progress.TotalObjects}");
                _fetchFinished = progress.ReceivedObjects == progress.TotalObjects;
            }

            return(true);
        }
        private static bool OnCloneProgress(TransferProgress progress)
        {
            int currentLineCursor = Console.CursorTop;

            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write(new string(' ', Console.WindowWidth));
            Console.SetCursorPosition(0, currentLineCursor);
            Console.Write(progress.ReceivedObjects + "/" + progress.TotalObjects);
            return(true);
        }
示例#32
0
        private bool OnTransferProgress(TransferProgress progress)
        {
            if (progress.ReceivedObjects % (progress.TotalObjects / 10) == 0 && !_fetchFinished)
            {
                _logger.Verbose($"{progress.ReceivedObjects} / {progress.TotalObjects}");
                _fetchFinished = progress.ReceivedObjects == progress.TotalObjects;
            }

            return(true);
        }
示例#33
0
        private bool CloneTransferProgressHandler(TransferProgress progress)
        {
            if (progress.TotalObjects > 0)
            {
                double progressPercentage = progress.ReceivedObjects / (double)progress.TotalObjects;
                _logger.LogDebug($"Clone progress {progressPercentage:P2} : received objects: {progress.ReceivedObjects}/{progress.TotalObjects} objects)");
            }

            return(true);
        }
示例#34
0
 public static IScriptCommand TransferChild(IEntryModel srcModel, IEntryModel destDirModel,
                                            Func <IEntryModel, bool> filterFunc = null, bool recrusive = false, IScriptCommand nextCommand = null)
 {
     return(WPFScriptCommands.List(srcModel, filterFunc, null, recrusive, ems =>
                                   WPFScriptCommands.ReportProgress(TransferProgress.IncrementTotalEntries(ems.Length),
                                                                    ScriptCommands.ForEach(ems, em =>
                                                                                           ScriptCommands.RunInSequence(
                                                                                               IOScriptCommands.Transfer(em, destDirModel),
                                                                                               WPFScriptCommands.ReportProgress(TransferProgress.IncrementProcessedEntries())),
                                                                                           nextCommand))));
 }
示例#35
0
 private static void Progress(TransferProgress e)
 {
     try
     {
         Console.WriteLine(e.GetDataPerSecondFormatted(SuffixStyle.Windows, "{0:###,##0.0}"));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
        public void DataLakeUploader_CancelUpload()
        {
            CancellationTokenSource myTokenSource = new CancellationTokenSource();
            var cancelToken    = myTokenSource.Token;
            var frontEnd       = new InMemoryFrontEnd();
            var mockedFrontend = new MockableFrontEnd(frontEnd);

            mockedFrontend.GetStreamLengthImplementation = (streamPath, isDownload) =>
            {
                // sleep for 2 second to allow for the cancellation to actual happen
                Thread.Sleep(2000);
                return(frontEnd.GetStreamLength(streamPath, isDownload));
            };

            mockedFrontend.StreamExistsImplementation = (streamPath, isDownload) =>
            {
                // sleep for 2 second to allow for the cancellation to actual happen
                Thread.Sleep(2000);
                return(frontEnd.StreamExists(streamPath, isDownload));
            };
            var up = CreateParameters(isResume: false);
            TransferProgress progress = null;
            var syncRoot = new object();
            IProgress <TransferProgress> progressTracker = new Progress <TransferProgress>(
                (p) =>
            {
                lock (syncRoot)
                {
                    //it is possible that these come out of order because of race conditions (multiple threads reporting at the same time); only update if we are actually making progress
                    if (progress == null || progress.TransferredByteCount < p.TransferredByteCount)
                    {
                        progress = p;
                    }
                }
            });
            var uploader = new DataLakeStoreTransferClient(up, mockedFrontend, cancelToken, progressTracker);

            Task uploadTask = Task.Run(() =>
            {
                uploader.Execute();
                Thread.Sleep(2000);
            }, cancelToken);

            myTokenSource.Cancel();
            Assert.True(cancelToken.IsCancellationRequested);

            while (uploadTask.Status == TaskStatus.Running || uploadTask.Status == TaskStatus.WaitingToRun)
            {
                Thread.Sleep(250);
            }

            // Verify that the file did not get uploaded completely.
            Assert.False(frontEnd.StreamExists(up.TargetStreamPath), "Uploaded stream exists when it should not yet have been completely created");
        }
示例#37
0
        public bool downloadFile(String url, out Stream s, String path, TransferProgress del)
        {
            this.transferProgressDelegate = del;
              byte[] buffer = new byte[4096];
              FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);

              WebRequest wr = WebRequest.Create(url);
              wr.Proxy = System.Net.GlobalProxySelection.Select;
              try
              {
            using (WebResponse response = wr.GetResponse())
            {
              using (Stream responseStream = response.GetResponseStream())
              {
            int count = 0;
            int dataRead = 0;
            do
            {
              count = responseStream.Read(buffer, 0, buffer.Length);
              fileStream.Write(buffer, 0, count);

              float progress = ((float)dataRead / (float)response.ContentLength) * 100.0f;
              OnProgress((int)progress);

              dataRead += count;
            } while (count != 0 && !abortTransfer);
              }
            }
              }
              catch (WebException wex)
              {
            Logger.Instance.log("No Connection to update server...");
            fileStream.Close();
            s = null;
            return false;
              }
              s = fileStream;
              //      fileStream.Close();
              return true;
        }
示例#38
0
 private void newSync()
 {
     var ftg = Global.Preferences.Brand == Brand.Photomic
                   ? "ftg"
                   : "kngftg";
     _sync = new vdFtp(
         _tp = new TransferProgress(callback),
         "ftp://ftp.viron.se",
         string.Format("{0}{1:000}", ftg, Global.Preferences.Fotografnummer),
         string.Format("{0:000}{1}", Global.Preferences.Fotografnummer, ftg));
     //_sync.SimulateBadConnection = true;
     //_sync.DelayTimeBetweenChunks = 20;
 }
示例#39
0
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            foreach ( var s in Directory.GetDirectories( Global.Preferences.MainPath ) )
                if ( Regex.IsMatch( s, @"_\d{5,6}$" ))
                    _existingOrders.Add(int.Parse(s.Substring(s.LastIndexOf('_') + 1)));

            ug.setColumnFullWidth( 0 );
            ug.subscribeToEvents();

            _sync = new vdFtp(
                _tp = callback,
                "ftp://ftp.photomic.com/",
                Global.Preferences.Brand == Brand.Photomic ? "plata" : "kngplata",
                "h6d9b5" );
            _strFtgFolder = string.Format( "ftg{0:000}", Global.Preferences.Fotografnummer );
            var w = _sync.getGetFolders();
            w.addFolder( _strFtgFolder );
            w.addFolder( "_uppdateringar" );
            w.addFolder( _strFtgFolder + "/standbylistor" );
            w.run();
            setMessage( "Hämtar data från Viron...\r\n" );
        }