Exemplo n.º 1
0
        public unsafe static void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
        {
            var state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
            var operation = (ReadOperation)state;

            operation.ThreadPoolBoundHandle.FreeNativeOverlapped(operation.Overlapped);

            operation.Offset += (int)numBytes;

            var buffer = operation.BoxedBuffer.Value;

            buffer.Advance((int)numBytes);
            var task = buffer.FlushAsync();

            if (numBytes == 0 || operation.Writer.Writing.IsCompleted)
            {
                operation.Writer.Complete();

                // The operation can be disposed when there's nothing more to produce
                operation.Dispose();
            }
            else if (task.IsCompleted)
            {
                operation.Read();
            }
            else
            {
                // Keep reading once we get the completion
                task.ContinueWith((t, s) => ((ReadOperation)s).Read(), operation);
            }
        }
Exemplo n.º 2
0
        public static unsafe void Update(int index, int[] analogData, byte[] digitalData)
        {
            //Create the structure
              var state = new JoystickState();
              state.Signature = (uint)0x53544143;
              state.NumAnalog = (char)63;
              state.NumDigital = (char)128;
              state.Analog = new int[state.NumAnalog];
              state.Digital = new char[state.NumDigital];

              //Fill it with our data
              if (analogData != null)
            Array.Copy(analogData, 0, state.Analog, 0, Math.Min(analogData.Length, state.Analog.Length));
              if (digitalData != null)
            Array.Copy(digitalData, 0, state.Digital, 0, Math.Min(digitalData.Length, state.Digital.Length));

              //Send the data
              uint bytesReturned = 0;
              NativeOverlapped overlapped = new NativeOverlapped();
              var h = _GetHandle(index);
              bool ret = DeviceIoControl(h, 0x00220000,
             state, (uint)Marshal.SizeOf(state),
             IntPtr.Zero, 0, ref bytesReturned, ref overlapped);

              if (!ret)
              {
            //TODO: Do something with this?
            int lastError = Marshal.GetLastWin32Error();

            //Invalidate the handle
            _CloseHandle(h);
            _handles[index] = null;
              }
        }
Exemplo n.º 3
0
		public static extern bool ReadFile(
			SafeFileHandle hFile,
			byte* pBuffer,
			int numBytesToRead,
			out int pNumberOfBytesRead,
			NativeOverlapped* lpOverlapped
			);
Exemplo n.º 4
0
        public static bool Eject(string driveLetter)
        {
            bool result = false;

            string fileName = string.Format(@"\\.\{0}:", driveLetter);

            IntPtr deviceHandle = _CreateFile(fileName);

            if (deviceHandle != INVALID_HANDLE_VALUE)
            {
                IntPtr null_ptr = IntPtr.Zero;
                int bytesReturned;
                NativeOverlapped overlapped = new NativeOverlapped();

                result = DeviceIoControl(
                    deviceHandle,
                    IOCTL_STORAGE_EJECT_MEDIA,
                    ref null_ptr,
                    0,
                    out null_ptr,
                    0,
                    out bytesReturned,
                    ref overlapped);
                CloseHandle(deviceHandle);
            }
            return result;
        }
Exemplo n.º 5
0
 public static extern bool ReadFile(
   SafeFileHandle hFile,
   IntPtr pBuffer,
   int numberOfBytesToRead,
   int[] pNumberOfBytesRead,
   NativeOverlapped[] lpOverlapped // should be fixed, if not null
   );
Exemplo n.º 6
0
 internal static bool HasOverlappedIoCompleted(NativeOverlapped lpOverlapped)
 {
     // this method is defined as a MACRO in winbase.h:
     // #define HasOverlappedIoCompleted(lpOverlapped) (((DWORD)(lpOverlapped)->Internal) != STATUS_PENDING)
     // OVERLAPPED::Internal === NativeOverlapped.InternalLow
     return lpOverlapped.InternalLow.ToInt32() != STATUS_PENDING;
 }
Exemplo n.º 7
0
        public static void WriteMail(string text)
        {
            CreateClientConnection();
            if (!handleC.Equals(new IntPtr(-1)))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(text);

                uint dwwr = new uint();
                System.Threading.NativeOverlapped temp = new System.Threading.NativeOverlapped();
                Console.WriteLine("here");

                if (WriteFile(handleC, buffer, (uint)buffer.Length, out dwwr, ref temp))
                {
                    Console.WriteLine("Write mail: " + text);
                }

                Console.WriteLine(handleC);
                Console.WriteLine(buffer);
                Console.WriteLine((uint)buffer.Length);
                Console.WriteLine(dwwr);
                Console.WriteLine(temp);
            }
            else
            {
                Console.WriteLine("OH NOOO");
            }
        }
