Example #1
0
        // This assumes preBuffer/postBuffer are pinned already

        private static unsafe bool TransmitFileHelper(
            SafeHandle socket,
            SafeHandle fileHandle,
            SafeHandle overlapped,
            byte[] preBuffer,
            byte[] postBuffer,
            TransmitFileOptions flags)
        {
            bool needTransmitFileBuffers = false;

            Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);

            if (preBuffer != null && preBuffer.Length > 0)
            {
                needTransmitFileBuffers        = true;
                transmitFileBuffers.Head       = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
                transmitFileBuffers.HeadLength = preBuffer.Length;
            }

            if (postBuffer != null && postBuffer.Length > 0)
            {
                needTransmitFileBuffers        = true;
                transmitFileBuffers.Tail       = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
                transmitFileBuffers.TailLength = postBuffer.Length;
            }

            bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
                                                        needTransmitFileBuffers ? &transmitFileBuffers : null, flags);

            return(success);
        }
 public SendFileInfo(string fileName, CrestronSocket socket, TransmitFileOptions flags, SendFileAsyncResult iar, AsyncCallback callback)
 {
     FileName = fileName;
     Socket   = socket;
     Flags    = flags;
     Iar      = iar;
     Callback = callback;
 }
Example #3
0
 internal static extern unsafe bool TransmitFile(
     SafeHandle socket,
     SafeHandle fileHandle,
     int numberOfBytesToWrite,
     int numberOfBytesPerSend,
     SafeHandle overlapped,
     TransmitFileBuffers* buffers,
     TransmitFileOptions flags);
Example #4
0
 internal static extern unsafe bool TransmitFile(
     SafeHandle socket,
     SafeHandle fileHandle,
     int numberOfBytesToWrite,
     int numberOfBytesPerSend,
     NativeOverlapped *overlapped,
     TransmitFileBuffers *buffers,
     TransmitFileOptions flags);
Example #5
0
 private static void CheckTransmitFileOptions(TransmitFileOptions flags)
 {
     // Note, UseDefaultWorkerThread is the default and is == 0.
     // Unfortunately there is no TransmitFileOptions.None.
     if (flags != TransmitFileOptions.UseDefaultWorkerThread)
     {
         throw new PlatformNotSupportedException(SR.net_sockets_transmitfileoptions_notsupported);
     }
 }
Example #6
0
 public static void SendFileAPM(this Socket socket, string filename, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, Action handler)
 {
     var callback = new AsyncCallback(asyncResult =>
     {
         ((Socket)asyncResult.AsyncState).EndSendFile(asyncResult);
         handler();
     });
     socket.BeginSendFile(filename, preBuffer, postBuffer, flags, callback, socket);
 }
Example #7
0
 private static void CheckTransmitFileOptions(TransmitFileOptions flags)
 {
     // Note, UseDefaultWorkerThread is the default and is == 0.
     // Unfortunately there is no TransmitFileOptions.None.
     if (flags != TransmitFileOptions.UseDefaultWorkerThread)
     {
         throw new PlatformNotSupportedException(SR.net_sockets_transmitfileoptions_notsupported);
     }
 }
Example #8
0
 /// <inheritdoc />
 public IAsyncResult BeginSendFile(string fileName,
                                   byte[] preBuffer,
                                   byte[] postBuffer,
                                   TransmitFileOptions flags,
                                   AsyncCallback callback,
                                   object state)
 {
     return(_socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback, state));
 }
