public TransmissionMenuItem(FileTransmissionEvent transmission) { Activated += delegate { NSWorkspace.SharedWorkspace.OpenFile(System.IO.Directory.GetParent(transmission.Path).FullName); }; transmissionEvent = transmission; updateTime = DateTime.Now; Title = TransmissionStatus(transmission.Status); switch (transmission.Type) { case FileTransmissionType.DOWNLOAD_NEW_FILE: Image = new NSImage(Path.Combine(NSBundle.MainBundle.ResourcePath, "Pixmaps", "Downloading.png")); break; case FileTransmissionType.UPLOAD_NEW_FILE: Image = new NSImage(Path.Combine(NSBundle.MainBundle.ResourcePath, "Pixmaps", "Uploading.png")); break; case FileTransmissionType.DOWNLOAD_MODIFIED_FILE: goto case FileTransmissionType.UPLOAD_MODIFIED_FILE; case FileTransmissionType.UPLOAD_MODIFIED_FILE: Image = new NSImage(Path.Combine(NSBundle.MainBundle.ResourcePath, "Pixmaps", "Updating.png")); break; } transmissionEvent.TransmissionStatus += TransmissionEvent; }
/// <summary> /// Uploads the file content to the remote document. /// </summary> /// <returns>The SHA-1 hash of the uploaded file content.</returns> /// <param name="localFile">Local file.</param> /// <param name="doc">Remote document.</param> /// <param name="transmissionManager">Transmission manager.</param> protected static byte[] UploadFile(IFileInfo localFile, IDocument doc, ActiveActivitiesManager transmissionManager) { byte[] hash = null; IFileUploader uploader = FileTransmission.ContentTaskUtils.CreateUploader(); FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(FileTransmissionType.UPLOAD_MODIFIED_FILE, localFile.FullName); transmissionManager.AddTransmission(transmissionEvent); transmissionEvent.ReportProgress(new TransmissionProgressEventArgs { Started = true }); using (var hashAlg = new SHA1Managed()) { try { using (var file = localFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { uploader.UploadFile(doc, file, transmissionEvent, hashAlg); hash = hashAlg.Hash; } } catch (Exception ex) { transmissionEvent.ReportProgress(new TransmissionProgressEventArgs { FailedException = ex }); throw; } } transmissionEvent.ReportProgress(new TransmissionProgressEventArgs { Completed = true }); return(hash); }
private void UpdateFileStatus(FileTransmissionEvent transmission, TransmissionProgressEventArgs e) { if (e == null) { e = transmission.Status; } string filePath = transmission.CachePath; if (filePath == null || !File.Exists(filePath)) { filePath = transmission.Path; } if (!File.Exists(filePath)) { Logger.Debug(String.Format("None exist {0} for file status update", filePath)); return; } if ((e.Aborted == true || e.Completed == true || e.FailedException != null)) { Notifications.FileSystemProgress.RemoveFileProgress(filePath); } else { double percent = transmission.Status.Percent.GetValueOrDefault() / 100; if (percent < 1) { Notifications.FileSystemProgress.SetFileProgress(filePath, percent); } else { Notifications.FileSystemProgress.RemoveFileProgress(filePath); } } }
/// <summary> /// Creates a new menu item, which updates itself on transmission events /// </summary> /// <param name="e">FileTransmissionEvent to listen to</param> /// <param name="parent">Parent control to avoid threading issues</param> public TransmissionMenuItem(FileTransmissionEvent e, Control parent) : base(e.Type.ToString()) { Path = e.Path; Type = e.Type; ParentControl = parent; transmissionEvent = e; switch (Type) { case FileTransmissionType.DOWNLOAD_NEW_FILE: Image = UIHelpers.GetBitmap("Downloading"); break; case FileTransmissionType.UPLOAD_NEW_FILE: Image = UIHelpers.GetBitmap("Uploading"); break; case FileTransmissionType.DOWNLOAD_MODIFIED_FILE: goto case FileTransmissionType.UPLOAD_MODIFIED_FILE; case FileTransmissionType.UPLOAD_MODIFIED_FILE: Image = UIHelpers.GetBitmap("Updating"); break; } Text = TransmissionStatus(transmissionEvent.Status); transmissionEvent.TransmissionStatus += TransmissionEvent; Click += TransmissionEventMenuItem_Click; }
public void SetUp() { this.transmissionEvent = new FileTransmissionEvent(FileTransmissionType.UPLOAD_NEW_FILE, "testfile"); this.fileLength = 1024 * 1024; this.localContent = new byte[this.fileLength]; if (this.localFileStream != null) { this.localFileStream.Dispose(); } this.localFileStream = new MemoryStream(this.localContent); if (this.hashAlg != null) { this.hashAlg.Dispose(); } this.hashAlg = new SHA1Managed(); using (RandomNumberGenerator random = RandomNumberGenerator.Create()) { random.GetBytes(this.localContent); } this.mockedMemStream = new Mock <MemoryStream>() { CallBase = true }; this.mockedDocument = new Mock <IDocument>(); this.mockedStream = new Mock <IContentStream>(); this.mockedStream.Setup(stream => stream.Length).Returns(this.fileLength); this.mockedStream.Setup(stream => stream.Stream).Returns(this.mockedMemStream.Object); this.mockedDocument.Setup(doc => doc.Name).Returns("test.txt"); }
/// <summary> /// Downloads the file and returns the SHA-1 hash of the content of the saved file /// </summary> /// <param name="remoteDocument">Remote document.</param> /// <param name="localFileStream">Local taget file stream.</param> /// <param name="status">Transmission status.</param> /// <param name="hashAlg">Hash algoritm, which should be used to calculate hash of the uploaded stream content</param> /// <exception cref="IOException">On any disc or network io exception</exception> /// <exception cref="DisposeException">If the remote object has been disposed before the dowload is finished</exception> /// <exception cref="AbortException">If download is aborted</exception> /// <exception cref="CmisException">On exceptions thrown by the CMIS Server/Client</exception> public void DownloadFile(IDocument remoteDocument, Stream localFileStream, FileTransmissionEvent status, HashAlgorithm hashAlg) { { byte[] buffer = new byte[8 * 1024]; int len; while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) { hashAlg.TransformBlock(buffer, 0, len, buffer, 0); } } long?fileLength = remoteDocument.ContentStreamLength; // Download content if exists if (fileLength > 0) { long offset = localFileStream.Position; long remainingBytes = (fileLength != null) ? (long)fileLength - offset : this.ChunkSize; try { do { offset += this.DownloadNextChunk(remoteDocument, offset, remainingBytes, status, localFileStream, hashAlg); } while(fileLength == null); } catch (DotCMIS.Exceptions.CmisConstraintException) { } } hashAlg.TransformFinalBlock(new byte[0], 0, 0); }
public void ConstructorAndPropertiesTest() { string path = "file"; FileTransmissionEvent e = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_MODIFIED_FILE, path); Assert.AreEqual(path, e.Path); Assert.AreEqual(FileTransmissionType.DOWNLOAD_MODIFIED_FILE, e.Type); Assert.IsNull(e.CachePath); e = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, path); Assert.AreEqual(path, e.Path); Assert.AreEqual(FileTransmissionType.DOWNLOAD_NEW_FILE, e.Type); Assert.IsNull(e.CachePath); e = new FileTransmissionEvent(FileTransmissionType.UPLOAD_MODIFIED_FILE, path); Assert.AreEqual(path, e.Path); Assert.AreEqual(FileTransmissionType.UPLOAD_MODIFIED_FILE, e.Type); Assert.IsNull(e.CachePath); e = new FileTransmissionEvent(FileTransmissionType.UPLOAD_NEW_FILE, path); Assert.AreEqual(path, e.Path); Assert.AreEqual(FileTransmissionType.UPLOAD_NEW_FILE, e.Type); Assert.IsNull(e.CachePath); string cachepath = "file.sync"; e = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, path, cachepath); Assert.AreEqual(path, e.Path); Assert.AreEqual(FileTransmissionType.DOWNLOAD_NEW_FILE, e.Type); Assert.AreEqual(cachepath, e.CachePath); }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Streams.ProgressStream"/> class. /// The given transmission event will be used to report the progress /// </summary> /// <param name='stream'> /// Stream which progress should be monitored. /// </param> /// <param name='e'> /// Transmission event where the progress should be reported to. /// </param> public ProgressStream(Stream stream, FileTransmissionEvent e) : base(stream) { if (e == null) { throw new ArgumentNullException("The event, where to publish the prgress cannot be null"); } try { e.Status.Length = stream.Length; } catch (NotSupportedException) { e.Status.Length = null; } this.transmissionEvent = e; this.blockingDetectionTimer = new Timer(2000); this.blockingDetectionTimer.Elapsed += delegate(object sender, ElapsedEventArgs args) { var transmissionArgs = new TransmissionProgressEventArgs { BitsPerSecond = (long)(this.bytesTransmittedSinceLastSecond / this.blockingDetectionTimer.Interval) }; this.transmissionEvent.ReportProgress(transmissionArgs); this.bytesTransmittedSinceLastSecond = 0; }; }
public void PositionTest() { var mockedStream = new Mock <Stream>(); FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(this.transmissionType, this.filename); transmissionEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) { if (args.Length != null && args.Length != this.length) { this.lengthCalls++; this.length = (long)args.Length; } if (args.ActualPosition != null) { this.positionCalls++; } }; mockedStream.Setup(s => s.SetLength(It.IsAny <long>())); mockedStream.SetupProperty(s => s.Position); using (ProgressStream progress = new ProgressStream(mockedStream.Object, transmissionEvent)) { progress.SetLength(100); Assert.AreEqual(1, this.lengthCalls); Assert.AreEqual(0, this.positionCalls); progress.Position = 50; progress.Position = 50; Assert.AreEqual(1, this.positionCalls); progress.Position = 55; Assert.AreEqual(2, this.positionCalls); Assert.AreEqual(1, this.lengthCalls); } }
private void UpdateFileStatus(FileTransmissionEvent transmission, TransmissionProgressEventArgs e) { if (e == null) { e = transmission.Status; } string filePath = transmission.CachePath; if (filePath == null || !File.Exists(filePath)) { filePath = transmission.Path; } if (!File.Exists(filePath)) { Logger.Error(String.Format("None exist {0} for file status update", filePath)); return; } string extendAttrKey = "com.apple.progress.fractionCompleted"; if ((e.Aborted == true || e.Completed == true || e.FailedException != null)) { Syscall.removexattr(filePath, extendAttrKey); try { NSFileAttributes attr = NSFileManager.DefaultManager.GetAttributes(filePath); attr.CreationDate = (new FileInfo(filePath)).CreationTime; NSFileManager.DefaultManager.SetAttributes(attr, filePath); } catch (Exception ex) { Logger.Error(String.Format("Exception to set {0} creation time for file status update: {1}", filePath, ex)); } } else { double percent = transmission.Status.Percent.GetValueOrDefault() / 100; if (percent < 1) { Syscall.setxattr(filePath, extendAttrKey, Encoding.ASCII.GetBytes(percent.ToString())); try { NSFileAttributes attr = NSFileManager.DefaultManager.GetAttributes(filePath); attr.CreationDate = new DateTime(1984, 1, 24, 8, 0, 0, DateTimeKind.Utc); NSFileManager.DefaultManager.SetAttributes(attr, filePath); } catch (Exception ex) { Logger.Error(String.Format("Exception to set {0} creation time for file status update: {1}", filePath, ex)); } } else { Syscall.removexattr(filePath, extendAttrKey); try { NSFileAttributes attr = NSFileManager.DefaultManager.GetAttributes(filePath); attr.CreationDate = (new FileInfo(filePath)).CreationTime; NSFileManager.DefaultManager.SetAttributes(attr, filePath); } catch (Exception ex) { Logger.Error(String.Format("Exception to set {0} creation time for file status update: {1}", filePath, ex)); } } } }
public void ListedTransmissionIsEqualToAdded() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); Assert.That(manager.AddTransmission(trans), Is.True); Assert.That(manager.ActiveTransmissions[0], Is.EqualTo(trans)); Assert.That(manager.ActiveTransmissionsAsList()[0], Is.EqualTo(trans)); }
public void AddingNonEqualTransmissionProducesNewEntryInList() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); var trans2 = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path2"); Assert.That(manager.AddTransmission(trans), Is.True); Assert.That(manager.AddTransmission(trans2), Is.True); Assert.That(manager.ActiveTransmissions.Count, Is.EqualTo(2)); }
public void AddingTheSameInstanceASecondTimeReturnsFalseAndIsNotListed() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); Assert.That(manager.AddTransmission(trans), Is.True); Assert.That(manager.AddTransmission(trans), Is.False); Assert.That(manager.ActiveTransmissions.Count, Is.EqualTo(1)); Assert.That(manager.ActiveTransmissions[0], Is.EqualTo(trans)); }
public void AFinishedTransmissionIsRemovedFromList() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); manager.AddTransmission(trans); trans.ReportProgress(new TransmissionProgressEventArgs { Completed = true }); Assert.That(manager.ActiveTransmissions, Is.Empty); }
private void TransmissionReport(object sender, TransmissionProgressEventArgs e) { using (var a = new NSAutoreleasePool()) { FileTransmissionEvent transmission = sender as FileTransmissionEvent; if (transmission == null) { return; } lock (transmissionLock) { if ((e.Aborted == true || e.Completed == true || e.FailedException != null)) { transmission.TransmissionStatus -= TransmissionReport; transmissionFiles.Remove(transmission.Path); } else { TimeSpan diff = NSDate.Now - transmissionFiles [transmission.Path]; if (diff.Seconds < notificationInterval) { return; } transmissionFiles [transmission.Path] = NSDate.Now; } // UpdateFileStatus (transmission, e); } notificationCenter.BeginInvokeOnMainThread(delegate { lock (transmissionLock) { NSUserNotification[] notifications = notificationCenter.DeliveredNotifications; foreach (NSUserNotification notification in notifications) { if (!IsNotificationTransmission(notification)) { continue; } bool pathCorrect = notification.InformativeText == transmission.Path; bool isCompleted = transmission.Status.Completed == true; bool isAlreadyStarted = startedTransmissions.Contains(transmission.Path); if (pathCorrect && (!isAlreadyStarted || isCompleted)) { notificationCenter.RemoveDeliveredNotification(notification); notification.DeliveryDate = NSDate.Now; notification.Subtitle = TransmissionStatus(transmission); notificationCenter.DeliverNotification(notification); return; } } } }); } }
/// <summary> /// Initialize (in the UI and syncing mechanism) an existing CmisSync synchronized folder. /// </summary> /// <param name="folderPath">Synchronized folder path</param> private void AddRepository(RepoInfo repositoryInfo) { Repository repo = new Repository(repositoryInfo, this.activityListenerAggregator); repo.SyncStatusChanged += delegate(SyncStatus status) { this.UpdateState(); }; repo.Queue.EventManager.AddEventHandler( new GenericSyncEventHandler <FileTransmissionEvent>( 50, delegate(ISyncEvent e) { FileTransmissionEvent transEvent = e as FileTransmissionEvent; transEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) { if (args.Aborted == true && args.FailedException != null) { this.ShowException( string.Format(Properties_Resources.TransmissionFailedOnRepo, repo.Name), string.Format("{0}{1}{2}", transEvent.Path, Environment.NewLine, args.FailedException.Message)); } }; return(false); })); repo.Queue.EventManager.AddEventHandler(new GenericHandleDublicatedEventsFilter <PermissionDeniedEvent, SuccessfulLoginEvent>()); repo.Queue.EventManager.AddEventHandler(new GenericHandleDublicatedEventsFilter <ProxyAuthRequiredEvent, SuccessfulLoginEvent>()); repo.Queue.EventManager.AddEventHandler( new GenericSyncEventHandler <ProxyAuthRequiredEvent>( 0, delegate(ISyncEvent e) { this.ProxyAuthReqired(repositoryInfo.DisplayName); return(true); })); repo.Queue.EventManager.AddEventHandler( new GenericSyncEventHandler <PermissionDeniedEvent>( 0, delegate(ISyncEvent e) { this.ShowChangePassword(repositoryInfo.DisplayName); return(true); })); repo.Queue.EventManager.AddEventHandler( new GenericSyncEventHandler <SuccessfulLoginEvent>( 0, delegate(ISyncEvent e) { this.SuccessfulLogin(repositoryInfo.DisplayName); return(false); })); this.repositories.Add(repo); repo.Initialize(); }
public void AbortWriteIfTransmissionEventIsAborting() { var transmission = new FileTransmissionEvent(this.transmissionType, this.filename); using (var stream = new MemoryStream()) using (var progressStream = new ProgressStream(stream, transmission)) { transmission.ReportProgress(new TransmissionProgressEventArgs() { Aborting = true }); Assert.Throws <AbortException>(() => progressStream.WriteByte(new byte())); } }
public void AbortReadIfTransmissionEventIsAborting() { byte[] content = new byte[1024]; var transmission = new FileTransmissionEvent(this.transmissionType, this.filename); using (var stream = new MemoryStream(content)) using (var progressStream = new ProgressStream(stream, transmission)) { transmission.ReportProgress(new TransmissionProgressEventArgs() { Aborting = true }); progressStream.ReadByte(); } }
public void EnsureBandwidthIsReportedIfProgressIsShorterThanOneSecond() { byte[] inputContent = new byte[1024]; FileTransmissionEvent transmission = new FileTransmissionEvent(this.transmissionType, this.filename); using (var inputStream = new MemoryStream(inputContent)) using (var outputStream = new MemoryStream()) using (var progressStream = new ProgressStream(inputStream, transmission)) { progressStream.CopyTo(outputStream); Assert.That(outputStream.Length == inputContent.Length); } Assert.Greater(transmission.Status.BitsPerSecond, 0); }
/// <summary> /// If a transmission is reported as finished/aborted/failed, the transmission is removed from the collection /// </summary> /// <param name='sender'> /// The transmission event. /// </param> /// <param name='e'> /// The progress parameters of the transmission. /// </param> private void TransmissionFinished(object sender, TransmissionProgressEventArgs e) { if (e.Aborted == true || e.Completed == true || e.FailedException != null) { lock (this.collectionLock) { FileTransmissionEvent transmission = sender as FileTransmissionEvent; if (transmission != null && this.activeTransmissions.Contains(transmission)) { this.activeTransmissions.Remove(transmission); transmission.TransmissionStatus -= this.TransmissionFinished; Logger.Debug("Transmission removed"); } } } }
public void AddingATransmissionFiresEvent() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); int eventCounter = 0; manager.ActiveTransmissions.CollectionChanged += delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { eventCounter++; Assert.That(e.NewItems.Count, Is.EqualTo(1)); Assert.That(e.NewItems[0], Is.EqualTo(trans)); }; manager.AddTransmission(trans); Assert.That(eventCounter, Is.EqualTo(1)); }
public void SetLengthTest() { var mockedStream = new Mock <Stream>(); FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(this.transmissionType, this.filename); transmissionEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) { if (args.Length != null) { this.lengthCalls++; } }; mockedStream.Setup(s => s.SetLength(It.IsAny <long>())); using (ProgressStream progress = new ProgressStream(mockedStream.Object, transmissionEvent)) { progress.SetLength(100); progress.SetLength(100); Assert.AreEqual(1, this.lengthCalls); } }
public void SeekTest() { using (Stream stream = new MemoryStream()) { FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(this.transmissionType, this.filename); transmissionEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) { if (args.ActualPosition != null) { this.positionCalls++; this.position = (long)args.ActualPosition; this.percent = (double)args.Percent; } }; using (ProgressStream progress = new ProgressStream(stream, transmissionEvent)) { progress.SetLength(100); progress.Seek(10, SeekOrigin.Begin); Assert.AreEqual(10, this.position); Assert.AreEqual(10, this.percent); progress.Seek(10, SeekOrigin.Current); Assert.AreEqual(20, this.position); Assert.AreEqual(20, this.percent); progress.Seek(10, SeekOrigin.Current); Assert.AreEqual(30, this.position); Assert.AreEqual(30, this.percent); progress.Seek(10, SeekOrigin.Current); Assert.AreEqual(40, this.position); Assert.AreEqual(40, this.percent); progress.Seek(5, SeekOrigin.Current); Assert.AreEqual(45, this.position); Assert.AreEqual(45, this.percent); progress.Seek(10, SeekOrigin.Current); Assert.AreEqual(55, this.position); Assert.AreEqual(55, this.percent); progress.SetLength(1000); progress.Seek(10, SeekOrigin.Current); Assert.AreEqual(65, this.position); Assert.AreEqual(6.5, this.percent); progress.Seek(0, SeekOrigin.End); Assert.AreEqual(100, this.percent); Assert.AreEqual(1000, this.position); } } }
public void PercentTest() { string filename = "test.txt"; FileTransmissionEvent transmission = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, filename); double?percent = null; transmission.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs e) { percent = e.Percent; }; transmission.ReportProgress(new TransmissionProgressEventArgs { }); Assert.Null(percent); this.expectedArgs = new TransmissionProgressEventArgs { Length = 100, ActualPosition = 0 }; transmission.ReportProgress(this.expectedArgs); Assert.AreEqual(0, percent); transmission.ReportProgress(new TransmissionProgressEventArgs() { ActualPosition = 10 }); Assert.AreEqual(10, percent); transmission.ReportProgress(new TransmissionProgressEventArgs() { ActualPosition = 100 }); Assert.AreEqual(100, percent); transmission.ReportProgress(new TransmissionProgressEventArgs() { Length = 1000 }); Assert.AreEqual(10, percent); transmission.ReportProgress(new TransmissionProgressEventArgs() { ActualPosition = 1000, Length = 2000 }); Assert.AreEqual(50, percent); }
private string TransmissionStatus(FileTransmissionEvent transmission) { string type = "Unknown"; switch (transmission.Type) { case FileTransmissionType.UPLOAD_NEW_FILE: type = Properties_Resources.NotificationFileUpload; break; case FileTransmissionType.UPLOAD_MODIFIED_FILE: type = Properties_Resources.NotificationFileUpdateRemote; break; case FileTransmissionType.DOWNLOAD_NEW_FILE: type = Properties_Resources.NotificationFileDownload; break; case FileTransmissionType.DOWNLOAD_MODIFIED_FILE: type = Properties_Resources.NotificationFileUpdateLocal; break; } string status = ""; if (transmission.Status.Aborted == true) { status = Properties_Resources.NotificationFileStatusAborted; } else if (transmission.Status.Completed == true) { status = Properties_Resources.NotificationFileStatusCompleted; //startedTransmissions.Remove (transmission.Path); } else if (transmission.Status.FailedException != null) { status = Properties_Resources.NotificationFileStatusFailed; } return(String.Format("{0} {1}", type, status)); }
public void SetUp() { this.transmissionEvent = new FileTransmissionEvent(FileTransmissionType.UPLOAD_NEW_FILE, "testfile"); this.lastChunk = 0; this.localContent = new byte[this.fileLength]; if (this.localFileStream != null) { this.localFileStream.Dispose(); } this.localFileStream = new MemoryStream(this.localContent); if (this.hashAlg != null) { this.hashAlg.Dispose(); } this.hashAlg = new SHA1Managed(); using (RandomNumberGenerator random = RandomNumberGenerator.Create()) { random.GetBytes(this.localContent); } if (this.remoteStream != null) { this.remoteStream.Dispose(); } this.remoteStream = new MemoryStream(); this.mockedDocument = new Mock <IDocument>(); this.mockedStream = new Mock <IContentStream>(); this.returnedObjectId = new Mock <IObjectId>(); this.mockedStream.Setup(stream => stream.Length).Returns(this.fileLength); this.mockedStream.Setup(stream => stream.Stream).Returns(this.remoteStream); this.mockedDocument.Setup(doc => doc.Name).Returns("test.txt"); this.mockedDocument.Setup(doc => doc.AppendContentStream(It.IsAny <IContentStream>(), It.Is <bool>(b => b == true), It.Is <bool>(b => b == true))) .Callback <IContentStream, bool, bool>((s, b, r) => s.Stream.CopyTo(this.remoteStream)) .Returns(this.returnedObjectId.Object) .Callback(() => this.lastChunk++); this.mockedDocument.Setup(doc => doc.AppendContentStream(It.IsAny <IContentStream>(), It.Is <bool>(b => b == false), It.Is <bool>(b => b == true))) .Callback <IContentStream, bool, bool>((s, b, r) => s.Stream.CopyTo(this.remoteStream)) .Returns(this.returnedObjectId.Object); }
public void AFinishedTransmissionFiresEvent() { var manager = new ActiveActivitiesManager(); var trans = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, "path"); int eventCounter = 0; manager.AddTransmission(trans); manager.ActiveTransmissions.CollectionChanged += delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { eventCounter++; Assert.That(e.NewItems, Is.Null); Assert.That(e.OldItems.Count, Is.EqualTo(1)); Assert.That(e.OldItems[0], Is.EqualTo(trans)); }; trans.ReportProgress(new TransmissionProgressEventArgs { Completed = true }); Assert.That(eventCounter, Is.EqualTo(1)); }
/// <summary> /// Add a new Transmission to the active transmission manager /// </summary> /// <param name="transmission">transmission which should be added</param> /// <returns>true if added</returns> public virtual bool AddTransmission(FileTransmissionEvent transmission) { if (transmission == null) { throw new ArgumentNullException(); } lock (this.collectionLock) { if (this.activeTransmissions.Contains(transmission)) { return(false); } transmission.TransmissionStatus += this.TransmissionFinished; this.activeTransmissions.Add(transmission); } transmission.ReportProgress(transmission.Status); return(true); }
private string TransmissionStatus(FileTransmissionEvent transmission) { string type = "Unknown"; switch (transmission.Type) { case FileTransmissionType.UPLOAD_NEW_FILE: type = "Upload new file"; break; case FileTransmissionType.UPLOAD_MODIFIED_FILE: type = "Update remote file"; break; case FileTransmissionType.DOWNLOAD_NEW_FILE: type = "Download new file"; break; case FileTransmissionType.DOWNLOAD_MODIFIED_FILE: type = "Update local file"; break; } if (transmission.Status.Aborted == true) { type += " aborted"; } else if (transmission.Status.Completed == true) { type += " completed"; } else if (transmission.Status.FailedException != null) { type += " failed"; } return(String.Format("{0} ({1:###.#}% {2})", type, Math.Round(transmission.Status.Percent.GetValueOrDefault(), 1), CmisSync.Lib.Utils.FormatBandwidth((long)transmission.Status.BitsPerSecond.GetValueOrDefault()))); }
public void WriteTest() { using (Stream stream = new MemoryStream()) { FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(this.transmissionType, this.filename); transmissionEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) { if (args.ActualPosition != null) { this.positionCalls++; this.position = (long)args.ActualPosition; this.percent = (double)args.Percent; } }; byte[] buffer = new byte[10]; using (ProgressStream progress = new ProgressStream(stream, transmissionEvent)) { progress.SetLength(buffer.Length * 10); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual(buffer.Length, this.position); Assert.AreEqual(10, this.percent); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual(buffer.Length * 2, this.position); Assert.AreEqual(20, this.percent); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual(buffer.Length * 3, this.position); Assert.AreEqual(30, this.percent); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual(buffer.Length * 4, this.position); Assert.AreEqual(40, this.percent); progress.Write(buffer, 0, buffer.Length / 2); Assert.AreEqual((buffer.Length * 4) + (buffer.Length / 2), this.position); Assert.AreEqual(45, this.percent); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual((buffer.Length * 5) + (buffer.Length / 2), this.position); Assert.AreEqual(55, this.percent); progress.SetLength(buffer.Length * 100); progress.Write(buffer, 0, buffer.Length); Assert.AreEqual((buffer.Length * 6) + (buffer.Length / 2), this.position); Assert.AreEqual(6.5, this.percent); } } }