Exemplo n.º 8
0
 internal static extern int WriteFileEx(
     IntPtr hFile,
     [MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
     int nNumberOfBytesToWrite,
     [In] ref System.Threading.NativeOverlapped lpOverlapped,
     [MarshalAs(UnmanagedType.FunctionPtr)] IOCompletionCallback callback
     );
Exemplo n.º 9
0
		unsafe public static void Free (NativeOverlapped *nativeOverlappedPtr)
		{
			if ((IntPtr) nativeOverlappedPtr == IntPtr.Zero)
				throw new ArgumentNullException ("nativeOverlappedPtr");

			Marshal.FreeHGlobal ((IntPtr) nativeOverlappedPtr);
		}
 private static unsafe void AsyncPSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
 {
     PipeStreamAsyncResult asyncResult = (PipeStreamAsyncResult) Overlapped.Unpack(pOverlapped).AsyncResult;
     asyncResult._numBytes = (int) numBytes;
     if (!asyncResult._isWrite && (((errorCode == 0x6d) || (errorCode == 0xe9)) || (errorCode == 0xe8)))
     {
         errorCode = 0;
         numBytes = 0;
     }
     if (errorCode == 0xea)
     {
         errorCode = 0;
         asyncResult._isMessageComplete = false;
     }
     else
     {
         asyncResult._isMessageComplete = true;
     }
     asyncResult._errorCode = (int) errorCode;
     asyncResult._completedSynchronously = false;
     asyncResult._isComplete = true;
     ManualResetEvent event2 = asyncResult._waitHandle;
     if ((event2 != null) && !event2.Set())
     {
         System.IO.__Error.WinIOError();
     }
     AsyncCallback callback = asyncResult._userCallback;
     if (callback != null)
     {
         callback(asyncResult);
     }
 }
Exemplo n.º 11
0
 public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
 {
     if (nativeOverlappedPtr == null)
     {
         throw new ArgumentNullException("nativeOverlappedPtr");
     }
     return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
 }
Exemplo n.º 12
0
    public HidDevice(string devicePath)
    {
      _devicePath = devicePath;

      _overlapped = new NativeOverlapped();
      _overlapped.EventHandle = NativeInterface.CreateEvent(IntPtr.Zero, false, false, null);
      _pinnedOverlapped = GCHandle.Alloc(_overlapped, GCHandleType.Pinned);
    }
Exemplo n.º 13
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="drive"></param>
 public static void Eject(String drive)
 {
     using (SafeFileHandle hDevice = Win32.CreateFile(String.Format(@"\\.\{0}:", drive), FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, Win32.EFileAttributes.Normal, IntPtr.Zero))
     {
         UInt32 retVal = 0;
         NativeOverlapped retOverlapped = new NativeOverlapped();
         Win32.DeviceIoControl(hDevice, Win32.EIOControlCode.StorageEjectMedia, null, 0, null, 0, ref retVal, ref retOverlapped);
     }
 }
Exemplo n.º 14
0
        public unsafe SafeNativeOverlapped(SafeCloseSocket socketHandle, NativeOverlapped* handle)
            : this((IntPtr)handle)
        {
            _safeCloseSocket = socketHandle;

            GlobalLog.Print("SafeNativeOverlapped#" + Logging.HashString(this) + "::ctor(socket#" + Logging.HashString(socketHandle) + ")");
#if DEBUG
            _safeCloseSocket.AddRef();
#endif
        }
Exemplo n.º 15
0
 internal static extern bool DeviceIoControl(Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
                                             uint IoControlCode,
                                             [MarshalAs(UnmanagedType.AsAny)]
                                             [In] object InBuffer,
                                             uint nInBufferSize,
                                             [MarshalAs(UnmanagedType.AsAny)]
                                             [Out] object OutBuffer,
                                             uint nOutBufferSize,
                                             ref uint pBytesReturned,
                                             [In] ref System.Threading.NativeOverlapped Overlapped);
Exemplo n.º 16
0
            private void Callback(uint errorCode, uint numBytes, NativeOverlapped* pNOlap)
            {
                // Execute the task
                _scheduler.TryExecuteTask(Task);

                // Put this item back into the pool for someone else to use
                var pool = _scheduler._availableWorkItems;
                if(pool != null) pool.Add(this);
                else Overlapped.Free(pNOlap);
            }
Exemplo n.º 17
0
        public unsafe SafeNativeOverlapped(SafeCloseSocket socketHandle, NativeOverlapped* handle)
            : this((IntPtr)handle)
        {
            SocketHandle = socketHandle;

            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"socketHandle:{socketHandle}");

#if DEBUG
            SocketHandle.AddRef();
#endif
        }
