Ejemplo n.º 1
0
        public void UpdateSharedMemoryKey(String sharedMemoryKey)
        {
            if (mappedOverlayStream != null)
            {
                mappedOverlayStream.Close();
                mappedOverlayStream = null;
            }

            shmemKey = sharedMemoryKey;
        }
        protected void Close()
        {
            if (_notifyEvent != null)
            {
                _notifyEvent.Close();
                _notifyEvent.Dispose();
                _notifyEvent = null;
            }

            if (_mutex != null)
            {
                _mutex.Close();
                _mutex.Dispose();
                _mutex = null;
            }
            if (_stream != null)
            {
                _stream.Close();
                _stream = null;
            }
            if (_memMappedFile != null)
            {
                _memMappedFile.Dispose();
                _memMappedFile = null;
            }
        }
Ejemplo n.º 3
0
 public void Dispose()
 {
     writer.Close();
     writer.Dispose();
     stream.Close();
     stream.Dispose();
     memoryMappedFile.Dispose();
 }
Ejemplo n.º 4
0
 public void Close()
 {
     sharedmem_mutex.Close();
     message_handled.Close();
     message_wait.Close();
     phile_stream.Close();
     phile.Dispose();
 }
Ejemplo n.º 5
0
		public void Dispose()
		{
			using (GetLock())
			{
				_memoryMappedViewHandle = IntPtr.Zero;

				if (!string.IsNullOrEmpty(_balanceFileName))
				{
					if (_balanceFileWriter != null)
					{
						_balanceFileWriter.Close();
						_balanceFileWriter.Dispose();
						_balanceFileWriter = null;
					}

					if (_balanceFile != null)
					{
						_balanceFile.Close();
						_balanceFile.Dispose();
						_balanceFile = null;
					}
				}

				if (_memoryMappedViewStream != null)
				{
					_memoryMappedViewStream.Close();
					_memoryMappedViewStream.Dispose();
					_memoryMappedViewStream = null;
				}

				if (_memoryMappedViewAccessor != null)
				{
					_memoryMappedViewAccessor.Dispose();
					_memoryMappedViewAccessor = null;
				}

				if (_memoryMappedFile != null)
				{
					_memoryMappedFile.Dispose();
					_memoryMappedFile = null;
				}

				if (_onDataUpdatedEvent != null)
				{
					_onDataUpdatedEvent.Close();
					_onDataUpdatedEvent.Dispose();
					_onDataUpdatedEvent = null;
				}
			}

			if (_onWriteLockMutex != null)
			{
				_onWriteLockMutex.Close();
				_onWriteLockMutex.Dispose();
				_onWriteLockMutex = null;
			}
		}
Ejemplo n.º 6
0
 public void Dispose()
 {
     if (!_disposed)
     {
         _stream.Close();
         _stream.Dispose();
         _file.Dispose();
         _disposed = true;
     }
 }
Ejemplo n.º 7
0
        public void DisposeMemoryMappedFile()
        {
            if (stream != null)
            {
                stream.Close();
            }

            if (memoryFile != null)
            {
                memoryFile.Dispose();
            }
        }
Ejemplo n.º 8
0
        public static void WriteToMMF(string[] lines)
        {
            const int mmfMaxSize  = 16 * 1024 * 1024; // allocated memory for this memory mapped file (bytes)
            const int mmfViewSize = 16 * 1024 * 1024; // how many bytes of the allocated memory can this process access

            MemoryMappedFile       mmf       = MemoryMappedFile.CreateOrOpen("ClipboardAppMemoryMappedFile", mmfMaxSize, MemoryMappedFileAccess.ReadWrite);
            MemoryMappedViewStream mmvStream = mmf.CreateViewStream(0, mmfViewSize);
            BinaryFormatter        formatter = new BinaryFormatter();

            formatter.Serialize(mmvStream, lines);
            mmvStream.Seek(0, SeekOrigin.Begin);
            mmvStream.Close();
        }