Example #9
0
        internal void SetUnmanagedStructures(byte[] preBuffer, byte[] postBuffer, FileStream fileStream, TransmitFileOptions flags, bool sync)
        {
            this.m_fileStream = fileStream;
            this.m_flags      = flags;
            this.m_buffers    = null;
            int num = 0;

            if ((preBuffer != null) && (preBuffer.Length > 0))
            {
                num++;
            }
            if ((postBuffer != null) && (postBuffer.Length > 0))
            {
                num++;
            }
            object[] objectsToPin = null;
            if (num != 0)
            {
                num++;
                objectsToPin        = new object[num];
                this.m_buffers      = new System.Net.TransmitFileBuffers();
                objectsToPin[--num] = this.m_buffers;
                if ((preBuffer != null) && (preBuffer.Length > 0))
                {
                    this.m_buffers.preBufferLength = preBuffer.Length;
                    objectsToPin[--num]            = preBuffer;
                }
                if ((postBuffer != null) && (postBuffer.Length > 0))
                {
                    this.m_buffers.postBufferLength = postBuffer.Length;
                    objectsToPin[--num]             = postBuffer;
                }
                if (sync)
                {
                    base.PinUnmanagedObjects(objectsToPin);
                }
                else
                {
                    base.SetUnmanagedStructures(objectsToPin);
                }
                if ((preBuffer != null) && (preBuffer.Length > 0))
                {
                    this.m_buffers.preBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
                }
                if ((postBuffer != null) && (postBuffer.Length > 0))
                {
                    this.m_buffers.postBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
                }
            }
            else if (!sync)
            {
                base.SetUnmanagedStructures(null);
            }
        }
 internal void SetUnmanagedStructures(byte[] preBuffer, byte[] postBuffer, FileStream fileStream, TransmitFileOptions flags, bool sync)
 {
     this.m_fileStream = fileStream;
     this.m_flags = flags;
     this.m_buffers = null;
     int num = 0;
     if ((preBuffer != null) && (preBuffer.Length > 0))
     {
         num++;
     }
     if ((postBuffer != null) && (postBuffer.Length > 0))
     {
         num++;
     }
     object[] objectsToPin = null;
     if (num != 0)
     {
         num++;
         objectsToPin = new object[num];
         this.m_buffers = new System.Net.TransmitFileBuffers();
         objectsToPin[--num] = this.m_buffers;
         if ((preBuffer != null) && (preBuffer.Length > 0))
         {
             this.m_buffers.preBufferLength = preBuffer.Length;
             objectsToPin[--num] = preBuffer;
         }
         if ((postBuffer != null) && (postBuffer.Length > 0))
         {
             this.m_buffers.postBufferLength = postBuffer.Length;
             objectsToPin[--num] = postBuffer;
         }
         if (sync)
         {
             base.PinUnmanagedObjects(objectsToPin);
         }
         else
         {
             base.SetUnmanagedStructures(objectsToPin);
         }
         if ((preBuffer != null) && (preBuffer.Length > 0))
         {
             this.m_buffers.preBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
         }
         if ((postBuffer != null) && (postBuffer.Length > 0))
         {
             this.m_buffers.postBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
         }
     }
     else if (!sync)
     {
         base.SetUnmanagedStructures(null);
     }
 }
Example #11
0
        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            CheckTransmitFileOptions(flags);

            // Open the file, if any
            // Open it before we send the preBuffer so that any exception happens first
            FileStream fileStream = OpenFile(fileName);

            SocketError errorCode = SocketError.Success;
            using (fileStream)
            {
                // Send the preBuffer, if any
                // This will throw on error
                if (preBuffer != null && preBuffer.Length > 0)
                {
                    Send(preBuffer);
                }

                // Send the file, if any
                if (fileStream != null)
                {
                    // This can throw ObjectDisposedException.
                    errorCode = SocketPal.SendFile(_handle, fileStream);
                }
            }

            if (errorCode != SocketError.Success)
            {
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
                throw socketException;
            }

            // Send the postBuffer, if any
            // This will throw on error
            if (postBuffer != null && postBuffer.Length > 0)
            {
                Send(postBuffer);
            }
        }
        public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("file not found");
            }

            CheckDisposed();

            if (!Connected)
            {
                throw new NotSupportedException("not connected to remote host");
            }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var ns = GetStream())
                {
                    if (preBuffer != null)
                    {
                        ns.Write(preBuffer, 0, preBuffer.Length);
                    }
                    fs.CopyTo(ns);
                    if (postBuffer != null)
                    {
                        ns.Write(postBuffer, 0, postBuffer.Length);
                    }
                }

            if (flags.HasFlag(TransmitFileOptions.Disconnect))
            {
                Close();
            }
        }
Example #13
0
 private void DoBeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileOverlappedAsyncResult asyncResult)
 {
     if (Socket.s_LoggingEnabled)
     Logging.Enter(Logging.Sockets, (object) this, "BeginSendFile", "");
       if (this.CleanedUp)
     throw new ObjectDisposedException(this.GetType().FullName);
       if (this.CleanedUp)
     throw new ObjectDisposedException(this.GetType().FullName);
       if (!this.Connected)
     throw new NotSupportedException(SR.GetString("net_notconnected"));
       FileStream fileStream = (FileStream) null;
       if (fileName != null && fileName.Length > 0)
     fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
       SafeHandle fileHandle = (SafeHandle) null;
       if (fileStream != null)
       {
     ExceptionHelper.UnmanagedPermission.Assert();
     try
     {
       fileHandle = (SafeHandle) fileStream.SafeFileHandle;
     }
     finally
     {
       CodeAccessPermission.RevertAssert();
     }
       }
       SocketError socketError = SocketError.SocketError;
       try
       {
     asyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, flags, ref this.Caches.SendOverlappedCache);
     socketError = (fileHandle == null ? UnsafeNclNativeMethods.OSSOCK.TransmitFile2(this.m_Handle, IntPtr.Zero, 0, 0, asyncResult.OverlappedHandle, asyncResult.TransmitFileBuffers, flags) : UnsafeNclNativeMethods.OSSOCK.TransmitFile(this.m_Handle, fileHandle, 0, 0, asyncResult.OverlappedHandle, asyncResult.TransmitFileBuffers, flags)) ? SocketError.Success : (SocketError) Marshal.GetLastWin32Error();
       }
       finally
       {
     socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
       }
       if (socketError != SocketError.Success)
       {
     asyncResult.ExtractCache(ref this.Caches.SendOverlappedCache);
     SocketException socketException = new SocketException(socketError);
     this.UpdateStatusAfterSocketError(socketException);
     if (Socket.s_LoggingEnabled)
       Logging.Exception(Logging.Sockets, (object) this, "BeginSendFile", (Exception) socketException);
     throw socketException;
       }
       else
       {
     if (!Socket.s_LoggingEnabled)
       return;
     Logging.Exit(Logging.Sockets, (object) this, "BeginSendFile", (object) socketError);
       }
 }
