private CefResponseFilterStatus filter(cef_response_filter_t *self, void *data_in, UIntPtr data_in_size, UIntPtr *data_in_read, void *data_out, UIntPtr data_out_size, UIntPtr *data_out_written)
        {
            CheckSelf(self);

            // TODO: Use some buffers instead of UnmanagedMemoryStream.

            // TODO: Remove UnmanagedMemoryStream - normal usage is buffer operations.
            UnmanagedMemoryStream m_in_stream  = null;
            UnmanagedMemoryStream m_out_stream = null;

            try
            {
                if (data_in != null)
                {
                    m_in_stream = new UnmanagedMemoryStream((byte *)data_in, (long)data_in_size, (long)data_in_size, FileAccess.Read);
                }

                m_out_stream = new UnmanagedMemoryStream((byte *)data_out, 0, (long)data_out_size, FileAccess.Write);

                {
                    long m_inRead;
                    long m_outWritten;
                    var  result           = Filter(m_in_stream, (long)data_in_size, out m_inRead, m_out_stream, (long)data_out_size, out m_outWritten);
                    *    data_in_read     = (UIntPtr)m_inRead;
                    *    data_out_written = (UIntPtr)m_outWritten;
                    return(result);
                }
            }
            finally
            {
                m_out_stream?.Dispose();
                m_in_stream?.Dispose();
            }
        }
        private static void SelfTest()
        {
            UnmanagedMemoryStream ms1 = new UnmanagedMemoryStream();
            BinaryStreamBase      ms  = ms1.CreateBinaryStream();
            Random rand = new Random();
            int    seed = rand.Next();

            rand = new Random(seed);
            byte[] data = new byte[255];
            rand.NextBytes(data);

            while (ms.Position < 1000000)
            {
                ms.Write(data, 0, rand.Next(256));
            }

            byte[] data2 = new byte[255];
            rand = new Random(seed);
            rand.NextBytes(data2);
            ms.Position = 0;
            Compare(data, data2, 255);
            while (ms.Position < 1000000)
            {
                int length = rand.Next(256);
                ms.ReadAll(data2, 0, length);
                Compare(data, data2, length);
            }
            ms.Dispose();
            ms1.Dispose();
        }
        private async Task ReadFromBlobAsync(UnmanagedMemoryStream stream, CloudPageBlob blob, long sourceAddress, long destinationAddress, uint readLength)
        {
            Debug.WriteLine($"AzureStorageDevice.ReadFromBlobAsync Called target={blob.Name}");

            try
            {
                await BlobManager.AsyncStorageReadMaxConcurrency.WaitAsync().ConfigureAwait(false);

                int numAttempts = 0;

                while (true) // retry loop
                {
                    numAttempts++;
                    try
                    {
                        if (this.underLease)
                        {
                            await this.BlobManager.ConfirmLeaseAsync().ConfigureAwait(false);
                        }

                        Debug.WriteLine($"starting download target={blob.Name} readLength={readLength} sourceAddress={sourceAddress}");

                        if (readLength > 0)
                        {
                            await blob.DownloadRangeToStreamAsync(stream, sourceAddress, readLength,
                                                                  accessCondition : null, options : this.BlobRequestOptionsWithoutRetry, operationContext : null, cancellationToken : this.BlobManager.CancellationToken)
                            .ConfigureAwait(BlobManager.ConfigureAwaitForStorage);
                        }

                        Debug.WriteLine($"finished download target={blob.Name} readLength={readLength} sourceAddress={sourceAddress}");

                        if (stream.Position != readLength)
                        {
                            throw new InvalidDataException($"wrong amount of data received from page blob, expected={readLength}, actual={stream.Position}");
                        }
                        break;
                    }
                    catch (StorageException e) when(this.underLease && IsTransientStorageError(e) && numAttempts < BlobManager.MaxRetries)
                    {
                        TimeSpan nextRetryIn = TimeSpan.FromSeconds(1 + Math.Pow(2, (numAttempts - 1)));

                        this.BlobManager?.HandleBlobError(nameof(ReadFromBlobAsync), $"could not write to page blob, will retry in {nextRetryIn}s", blob?.Name, e, false);
                        await Task.Delay(nextRetryIn).ConfigureAwait(false);

                        stream.Seek(0, SeekOrigin.Begin); // must go back to original position before retrying
                        continue;
                    }
                    catch (Exception exception) when(!IsFatal(exception))
                    {
                        this.BlobManager?.HandleBlobError(nameof(ReadFromBlobAsync), "could not read from page blob", blob?.Name, exception, false);
                        throw;
                    }
                }
            }
            finally
            {
                BlobManager.AsyncStorageReadMaxConcurrency.Release();
                stream.Dispose();
            }
        }
        private async System.Threading.Tasks.Task <bool> CompareImagesAsync(ScratchImage dds, ScratchImage png)
        {
            Guid        codec    = DirectXTexNet.TexHelper.Instance.GetWICCodec(WICCodecs.PNG);
            TexMetadata metadata = dds.GetMetadata();

            UnmanagedMemoryStream ddsStream;

            if (IsCompressed(metadata.Format))
            {
                using (ScratchImage decompressed = dds.Decompress(DXGI_FORMAT.UNKNOWN))
                {
                    ddsStream = decompressed.SaveToWICMemory(0, WIC_FLAGS.NONE, codec);
                }
            }
            else
            {
                ddsStream = dds.SaveToWICMemory(0, WIC_FLAGS.NONE, codec);
            }

            UnmanagedMemoryStream pngStream = png.SaveToWICMemory(0, WIC_FLAGS.NONE, codec);

            var  scompare = new StreamCompare();
            bool result   = await scompare.AreEqualAsync(ddsStream, pngStream);

            ddsStream.Dispose();
            pngStream.Dispose();

            return(result);
        }
        private static void SelfTest()
        {
            UnmanagedMemoryStream ms1 = new UnmanagedMemoryStream();
            BinaryStreamBase ms = ms1.CreateBinaryStream();
            Random rand = new Random();
            int seed = rand.Next();
            rand = new Random(seed);
            byte[] data = new byte[255];
            rand.NextBytes(data);

            while (ms.Position < 1000000)
            {
                ms.Write(data, 0, rand.Next(256));
            }

            byte[] data2 = new byte[255];
            rand = new Random(seed);
            rand.NextBytes(data2);
            ms.Position = 0;
            Compare(data, data2, 255);
            while (ms.Position < 1000000)
            {
                int length = rand.Next(256);
                ms.ReadAll(data2, 0, length);
                Compare(data, data2, length);
            }
            ms.Dispose();
            ms1.Dispose();
        }