Exemplo n.º 18
0
      public virtual int SharedLockFile( sqlite3_file pFile, long offset, long length )
      {
        Debug.Assert( length == SHARED_SIZE );
        Debug.Assert( offset == SHARED_FIRST );
        System.Threading.NativeOverlapped ovlp = new System.Threading.NativeOverlapped();
        ovlp.OffsetLow = (int)offset;
        ovlp.OffsetHigh = 0;
        ovlp.EventHandle = IntPtr.Zero;

        return LockFileEx( pFile.fs.Handle, LOCKFILE_FAIL_IMMEDIATELY, 0, (uint)length, 0, ref ovlp ) ? 1 : 0;
      }
Exemplo n.º 19
0
		unsafe public static Overlapped Unpack (NativeOverlapped *nativeOverlappedPtr)
		{
			if ((IntPtr) nativeOverlappedPtr == IntPtr.Zero)
				throw new ArgumentNullException ("nativeOverlappedPtr");

			Overlapped result = new Overlapped ();
			result.offsetL = nativeOverlappedPtr->OffsetLow;
			result.offsetH = nativeOverlappedPtr->OffsetHigh;
			result.evt = (int)nativeOverlappedPtr->EventHandle;
			return result;
		}
 private static unsafe void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
 {
     PipeAsyncResult asyncResult = (PipeAsyncResult) Overlapped.Unpack(pOverlapped).AsyncResult;
     asyncResult._numBytes = (int) numBytes;
     if (errorCode == 0x6dL)
     {
         errorCode = 0;
     }
     asyncResult._errorCode = (int) errorCode;
     asyncResult._userCallback(asyncResult);
 }
        private static extern bool DeviceIoControl(
            IntPtr hDevice,
            UInt32 IoControlCode,
            [MarshalAs(UnmanagedType.AsAny)]
            [In] object InBuffer,
            uint nInBufferSize,
            [In] IntPtr OutBuffer,
            uint nOutBufferSize,
            ref uint pBytesReturned,
//            IntPtr Overlapped
            ref System.Threading.NativeOverlapped Overlapped
            );
Exemplo n.º 22
0
 public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr)
 {
     if (nativeOverlappedPtr == null)
     {
         throw new ArgumentNullException("nativeOverlappedPtr");
     }
     Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
     OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
     OverlappedData overlappedData = overlapped.m_overlappedData;
     overlapped.m_overlappedData = null;
     OverlappedDataCache.CacheOverlappedData(overlappedData);
 }
Exemplo n.º 23
0
 public unsafe static int MQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
                                              SafeNativeMethods.ReceiveCallback receiveCallback, ITransaction transaction)
 {
     try
     {
         return IntMQReceiveMessageByLookupId(handle, lookupId, action, properties, overlapped, receiveCallback, transaction);
     }
     catch (EntryPointNotFoundException)
     {
         throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported));
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Create a sparse file.
 /// </summary>
 /// <param name="hFileHandle">Handle of the file to convert to a sparse file.</param>
 /// <returns></returns>
 public static void Convert(SafeFileHandle hFileHandle)
 {
     // Use the DeviceIoControl function with the FSCTL_SET_SPARSE control
     // code to mark the file as sparse. If you don't mark the file as
     // sparse, the FSCTL_SET_ZERO_DATA control code will actually write
     // zero bytes to the file instead of marking the region as sparse
     // zero area.
     int bytesReturned = 0;
     var lpOverlapped = new NativeOverlapped();
     NativeMethods.DeviceIoControl(hFileHandle,
         EIoControlCodes.FsctlSetSparse, IntPtr.Zero, 0, IntPtr.Zero, 0,
         ref bytesReturned, ref lpOverlapped);
 }