Example #14
0
 public abstract Task SendFileAsync(Socket s, string fileName, ArraySegment <byte> preBuffer, ArraySegment <byte> postBuffer, TransmitFileOptions flags);
Example #15
0
 public override Task SendFileAsync(Socket s, string fileName, ArraySegment <byte> preBuffer, ArraySegment <byte> postBuffer, TransmitFileOptions flags) =>
 Task.Factory.FromAsync(
     (callback, state) => s.BeginSendFile(fileName, preBuffer.Array, postBuffer.Array, flags, callback, state),
     s.EndSendFile, null);
        /// <summary>
        /// Extends BeginSendFile so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginSendFile(this Socket socket, String fileName, Byte[] preBuffer, Byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback)
        {
            if(socket == null) throw new ArgumentNullException("socket");

            return socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback, null);
        }
Example #17
0
        public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle?fileHandle, ReadOnlySpan <byte> preBuffer, ReadOnlySpan <byte> postBuffer, TransmitFileOptions flags)
        {
            fixed(byte *prePinnedBuffer = preBuffer)
            fixed(byte *postPinnedBuffer = postBuffer)
            {
                bool success = TransmitFileHelper(handle, fileHandle, null, (IntPtr)prePinnedBuffer, preBuffer.Length, (IntPtr)postPinnedBuffer, postBuffer.Length, flags);

                return(success ? SocketError.Success : GetLastSocketError());
            }
        }
Example #18
0
        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            // Open the file, if any
            FileStream fileStream = OpenFile(fileName);

            SocketError errorCode;
            using (fileStream)
            {
                SafeFileHandle fileHandle = fileStream?.SafeFileHandle;

                // This can throw ObjectDisposedException.
                errorCode = SocketPal.SendFile(_handle, fileHandle, preBuffer, postBuffer, flags);
            }

            if (errorCode != SocketError.Success)
            {
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
                throw socketException;
            }

            // If the user passed the Disconnect and/or ReuseSocket flags, then TransmitFile disconnected the socket.
            // Update our state to reflect this.
            if ((flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
            {
                SetToDisconnected();
                _remoteEndPoint = null;
            }
        }
Example #19
0
		public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_connected)
				throw new NotSupportedException ();
			if (!is_blocking)
				throw new InvalidOperationException ();

			if (!SendFile_internal (safe_handle, fileName, preBuffer, postBuffer, flags)) {
				SocketException exc = new SocketException ();
				if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
					throw new FileNotFoundException ();
				throw exc;
			}
		}
        } // SetUnmanagedStructures()

        internal void SetUnmanagedStructures(byte[] preBuffer, byte[] postBuffer, FileStream fileStream, TransmitFileOptions flags, ref OverlappedCache overlappedCache)
        {
            SetupCache(ref overlappedCache);
            SetUnmanagedStructures(preBuffer, postBuffer, fileStream, flags, false);
        }