Пример #6
0
        protected override Image GetDrawingImage()
        {
            if (_currentDDS != null && !_currentDDS.IsDisposed)
            {
                _currentDDS.Dispose();
            }

            _currentDDS = GetScratchImage();

            try
            {
                Guid codec = TexHelper.Instance.GetWICCodec(WICCodecs.PNG);

                UnmanagedMemoryStream imageStream = _currentDDS.SaveToWICMemory(0, WIC_FLAGS.NONE, codec);

                Image image = Image.FromStream(imageStream);

                imageStream.Close();
                imageStream?.Dispose();

                return(image);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #7
0
            protected override unsafe void OnExecute(Tangle <T> tangle, out NoneType result)
            {
                result = NoneType.None;

                BTreeValue *pValue;
                ushort      keyType;
                long?       capacity = BytesToCopy.GetValueOrDefault(Input.Length - Input.Position);

                using (var nodeRange = tangle.BTree.LockValue(NodeIndex, ValueIndex, capacity, out pValue, out keyType))
                    using (var dataRange = tangle.BTree.DataStream.AccessRange(pValue->DataOffset, pValue->DataLength + pValue->ExtraDataBytes)) {
                        var stream = new UnmanagedMemoryStream(dataRange.Pointer, 0, dataRange.Size, FileAccess.ReadWrite);

                        if (BufferSize.HasValue)
                        {
                            Input.CopyTo(stream, BufferSize.Value);
                        }
                        else
                        {
                            Input.CopyTo(stream);
                        }

                        stream.Dispose();

                        tangle.BTree.UnlockValue(pValue, keyType);
                        tangle.BTree.UnlockNode(nodeRange);
                    }
            }
Пример #8
0
            protected override unsafe void OnExecute(Tangle <T> tangle, out NoneType result)
            {
                result = NoneType.None;

                BTreeValue *pValue;
                ushort      keyType;

                using (var nodeRange = tangle.BTree.LockValue(NodeIndex, ValueIndex, null, out pValue, out keyType))
                    using (var dataRange = tangle.BTree.DataStream.AccessRange(pValue->DataOffset, pValue->DataLength + pValue->ExtraDataBytes)) {
                        var stream = new UnmanagedMemoryStream(dataRange.Pointer, pValue->DataLength);

                        if (BufferSize.HasValue)
                        {
                            stream.CopyTo(Output, BufferSize.Value);
                        }
                        else
                        {
                            stream.CopyTo(Output);
                        }

                        stream.Dispose();

                        tangle.BTree.UnlockValue(pValue, keyType);
                        tangle.BTree.UnlockNode(nodeRange);
                    }
            }
Пример #9
0
        public static void CannotUseStreamAfterDispose()
        {
            using (var manager = new UmsManager(FileAccess.ReadWrite, 1000))
            {
                UnmanagedMemoryStream stream = manager.Stream;
                UmsTests.ReadWriteUmsInvariants(stream);

                stream.Dispose();
                Assert.False(stream.CanRead);
                Assert.False(stream.CanWrite);
                Assert.False(stream.CanSeek);

                Assert.Throws <ObjectDisposedException>(() => { long x = stream.Capacity; });

                Assert.Throws <ObjectDisposedException>(() => { long y = stream.Length; });
                Assert.Throws <ObjectDisposedException>(() => { stream.SetLength(2); });

                Assert.Throws <ObjectDisposedException>(() => { long z = stream.Position; });
                Assert.Throws <ObjectDisposedException>(() => { stream.Position = 2; });

                Assert.Throws <ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin));
                Assert.Throws <ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Current));
                Assert.Throws <ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.End));

                byte[] buffer = ArrayHelpers.CreateByteArray(10);
                Assert.Throws <ObjectDisposedException>(() => stream.Read(buffer, 0, buffer.Length));
                Assert.Throws <ObjectDisposedException>(() => stream.ReadByte());

                Assert.Throws <ObjectDisposedException>(() => stream.WriteByte(0));
                Assert.Throws <ObjectDisposedException>(() => stream.Write(buffer, 0, buffer.Length));
            }
        }
        /// <summary>
        /// Wraps the downloadToStream logic to retry/recover the download operation
        /// in the case that the last time the input stream has been written to exceeds a threshold.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="blobOffset"></param>
        /// <param name="length"></param>
        /// <param name="accessCondition"></param>
        /// <param name="options"></param>
        /// <param name="operationContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task downloadToStreamWrapper(UnmanagedMemoryStream stream, long blobOffset, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
        {
            long startingOffset = blobOffset;
            LargeDownloadStream largeDownloadStream = null;

            while (true)
            {
                try
                {
                    largeDownloadStream = new LargeDownloadStream(stream, blobOffset);
                    CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(largeDownloadStream.CancellationToken, cancellationToken);
                    Task  downloadTask          = this.LargeDownloadToFileSettings.Blob.DownloadRangeToStreamAsync(largeDownloadStream, blobOffset, length, this.accessConditions, this.blobRequestOptions, this.operationContext, cts.Token);
                    await downloadTask;
                    largeDownloadStream.Close();
                    break;
                }
                catch (OperationCanceledException)
                    // only catch if the stream triggered the cancellation
                    when(!cancellationToken.IsCancellationRequested)
                    {
                        blobOffset = startingOffset + largeDownloadStream.Position;
                        largeDownloadStream.Close();
                        length -= (blobOffset - startingOffset);
                        Console.WriteLine($"cancellation for offset:{startingOffset}, now at position:{blobOffset}. With remaining length:{length}");
                        if (length == 0)
                        {
                            break;
                        }
                    }
            }

            stream.Dispose();
        }