Exemplo n.º 25
0
        static void WriteMail(string text)
        {
            if (!handleS.Equals(new IntPtr(-1)))
            {
                byte[] buffer = Encoding.ASCII.GetBytes(text);

                uint dwwr;
                System.Threading.NativeOverlapped temp = new System.Threading.NativeOverlapped();
                if (WriteFile(handleS, buffer, (uint)buffer.Length, out dwwr, ref temp))
                {
                    Console.WriteLine("Write mail: " + text);
                }
            }
        }
Exemplo n.º 26
0
		private static unsafe void pSSAsyncWaitForConnectionCallbackWrapper(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
		{
			try
			{
				pSSAsyncWaitForConnectionCallback(errorCode, numBytes, pOverlapped);
			}
			catch (ObjectDisposedException)
			{
			}
			catch (Exception err)
			{
				XMS.Core.Container.LogService.Warn(err);
			}
		}
Exemplo n.º 27
0
 public static bool MarkAsSparseFile(FileStream fileStream)
 {
     int bytesReturned = 0;
     NativeOverlapped lpOverlapped = new NativeOverlapped();
     return DeviceIoControl(
         fileStream.SafeFileHandle,
         590020, //FSCTL_SET_SPARSE,
         IntPtr.Zero,
         0,
         IntPtr.Zero,
         0,
         ref bytesReturned,
         ref lpOverlapped);
 }
Exemplo n.º 28
0
        public unsafe SafeNativeOverlapped(SafeCloseSocket socketHandle, NativeOverlapped* handle)
            : this((IntPtr)handle)
        {
            SocketHandle = socketHandle;

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("SafeNativeOverlapped#" + LoggingHash.HashString(this) + "::ctor(socket#" + LoggingHash.HashString(socketHandle) + ")");
            }

#if DEBUG
            SocketHandle.AddRef();
#endif
        }
        public static FileAllocatedRangeBuffer[] GetSparseRanges(string fileName)
        {
            var allocRanges = new FileAllocatedRangeBuffer[1024];

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                FileAllocatedRangeBuffer queryRange;

                queryRange.FileOffset = 0;
                queryRange.Length = fs.Length;

                var hQueryRange = GCHandle.Alloc(queryRange, GCHandleType.Pinned);
                var hAllocRanges = GCHandle.Alloc(allocRanges, GCHandleType.Pinned);

                var nbytes = 0;
                bool bFinished;
                do
                {
                    var lpOverlapped = new NativeOverlapped();
                    bFinished =
                        SparseFileWrapper.DeviceIoControl(
                        fs.SafeFileHandle,
                        EIoControlCode.FsctlQueryAllocatedRanges,
                        hQueryRange.AddrOfPinnedObject(),
                        Marshal.SizeOf(queryRange),
                        hAllocRanges.AddrOfPinnedObject(),
                        Marshal.SizeOf(typeof(FileAllocatedRangeBuffer)) * 1024,
                        ref nbytes, ref lpOverlapped);

                    if (!bFinished) CheckLastWin32Error();

                    var allocRangeCount = nbytes / Marshal.SizeOf(typeof(FileAllocatedRangeBuffer));

                    if (bFinished || allocRangeCount <= 0) continue;

                    queryRange.FileOffset =
                        allocRanges[allocRangeCount - 1].FileOffset +
                        allocRanges[allocRangeCount - 1].Length;

                    queryRange.Length = fs.Length - queryRange.FileOffset;

                } while (!bFinished);

                hAllocRanges.Free();
                hQueryRange.Free();
            }

            return allocRanges;
        }
        private static unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
        {
            Overlapped overlapped = Overlapped.Unpack(nativeOverlapped);
            BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult) overlapped.AsyncResult;
            overlapped.AsyncResult = null;
            object result = null;
            SocketError notSocket = (SocketError) errorCode;
            switch (notSocket)
            {
                case SocketError.Success:
                case SocketError.OperationAborted:
                    break;

                default:
                {
                    Socket asyncObject = asyncResult.AsyncObject as Socket;
                    if (asyncObject == null)
                    {
                        notSocket = SocketError.NotSocket;
                    }
                    else if (asyncObject.CleanedUp)
                    {
                        notSocket = SocketError.OperationAborted;
                    }
                    else
                    {
                        try
                        {
                            SocketFlags flags;
                            if (!UnsafeNclNativeMethods.OSSOCK.WSAGetOverlappedResult(asyncObject.SafeHandle, asyncResult.m_Cache.NativeOverlapped, out numBytes, false, out flags))
                            {
                                notSocket = (SocketError) Marshal.GetLastWin32Error();
                            }
                        }
                        catch (ObjectDisposedException)
                        {
                            notSocket = SocketError.OperationAborted;
                        }
                    }
                    break;
                }
            }
            asyncResult.ErrorCode = (int) notSocket;
            result = asyncResult.PostCompletion((int) numBytes);
            asyncResult.ReleaseUnmanagedStructures();
            asyncResult.InvokeCallback(result);
        }
        public void AllowCancellation(SafeHandle handle, NativeOverlapped* overlapped) {
            Contract.Assert(handle != null, "Handle cannot be null");
            Contract.Assert(!handle.IsInvalid, "Handle cannot be invalid");
            Contract.Assert(overlapped != null, "Overlapped cannot be null");
            Contract.Assert(this._handle == null && this._overlapped == null, "Cancellation is already allowed.");

            if (!_cancellationToken.CanBeCanceled) {
                return;
            }

            this._handle = handle;
            this._overlapped = overlapped;
            if (this._cancellationToken.IsCancellationRequested) {
                this.Cancel();
            }
            else {
                this._cancellationRegistration = this._cancellationToken.Register(Cancel);
            }
        }