Ejemplo n.º 9
0
        public void ChangeImage(byte[] pixeldata, byte[] bmiInfoHeader)
        {
            try
            {
                MemoryMappedFile mmap = MemoryMappedFile.CreateOrOpen("AmbiBox_XBMC_SharedMemory", pixeldata.Length + 11,
                                                                      MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, HandleInheritability.Inheritable);

                MemoryMappedViewStream viewStream = mmap.CreateViewStream();

                Stopwatch sw = new Stopwatch();
                sw.Start();

                while (true)
                {
                    viewStream.Seek(0, SeekOrigin.Begin);
                    if (viewStream.ReadByte() == 0xF8)
                    {
                        break;
                    }

                    if (sw.ElapsedMilliseconds > coreObject.ambiBoxChangeImageDelay)
                    {
                        sw.Stop();
                        viewStream.Dispose();
                        mmap.Dispose();
                        return;
                    }
                }

                viewStream.Seek(0, SeekOrigin.Begin);
                viewStream.WriteByte(0xF0);                                                                            // Begin
                viewStream.WriteByte((byte)(coreObject.GetCaptureWidth() & 0xff));                                     // Width
                viewStream.WriteByte((byte)((coreObject.GetCaptureWidth() >> 8) & 0xff));                              // Width
                viewStream.WriteByte((byte)(coreObject.GetCaptureHeight() & 0xff));                                    // Height
                viewStream.WriteByte((byte)((coreObject.GetCaptureHeight() >> 8) & 0xff));                             // Height
                viewStream.WriteByte((byte)(int)(coreObject.GetCaptureWidth() / coreObject.GetCaptureHeight() * 100)); // Aspect ratio
                viewStream.WriteByte(0x00);                                                                            // Image format (RGBA)
                viewStream.WriteByte((byte)(pixeldata.Length & 0xff));                                                 // Length
                viewStream.WriteByte((byte)((pixeldata.Length >> 8) & 0xff));                                          // Length
                viewStream.WriteByte((byte)((pixeldata.Length >> 16) & 0xff));                                         // Length
                viewStream.WriteByte((byte)((pixeldata.Length >> 24) & 0xff));                                         // Length

                viewStream.Write(pixeldata, 0, pixeldata.Length);                                                      // Copy pixeldata into mmap
                viewStream.Close();
            }
            catch (Exception e)
            {
                //Log.Error("Error occurred durin AmbiBox changeImage()");
                //Log.Error(e.Message);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Peek ahead bytes but do not chnage the seek pointer in sequential access
        /// </summary>
        /// <param name="position">The position in the file at which to begin reading
        /// relative to the current position in the file. Default is 0</param>
        /// <param name="count">The number of bytes to read. Default is 1.</param>
        /// <returns>A byte array</returns>
        public byte[] PeekBytes(int count = 1, long position = 0)
        {
            MemoryMappedViewStream tempPeek = this.MemoryFile.CreateViewStream(position, count, MemoryMappedFileAccess.Read);

            if (tempPeek != null && count > 0)
            {
                byte[] iodata = new byte[count];
                tempPeek.Read(iodata, (int)0, count);
                tempPeek.Close();
                tempPeek.Dispose();
                tempPeek = null;
                return(iodata);
            }

            return(null);
        }
Ejemplo n.º 11
0
        private List <P> getPs()
        {
            MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AIDA64_SensorValues");

            if (mmf == null)
            {
                MessageBox.Show("Файл не найден в памяти.\r\nУбедитесь, что AIDA запущена \r\nи настроена на использование совместной памяти с внешними приложениями.");
            }
            MemoryMappedViewStream mmvs = mmf.CreateViewStream();

            mmvs.Position = 0;
            StreamReader sr    = new StreamReader(mmvs);
            string       input = sr.ReadToEnd();

            mmvs.Close();
            input = input.Replace("\0", "");
            Console.WriteLine(input);

            List <P> res = new List <P>();

            XDocument doc = XDocument.Parse("<root>" + input + "</root>");

            foreach (XElement el in doc.Root.Elements())
            {
                try
                {
                    P p = new P();
                    p.type  = el.Name.ToString();
                    p.id    = el.Element("id").Value;
                    p.name  = el.Element("label").Value;
                    p.value = el.Element("value").Value;
                    if (ids.Contains(p.id))
                    {
                        ps.Add(p);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("!!! " + ex.Message);
                }
            }

            return(res);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Writes the message to a memory mapped file, where the memory mapped file name is WebsocketPipe.Address + id.
        /// mmf format: [wasread? 1 byte][datasize(int)][length(int)][msg][length(int)][msg]...
        /// If wasread=0, then writes the new message to the end of the message list and advances the number of messages +1.
        /// If wasread=1, clears the mmf and then writes the new message.
        /// </summary>
        /// <param name="wp">The calling WebsocketPipe</param>
        /// <param name="msg">The message to write.</param>
        /// <param name="to">The stream to write the mmf filename to.</param>
        /// <param name="id">The id of the targer we are writing to, since there may be many we open a mmf for each</param>
        public virtual void WriteMessage(WebsocketPipeMessageInfo msg, Stream to)
        {
            if (msg.Data.Length < this.UseInternalPacketDataSendingIfMsgByteSizeIsLessThen)
            {
                // write that this is an internal message.
                to.WriteByte(1);
                WebsocketAsInternalDataSocket.WriteMessage(msg, to);
                return;
            }

            // write that this is a mmf msg.
            to.WriteByte(0);

            // make the id and write it to the stream.
            string id = MakeValidMmfID(msg.DataSocketId);

            byte[] mmfnamebuffer = ASCIIEncoding.ASCII.GetBytes(id);
            to.Write(mmfnamebuffer, 0, mmfnamebuffer.Length);

            Mutex mu = new Mutex(false, id + "_mutex");

            if (!mu.WaitOne(MemoryMappedFileAccessTimeout))
            {
                throw new Exception("Memory mapped file access timedout.");
            }

            // The data size for a single message.
            int totalDataSize = msg.Data.Length + sizeof(int) + 1;

            // Creating/Opening the stream.
            MemoryMappedViewStream strm = GetDataWritingMemoryMappedViewStream(id, ref totalDataSize);

            // we are at the position of the write, and are ready for the message write.
            msg.WriteToStream(strm);

            strm.Flush();
            strm.Close();
            strm.Dispose();
            strm = null;

            // release the mutex.
            mu.ReleaseMutex();
        }
Ejemplo n.º 13
0
        public PLYToSchematic(string path, float scale, int colorLimit, bool holes, bool flood, bool lonely) : base(path, scale, colorLimit, holes, flood, lonely)
        {
            MemoryMappedFile       mmf = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
            MemoryMappedViewStream mms = mmf.CreateViewStream();

            DataHeader header = ReadDataHeader(new StreamReader(mms));

            Console.WriteLine("[LOG] Start reading PLY data...");
            DataBody body = header.binary ? ReadDataBodyBinary(header, new BinaryReader(mms)) : ReadDataBodyAscii(header, new StreamReader(mms));

            mms.Close();
            Console.WriteLine("[LOG] Done.");

            VoxelizeData(new BodyDataDTO()
            {
                BodyVertices = body.vertices,
                BodyColors   = body.colors
            });
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            MemoryMappedFile       mmf     = MemoryMappedFile.CreateNew("AAB", 1024);
            MemoryMappedViewStream mStream = mmf.CreateViewStream();
            BinaryWriter           bw      = new BinaryWriter(mStream);
            Mutex mx = new Mutex(true, "sync");

            while (true)
            {
                mx.WaitOne();
                Thread.Sleep(2000);
                var random    = new Random();
                var nextValue = random.Next().ToString();
                Console.WriteLine(nextValue);
                bw.Write(nextValue);
                mx.ReleaseMutex();
            }
            bw.Close();
            mStream.Close();
        }
Ejemplo n.º 15
0
        public SMemIPCData SendMessage(SMemIPCData data_in)
        {
            try
            {
                sharedmem_mutex.WaitOne(); //take the mutex

                //save message in shared memory
                IPCCodec.Serialize(phile_stream, data_in);
                //prepare the message prefix
                phile_prefix.Write(0, phile_stream.Position);
                message_wait.Set();        //signal message ready

                message_handled.WaitOne(); //wait for reply ready signal
                //copy results from shared memory
                long result_size = phile_prefix.ReadInt64(0);
                if (result_size > phile_stream.Capacity)
                {
                    //enlarge the view stream if the result is too big
                    try
                    {
                        phile_stream.Close();
                        phile_stream = phile.CreateViewStream(sizeof(long), result_size);
                    }
                    catch
                    {
                        throw new SystemException("ijiCore: Result set too large.");
                    }
                }
                return(IPCCodec.Deserialize(phile_stream));
            }
            catch (Exception e)
            {
                return(null);
            }
            finally
            {
                sharedmem_mutex.ReleaseMutex();
            }
        }
Ejemplo n.º 16
0
        public static string ReadInChunks(long offset, long limit, string path)
        {
            StringBuilder          resultAsString         = new StringBuilder();
            MemoryMappedFile       memoryMappedFile       = MemoryMappedFile.CreateFromFile(path);
            MemoryMappedViewStream memoryMappedViewStream = memoryMappedFile.CreateViewStream(offset, limit, MemoryMappedFileAccess.Read);

            {
                for (long i = offset; i < limit; i++)
                {
                    //Reads a byte from a stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
                    int result = memoryMappedViewStream.ReadByte();
                    if (result == -1)
                    {
                        break;
                    }
                    char letter = (char)result;
                    resultAsString.Append(letter);
                }
            }
            Console.WriteLine(resultAsString.ToString());
            memoryMappedViewStream.Close();
            memoryMappedFile.Dispose();
            return(resultAsString.ToString());
        }
Ejemplo n.º 17
0
        //http://www.minecraftwiki.net/wiki/Region_file_format
        public void Read(String path, int startX, int endX, int startZ, int endZ)
        {
            Chunks = new Chunk[32, 32];
            Match m = Regex.Match(path, @"r\.(-?\d+)\.(-?\d+)\.mca");

            Coords.X = int.Parse(m.Groups[1].Value);
            Coords.Z = int.Parse(m.Groups[2].Value);

            if (!File.Exists(path))
            {
                return;
            }

            signal    = new ManualResetEvent(false);
            taskCount = (endX - startX + 1) * (endZ - startZ + 1);

            byte[] header = new byte[8192];

            using (MemoryMappedFile file = MemoryMappedFile.CreateFromFile(path, FileMode.Open))
            {
                using (MemoryMappedViewStream reader = file.CreateViewStream())
                {
                    reader.Read(header, 0, 8192);

                    for (int chunkZ = startZ; chunkZ <= endZ; chunkZ++)
                    {
                        for (int chunkX = startX; chunkX <= endX; chunkX++)
                        {
                            Chunk c = new Chunk();
                            c.Coords.X = Coords.X;
                            c.Coords.Z = Coords.Z;
                            c.Coords.RegiontoChunk();
                            c.Coords.Add(chunkX, chunkZ);

                            int i = 4 * (chunkX + chunkZ * 32);

                            byte[] temp = new byte[4];
                            temp[0] = 0;
                            Array.Copy(header, i, temp, 1, 3);
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(temp);
                            }
                            long offset = ((long)BitConverter.ToInt32(temp, 0)) * 4096;
                            int  length = header[i + 3] * 4096;

                            temp = new byte[4];
                            Array.Copy(header, i + 4096, temp, 0, 4);
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(temp);
                            }
                            c.Timestamp = BitConverter.ToInt32(temp, 0);

                            if (offset == 0 && length == 0)
                            {
                                Chunks[chunkX, chunkZ] = c;
                                if (Interlocked.Decrement(ref taskCount) == 0)
                                {
                                    signal.Set();
                                }
                                continue;
                            }

                            reader.Seek(offset, SeekOrigin.Begin);

                            temp = new byte[4];
                            reader.Read(temp, 0, 4);
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(temp);
                            }
                            int exactLength = BitConverter.ToInt32(temp, 0);

                            c.CompressionType = (byte)reader.ReadByte();

                            c.RawData = new byte[exactLength - 1];
                            reader.Read(c.RawData, 0, exactLength - 1);

                            Chunks[chunkX, chunkZ] = c;

                            ThreadPool.QueueUserWorkItem(Decompress, c);
                        }
                    }
                    reader.Close();
                }
            }
            signal.WaitOne();
            signal.Dispose();
            signal = null;
        }
Ejemplo n.º 18
0
 public void Dispose()
 {
     fs.Close();
     file.Dispose();
 }
Ejemplo n.º 19
0
        protected MemoryMappedViewStream GetDataWritingMemoryMappedViewStream(string id, ref int totalDataSize)
        {
            bool needAppend = false;
            bool needNew    = true;

            MemoryMappedViewStream strm = null;
            BinaryReader           rw   = null;

            if (MemoryMapByID.ContainsKey(id))
            {
                // Check the size. If smaller then need to increase.
                MemoryMappedFile mmf = MemoryMapByID[id].Item2;
                strm = mmf.CreateViewStream(0, 0, MemoryMappedFileAccess.ReadWrite);
                strm.Seek(0, SeekOrigin.Begin);
                rw = new BinaryReader(strm);

                needAppend = rw.ReadByte() == 0;

                // need to update the data size.
                if (needAppend)
                {
                    totalDataSize = totalDataSize + MemoryMapByID[id].Item1;
                }

                // we need a new file if the data required
                needNew = totalDataSize + MMFHeaderSize > ToMMFFileSize(MemoryMapByID[id].Item1);
            }

            byte[] oldData = null;
            if (needAppend && needNew)
            {
                // the old data to copy
                oldData = new byte[rw.ReadInt32()];
                // reading the data into the old data array.
                strm.Read(oldData, 0, oldData.Length);
            }
            else if (needAppend)
            {
                // seek to data end.
                strm.Seek(MemoryMapByID[id].Item1 + MMFHeaderSize, SeekOrigin.Begin);
            }

            BinaryWriter wr;

            if (needNew)
            {
                // destorying the old.
                if (needAppend)
                {
                    strm.Close();
                    strm.Dispose();
                    MemoryMapByID[id].Item2.Dispose();
                }

                TotalNumberOfMemoryMappedFilesCreated++;

                // dispose the old.
                if (MemoryMapByID.ContainsKey(id))
                {
                    MemoryMapByID[id].Item2.Dispose();
                }
                MemoryMappedFile mmf = MemoryMappedFile.CreateNew(id, ToMMFFileSize(totalDataSize));
                strm = mmf.CreateViewStream(0, 0, MemoryMappedFileAccess.ReadWrite);

                wr = new BinaryWriter(strm);
                MemoryMapByID[id] = new Tuple <int, MemoryMappedFile>(totalDataSize, mmf);
                mmf = null;

                wr.Write((byte)0);
                wr.Write(totalDataSize);
                if (needAppend)
                {
                    wr.Write(oldData);
                }
                // at write position for new data.
            }
            else
            {
                wr = new BinaryWriter(strm);
                strm.Seek(0, SeekOrigin.Begin);
                wr.Write((byte)0);
                wr.Write(totalDataSize);
                if (needAppend)
                {
                    wr.Seek(MemoryMapByID[id].Item1 + MMFHeaderSize, SeekOrigin.Begin);
                }
                // at write position.
            }

            wr      = null;
            oldData = null;
            return(strm);
        }