Пример #11
0
 internal void Dispose()
 {
     if (_Stream != null)
     {
         _Stream.Dispose();
     }
 }
Пример #12
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         _stream.Dispose();
     }
     Marshal.FreeHGlobal(_memory);
 }
Пример #13
0
            private unsafe static int Read(
                out IntPtr buffer_p,
                out UIntPtr len_p,
                out GitObjectType type_p,
                IntPtr backend,
                ref GitOid oid)
            {
                buffer_p = IntPtr.Zero;
                len_p    = UIntPtr.Zero;
                type_p   = GitObjectType.Bad;

                OdbBackend odbBackend = MarshalOdbBackend(backend);

                if (odbBackend == null)
                {
                    return((int)GitErrorCode.Error);
                }

                UnmanagedMemoryStream memoryStream = null;

                try
                {
                    ObjectType objectType;
                    int        toReturn = odbBackend.Read(new ObjectId(oid), out memoryStream, out objectType);

                    if (toReturn != 0)
                    {
                        return(toReturn);
                    }

                    if (memoryStream == null)
                    {
                        return((int)GitErrorCode.Error);
                    }

                    len_p  = new UIntPtr((ulong)memoryStream.Capacity);
                    type_p = objectType.ToGitObjectType();

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    buffer_p = new IntPtr(memoryStream.PositionPointer);
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return((int)GitErrorCode.Error);
                }
                finally
                {
                    if (memoryStream != null)
                    {
                        memoryStream.Dispose();
                    }
                }

                return((int)GitErrorCode.Ok);
            }
 public void Test()
 {
     MemoryPoolTest.TestMemoryLeak();
     SelfTest();
     UnmanagedMemoryStream ms = new UnmanagedMemoryStream();
     BinaryStreamTest.Test(ms);
     Assert.IsTrue(true);
     ms.Dispose();
     MemoryPoolTest.TestMemoryLeak();
 }
        public void Test()
        {
            MemoryPoolTest.TestMemoryLeak();
            SelfTest();
            UnmanagedMemoryStream ms = new UnmanagedMemoryStream();

            BinaryStreamTest.Test(ms);
            Assert.IsTrue(true);
            ms.Dispose();
            MemoryPoolTest.TestMemoryLeak();
        }