Example #21
0
 /// <summary>
 /// Sends the file <paramref name="fileName"/> and buffers of data to a connected <see cref="T:System.Net.Sockets.Socket"/> object using the specified <see cref="T:System.Net.Sockets.TransmitFileOptions"/> value.
 /// </summary>
 /// <param name="fileName">A <see cref="T:System.String"/> that contains the path and name of the file to be sent. This parameter can be null. </param><param name="preBuffer">A <see cref="T:System.Byte"/> array that contains data to be sent before the file is sent. This parameter can be null. </param><param name="postBuffer">A <see cref="T:System.Byte"/> array that contains data to be sent after the file is sent. This parameter can be null. </param><param name="flags">One or more of <see cref="T:System.Net.Sockets.TransmitFileOptions"/> values. </param><exception cref="T:System.NotSupportedException">The operating system is not Windows NT or later.- or - The socket is not connected to a remote host. </exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> object has been closed. </exception><exception cref="T:System.InvalidOperationException">The <see cref="T:System.Net.Sockets.Socket"/> object is not in blocking mode and cannot accept this synchronous call. </exception><exception cref="T:System.IO.FileNotFoundException">The file <paramref name="fileName"/> was not found. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. See the Remarks section for more information. </exception>
 public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     if (Socket.s_LoggingEnabled)
     Logging.Enter(Logging.Sockets, (object) this, "SendFile", "");
       if (this.CleanedUp)
     throw new ObjectDisposedException(this.GetType().FullName);
       if (!this.Connected)
     throw new NotSupportedException(SR.GetString("net_notconnected"));
       this.ValidateBlockingMode();
       TransmitFileOverlappedAsyncResult overlappedAsyncResult = new TransmitFileOverlappedAsyncResult(this);
       FileStream fileStream = (FileStream) null;
       if (fileName != null && fileName.Length > 0)
     fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
       SafeHandle fileHandle = (SafeHandle) null;
       if (fileStream != null)
       {
     ExceptionHelper.UnmanagedPermission.Assert();
     try
     {
       fileHandle = (SafeHandle) fileStream.SafeFileHandle;
     }
     finally
     {
       CodeAccessPermission.RevertAssert();
     }
       }
       SocketError socketError = SocketError.Success;
       try
       {
     overlappedAsyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, TransmitFileOptions.UseDefaultWorkerThread, true);
     if ((fileHandle != null ? (!UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking(this.m_Handle.DangerousGetHandle(), fileHandle, 0, 0, (SafeHandle) SafeNativeOverlapped.Zero, overlappedAsyncResult.TransmitFileBuffers, flags) ? 1 : 0) : (!UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking2(this.m_Handle.DangerousGetHandle(), IntPtr.Zero, 0, 0, (SafeHandle) SafeNativeOverlapped.Zero, overlappedAsyncResult.TransmitFileBuffers, flags) ? 1 : 0)) != 0)
       socketError = (SocketError) Marshal.GetLastWin32Error();
       }
       finally
       {
     overlappedAsyncResult.SyncReleaseUnmanagedStructures();
       }
       if (socketError != SocketError.Success)
       {
     SocketException socketException = new SocketException(socketError);
     this.UpdateStatusAfterSocketError(socketException);
     if (Socket.s_LoggingEnabled)
       Logging.Exception(Logging.Sockets, (object) this, "SendFile", (Exception) socketException);
     throw socketException;
       }
       else
       {
     if ((overlappedAsyncResult.Flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != TransmitFileOptions.UseDefaultWorkerThread)
     {
       this.SetToDisconnected();
       this.m_RemoteEndPoint = (EndPoint) null;
     }
     if (!Socket.s_LoggingEnabled)
       return;
     Logging.Exit(Logging.Sockets, (object) this, "SendFile", (object) socketError);
       }
 }
Example #22
0
 public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
 {
     TransmitFileOverlappedAsyncResult asyncResult = new TransmitFileOverlappedAsyncResult(this, state, callback);
       asyncResult.StartPostingAsyncOp(false);
       this.DoBeginSendFile(fileName, preBuffer, postBuffer, flags, asyncResult);
       asyncResult.FinishPostingAsyncOp(ref this.Caches.SendClosureCache);
       return (IAsyncResult) asyncResult;
 }
		private static bool SendFile (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
		{
			throw new System.NotImplementedException();
		}
		public static IObservable<Unit> SendFileObservable(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
		{
			Contract.Requires(socket != null);
			Contract.Ensures(Contract.Result<IObservable<Unit>>() != null);

			return Task.Factory.FromAsync<string, Tuple<byte[], byte[]>, TransmitFileOptions>(
				(fn, buffers, fg, callback, state) => socket.BeginSendFile(fn, buffers.Item1, buffers.Item2, fg, callback, state),
				socket.EndSendFile,
				fileName,
				Tuple.Create(preBuffer, postBuffer),
				flags,
				state: null)
				.ToObservable();
		}
Example #25
0
 public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
 {
     throw null;
 }
Example #26
0
 public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     UnderlyingObject.SendFile(fileName, preBuffer,postBuffer,flags);
 }
Example #27
0
		public IAsyncResult BeginSendFile (string fileName,
						   byte[] preBuffer,
						   byte[] postBuffer,
						   TransmitFileOptions flags,
						   AsyncCallback callback,
						   object state)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (!connected)
				throw new NotSupportedException ();

			if (!File.Exists (fileName))
				throw new FileNotFoundException ();

			SendFileHandler d = new SendFileHandler (SendFile);
			return new SendFileAsyncResult (d, d.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => {
				SendFileAsyncResult sfar = new SendFileAsyncResult (d, ar);
				callback (sfar);
			}, state));
		}
Example #28
0
        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            CheckTransmitFileOptions(flags);

            // Open the file, if any
            // Open it before we send the preBuffer so that any exception happens first
            FileStream fileStream = OpenFile(fileName);

            SocketError errorCode = SocketError.Success;

            using (fileStream)
            {
                // Send the preBuffer, if any
                // This will throw on error
                if (preBuffer != null && preBuffer.Length > 0)
                {
                    Send(preBuffer);
                }

                // Send the file, if any
                if (fileStream != null)
                {
                    // This can throw ObjectDisposedException.
                    errorCode = SocketPal.SendFile(_handle, fileStream);
                }
            }

            if (errorCode != SocketError.Success)
            {
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(this, socketException);
                }
                throw socketException;
            }

            // Send the postBuffer, if any
            // This will throw on error
            if (postBuffer != null && postBuffer.Length > 0)
            {
                Send(postBuffer);
            }
        }