Exemplo n.º 32
0
 protected void WriteComm(byte[] buf)
 {
     new Thread(() =>
     {
         NativeOverlapped ov = new System.Threading.NativeOverlapped();
         if (!GWin32.WriteFileEx(m_hCommPort, buf, (uint)buf.Length, ref ov, (uint err, uint b, ref NativeOverlapped c) =>
         {
             if (err != 0)
             {
                 Console.WriteLine("Write come done " + err);
             }
             Console.WriteLine("Write come done tran=" + b);
         }))
         {
             Console.WriteLine("failed write comm " + getWinErr());
         }
         // IOCompletion routine is only called once this thread is in an alertable wait state.
         gwait();
     }).Start();
 }
Exemplo n.º 33
0
        public static void WriteMail(string text)
        {
            if (!handleS.Equals(new IntPtr(-1)))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(text);

                uint dwwr;
                System.Threading.NativeOverlapped temp = new System.Threading.NativeOverlapped();

                //if (WriteFile(handleS, buffer, (uint)buffer.Length, out dwwr, ref temp))
                //{
                //    Console.WriteLine("Write mail: " + text);
                //}

                using (var file = new FileStream("\\\\.\\mailslot\\mailServer", FileMode.Append, FileAccess.Write, FileShare.Write))
                {
                    file.Write(Encoding.UTF8.GetBytes(text), 0, text.Length);
                    file.Close();
                }
            }
        }
        public static FileStream CreateStream(string fileName)
        {
            if (!IsVolumeSupportsSparseFiles(fileName))
            {
                throw new UnsupportedVolumeException("Specified volume does not support sparse files.");
            }

            const uint dwShareMode = (uint)EFileShare.None;
            const uint dwDesiredAccess = (uint)EFileAccess.GenericWrite;
            const uint dwFlagsAndAttributes = (uint)EFileAttributes.Normal;
            const uint dwCreationDisposition = (uint)ECreationDisposition.CreateAlways;

            var fileHandle =
                SparseFileWrapper.CreateFileW(
                    fileName,
                    dwDesiredAccess,
                    dwShareMode,
                    IntPtr.Zero,
                    dwCreationDisposition,
                    dwFlagsAndAttributes,
                    IntPtr.Zero);

            var bytesReturned = 0;
            var lpOverlapped = new NativeOverlapped();

            // ReSharper disable once UnusedVariable
            var result =
                SparseFileWrapper.DeviceIoControl(
                    fileHandle,
                    EIoControlCode.FsctlSetSparse,
                    IntPtr.Zero,
                    0,
                    IntPtr.Zero,
                    0,
                    ref bytesReturned,
                    ref lpOverlapped);

            return new FileStream(fileHandle, FileAccess.Write);
        }