Пример #16
0
        /// <summary>
        /// A portion of the file contents have been received. This method will
        /// be called multiple times until the download is complete. Return
        /// |true| to continue receiving data and |false| to cancel.
        /// </summary>
        private int received_data(cef_download_handler_t *self, void *data, int data_size)
        {
            ThrowIfObjectDisposed();

            var m_stream = new UnmanagedMemoryStream((byte *)data, data_size, data_size, FileAccess.Read);

            var handled = this.ReceivedData(m_stream);

            m_stream.Dispose();

            return(handled ? 1 : 0);
        }
Пример #17
0
 public object[] RetriveParameters()
 {
     object[] data = null;
     unsafe
     {
         UnmanagedMemoryStream memStream = new UnmanagedMemoryStream((byte *)dataptr.ToPointer(), BUFFER_SIZE, BUFFER_SIZE, FileAccess.ReadWrite);
         BinaryFormatter       formatter = new BinaryFormatter();
         data = (object[])formatter.Deserialize(memStream);
         memStream.Dispose();
     }
     return(data);
 }
Пример #18
0
        private async Task WritePortionToBlobAsync(UnmanagedMemoryStream stream, CloudPageBlob blob, IntPtr sourceAddress, long destinationAddress, long offset, uint length)
        {
            try
            {
                await BlobManager.AsyncStorageWriteMaxConcurrency.WaitAsync().ConfigureAwait(false);

                int  numAttempts    = 0;
                long streamPosition = stream.Position;

                while (true) // retry loop
                {
                    numAttempts++;
                    try
                    {
                        if (this.underLease)
                        {
                            await this.BlobManager.ConfirmLeaseAsync().ConfigureAwait(false);
                        }

                        if (length > 0)
                        {
                            await blob.WritePagesAsync(stream, destinationAddress + offset,
                                                       contentChecksum : null, accessCondition : null, options : this.BlobRequestOptionsWithoutRetry, operationContext : null, cancellationToken : this.BlobManager.CancellationToken)
                            .ConfigureAwait(BlobManager.ConfigureAwaitForStorage);
                        }
                        break;
                    }
                    catch (StorageException e) when(this.underLease && IsTransientStorageError(e) && numAttempts < BlobManager.MaxRetries)
                    {
                        TimeSpan nextRetryIn = TimeSpan.FromSeconds(1 + Math.Pow(2, (numAttempts - 1)));

                        this.BlobManager?.HandleBlobError(nameof(WritePortionToBlobAsync), $"could not write to page blob, will retry in {nextRetryIn}s", blob?.Name, e, false);
                        await Task.Delay(nextRetryIn).ConfigureAwait(false);

                        stream.Seek(streamPosition, SeekOrigin.Begin);  // must go back to original position before retrying
                        continue;
                    }
                    catch (Exception exception) when(!IsFatal(exception))
                    {
                        this.BlobManager?.HandleBlobError(nameof(WritePortionToBlobAsync), "could not write to page blob", blob?.Name, exception, false);
                        throw;
                    }
                }
                ;
            }
            finally
            {
                BlobManager.AsyncStorageWriteMaxConcurrency.Release();
                stream.Dispose();
            }
        }