Example #29
0
		static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
 /// <summary>
 /// Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.
 /// </summary>
 /// <param name="fileName">
 /// A string that contains the path and name of the file to send. This parameter can be null.
 /// </param>
 /// <param name="preBuffer">
 /// A Byte array that contains data to be sent before the file is sent. This parameter can be null.
 /// </param>
 /// <param name="postBuffer">
 /// A Byte array that contains data to be sent after the file is sent. This parameter can be null.
 /// </param>
 /// <param name="flags">A bitwise combination of TransmitFileOptions values.</param>
 /// <returns>Task</returns>
 public static Task SendFileAsync(this Socket value, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     return(Task.Factory.FromAsync(value.BeginSendFile(fileName, preBuffer, postBuffer, flags, null, null), value.EndSendFile));
 }
Example #31
0
        public IAsyncResult BeginSendFile(
            string fileName,
            byte[] preBuffer,
            byte[] postBuffer,
            TransmitFileOptions flags,
            AsyncCallback callback,
            object state)
        {

            // Start the context flowing.  No lock necessary.
            TransmitFileOverlappedAsyncResult asyncResult = new TransmitFileOverlappedAsyncResult(this,state,callback);
            asyncResult.StartPostingAsyncOp(false);

            // Start the operation.
            DoBeginSendFile(fileName, preBuffer, postBuffer, flags, asyncResult);

            // Finish the op, collect the context or maybe call the callback.
            asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
            return asyncResult;
        }
Example #32
0
        private bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped, TransmitFileOptions flags)
        {
            EnsureDynamicWinsockMethods();
            TransmitPacketsDelegate transmitPackets = m_DynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);

            return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
        }
Example #33
0
        public static unsafe SocketError SendFileAsync(SafeCloseSocket handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);

            SocketError errorCode = TransmitFileHelper(handle, fileStream?.SafeFileHandle, asyncResult.OverlappedHandle, preBuffer, postBuffer, flags);

            // This will release resources if necessary
            errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);

            return(errorCode);
        }
Example #34
0
        private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
        {
            FileStream fileStream = OpenFile(fileName);

            TransmitFileAsyncResult asyncResult = new TransmitFileAsyncResult(this, state, callback);
            asyncResult.StartPostingAsyncOp(false);

            SocketError errorCode = SocketPal.SendFileAsync(_handle, fileStream, preBuffer, postBuffer, flags, asyncResult);

            // Check for synchronous exception
            if (errorCode != SocketError.Success)
            {
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
                throw socketException;
            }

            asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);

            return asyncResult;
        }
Example #35
0
        private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
        {
            CheckTransmitFileOptions(flags);

            // Open the file, if any
            // Open it before we send the preBuffer so that any exception happens first
            FileStream fileStream = OpenFile(fileName);

            return(TaskToApm.Begin(SendFileInternalAsync(fileStream, preBuffer, postBuffer), callback, state));
        }
Example #36
0
        /// <summary>
        /// Extends BeginSendFile so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginSendFile(this Socket socket, String fileName, Byte[] preBuffer, Byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            return(socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback, null));
        }
Example #37
0
        public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags) {
            if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "SendFile", "");

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (!Connected) {
                throw new NotSupportedException(SR.GetString(SR.net_notconnected));
            }

            ValidateBlockingMode();
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::SendFile() SRC:" + ValidationHelper.ToString(LocalEndPoint) + " DST:" + ValidationHelper.ToString(RemoteEndPoint) + " fileName:" + fileName);

            TransmitFileOverlappedAsyncResult asyncResult = new TransmitFileOverlappedAsyncResult(this);

            FileStream fileStream = null;
            if (fileName != null && fileName.Length>0) {
                fileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);
            }

            SafeHandle fileHandle = null;

            if (fileStream != null) {
                ExceptionHelper.UnmanagedPermission.Assert();
                try {
                    fileHandle = fileStream.SafeFileHandle;
                }
                finally {
                    SecurityPermission.RevertAssert();
                }
            }

            SocketError errorCode = SocketError.Success;
            try {
                asyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, 0, true);

                // This can throw ObjectDisposedException.
                if (fileHandle != null ?
                    !UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking(m_Handle.DangerousGetHandle(), fileHandle, 0, 0, SafeNativeOverlapped.Zero, asyncResult.TransmitFileBuffers, flags) :
                    !UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking2(m_Handle.DangerousGetHandle(), IntPtr.Zero, 0, 0, SafeNativeOverlapped.Zero, asyncResult.TransmitFileBuffers, flags))
                {
                    errorCode = (SocketError) Marshal.GetLastWin32Error();
                }
            }
            finally {
                asyncResult.SyncReleaseUnmanagedStructures();
            }