Exemplo n.º 35
0
            // call back helper
            static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
                                                                                uint numBytes, // No. of bytes transferred 
                                                                                NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
                                                                                )
            {
                Overlapped overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
                _IOCompletionCallback helper  = overlapped.iocbHelper;

                if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext())
                {
        	      // We got here because of UnsafePack (or) Pack with EC flow supressed
                    IOCompletionCallback callback = overlapped.UserCallback;
                    callback( errorCode,  numBytes,  pOVERLAP);
                }
                else
                {
                    // We got here because of Pack
                    helper._errorCode = errorCode;
                    helper._numBytes = numBytes;
                    helper._pOVERLAP = pOVERLAP;
                    ExecutionContext.Run(helper._executionContext.CreateCopy(), _ccb, helper);
                }                    
            }
 private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
 {
     HttpResponseStreamAsyncResult asyncResult = Overlapped.Unpack(nativeOverlapped).AsyncResult as HttpResponseStreamAsyncResult;
     object result = null;
     try
     {
         if ((errorCode != 0) && (errorCode != 0x26))
         {
             asyncResult.ErrorCode = (int) errorCode;
             result = new HttpListenerException((int) errorCode);
         }
         else if (asyncResult.m_DataChunks == null)
         {
             result = 0;
             if (Logging.On)
             {
                 Logging.Dump(Logging.HttpListener, asyncResult, "Callback", IntPtr.Zero, 0);
             }
         }
         else
         {
             result = (asyncResult.m_DataChunks.Length == 1) ? ((object) asyncResult.m_DataChunks[0].BufferLength) : ((object) 0);
             if (Logging.On)
             {
                 for (int i = 0; i < asyncResult.m_DataChunks.Length; i++)
                 {
                     Logging.Dump(Logging.HttpListener, asyncResult, "Callback", (IntPtr) asyncResult.m_DataChunks[0].pBuffer, (int) asyncResult.m_DataChunks[0].BufferLength);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         result = exception;
     }
     asyncResult.InvokeCallback(result);
 }
 internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP)
 {
     do
     {
         Overlapped overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
         _IOCompletionCallback iocbHelper = overlapped.iocbHelper;
         if (((iocbHelper == null) || (iocbHelper._executionContext == null)) || iocbHelper._executionContext.IsDefaultFTContext(true))
         {
             overlapped.UserCallback(errorCode, numBytes, pOVERLAP);
         }
         else
         {
             iocbHelper._errorCode = errorCode;
             iocbHelper._numBytes = numBytes;
             iocbHelper._pOVERLAP = pOVERLAP;
             using (ExecutionContext context = iocbHelper._executionContext.CreateCopy())
             {
                 ExecutionContext.Run(context, _ccb, iocbHelper, true);
             }
         }
         OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
     }
     while (pOVERLAP != null);
 }
Exemplo n.º 38
0
 internal static extern bool ReadFile(
     IntPtr hFile,
     [MarshalAs(UnmanagedType.LPArray)][Out] byte[] lpBuffer,
     uint nNumberOfBytesToRead,
     out uint lpNumberOfBytesRead,
     [In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 39
0
 public static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer,
                                     uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
                                     [In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 40
0
 internal static extern bool UnlockFileEx(Microsoft.Win32.SafeHandles.SafeFileHandle handle, uint reserved, uint countLow, uint countHigh, ref System.Threading.NativeOverlapped overlapped);
Exemplo n.º 41
0
        public void Start(IComApp app)
        {
            GWin32.PurgeComm(m_hCommPort, 0x0004 | 0x0008);
            app.OnStart(this);
            if (_thread != null)
            {
                return;
            }
            threadStarted = true;
            new Thread(() =>
            {
                bool inWrite        = false;
                uint writeErr       = 0;
                uint writeOk        = 0;
                NativeOverlapped ov = new System.Threading.NativeOverlapped();
                while (threadStarted)
                {
                    if (m_hCommPort == null || m_hCommPort.IsInvalid)
                    {
                        break;
                    }
                    SerWriteInfo wi = null;
                    lock (_writeQueueLock)
                    {
                        if (_writeQueue.Count == 0)
                        {
                            Monitor.Wait(_writeQueueLock);
                        }
                        while (inWrite)
                        {
                            Thread.Sleep(100);
                            Console.WriteLine("in write wait");
                        }
                        wi = _writeQueue[0];
                        _writeQueue.RemoveAt(0);
                    }
                    //if (wi.Done != null) try { wi.Done(0, "no buf"); } catch { };
                    //continue;
                    if (wi == null || wi.buf == null || wi.buf.Length == 0)
                    {
                        if (wi.Done != null)
                        {
                            try { wi.Done(0, "no buf"); } catch { }
                        }
                        ;
                        continue;
                    }
                    inWrite = true;
                    ResetOverlapped(ov);
                    var writeRes = GWin32.WriteFileEx(m_hCommPort, wi.buf, (uint)wi.buf.Length, ref ov, (uint err, uint b, ref NativeOverlapped c) =>
                    {
                        writeErr = err;
                        writeOk  = b;
                        inWrite  = false;
                    });
                    if (!writeRes)
                    {
                        //Console.WriteLine("failed write comm " + getWinErr());
                        if (wi.Done != null)
                        {
                            try { wi.Done(255, "failed write comm " + getWinErr()); } catch { }
                        }
                        ;
                        inWrite = false;
                    }
                    // IOCompletion routine is only called once this thread is in an alertable wait state.
                    gwait(); //only with thread
                    if (writeRes)
                    {
                        if (wi.Done != null)
                        {
                            try { wi.Done(writeErr, writeErr == 0 ? writeOk.ToString() : "WriteError"); } catch { }
                        }
                    }
                }
                Console.WriteLine("Com Write Queue done");
            }).Start();
            _thread = new Thread(() =>
            {
                var tbuf             = new byte[2048];
                var buf1             = new byte[1];
                NativeOverlapped ovo = new System.Threading.NativeOverlapped();
                try
                {
                    while (threadStarted)
                    {
                        SetTimeout(0); //set always wait
                        GWin32.SetLastError(0);
                        ResetOverlapped(ovo);
                        GWin32.ReadFileEx(m_hCommPort, buf1, (uint)buf1.Length, ref ovo, (uint err, uint len, ref NativeOverlapped ovoo) =>
                        {
                            if (err != 0)
                            {
                                Console.WriteLine("read got err " + err);
                            }
                            else
                            {
                                SetTimeout();
                                uint numRead;
                                NativeOverlapped ov = new System.Threading.NativeOverlapped();
                                ov.EventHandle      = GWin32.CreateEvent(IntPtr.Zero, true, false, null);

                                if (!GWin32.ReadFile(m_hCommPort, tbuf, (uint)tbuf.Length, out numRead, ref ov))
                                {
                                    if (GWin32.GetLastError() == 997) //IO Pending
                                    {
                                        GWin32.WaitForSingleObject(ov.EventHandle, GWin32.INFINITE);
                                    }
                                    else
                                    {
                                        Console.WriteLine("read got err " + getWinErr());
                                    }
                                    GWin32.GetOverlappedResult(m_hCommPort, ref ov, out numRead, true);
                                }
                                GWin32.CloseHandle(ov.EventHandle);
                                ov.EventHandle = IntPtr.Zero;
                                //Console.WriteLine("got data " + numRead);
                                var buf = new byte[1 + numRead];
                                buf[0]  = buf1[0];
                                if (numRead > 0)
                                {
                                    Array.Copy(tbuf, 0, buf, 1, numRead);
                                    app.OnData(buf);
                                }
                                //Console.WriteLine(BitConverter.ToString(buf));
                            }
                        });
                        var le = GWin32.GetLastError();
                        if (le != 0)
                        {
                            _thread = null;
                            Console.WriteLine("Read Error " + le);
                            break;
                        }
                        gwait();
                    }
                } catch (InvalidOperationException iv)
                {
                    _thread       = null;
                    threadStarted = false;
                    if (onErr != null)
                    {
                        onErr.OnError("InvalidOperationException " + iv.Message, true);
                        return;
                    }
                    Console.WriteLine("InvalidOperationException " + iv.Message);
                }
                Close();
                onErr.OnError("thread done", true);
                Console.WriteLine("thread done");
            });
            _thread.Start();
        }
Exemplo n.º 42
0
 static internal extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, [System.Runtime.InteropServices.In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 43
0
 internal static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer, int nNumberOfBytesToRead, out uint lpNumberOfBytesRead, ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 44
0
 static extern bool ReadFile(SafeFileHandle hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead,
                             out uint lpNumberOfBytesRead, [In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 45
0
 static extern bool GetOverlappedResultEx(IntPtr hFile, [In] ref System.Threading.NativeOverlapped lpOverlapped,
                                          out uint lpNumberOfBytesTransferred, int dwMilliseconds, bool bAltertable);
Exemplo n.º 46
0
 public void Start(IX4Tran tran)
 {
     GWin32.PurgeComm(m_hCommPort, 0x0004 | 0x0008);
     WriteComm(new byte[] { 0xA5, 0x60 });
     if (_thread != null)
     {
         return;
     }
     threadStarted = true;
     _thread       = new Thread(() =>
     {
         NativeOverlapped ov = new System.Threading.NativeOverlapped();
         try
         {
             while (threadStarted)
             {
                 var buf1 = new byte[1];
                 SetTimeout(0); //set always wait
                 GWin32.SetLastError(0);
                 GWin32.ReadFileEx(m_hCommPort, buf1, (uint)buf1.Length, ref ov, (uint err, uint len, ref NativeOverlapped ov1) =>
                 {
                     if (err != 0)
                     {
                         Console.WriteLine("read got err " + err);
                     }
                     else
                     {
                         SetTimeout();
                         uint numRead;
                         ov.EventHandle = GWin32.CreateEvent(IntPtr.Zero, true, false, null);
                         var tbuf       = new byte[2048];
                         if (!GWin32.ReadFile(m_hCommPort, tbuf, (uint)tbuf.Length, out numRead, ref ov))
                         {
                             if (GWin32.GetLastError() == 997) //IO Pending
                             {
                                 GWin32.WaitForSingleObject(ov.EventHandle, GWin32.INFINITE);
                             }
                             else
                             {
                                 Console.WriteLine("read got err " + getWinErr());
                             }
                             GWin32.GetOverlappedResult(m_hCommPort, ref ov, out numRead, true);
                         }
                         GWin32.CloseHandle(ov.EventHandle);
                         ov.EventHandle = IntPtr.Zero;
                         //Console.WriteLine("got data " + numRead);
                         var buf = new byte[1 + numRead];
                         buf[0]  = buf1[0];
                         if (numRead > 0)
                         {
                             Array.Copy(tbuf, 0, buf, 1, numRead);
                             tran.Translate(buf);
                         }
                         //Console.WriteLine(BitConverter.ToString(buf));
                     }
                 });
                 var le = GWin32.GetLastError();
                 if (le != 0)
                 {
                     _thread = null;
                     Console.WriteLine("Read Error " + le);
                     break;
                 }
                 gwait();
             }
         } catch (InvalidOperationException iv)
         {
             _thread       = null;
             threadStarted = false;
             Console.WriteLine("InvalidOperationException " + iv.Message);
         }
         Console.WriteLine("thread done");
     });
     _thread.Start();
 }
Exemplo n.º 47
0
 static extern bool ConnectNamedPipe(IntPtr hNamedPipe,
                                     [In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 48
0
 public static extern bool WriteFileEx(SafeFileHandle hFile, byte[] lpBuffer,
                                       uint nNumberOfBytesToWrite, [In] ref System.Threading.NativeOverlapped lpOverlapped,
                                       WriteFileCompletionDelegate lpCompletionRoutine);
Exemplo n.º 49
0
 static extern bool GetOverlappedResult(SafeFileHandle hFile, [In] ref System.Threading.NativeOverlapped lpOverlapped,
                                        out uint lpNumberOfBytesTransferred, bool bWait);
Exemplo n.º 50
0
 static extern bool LockFileEx(IntPtr hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, [In] ref System.Threading.NativeOverlapped lpOverlapped);
Exemplo n.º 51
0
 public static extern bool ReadFileEx(IntPtr hFile, [Out] byte[] lpBuffer,
                                      uint nNumberOfBytesToRead, [In] ref System.Threading.NativeOverlapped lpOverlapped,
                                      WriteFileCompletionDelegate lpCompletionRoutine);
Exemplo n.º 52
0
 public static extern bool GetOverlappedResult(IntPtr hFile,
                                               ref System.Threading.NativeOverlapped lpOverlapped,
                                               out uint lpNumberOfBytesTransferred, bool bWait);
Exemplo n.º 53
0
 static internal extern bool ReadFile(IntPtr hFile, IntPtr lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, [In] ref System.Threading.NativeOverlapped lpOverlapped);