Пример #19
0
 /// <summary>
 ///		Releases unmanaged and - optionally - managed resources
 /// </summary>
 /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (disposing)
         {
             (jsonTextReader as IDisposable)?.Dispose();
             streamReader?.Dispose();
             unmanagedMemoryStream?.Dispose();
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
Пример #20
0
        protected override void OnDispose(bool disposing)
        {
            if (disposing)
            {
                _stream.Dispose();
            }

            if (CanDestroyImmediately)
            {
                Destroy();
            }
            else if (Core.Instance is not null)
            {
                Graphics.Resources.QueueDestroy(this);
            }
        }
Пример #21
0
        /// <summary>
        /// Set |substitute_data| to the replacement for the data in |data| if
        /// data should be modified.
        /// </summary>
        private void process_data(cef_content_filter_t *self, /*const*/ void *data, int data_size, cef_stream_reader_t **substitute_data)
        {
            ThrowIfObjectDisposed();

            var             m_stream = new UnmanagedMemoryStream((byte *)data, data_size, data_size, FileAccess.Read);
            CefStreamReader m_substitute_data;

            this.ProcessData(m_stream, out m_substitute_data);

            if (m_substitute_data != null)
            {
                *substitute_data = m_substitute_data.GetNativePointerAndAddRef();
            }

            m_stream.Dispose();
        }
Пример #22
0
        private static string writeStreamToTempLocation(UnmanagedMemoryStream inputStream, string extension)
        {
            string filePath = String.Format(System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N") + extension);

            using (FileStream outputStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) {
                int    readByte;
                byte[] copyBuffer = new byte[524288]; //0,5MB every cycle (512*1024 byte)
                while ((readByte = inputStream.Read(copyBuffer, 0, copyBuffer.Length)) > 0)
                {
                    outputStream.Write(copyBuffer, 0, readByte);
                }
                outputStream.Flush();
            }
            inputStream.Dispose();
            return(filePath);
        }
Пример #23
0
        unsafe public (int, NativeDataView, Stream) DecodePDU(IntPtr bytes, int len)
        {
            Stream dataStream = new UnmanagedMemoryStream((byte *)bytes, len);

            try
            {
                using (var reader = new BinaryReader(dataStream, Encoding.ASCII, true))
                {
                    // 读取包头信息,magic number检验(这里也可以用hash摘要算法,计算消息体数据摘要)
                    int cmd      = IPAddress.NetworkToHostOrder(reader.ReadInt16());
                    int udLen    = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                    int magicNum = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                    reader.Dispose();

                    if (magicNum == VERIFIED_MAGIC_NUM)
                    {
                        // magic number校验正确
#if UNITY_EDITOR
                        if (DUMP_RECV_HEX)
                        {
                            int    bodyLen   = len - PROTO_HEADER_SIZE; // the udLen===bodyLen
                            string wholeHexs = YASIO_NI.DumpHex(bytes, len);
                            UnityEngine.Debug.LogFormat("cmd={0}, udLen/bodyLen={1}/{2}, wholeHexs: {3}\n", cmd, udLen, bodyLen, wholeHexs);
                            string bodyHexs = YASIO_NI.DumpHex(bytes + PROTO_HEADER_SIZE, bodyLen);
                            UnityEngine.Debug.LogFormat("cmd={0}, bodyHexs: {1}\n", cmd, bodyHexs);
                        }
#endif
                        NativeDataView ud = new NativeDataView {
                            ptr = bytes + PROTO_HEADER_SIZE, len = len - PROTO_HEADER_SIZE
                        };

                        return(cmd, ud, dataStream);
                    }
                    else
                    {
                        UnityEngine.Debug.LogErrorFormat("SampleNetworkPacketHandler.DecodePDU: check magic number failed, magicNum={0}, VERIFIED_MAGIC_NUM={1}", magicNum, VERIFIED_MAGIC_NUM);
                    }
                }
            }
            finally
            {
                dataStream?.Dispose();
            }

            return(-1, NativeDataView.NullValue, null);
        }
Пример #24
0
        void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (SynchronizeOver != null)
            {
                UnmanagedMemoryStream stream = null;

                if (_progress.ErrorEncountered)
                {
                    stream = Properties.Resources.errorSound;
                }
                else if (_progress.WarningsEncountered)
                {
                    stream = Properties.Resources.warningSound;
                }
                else
                {
                    if (HasFeature(SyncUIFeatures.PlaySoundIfSuccessful))
                    {
                        stream = Properties.Resources.finishedSound;
                    }
                }

                if (stream != null)
                {
                    using (SoundPlayer player = new SoundPlayer(stream))
                    {
                        player.PlaySync();
                    }
                    stream.Dispose();
                }

                if (e.Cancelled)
                {
                    var r = new SyncResults();
                    r.Succeeded = false;
                    r.Cancelled = true;
                    SynchronizeOver.Invoke(r, null);
                }
                else                 //checking e.Result if there was a cancellation causes an InvalidOperationException
                {
                    SynchronizeOver.Invoke(e.Result as SyncResults, null);
                }
            }
        }
Пример #25
0
        public void StoreResults(object[] returnlist)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            unsafe
            {
                UnmanagedMemoryStream memStream = new UnmanagedMemoryStream((byte *)dataptr.ToPointer(), BUFFER_SIZE, BUFFER_SIZE, FileAccess.ReadWrite);
                try
                {
                    formatter.Serialize(memStream, returnlist);
                }
                catch
                {
                }

                memStream.Flush();
                memStream.Dispose();
            }
        }