#if TRAVE
            try
            {
                GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::SendFile() SRC:" + ValidationHelper.ToString(LocalEndPoint) + " DST:" + ValidationHelper.ToString(RemoteEndPoint) + " UnsafeNclNativeMethods.OSSOCK.TransmitFile returns errorCode:" + errorCode);
            }
            catch (ObjectDisposedException) { }
#endif

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketError.Success) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException(errorCode);
                UpdateStatusAfterSocketError(socketException);
                if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "SendFile", socketException);
                throw socketException;
            }

            if ((asyncResult.Flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket) )!=0) {
                SetToDisconnected();
                m_RemoteEndPoint = null;
            }

            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "SendFile", errorCode);
            return;
        }
Example #38
0
 public static unsafe SocketError SendFile(SafeCloseSocket handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     fixed (byte* prePinnedBuffer = preBuffer)
     fixed (byte* postPinnedBuffer = postBuffer)
     {
         return TransmitFileHelper(handle, fileHandle, SafeNativeOverlapped.Zero, preBuffer, postBuffer, flags);
     }
 }
Example #39
0
        private void DoBeginSendFile(
            string fileName,
            byte[] preBuffer,
            byte[] postBuffer,
            TransmitFileOptions flags,
            TransmitFileOverlappedAsyncResult asyncResult)
        {
            if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "BeginSendFile", "");

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

#if FEATURE_PAL
            throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
#endif // FEATURE_PAL


            if (!Connected) {
                throw new NotSupportedException(SR.GetString(SR.net_notconnected));
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginSendFile() SRC:" + ValidationHelper.ToString(LocalEndPoint) + " DST:" + ValidationHelper.ToString(RemoteEndPoint) + " fileName:" + fileName);

            FileStream fileStream = null;
            if (fileName != null && fileName.Length>0) {
                fileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);
            }

            SafeHandle fileHandle = null;

            if (fileStream != null) {
                ExceptionHelper.UnmanagedPermission.Assert();
                try {
                    fileHandle = fileStream.SafeFileHandle;
                }
                finally {
                    SecurityPermission.RevertAssert();
                }
            }

            // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
            // avoid a Socket leak in case of error.
            SocketError errorCode = SocketError.SocketError;
            try
            {
                asyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, flags, ref Caches.SendOverlappedCache);
                bool result = false;

                // This can throw ObjectDisposedException.
                if (fileHandle != null){
                    result = UnsafeNclNativeMethods.OSSOCK.TransmitFile(m_Handle,fileHandle,0,0,asyncResult.OverlappedHandle,asyncResult.TransmitFileBuffers,flags);
                }
                else{
                    result = UnsafeNclNativeMethods.OSSOCK.TransmitFile2(m_Handle,IntPtr.Zero,0,0,asyncResult.OverlappedHandle,asyncResult.TransmitFileBuffers,flags);
                }
                if(!result)
                {
                    errorCode =  (SocketError)Marshal.GetLastWin32Error();
                }
                else
                {
                    errorCode = SocketError.Success;
                }
            }
            finally
            {
                errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
            }

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketError.Success) {
                //
                // update our internal state after this socket error and throw
                //
                asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
                SocketException socketException = new SocketException(errorCode);
                UpdateStatusAfterSocketError(socketException);

                if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "BeginSendFile", socketException);
                throw socketException;
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginSendFile() UnsafeNclNativeMethods.OSSOCK.send returns:" + errorCode.ToString());

            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "BeginSendFile", errorCode);
        }
Example #40
0
        // This assumes preBuffer/postBuffer are pinned already 

        private static unsafe SocketError TransmitFileHelper(
            SafeHandle socket, 
            SafeHandle fileHandle,
            SafeHandle overlapped,
            byte[] preBuffer,
            byte[] postBuffer,
            TransmitFileOptions flags)
        {
            bool needTransmitFileBuffers = false;
            Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);

            if (preBuffer != null && preBuffer.Length > 0)
            {
                needTransmitFileBuffers = true;
                transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
                transmitFileBuffers.HeadLength = preBuffer.Length;
            }

            if (postBuffer != null && postBuffer.Length > 0)
            {
                needTransmitFileBuffers = true;
                transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
                transmitFileBuffers.TailLength = postBuffer.Length;
            }

            bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
                needTransmitFileBuffers ? &transmitFileBuffers : null, flags);

            return success ? SocketError.Success : GetLastSocketError();
        }
Example #41
0
 public override Task SendFileAsync(Socket s, string fileName, ArraySegment <byte> preBuffer, ArraySegment <byte> postBuffer, TransmitFileOptions flags) =>
 Task.Run(() => s.SendFile(fileName, preBuffer.Array, postBuffer.Array, flags));
Example #42
0
        public static unsafe SocketError SendFileAsync(SafeCloseSocket handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);

            SocketError errorCode = TransmitFileHelper(handle, fileStream?.SafeFileHandle, asyncResult.OverlappedHandle, preBuffer, postBuffer, flags);

            // This will release resources if necessary
            errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);

            return errorCode;
        }
