/// <summary> /// Private constructor for initializing <b>client side</b> sessions. /// </summary> /// <param name="router">The message router.</param> /// <param name="serverEP">The server endpoint.</param> /// <param name="direction">The transfer direction.</param> /// <param name="stream">The input or output stream.</param> private StreamTransferSession(MsgRouter router, MsgEP serverEP, TransferDirection direction, EnhancedStream stream) { ReliableTransferHandler handler; reliableSession = router.CreateReliableTransferSession(); reliableSession.SessionHandler = handler = new ReliableTransferHandler(reliableSession); handler.BeginTransferEvent += new ReliableTransferDelegate(OnBeginTransfer); handler.EndTransferEvent += new ReliableTransferDelegate(OnEndTransfer); if (direction == TransferDirection.Upload) { handler.SendEvent += new ReliableTransferDelegate(OnSend); } else { handler.ReceiveEvent += new ReliableTransferDelegate(OnReceive); } this.router = router; this.serverEP = serverEP; this.direction = direction; this.args = null; this.stream = stream; this.started = false; this.closed = false; this.streamClosed = false; this.arTransfer = null; this.simError = false; this.simCancel = false; this.delay = 0; }
/// <summary> /// Private constructor for initializing <b>server side</b> sessions. /// </summary> /// <param name="router">The message router.</param> /// <param name="msg">The <see cref="ReliableTransferMsg" /> that initiated this session.</param> /// <param name="direction">The transfer direction supported by the server.</param> /// <param name="stream">The input or output stream.</param> /// <exception cref="InvalidOperationException"> /// Thrown if the client requested transfer direction does not match the /// direction implied by this method. /// </exception> private StreamTransferSession(MsgRouter router, ReliableTransferMsg msg, TransferDirection direction, EnhancedStream stream) { if (direction != msg.Direction) { throw new InvalidOperationException(string.Format("Transfer direction [{0}] is not supported.", msg.Direction)); } ReliableTransferHandler handler; reliableSession = msg.Session; reliableSession.SessionHandler = handler = new ReliableTransferHandler(reliableSession); handler.BeginTransferEvent += new ReliableTransferDelegate(OnBeginTransfer); handler.EndTransferEvent += new ReliableTransferDelegate(OnEndTransfer); if (direction == TransferDirection.Upload) { handler.ReceiveEvent += new ReliableTransferDelegate(OnReceive); } else { handler.SendEvent += new ReliableTransferDelegate(OnSend); } this.router = router; this.direction = direction; this.args = msg.Args; this.stream = stream; this.started = false; this.closed = false; this.arTransfer = null; this.simError = false; this.simCancel = false; this.delay = 0; }
private void OnTransferComplete(int total, TransferDirection direction) { if (TransferComplete != null) { TransferComplete(total, direction); } }
internal FtpDataStream GetPassiveDataStream(TransferDirection direction) { TcpClient client = new TcpClient(); int port = 0; try { port = GetPassivePort(); client.Connect(m_server, port); if (direction == TransferDirection.Download) { return(new FtpInputDataStream(this, client)); } else { return(new FtpOutputDataStream(this, client)); } } catch (IOException ie) { throw new Exception("Failed to open passive port (" + port + ") data connection due to IO exception: " + ie.Message + ".", ie); } catch (SocketException se) { throw new Exception("Failed to open passive port (" + port + ") data connection due to socket exception: " + se.Message + ".", se); } }
private FtpDataStream GetStream(long offset, TransferDirection dir) { m_parent.CheckSessionCurrentDirectory(); FtpSessionConnected Session = m_parent.Session; if (offset != 0) { Session.ControlChannel.REST(offset); } FtpDataStream stream = Session.ControlChannel.GetDataStream(dir); try { if (dir == TransferDirection.Download) { Session.ControlChannel.RETR(m_name); } else { Session.ControlChannel.STOR(m_name); } } catch { stream.Close(); throw; } return(stream); }
public TransferEventArgs(string localFilePath, string remoteFilename, TransferDirection direction, FTPTransferType transferType) { this.localFilePath = localFilePath; this.remoteFilename = remoteFilename; this.direction = direction; this.transferType = transferType; }
public TransferEventArgs(Stream localStream, string remoteFilename, TransferDirection direction, FTPTransferType transferType) { this.localStream = localStream; this.remoteFilename = remoteFilename; this.direction = direction; this.transferType = transferType; }
public TransferEventArgs(byte[] localByteArray, string remoteFilename, TransferDirection direction, FTPTransferType transferType) { this.localByteArray = localByteArray; this.remoteFilename = remoteFilename; this.direction = direction; this.transferType = transferType; }
internal FtpFileTransferer(FtpDirectory transferStarter, string localFile, string remoteFile, long totalBytes, TransferDirection dir) { m_transferStarter = transferStarter; m_transferDirection = dir; m_session = transferStarter.FtpSession; m_localFile = localFile; m_remoteFile = remoteFile; m_totalBytes = totalBytes; if (dir == TransferDirection.Upload) { m_beginEvent = new FileEventDelegate(m_session.Host.RaiseBeginPutFileEvent); m_endEvent = new FileEventDelegate(m_session.Host.RaiseEndPutFile); m_streamCopyRoutine = new StreamCopyDelegate(LocalToRemote); m_ftpFileCommandRoutine = new FtpDelegate(m_session.ControlChannel.STOR); m_localFileOpenMode = FileMode.Open; } else { m_beginEvent = new FileEventDelegate(m_session.Host.RaiseBeginGetFileEvent); m_endEvent = new FileEventDelegate(m_session.Host.RaiseEndGetFile); m_streamCopyRoutine = new StreamCopyDelegate(RemoteToLocal); m_ftpFileCommandRoutine = new FtpDelegate(m_session.ControlChannel.RETR); m_localFileOpenMode = FileMode.Create; } }
internal void TransferEventArgs_Instantiates_With_The_Given_Data(TransferDirection direction, string username, string filename, int token, TransferOptions options) { var dl = new Transfer(direction, username, filename, token, options); var d = new TransferEventArgs(dl); Assert.Equal(direction, d.Direction); Assert.Equal(0, d.AverageSpeed); Assert.Equal(0, d.BytesTransferred); Assert.Equal(0, d.BytesRemaining); Assert.Equal(default(TimeSpan), d.ElapsedTime); Assert.Equal(default(TimeSpan), d.RemainingTime); Assert.Null(d.StartTime); Assert.Null(d.EndTime); Assert.Null(d.IPAddress); Assert.Equal(0, d.PercentComplete); Assert.Null(d.Port); Assert.Equal(dl.RemoteToken, d.RemoteToken); Assert.Equal(0, d.Size); Assert.Equal(dl.Username, d.Username); Assert.Equal(dl.Filename, d.Filename); Assert.Equal(dl.Token, d.Token); Assert.Equal(dl.State, d.State); Assert.Equal(options, d.Options); Assert.Equal(dl.Data, d.Data); }
protected OneFileTransferModel(IDataService dataService, int friendNumber, int fileNumber, string name, long fileSizeInBytes, TransferDirection direction, Stream stream, long transferredBytes = 0) { _toxModel = dataService.ToxModel; _fileTransferResumer = dataService.FileTransferResumer; _stream = stream; if (_stream != null) { if (_stream.CanWrite) { _stream.SetLength(fileSizeInBytes); } _stream.Position = transferredBytes; } _fileSizeInBytes = fileSizeInBytes; _direction = direction; SetInitialStateBasedOnDirection(direction); Name = name; _friendNumber = friendNumber; _fileNumber = fileNumber; _toxModel.FileControlReceived += FileControlReceivedHandler; _toxModel.FileChunkRequested += FileChunkRequestedHandler; _toxModel.FileChunkReceived += FileChunkReceivedHandler; _toxModel.FriendConnectionStatusChanged += FriendConnectionStatusChangedHandler; Application.Current.Suspending += AppSuspendingHandler; }
internal void OnEndFileTransfer(string localFileName, string remoteFileName, TransferDirection transferDirection) { if ((object)EndFileTransfer != null) { EndFileTransfer(this, new EventArgs <string, string, TransferDirection>(localFileName, remoteFileName, transferDirection)); } }
private void OnTransferBegin(int total, TransferDirection direction, CompressionState state) { if (TransferBegin != null) { TransferBegin(total, direction, state); } }
protected virtual void SendLog(TransferDirection direction, String format, params Object[] parameters) { if (this.OnLog != null) { this.OnLog(this, new ClientLogArgs(direction, format, parameters)); } }
protected virtual void SendLog(TransferDirection direction, String message) { if (this.OnLog != null) { this.OnLog(this, new ClientLogArgs(direction, message)); } }
/// <summary> /// Initializes a new instance of the <see cref="TransferRequest"/> class. /// </summary> /// <param name="direction">The direction of the transfer (download, upload).</param> /// <param name="token">The unique token for the transfer.</param> /// <param name="filename">The name of the file being transferred.</param> /// <param name="fileSize">The size of the file being transferred.</param> public TransferRequest(TransferDirection direction, int token, string filename, long fileSize = 0) { Direction = direction; Token = token; Filename = filename; FileSize = fileSize; }
internal FtpDataStream GetPassiveDataStream(TransferDirection direction) { TcpClient client = new TcpClient(); try { client.Connect(m_server, GetPassivePort()); if (direction == TransferDirection.Download) { return(new FtpInputDataStream(this, client)); } else { return(new FtpOutputDataStream(this, client)); } } catch (IOException ie) { throw new FtpException("Failed to open data connecton.", ie); } catch (SocketException se) { throw new FtpException("Failed to open data connecton.", se); } }
public override void ChildWantMove(Node child, TransferDirection direction) { switch (direction) { case TransferDirection.Left: Log.Warning($"{nameof(FixedContainerNode)}.{nameof(ChildWantMove)} was called with Left, ({child.GetType()}) but Fixed container cannot change its childs nodes"); break; case TransferDirection.Up: Log.Warning($"{nameof(FixedContainerNode)}.{nameof(ChildWantMove)} was called with up, ({child.GetType()}) but Fixed container cannot change its childs nodes"); break; case TransferDirection.Right: Log.Warning($"{nameof(FixedContainerNode)}.{nameof(ChildWantMove)} was called with right, ({child.GetType()}) but Fixed container cannot change its childs nodes"); break; case TransferDirection.Down: Log.Warning($"{nameof(FixedContainerNode)}.{nameof(ChildWantMove)} was called with down, ({child.GetType()}) but Fixed container cannot change its childs nodes"); break; default: Log.Error($"{nameof(ContainerNode)}.{nameof(ChildWantMove)} was called with unknown {typeof(TransferDirection).ToString()} ({direction.ToString()})"); break; } }
protected virtual void TriggerOnTransferProgress(TransferDirection direction, Int64 position) { if (OnTransferProgress != null) { OnTransferProgress(this, new TransferProgressEventArgs(direction, position)); } }
public override void ChildWantMove(Node child, TransferDirection direction) { switch (direction) { case TransferDirection.Left: MoveChildLeft(child); break; case TransferDirection.Up: MoveChildUp(child); break; case TransferDirection.Right: MoveChildRight(child); break; case TransferDirection.Down: MoveChildDown(child); break; default: Log.Error($"{nameof(ContainerNode)}.{nameof(ChildWantMove)} was called with unknown {typeof(TransferDirection).ToString()} ({direction.ToString()})"); break; } }
public async Task SendTransferRequest(Guid conferenceId, Guid participantId, TransferDirection transferDirection) { try { var conference = await GetConference(conferenceId); var transferringParticipant = conference.Participants.SingleOrDefault(x => x.Id == participantId); if (transferringParticipant == null) { _logger.LogDebug("Participant {participant} does not exist in {conference}", participantId, conferenceId); throw new ParticipantNotFoundException(conferenceId, Context.User.Identity.Name); } await Clients.Group(VhOfficersGroupName).HearingTransfer(conferenceId, participantId, transferDirection); _logger.LogTrace( "Participant Transfer: Participant Id: {participant} | Conference Id: {conference} | Direction: {direction}", participantId, conferenceId, transferDirection); foreach (var participant in conference.Participants) { await Clients.Group(participant.Username.ToLowerInvariant()).HearingTransfer(conferenceId, participantId, transferDirection); } } catch (Exception ex) { _logger.LogError(ex, "Error occured when transferring participant"); } }
protected virtual void TriggerOnTransferStart(TransferDirection direction, Int64 size) { if (OnTransferStart != null) { OnTransferStart(this, new TransferStartEventArgs(direction, size)); } }
public FileTransfer InitializeFileTransfer( TransferDirection direction, FileTransferInitiator initiator, ServerInfo remoteServerInfo, string fileName, long fileSizeInBytes, string localFolderPath, string remoteFolderPath, long transferResponseCode, int remoteServerRetryLimit, int remoteServerTransferId) { var fileTransfer = new FileTransfer { Status = FileTransferStatus.Pending, RequestInitiatedTime = DateTime.Now, TransferDirection = direction, Initiator = initiator, RemoteServerInfo = remoteServerInfo, FileName = fileName, FileSizeInBytes = fileSizeInBytes, LocalFolderPath = localFolderPath, RemoteFolderPath = remoteFolderPath, TransferResponseCode = transferResponseCode, RemoteServerRetryLimit = remoteServerRetryLimit, RemoteServerTransferId = remoteServerTransferId }; AssignNewFileTransferId(fileTransfer); return(fileTransfer); }
private void OnTransferProgress(int total, int current, TransferDirection direction) { if (TransferProgress != null) { TransferProgress(total, current, direction); } }
protected OneFileTransferModel(int friendNumber, int fileNumber, string name, long fileSizeInBytes, TransferDirection direction, Stream stream, long transferredBytes = 0) { _stream = stream; if (_stream != null) { if (_stream.CanWrite) { _stream.SetLength(fileSizeInBytes); } _stream.Position = transferredBytes; } _fileSizeInBytes = fileSizeInBytes; _direction = direction; SetInitialStateBasedOnDirection(direction); Name = name; _friendNumber = friendNumber; _fileNumber = fileNumber; ToxModel.Instance.FileControlReceived += FileControlReceivedHandler; ToxModel.Instance.FileChunkRequested += FileChunkRequestedHandler; ToxModel.Instance.FileChunkReceived += FileChunkReceivedHandler; ToxModel.Instance.FriendConnectionStatusChanged += FriendConnectionStatusChangedHandler; Application.Current.Suspending += AppSuspendingHandler; }
/// <summary> /// Initializes a new instance of the <see cref="PeerTransferRequest"/> class. /// </summary> /// <param name="direction">The direction of the transfer (download, upload).</param> /// <param name="token">The unique token for the transfer.</param> /// <param name="filename">The name of the file being transferred.</param> /// <param name="fileSize">The size of the file being transferred.</param> internal PeerTransferRequest(TransferDirection direction, int token, string filename, int fileSize = 0) { Direction = direction; Token = token; Filename = filename; FileSize = fileSize; }
protected virtual void TriggerOnTransferEnd(TransferDirection direction) { if (OnTransferEnd != null) { OnTransferEnd(this, new TransferEndEventArgs(direction)); } }
/// <summary> /// Initializes a new instance of the <see cref="Transfer"/> class. /// </summary> /// <param name="direction">The transfer direction.</param> /// <param name="username">The username of the peer to or from which the file is to be transferred.</param> /// <param name="filename">The filename of the file to be transferred.</param> /// <param name="token">The unique token for the transfer.</param> /// <param name="state">The state of the transfer.</param> /// <param name="size">The size of the file to be transferred, in bytes.</param> /// <param name="startOffset">The start offset of the transfer, in bytes.</param> /// <param name="bytesTransferred">The total number of bytes transferred.</param> /// <param name="averageSpeed">The current average download speed.</param> /// <param name="startTime"> /// The time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state. /// </param> /// <param name="endTime"> /// The time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state. /// </param> /// <param name="remoteToken">The remote unique token for the transfer.</param> /// <param name="ipEndPoint">The ip endpoint of the remote transfer connection, if one has been established.</param> public Transfer( TransferDirection direction, string username, string filename, int token, TransferStates state, long size, long startOffset, long bytesTransferred = 0, double averageSpeed = 0, DateTime?startTime = null, DateTime?endTime = null, int?remoteToken = null, IPEndPoint ipEndPoint = null) { Direction = direction; Username = username; Filename = filename; Token = token; State = state; Size = size; StartOffset = startOffset; BytesTransferred = bytesTransferred; AverageSpeed = averageSpeed; StartTime = startTime; EndTime = endTime; RemoteToken = remoteToken; IPEndPoint = ipEndPoint; }
private FtpDataStream GetStream(long offset, TransferDirection dir) { m_parent.CheckSessionCurrentDirectory(); SessionConnected session = m_parent.FtpSession; if (offset != 0) { session.ControlChannel.REST(offset); } FtpDataStream stream = session.ControlChannel.GetPassiveDataStream(dir); try { if (dir == TransferDirection.Download) { session.ControlChannel.RETR(m_name); } else { session.ControlChannel.STOR(m_name); } } catch (Exception) { stream.Dispose(); throw; } return(stream); }
/// <summary> /// Initializes a new instance of <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/> class. /// </summary> /// <param name="data"> /// Data of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> /// <param name="direction"> /// <see cref="Kamilla.Network.TransferDirection"/> of /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> /// <param name="flags"> /// The <see cref="Kamilla.Network.PacketFlags"/> of /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> /// <param name="wowFlags"> /// The <see cref="Kamilla.Network.Protocols.Wow.WowPacketFlags"/> of /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> /// <param name="arrivalTicks"> /// Number of milliseconds passed from the Operation System start to the packet arrival event. /// </param> /// <param name="arrivalTime"> /// An instance of <see cref="System.DateTime"/> representing the moment when /// the packet <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/> arrived. /// </param> /// <param name="opcode"> /// The opcode of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> /// <param name="connectionId"> /// The connection id of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>. /// </param> public WowPacket(byte[] data, TransferDirection direction, PacketFlags flags, WowPacketFlags wowFlags, DateTime arrivalTime, uint arrivalTicks, uint opcode, int connectionId) : base(data, direction, flags, arrivalTime, arrivalTicks) { m_opcode = opcode; m_connectionId = connectionId; m_wowFlags = wowFlags; }
internal void TransferEventArgs_Instantiates_With_The_Given_Data(TransferDirection direction, string username, string filename, int token, TransferOptions options) { var dl = new TransferInternal(direction, username, filename, token, options); var xfer = new Transfer(dl); var d = new TransferEventArgs(xfer); Assert.Equal(xfer, d.Transfer); }
/// <summary> /// Initializes a new instance of <see cref="Kamilla.Network.Packet"/> class /// with the specified data, <see cref="Kamilla.Network.TransferDirection"/>, /// <see cref="Kamilla.Network.PacketFlags"/>, and arrival time and ticks. /// </summary> /// <param name="data"> /// Data of the new <see cref="Kamilla.Network.Packet"/>. /// </param> /// <param name="direction"> /// <see cref="Kamilla.Network.TransferDirection"/> of the new <see cref="Kamilla.Network.Packet"/>. /// </param> /// <param name="flags"> /// <see cref="Kamilla.Network.PacketFlags"/> of the new <see cref="Kamilla.Network.Packet"/>. /// </param> /// <param name="arrivalTicks"> /// Number of milliseconds passed from the Operation System start to the packet arrival event. /// </param> /// <param name="arrivalTime"> /// An instance of <see cref="System.DateTime"/> representing the moment when /// the packet <see cref="Kamilla.Network.Packet"/> arrived. /// </param> public Packet(byte[] data, TransferDirection direction, PacketFlags flags, DateTime arrivalTime, uint arrivalTicks) { m_arrivalDateTime = arrivalTime; m_arrivalTicks = arrivalTicks; m_data = data; m_direction = direction; m_flags = flags; }
public static async Task<OneFileTransferModel> CreateInstance(int friendNumber, int fileNumber, string name, long fileSizeInBytes, TransferDirection direction, StorageFile file, long transferredBytes = 0) { if (file != null) FileTransferResumer.Instance.RecordTransfer(file, friendNumber, fileNumber, direction); var fileStream = file == null ? null : await GetStreamBasedOnDirection(file, direction); return new OneFileTransferModel(friendNumber, fileNumber, name, fileSizeInBytes, direction, fileStream, transferredBytes); }
protected static async Task<Stream> GetStreamBasedOnDirection(StorageFile file, TransferDirection direction) { switch (direction) { case TransferDirection.Up: return await file.OpenStreamForReadAsync(); case TransferDirection.Down: return await file.OpenStreamForWriteAsync(); } return null; }
protected virtual void SetInitialStateBasedOnDirection(TransferDirection direction) { switch (direction) { case TransferDirection.Up: State = FileTransferState.BeforeUpload; break; case TransferDirection.Down: State = FileTransferState.BeforeDownload; break; } }
protected override void SetInitialStateBasedOnDirection(TransferDirection direction) { switch (direction) { case TransferDirection.Up: State = FileTransferState.Uploading; break; case TransferDirection.Down: State = FileTransferState.Downloading; break; } }
public static DataSet GetInstruments(int positionTransferID, TransferDirection txDirection, int instrumentID) { using (IDalSession session = NHSessionFactory.CreateSession()) { DataSet returnValue = new DataSet(); IPositionTransfer transfer = PositionTransferMapper.getTransfer(session, positionTransferID); IPositionTransferDetailCollection details = transfer.TransferDetails; var detailInstruments = details.Where(d => d.InstrumentOfPosition.Key != instrumentID); if (transfer.AIsInternal && transfer.BIsInternal) { IPositionTransferPortfolio port = (txDirection == TransferDirection.FromAtoB ? transfer.APortfolioBefore : transfer.BPortfolioBefore); returnValue = port.Positions.Where(p => p.IsFundPosition) .Select(p => new { Key = p.InstrumentOfPosition.Key, Description = p.InstrumentDescription }) .Except(detailInstruments.Select(d => new { Key = d.InstrumentOfPosition.Key, Description = d.InstrumentDescription })) .OrderBy(o => o.Description) .ToDataSet(); } else { returnValue = Instruments.InstrumentMapper.GetTradeableInstrumentsForDropDownList(session) .Select(p => new { Key = p.Key, Description = p.Value }) .Except(detailInstruments.Select(d => new { Key = d.InstrumentOfPosition.Key, Description = d.InstrumentDescription })) .OrderBy(o => o.Description) .ToDataSet(); } Utility.AddEmptyFirstRow(returnValue); return returnValue; } }
public new static async Task<OneFileTransferModel> CreateInstance(int friendNumber, int fileNumber, string name, long fileSizeInBytes, TransferDirection direction, StorageFile file, long transferredBytes = 0) { if (file != null) FileTransferResumer.Instance.RecordTransfer(file, friendNumber, fileNumber, direction); var fileStream = file == null ? null : await GetStreamBasedOnDirection(file, direction); var oneBrokenFileDownloadModel = new OneBrokenFileTransferModel(friendNumber, fileNumber, name, fileSizeInBytes, direction, fileStream, transferredBytes); if (direction == TransferDirection.Down) { ToxModel.Instance.FileSeek(friendNumber, fileNumber, transferredBytes); ToxModel.Instance.FileControl(friendNumber, fileNumber, ToxFileControl.Resume); } return oneBrokenFileDownloadModel; }
/// <summary> /// Records a file transfer for future resuming between core restarts. /// </summary> /// <param name="file">The file associated with the transfer.</param> /// <param name="friendNumber">The friend number of the transfer.</param> /// <param name="fileNumber">The file number of the transfer.</param> /// <param name="direction">The direction of the transfer.</param> public void RecordTransfer(StorageFile file, int friendNumber, int fileNumber, TransferDirection direction) { // TODO: Maybe we should try to make place for newer items? if (_futureAccesList.MaximumItemsAllowed == _futureAccesList.Entries.Count) return; var metadata = new TransferMetadata { FriendNumber = friendNumber, FileNumber = fileNumber, FileId = ToxModel.Instance.FileGetId(friendNumber, fileNumber), TransferredBytes = 0, Direction = direction }; var xmlMetadata = SerializeMetadata(metadata); _futureAccesList.Add(file, xmlMetadata); }
internal FtpFileTransferer(FtpDirectory transferStarter, string localFile, string remoteFile, long totalBytes, TransferDirection dir) { m_transferStarter = transferStarter; m_transferDirection = dir; m_session = transferStarter.Session; m_localFile = localFile; m_remoteFile = remoteFile; m_totalBytes = totalBytes; if (dir == TransferDirection.Upload) { m_streamCopyRoutine = LocalToRemote; m_ftpFileCommandRoutine = m_session.ControlChannel.STOR; m_localFileOpenMode = FileMode.Open; } else { m_streamCopyRoutine = RemoteToLocal; m_ftpFileCommandRoutine = m_session.ControlChannel.RETR; m_localFileOpenMode = FileMode.Create; } }
private void OnTransferProgress(int total, int current, TransferDirection direction) { if (TransferProgress != null) TransferProgress(total, current, direction); }
private void OnTransferComplete(int total, TransferDirection direction) { if (TransferComplete != null) TransferComplete(total, direction); }
private void OnTransferBegin(int total, TransferDirection direction, CompressionState state) { if (TransferBegin != null) TransferBegin(total, direction, state); }
protected virtual void TriggerOnTransferProgress(TransferDirection direction, Int64 position) { if (OnTransferProgress != null) OnTransferProgress(this, new TransferProgressEventArgs(direction, position)); }
private FtpDataStream GetStream(long offset, TransferDirection dir) { m_parent.CheckSessionCurrentDirectory(); SessionConnected session = m_parent.FtpSession; if(offset != 0) session.ControlChannel.REST(offset); FtpDataStream stream = session.ControlChannel.GetPassiveDataStream(dir); try { if(dir == TransferDirection.Download) session.ControlChannel.RETR(m_name); else session.ControlChannel.STOR(m_name); }catch(Exception) { stream.Dispose(); throw; } return stream; }
internal void TransferData(TransferDirection direction, FtpsRequest request, Stream data) { TransferData(direction, request, data, 0); }
internal void OnFileTransferProgress(ProcessProgress<long> fileTransferProgress, TransferDirection transferDirection) { if (FileTransferProgress != null) FileTransferProgress(this, new EventArgs<ProcessProgress<long>,TransferDirection>(fileTransferProgress, transferDirection)); }
internal void OnEndFileTransfer(string localFileName, string remoteFileName, TransferDirection transferDirection) { if (EndFileTransfer != null) EndFileTransfer(this, new EventArgs<string,string,TransferDirection>(localFileName, remoteFileName, transferDirection)); }
private OneBrokenFileTransferModel(int friendNumber, int fileNumber, string name, long fileSizeInBytes, TransferDirection direction, Stream stream, long transferredBytes = 0) : base(friendNumber, fileNumber, name, fileSizeInBytes, direction, stream, transferredBytes) { }
private Stream CreateZlibStream(TransferDirection direction, Stream stream) { DeflateStream zstream = null; switch (direction) { case TransferDirection.ToClient: zstream = new DeflateStream(stream, CompressionMode.Decompress, true); // zlib fix to ignore first two bytes of header data zstream.BaseStream.ReadByte(); zstream.BaseStream.ReadByte(); break; case TransferDirection.ToServer: zstream = new DeflateStream(stream, CompressionMode.Compress, true); // this is a fix for the DeflateStream class only when sending compressed data to the server. // Zlib has two bytes of data attached to the header that we have to write before processing the data stream. zstream.BaseStream.WriteByte(120); zstream.BaseStream.WriteByte(218); break; } return zstream; }
internal void OpenDataConnAndTransferData(TransferDirection direction, FtpsRequest request, Stream data, long restartPosition) { try { // create a thread to begin the porocess of opening a data connection to the remote server OpenDataConn(); // check for a restart position if (restartPosition > 0) { // instruct the server to restart file transfer at the same position where the output stream left off SendRequest(new FtpsRequest(_encode, FtpsCmd.Rest, restartPosition.ToString(CultureInfo.InvariantCulture))); // set the data stream to the same position as the server data.Position = restartPosition; } // send the data transfer command that requires a separate data connection to be established to transmit data SendRequest(request); // wait for the data connection thread to signal back that a connection has been established WaitForDataConn(); // test to see if the data connection failed to be established sometime the active connection fails due to security settings on the ftp server if (_dataConn == null) throw new FtpsDataConnectionException("Unable to establish a data connection to the destination. The destination may have refused the connection."); // create the data stream object - handles creation of SslStream and DeflateStream objects as well Stream conn = _dataConn.GetStream(); // test to see if we need to enable ssl/tls explicit mode if (_securityProtocol != FtpsSecurityProtocol.None) conn = CreateSslStream(conn); // test to see if we need to enable compression by using the DeflateStream if (_isCompressionEnabled) conn = CreateZlibStream(direction, conn); // based on the direction of the data transfer we need to handle the input and output streams switch (direction) { case TransferDirection.ToClient: TransferBytes(conn, data, _maxDownloadSpeed * 1024); break; case TransferDirection.ToServer: TransferBytes(data, conn, _maxUploadSpeed * 1024); break; } } finally { // reset the transfer size used to calc % completed SetTransferSize(-1); // attempt to close the data connection CloseDataConn(); } // if no errors occurred and this is not a quoted command then we will wait for the server to send a closing connection message WaitForHappyCodes(FtpsResponseCode.ClosingDataConnection); // automatic integrity check with file transfer if (_autoHashAlgorithm != HashingAlgorithm.None && request.IsFileTransfer) DoIntegrityCheck(request, data, restartPosition); }
internal void TransferData(TransferDirection direction, FtpsRequest request, Stream data, long restartPosition) { if (_commandConn == null || _commandConn.Connected == false) throw new FtpsConnectionClosedException("Connection is closed."); if (request == null) throw new ArgumentNullException("request", "value is required"); if (data == null) throw new ArgumentNullException("data", "value is required"); switch (direction) { case TransferDirection.ToClient: if (!data.CanWrite) throw new FtpsDataTransferException("Data transfer error. Data conn does not allow write operation."); break; case TransferDirection.ToServer: if (!data.CanRead) throw new FtpsDataTransferException("Data transfer error. Data conn does not allow read operation."); break; } // if this is a restart then the data stream must support seeking if (restartPosition > 0 && !data.CanSeek) throw new FtpsDataTransferException("Data transfer restart error. Data conn does not allow seek operation."); OpenDataConnAndTransferData(direction, request, data, restartPosition); }
protected virtual void TriggerOnTransferEnd(TransferDirection direction) { if (OnTransferEnd != null) OnTransferEnd(this, new TransferEndEventArgs(direction)); }
internal DataStream GetPassiveDataStream(TransferDirection direction) { TcpClient client = new TcpClient(); int port = 0; try { port = GetPassivePort(); client.Connect(m_server, port); if (direction == TransferDirection.Download) return new InputDataStream(this, client); else return new OutputDataStream(this, client); } catch (IOException ie) { throw new System.Exception("Failed to open passive port (" + port + ") data connection due to IO exception: " + ie.Message + ".", ie); } catch (SocketException se) { throw new System.Exception("Failed to open passive port (" + port + ") data connection due to socket exception: " + se.Message + ".", se); } }
internal void TransferData(TransferDirection direction, FtpRequest request, Stream data, long restartPosition) { if (_commandConn == null || _commandConn.Connected == false) throw new FtpConnectionClosedException("Connection is closed."); if (request == null) throw new ArgumentNullException("request", "value is required"); if (data == null) throw new ArgumentNullException("data", "value is required"); switch (direction) { case TransferDirection.ToClient: if (!data.CanWrite) throw new FtpDataTransferException("Data transfer error. Data conn does not allow write operation."); break; case TransferDirection.ToServer: if (!data.CanRead) throw new FtpDataTransferException("Data transfer error. Data conn does not allow read operation."); break; } // if this is a restart then the data stream must support seeking if (restartPosition > 0 && !data.CanSeek) throw new FtpDataTransferException("Data transfer restart error. Data conn does not allow seek operation."); try { // create a thread to begin the process of opening a data connection to the remote server OpenDataConn(); // check for a restart position if (restartPosition > 0) { // instruct the server to restart file transfer at the same position where the output stream left off SendRequest(new FtpRequest(_encoding, FtpCmd.Rest, restartPosition.ToString(CultureInfo.InvariantCulture))); // set the data stream to the same position as the server data.Position = restartPosition; } // send the data transfer command that requires a separate data connection to be established to transmit data SendRequest(request); // wait for the data connection thread to signal back that a connection has been established WaitForDataConn(); // test to see if the data connection failed to be established sometime the active connection fails due to security settings on the ftp server if (_dataConn == null) throw new FtpDataConnectionException("Unable to establish a data connection to the destination. The destination may have refused the connection."); // create the data stream object - handles creation of SslStream and DeflateStream objects as well Stream conn = _dataConn.GetStream(); // test to see if we need to enable ssl/tls explicit mode if (_securityProtocol != FtpSecurityProtocol.None) { conn = CreateSslStream(conn); } // test to see if we need to enable compression by using the DeflateStream if (_isCompressionEnabled) { conn = CreateZlibStream(direction, conn); } // based on the direction of the data transfer we need to handle the input and output streams switch (direction) { case TransferDirection.ToClient: TransferBytes(conn, data, _maxDownloadSpeed * 1024); break; case TransferDirection.ToServer: TransferBytes(data, conn, _maxUploadSpeed * 1024); break; } } finally { // attempt to close the data connection CloseDataConn(); } // if no errors occurred and this is not a quoted command then we will wait for the server to send a closing connection message WaitForHappyCodes(FtpResponseCode.ClosingDataConnection); // integrity check if (_hashAlgorithm != HashingFunction.None && request.IsFileTransfer) DoIntegrityCheck(request, data, restartPosition); }