Пример #26
0
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            if (listening)
            {
                listening = false;
                waiter.Cancel();
                listener.GetAwaiter().GetResult();
                listener = null;
            }

            mvs?.Dispose();
            fileHandle?.Dispose();
            globalHandle?.Dispose();
            mux?.Dispose();
            forEverClosed?.Dispose();
            mvs           = null;
            fileHandle    = null;
            globalHandle  = null;
            mux           = null;
            forEverClosed = null;
        }
Пример #27
0
 public void Dispose()
 {
     if (_unmanagedStream != null)
     {
         _unmanagedStream.Dispose();
     }
     if (_bufferHandle != null)
     {
         _bufferHandle.Free();
     }
     if (_mapView != IntPtr.Zero)
     {
         NativeMethods.UnmapViewOfFile(_mapView);
         _mapView = IntPtr.Zero;
     }
     if (_mappedFile != IntPtr.Zero)
     {
         NativeMethods.CloseHandle(_mappedFile);
         _mappedFile = IntPtr.Zero;
     }
 }
Пример #28
0
 public void Dispose()
 {
     if (unmanagedStream != null)
     {
         unmanagedStream.Dispose();
     }
     if (bufferHandle != null)
     {
         bufferHandle.Free();
     }
     if (mapView != IntPtr.Zero)
     {
         UnmapViewOfFile(mapView);
         mapView = IntPtr.Zero;
     }
     if (mappedFile != IntPtr.Zero)
     {
         CloseHandle(mappedFile);
         mappedFile = IntPtr.Zero;
     }
 }