Example #43
0
 public override Task SendFileAsync(Socket s, string fileName, ArraySegment <byte> preBuffer, ArraySegment <byte> postBuffer, TransmitFileOptions flags) =>
 s.SendFileAsync(fileName, preBuffer, postBuffer, flags, _cts.Token).AsTask();
Example #44
0
        private void SendFileInternal(string?fileName, byte[]?preBuffer, byte[]?postBuffer, TransmitFileOptions flags)
        {
            CheckTransmitFileOptions(flags);

            // Open the file, if any
            // Open it before we send the preBuffer so that any exception happens first
            FileStream?fileStream = OpenFile(fileName);

            SocketError errorCode = SocketError.Success;

            using (fileStream)
            {
                // Send the preBuffer, if any
                // This will throw on error
                if (preBuffer != null && preBuffer.Length > 0)
                {
                    Send(preBuffer);
                }

                // Send the file, if any
                if (fileStream != null)
                {
                    // This can throw ObjectDisposedException.
                    errorCode = SocketPal.SendFile(_handle, fileStream);
                }
            }

            if (errorCode != SocketError.Success)
            {
                UpdateSendSocketErrorForDisposed(ref errorCode);

                UpdateStatusAfterSocketErrorAndThrowException(errorCode);
            }

            // Send the postBuffer, if any
            // This will throw on error
            if (postBuffer != null && postBuffer.Length > 0)
            {
                Send(postBuffer);
            }
        }
Example #45
0
        public static unsafe SocketError SendFile(SafeCloseSocket handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            fixed(byte *prePinnedBuffer = preBuffer)
            fixed(byte *postPinnedBuffer = postBuffer)
            {
                bool success = TransmitFileHelper(handle, fileHandle, SafeNativeOverlapped.Zero, preBuffer, postBuffer, flags);

                return(success ? SocketError.Success : SocketPal.GetLastSocketError());
            }
        }
 public System.IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, System.AsyncCallback callback, object state)
 {
 }
Example #47
0
        public static unsafe SocketError SendFileAsync(SafeCloseSocket handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
            try
            {
                bool success = TransmitFileHelper(
                    handle,
                    fileStream?.SafeFileHandle,
                    asyncResult.OverlappedHandle,
                    preBuffer,
                    postBuffer,
                    flags);

                return(asyncResult.ProcessOverlappedResult(success, 0));
            }
            catch
            {
                asyncResult.ReleaseUnmanagedStructures();
                throw;
            }
        }
Example #48
0
        internal bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped, TransmitFileOptions flags)
        {
            EnsureDynamicWinsockMethods();
            TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate <TransmitPacketsDelegate>(socketHandle);

            return(transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags));
        }
        //
        // SetUnmanagedStructures -
        // Fills in Overlapped Structures used in an Async Overlapped Winsock call
        //   these calls are outside the runtime and are unmanaged code, so we need
        //   to prepare specific structures and ints that lie in unmanaged memory
        //   since the Overlapped calls can be Async
        //
        internal void SetUnmanagedStructures(byte[] preBuffer, byte[] postBuffer, FileStream fileStream, TransmitFileOptions flags, bool sync) {
            //
            // fill in flags if we use it.
            //
            m_fileStream = fileStream;
            m_flags = flags;

            //
            // Fill in Buffer Array structure that will be used for our send/recv Buffer
            //
            m_buffers = null;
            int buffsNumber = 0;

            if (preBuffer != null && preBuffer.Length>0)
                ++buffsNumber;

            if (postBuffer != null && postBuffer.Length>0)
                ++buffsNumber;

            object[] objectsToPin = null;
            if (buffsNumber != 0)
            {
                ++buffsNumber;
                objectsToPin = new object[buffsNumber];

                m_buffers = new TransmitFileBuffers();
                
                objectsToPin[--buffsNumber] = m_buffers;

                if (preBuffer != null && preBuffer.Length>0) {
                    m_buffers.preBufferLength = preBuffer.Length;
                    objectsToPin[--buffsNumber] = preBuffer;
                }

                if (postBuffer != null && postBuffer.Length>0) {
                    m_buffers.postBufferLength = postBuffer.Length;
                    objectsToPin[--buffsNumber] = postBuffer;
                }

                if (sync)
                {
                    base.PinUnmanagedObjects(objectsToPin);
                }
                else
                {
                    base.SetUnmanagedStructures(objectsToPin);
                }

                if (preBuffer != null && preBuffer.Length > 0)
                {
                    m_buffers.preBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
                }

                if (postBuffer != null && postBuffer.Length > 0)
                {
                    m_buffers.postBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
                }
            }
            else if (!sync)
            {
                base.SetUnmanagedStructures(null);
            }

        } // SetUnmanagedStructures()
