public static string ZZReadMappedMemoryData() { string Data = string.Empty; try { using (System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting("NICSQLToolsUpdateMap")) { System.Threading.Mutex mutex = System.Threading.Mutex.OpenExisting("NICSQLToolsUpdateMapMutex"); using (System.IO.MemoryMappedFiles.MemoryMappedViewStream stream = mmf.CreateViewStream()) { System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); Data = reader.ReadString(); } mutex.WaitOne(); } if (Data == string.Empty) { System.Diagnostics.Process.GetCurrentProcess().Kill(); } Properties.Settings.Default["DatabaseConnectionString"] = Data.Split(Convert.ToChar("||"))[0]; } catch (System.IO.FileNotFoundException) { Console.WriteLine("Memory-mapped file does not exist. Run Process A first."); } return(Data.Split(Convert.ToChar("||"))[1]); }
/// <summary> /// Opens the dbase stream /// </summary> public void Open() { #if USE_MEMORYMAPPED_FILE if (!MemMappedFiles.ContainsKey(_filename)) { System.IO.MemoryMappedFiles.MemoryMappedFile memMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(_filename, FileMode.Open); MemMappedFiles.Add(_filename, memMappedFile); } if (!_haveRegistredForUsage) { if (MemMappedFilesRefConter.ContainsKey(_filename)) { MemMappedFilesRefConter[_filename]++; } else { MemMappedFilesRefConter.Add(_filename, 1); } _haveRegistredForUsage = true; } _dbfStream = MemMappedFiles[_filename].CreateViewStream(); #else _dbfStream = new FileStream(_filename, FileMode.Open, FileAccess.Read); #endif //br = new BinaryReader(_dbfStream); IsOpen = true; if (!_headerIsParsed) //Don't read the header if it's already parsed { ParseDbfHeader(_filename); } }
static IntPtr getHandle(string key) { using (System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting(key)) { using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { IntPtr handler = IntPtr.Zero; accessor.Read(0, out handler); return(handler); } } }
private void WriteHandle(string key, IntPtr handler) { System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(key, 1024000); using (System.IO.MemoryMappedFiles.MemoryMappedViewStream stream = mmf.CreateViewStream()) { using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Write(0, ref handler); } } }
public MMFinterComT(string ctrIpcChannelNameStr, string ctrIpcThreadName, int ctrMMFSize) { this.DipositChlName = ctrIpcChannelNameStr; this.DipositSize = ctrMMFSize; this.DipositThrdName = ctrIpcThreadName; mmf = MemoryMappedFile.CreateOrOpen(DipositChlName, DipositSize); accessor = mmf.CreateViewAccessor(0, DipositSize, System.IO.MemoryMappedFiles.MemoryMappedFileAccess.ReadWrite); //if (started) //smLock = new System.Threading.Mutex(true, IpcMutxName, out locked); ReadPosition = -1; writePosition = -1; this.dataToSend = new List <byte[]>(); this.statusSet = new List <string>(); }
public virtual void Close() { if (accessor != null) { try { accessor.Dispose(); accessor = null; } catch { } } if (this.mmf != null) { try { mmf.Dispose(); mmf = null; } catch { } } disposed = true; GC.SuppressFinalize(this); }
private Stream CheckCreateMemoryMappedStream(string filename, ref bool haveRegistredForUsage) { if (!_memMappedFiles.ContainsKey(filename)) { System.IO.MemoryMappedFiles.MemoryMappedFile memMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(filename, FileMode.Open); _memMappedFiles.Add(filename, memMappedFile); } if (!haveRegistredForUsage) { if (_memMappedFilesRefConter.ContainsKey(filename)) { _memMappedFilesRefConter[filename]++; } else { _memMappedFilesRefConter.Add(filename, 1); } haveRegistredForUsage = true; } return(_memMappedFiles[filename].CreateViewStream()); }
/// <summary> /// free all used ressources, /// abort all work /// </summary> public void stop_instance() { //delete old mutex bool initial_owned; System.Threading.Mutex shm_mutex = new System.Threading.Mutex(true, "Global\\" + export_name + "_mutex", out initial_owned); if (!initial_owned) { shm_mutex.WaitOne(250); } if (memory_file != null && memory_file.SafeMemoryMappedFileHandle.IsInvalid != true) { memory_file.Dispose(); } memory_file = null; shm_mutex.ReleaseMutex(); shm_mutex.Dispose(); shm_mutex = null; memory_file_size = 0; _in_progress = false; }
/// <summary> /// this funtion is calles from parent process to /// transfer the new data to the plugin class /// </summary> /// <param name="data">list with all new log data items</param> public void add_log_data(List<LogDataSet> data) { if (_in_progress) //the current process is locked return; //export current data to a buffer for file writing _in_progress = true; AquaComputer.Logdata.LogDataExport export = new Logdata.LogDataExport(); export.logdata = data; export.name = export_name; export.exportTime = DateTime.Now; byte[] buffer = export.ToBuffer(); if (buffer == null || export_name == null || export_name == string.Empty) { _in_progress = false; return; } //try to create a new shared memory file if (memory_file == null || memory_file.SafeMemoryMappedFileHandle.IsClosed || memory_file.SafeMemoryMappedFileHandle.IsInvalid) { try { memory_file = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew(export_name, buffer.LongLength * 2); memory_file_size = buffer.Length * 2; } catch { memory_file = null; memory_file_size = 0; } } //not able to craeate to use a shared memory file with the current settings if (memory_file == null) { _in_progress = false; return; } //check if the file used from external ressources //wait until all locks are released or timeout elapsed bool initial_owned; System.Threading.Mutex shm_mutex = new System.Threading.Mutex(true, "Global\\" + export_name + "_mutex", out initial_owned); if (!initial_owned) { bool mutex_is_free = shm_mutex.WaitOne(50); if (mutex_is_free == false) { _in_progress = false; return; } } if (memory_file_size < buffer.Length) { //file buffer is too small, create file buffer memory_file.Dispose(); memory_file = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew(export_name, buffer.LongLength * 2); memory_file_size = buffer.Length * 2; } //acces file to write data to ram segement using(var accessor = memory_file.CreateViewAccessor(0, memory_file_size)) { if (accessor != null) { accessor.WriteArray<byte>(0, buffer, 0, buffer.Length); //reset rest of data array to 0 byte[] reset_buffer = new byte[memory_file_size - buffer.Length]; for (int i = 0; i < reset_buffer.Length; i++) reset_buffer[i] = 0; accessor.WriteArray<byte>(buffer.Length, reset_buffer, 0, reset_buffer.Length); } } //release ressources shm_mutex.ReleaseMutex(); //release mutex _in_progress = false; }
/// <summary> /// free all used ressources, /// abort all work /// </summary> public void stop_instance() { //delete old mutex bool initial_owned; System.Threading.Mutex shm_mutex = new System.Threading.Mutex(true, "Global\\" + export_name + "_mutex", out initial_owned); if (!initial_owned) { shm_mutex.WaitOne(250); } if (memory_file != null && memory_file.SafeMemoryMappedFileHandle.IsInvalid != true) memory_file.Dispose(); memory_file = null; shm_mutex.ReleaseMutex(); shm_mutex.Dispose(); shm_mutex = null; memory_file_size = 0; _in_progress = false; }
void Init() { MMF = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting( path, System.IO.MemoryMappedFiles.MemoryMappedFileRights.Read, HandleInheritability.None); }
void Init() { MMF = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting ( path, System.IO.MemoryMappedFiles.MemoryMappedFileRights.Read, HandleInheritability.None); }
internal bool Run(string uuid, string mode) { bool run = false; XcDiagProcessInfo xcdiagProcessInfo = GetXcDiagProcessInfo(mode); if (xcdiagProcessInfo != null) // If got xcdiag process info { this.log.Info("Received xcdiag request"); xcdiagProcessInfo.processStartInfo.CreateNoWindow = true; xcdiagProcessInfo.processStartInfo.ErrorDialog = false; xcdiagProcessInfo.processStartInfo.RedirectStandardError = true; xcdiagProcessInfo.processStartInfo.RedirectStandardOutput = true; xcdiagProcessInfo.processStartInfo.UseShellExecute = false; xcdiagProcessInfo.processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process xcdiagProcess = null; try { xcdiagProcess = System.Diagnostics.Process.Start(xcdiagProcessInfo.processStartInfo); if (xcdiagProcess == null) { log.Info("xcdiag process already running in: \"{0}\"", xcdiagProcessInfo.processStartInfo.FileName); } } catch (System.IO.FileNotFoundException filenotfoundEx) { log.Exception("Cannot launch xcdiag (file not found)", filenotfoundEx); } catch (System.ObjectDisposedException objdisposedEx) { log.Exception("Cannot launch xcdiag (object disposed)", objdisposedEx); } catch (System.InvalidOperationException invalidopEx) { log.Exception("Cannot launch xcdiag (invalid operation)", invalidopEx); } catch (System.ComponentModel.Win32Exception win32Ex) { log.Exception("Cannot launch xcdiag (win32 error)", win32Ex); } catch (System.Exception ex) { log.Exception("Cannot launch xcdiag", ex); } if (xcdiagProcess != null) // If launched xcdiag { // Tends to block until process finishes. string xcdiagError = xcdiagProcess.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(xcdiagError)) { log.Error("xcdiag produced error output: {0}", xcdiagError); } xcdiagProcess.WaitForExit(); // Oooooh. if (xcdiagProcess.ExitCode != 0) // If xcdiag reported an error { log.Error("xcdiag exited with error code '{0}'", xcdiagProcess.ExitCode); } // Ends if xcdiag reported an error else // else xcdiag ran ok { System.Text.StringBuilder dataBuffer = null; // Make a big ol' string containing the data, encoding each byte as 2-digit ASCII hex. #if MEMORYMAPFILE_SUPPORTED using (System.IO.MemoryMappedFiles.MemoryMappedFile memmapXcDiag = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(xcdiagProcessInfo.xcDiagOutputPath)) #else // !MEMORYMAPFILE_SUPPORTED //// Create a memory mapped view of the zip file //hFile = CreateFileA(szXcDiagOut, // GENERIC_READ | GENERIC_WRITE, // 0, // NULL, // OPEN_EXISTING, // FILE_ATTRIBUTE_NORMAL, // NULL); using (Microsoft.Win32.SafeHandles.SafeFileHandle mapHandle = wcf.Native.FileFunctions.CreateFile(xcdiagProcessInfo.xcDiagOutputPath , global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_READ | global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_WRITE , System.IO.FileShare.None , IntPtr.Zero , System.IO.FileMode.Open , System.IO.FileAttributes.Normal , IntPtr.Zero)) #endif // MEMORYMAPFILE_SUPPORTED { // Finish creating the native mapping, and then work out how to read bytes... #if MEMORYMAPFILE_SUPPORTED using (System.IO.MemoryMappedFiles.MemoryMappedViewStream streamXcDiag = memmapXcDiag.CreateViewStream()) #else // !MEMORYMAPFILE_SUPPORTED long fileSize = new System.IO.FileInfo(xcdiagProcessInfo.xcDiagOutputPath).Length; //hMapFile = CreateFileMapping( // hFile, // current file handle // NULL, // default security // PAGE_READWRITE, // read/write permission // 0, // size of mapping object, high // filesize, // size of mapping object, low // NULL); // name of mapping object using (Microsoft.Win32.SafeHandles.SafeFileHandle xcDiagOutputMappingHandle = wcf.Native.MappingFunctions.CreateFileMapping(mapHandle , IntPtr.Zero , global::XenClientGuestService.Native.FileMapProtection.PageReadWrite , 0 , checked ((uint)fileSize) , null)) #endif // MEMORYMAPFILE_SUPPORTED { #if MEMORYMAPFILE_SUPPORTED long fileSize = streamXcDiag.Length; #else // !MEMORYMAPFILE_SUPPORTED //// Map the view //lpMapAddress = (unsigned char *)MapViewOfFile( // hMapFile, // handle to mapping object // FILE_MAP_ALL_ACCESS, // read/write // 0, // high-order 32 bits of file offset // 0, // low-order 32 bits of file offset // filesize); // number of bytes to map using (wcf.Native.FileMappingViewHandle mappingViewHandler = wcf.Native.MappingFunctions.MapViewOfFile(xcDiagOutputMappingHandle , global::XenClientGuestService.Native.FileMapAccess.FileMapAllAccess , 0 , 0 , (checked ((UInt32)fileSize)))) #endif // !MEMORYMAPFILE_SUPPORTED { #if MEMORYMAPFILE_SUPPORTED System.IO.BinaryReader reader = new System.IO.BinaryReader(streamXcDiag); #else // !MEMORYMAPFILE_SUPPORTED wcf.Native.FileMappingViewHandle.ViewReader reader = mappingViewHandler.CreateViewReader(); #endif // !MEMORYMAPFILE_SUPPORTED int resultSize = checked ((int)(fileSize * 2)); dataBuffer = new StringBuilder(resultSize, resultSize); for (int byteIter = 0; byteIter < fileSize; ++byteIter) { byte b = reader.ReadByte(); dataBuffer.Append(b.ToString("x2")); } // Ends loop over bytes } // Ends using map view handle } // Ends using Memory Map view } // Ends using Memory Map file string data = dataBuffer.ToString(); byte[] stringBytes = System.Text.Encoding.Default.GetBytes(data); byte[] asciiBytes = System.Text.ASCIIEncoding.Convert(Encoding.Default, Encoding.ASCII, stringBytes); data = System.Text.Encoding.ASCII.GetString(asciiBytes); Gather(uuid, data); } // Ends else xcdiag ran ok } // Ends if launched xcdiag } // Ends if got xcdiag process info return(run); }
/// <summary> /// this funtion is calles from parent process to /// transfer the new data to the plugin class /// </summary> /// <param name="data">list with all new log data items</param> public void add_log_data(List <LogDataSet> data) { if (_in_progress) //the current process is locked { return; } //export current data to a buffer for file writing _in_progress = true; AquaComputer.Logdata.LogDataExport export = new Logdata.LogDataExport(); export.logdata = data; export.name = export_name; export.exportTime = DateTime.Now; byte[] buffer = export.ToBuffer(); if (buffer == null || export_name == null || export_name == string.Empty) { _in_progress = false; return; } //try to create a new shared memory file if (memory_file == null || memory_file.SafeMemoryMappedFileHandle.IsClosed || memory_file.SafeMemoryMappedFileHandle.IsInvalid) { try { memory_file = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew(export_name, buffer.LongLength * 2); memory_file_size = buffer.Length * 2; } catch { memory_file = null; memory_file_size = 0; } } //not able to craeate to use a shared memory file with the current settings if (memory_file == null) { _in_progress = false; return; } //check if the file used from external ressources //wait until all locks are released or timeout elapsed bool initial_owned; System.Threading.Mutex shm_mutex = new System.Threading.Mutex(true, "Global\\" + export_name + "_mutex", out initial_owned); if (!initial_owned) { bool mutex_is_free = shm_mutex.WaitOne(50); if (mutex_is_free == false) { _in_progress = false; return; } } if (memory_file_size < buffer.Length) { //file buffer is too small, create file buffer memory_file.Dispose(); memory_file = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew(export_name, buffer.LongLength * 2); memory_file_size = buffer.Length * 2; } //acces file to write data to ram segement using (var accessor = memory_file.CreateViewAccessor(0, memory_file_size)) { if (accessor != null) { accessor.WriteArray <byte>(0, buffer, 0, buffer.Length); //reset rest of data array to 0 byte[] reset_buffer = new byte[memory_file_size - buffer.Length]; for (int i = 0; i < reset_buffer.Length; i++) { reset_buffer[i] = 0; } accessor.WriteArray <byte>(buffer.Length, reset_buffer, 0, reset_buffer.Length); } } //release ressources shm_mutex.ReleaseMutex(); //release mutex _in_progress = false; }