Пример #29
0
        internal Engine()
        {
            gameInfo = new GameInfo();
            board    = new Board(7);
            gEngine  = new GraphicsEngine();

            bw         = new BackgroundWorker();
            bw.DoWork += CheckHints;

            gameInfo.GameMode = 1;

            swapHelper    = new Swapped();
            cascadeHelper = new Cascader();

            UnmanagedMemoryStream lChange = Properties.Resources.ChangeLevel;

            byte[] blevelChange = new byte[lChange.Capacity];
            lChange.Read(blevelChange, 0, (int)lChange.Capacity);
            levelChange = new Sound(blevelChange);
            lChange.Dispose();

            UnmanagedMemoryStream uMatch = Properties.Resources.matched;

            byte[] matched = new byte[uMatch.Capacity];
            uMatch.Read(matched, 0, (int)uMatch.Capacity);
            match = new Sound(matched);
            uMatch.Dispose();

            UnmanagedMemoryStream uApplause = Properties.Resources.applause;

            byte[] bApplause = new byte[uApplause.Capacity];
            uApplause.Read(bApplause, 0, (int)uApplause.Capacity);
            applause = new Sound(bApplause);
            uApplause.Dispose();

            match.Volume       = 128;
            levelChange.Volume = 20;
            applause.Volume    = 50;
            gameInfo.Sound     = true;
        }
Пример #30
0
        private async Task WritePortionToBlobAsync(UnmanagedMemoryStream stream, CloudPageBlob blob, IntPtr sourceAddress, long destinationAddress, long offset, uint length)
        {
            try
            {
                if (this.underLease)
                {
                    await this.BlobManager.ConfirmLeaseAsync().ConfigureAwait(false);
                }

                await blob.WritePagesAsync(stream, destinationAddress + offset,
                                           contentChecksum : null, accessCondition : null, options : this.BlobRequestOptions, operationContext : null, cancellationToken : this.BlobManager.CancellationToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                this.BlobManager?.HandleBlobError(nameof(WritePortionToBlobAsync), "could not write to page blob", blob?.Name, exception, true);
                throw;
            }
            finally
            {
                stream.Dispose();
            }
        }
Пример #31
0
        static void DoIt(string k, string add, bool mode = false)
        {
            if (DbKeyOpen(k + add))
            {
                unsafe {
                    UInt32 bufferLen = 0;
                    byte * buffer    = DbGet(out bufferLen);

                    // ++buffer - this is correction for zero byte artefact
                    var ums = new UnmanagedMemoryStream(++buffer, (Int32)bufferLen, (Int32)bufferLen, FileAccess.Read);
                    try {
                        // Create a byte array to hold data from unmanaged memory.
                        byte[] data = new byte[bufferLen - 1];

                        // Read from unmanaged memory to the byte array.
                        ums.Read(data, 0, (int)bufferLen - 1);

                        // Save data as is
                        DbSaveBinary(add + ".bin");

                        // Save data as formated json
                        if (mode)
                        {
                            string s = Encoding.Unicode.GetString(data);
                            File.WriteAllText(add + ".json", JToken.Parse(s).ToString(Formatting.Indented));
                        }
                    }
                    finally {
                        if (ums != null)
                        {
                            ums.Dispose();
                        }
                        ums = null;
                    }

                    DbKeyClose();
                }
            }
        }
Пример #32
0
        public void StoreParameters(string name, object[] paramlist)
        {
            int plen = (paramlist == null) ? 0 : paramlist.Length;

            object[] data = new object[plen + (int)SIPCArgsIndex.Args];
            data[(int)SIPCArgsIndex.Name]      = name;
            data[(int)SIPCArgsIndex.Exception] = null;
            data[(int)SIPCArgsIndex.Returnval] = null;
            if (plen != 0)
            {
                paramlist.CopyTo(data, (int)SIPCArgsIndex.Args);
            }
            BinaryFormatter formatter = new BinaryFormatter();

            unsafe
            {
                UnmanagedMemoryStream memStream = new UnmanagedMemoryStream((byte *)dataptr.ToPointer(), BUFFER_SIZE, BUFFER_SIZE, FileAccess.ReadWrite);
                formatter.Serialize(memStream, data);
                memStream.Flush();
                memStream.Dispose();
            }
        }