Example #50
0
        private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
        {
            Assert.True(Capability.IPv6Support());

            EventWaitHandle completed = new ManualResetEvent(false);

            int port;
            using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
            {
                using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    sock.Connect(new IPEndPoint(_serverAddress, port));
                    using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
                    {
                        args.Completed += OnCompleted;
                        args.UserToken = completed;
                        args.SendPacketsElements = new[] { element };
                        args.SendPacketsFlags = flags;

                        if (sock.SendPacketsAsync(args))
                        {
                            Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
                        }
                        Assert.Equal(SocketError.Success, args.SocketError);
                        Assert.Equal(bytesExpected, args.BytesTransferred);
                    }

                    switch (flags)
                    {
                        case TransmitFileOptions.Disconnect:
                            // Sending data again throws with socket shut down error.
                            Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); });
                            break;
                        case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
                            // Able to send data again with reuse socket flag set.
                            Assert.Equal(1, sock.Send(new byte[1] { 01 }));
                            break;
                    }
                }
            }
        }
Example #51
0
 public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
 }
Example #52
0
 private extern static bool SendFile(IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
Example #53
0
 /// <inheritdoc />
 public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     _socket.SendFile(fileName, preBuffer, postBuffer, flags);
 }
Example #54
0
        /// <summary>
        /// Sends the file <paramref name="fileName"/> to a connected <see cref="Socket"/> object.
        /// </summary>
        /// <param name="socket">The target socket.</param>
        /// <param name="fileName">A string that contains the path and name of the file to send. This parameter can be <see langword="null"/>.</param>
        /// <param name="preBuffer">A byte array that contains data to be sent before the file is sent. This parameter can be <see langword="null"/>.</param>
        /// <param name="postBuffer">A byte array that contains data to be sent after the file is sent. This parameter can be <see langword="null"/>.</param>
        /// <param name="flags">A bitwise combination of <see cref="TransmitFileOptions"/> values.</param>
        /// <exception cref="FileNotFoundException">The file <paramref name="fileName"/> was not found.</exception>
        /// <exception cref="SocketException">An error occurred when attempting to access the <paramref name="socket"/>.</exception>
        /// <exception cref="NotSupportedException">The operating system is not Windows NT or later or rhe <paramref name="socket"/> is not connected to a remote host.</exception>
        /// <exception cref="ObjectDisposedException">Thrown if the <paramref name="socket"/> has been closed.</exception>
        /// <returns>Returns <see cref="IAsyncOperation"/> representing the asynchronous operation.</returns>
        public static IAsyncOperation SendFileAsync(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            var op = new ApmResult <Socket, VoidResult>(socket);

            socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, OnSendFileCompleted, op);
            return(op);
        }
Example #55
0
		public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (!connected)
				throw new NotSupportedException ();

			if (!blocking)
				throw new InvalidOperationException ();

			if (!SendFile (socket, fileName, preBuffer, postBuffer, flags)) {
				SocketException exc = new SocketException ();
				if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
					throw new FileNotFoundException ();
				throw exc;
			}
		}
        public static IObservable <Unit> SendFileObservable(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            Contract.Requires(socket != null);
            Contract.Ensures(Contract.Result <IObservable <Unit> >() != null);

            return(Task.Factory.FromAsync <string, Tuple <byte[], byte[]>, TransmitFileOptions>(
                       (fn, buffers, fg, callback, state) => socket.BeginSendFile(fn, buffers.Item1, buffers.Item2, fg, callback, state),
                       socket.EndSendFile,
                       fileName,
                       Tuple.Create(preBuffer, postBuffer),
                       flags,
                       state: null)
                   .ToObservable());
        }
Example #57
0
		public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_connected)
				throw new NotSupportedException ();
			if (!File.Exists (fileName))
				throw new FileNotFoundException ();

			SendFileHandler handler = new SendFileHandler (SendFile);

			return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
		}
Example #58
0
        private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
        {
            Assert.True(Capability.IPv6Support());

            EventWaitHandle completed = new ManualResetEvent(false);

            int port;

            using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
            {
                using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    sock.Connect(new IPEndPoint(_serverAddress, port));
                    using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
                    {
                        args.Completed          += OnCompleted;
                        args.UserToken           = completed;
                        args.SendPacketsElements = new[] { element };
                        args.SendPacketsFlags    = flags;

                        if (sock.SendPacketsAsync(args))
                        {
                            Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
                        }
                        Assert.Equal(SocketError.Success, args.SocketError);
                        Assert.Equal(bytesExpected, args.BytesTransferred);
                    }

                    switch (flags)
                    {
                    case TransmitFileOptions.Disconnect:
                        // Sending data again throws with socket shut down error.
                        Assert.Throws <SocketException>(() => { sock.Send(new byte[1] {
                                01
                            }); });
                        break;

                    case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
                        // Able to send data again with reuse socket flag set.
                        Assert.Equal(1, sock.Send(new byte[1] {
                            01
                        }));
                        break;
                    }
                }
            }
        }
Example #59
0
		extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
Example #60
0
 public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
 {
     UnderlyingObject.SendFile(fileName, preBuffer, postBuffer, flags);
 }