예제 #1
0
        /// <summary>
        /// Opens an existing named mutex.
        /// </summary>
        /// <param name="name">The name of a system-wide named mutex object.</param>
        /// <returns>A <see cref="NamedMutex"/> object that represents a named system mutex.</returns>
        /// <remarks>The OpenExisting method attempts to open an existing named mutex.
        /// If the system mutex does not exist, this method throws an exception instead of creating the system object.
        /// Two calls to this method with the same value for name do not necessarily return the same <see cref="NamedMutex"/> object, even though they represent the same named system mutex.</remarks>
        /// <exception cref="ArgumentException">name is a zero-length string.
        /// -or-
        /// name is longer than 260 characters.</exception>
        /// <exception cref="ArgumentNullException">name is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="WaitHandleCannotBeOpenedException">The named mutex does not exist.</exception>
        public static NamedMutex OpenExisting(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (name.Length < 1)
            {
                throw new ArgumentException("name is a zero-length string.");
            }
            if (name.Length > 260)
            {
                throw new ArgumentException("name is longer than 260 characters.");
            }

            bool       created;
            NamedMutex m = new NamedMutex(false, name, out created);

            if (created)
            {
                //mutex doesnt already exist
                m.Dispose(true);
                throw new WaitHandleCannotBeOpenedException();
            }
            return(m);
        }
예제 #2
0
파일: Program.cs 프로젝트: BeL1kOFF/SHATE
        static void Main()
        {
            Boolean firstInstance;

            using (NamedMutex mx = new NamedMutex(false, "2D2EBFAC-543A-4FE8-A4E6-D88F5A76B2A1", out firstInstance))
            {
                if (firstInstance)
                {
                    try
                    {
                        ScannerProxy.ScannerAPI.SetLabelSuffix();

                        Boolean start = true;
                        try
                        {
                            Assembly.Load("System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=3BE235DF1C8D2AD3");
                        }
                        catch
                        {
                            start = false;
                            MyClass.ShowError("Не установлен Sql Server Compact 3.5");
                        }
                        if (start)
                        {
                            Application.Run(new FormMain());
                        }
                        GC.KeepAlive(mx);
                    }
                    finally
                    {
                        ScannerProxy.ScannerAPI.RestoreLabelSuffix();
                    }
                }
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += FMSC.Utility.ErrorHandling.ErrorHandlers.UnhandledException;

            using (NamedMutex mutex = new NamedMutex(false, "Global\\" + "FScruiser"))
            {
                if (mutex.WaitOne(0, false))
                {
                    //not already running

                    //PreJit();
                    using (ViewController viewController = new ViewController())
                    using (ApplicationController appController = new ApplicationController(viewController))
                    {
                        if (args.Length > 1)
                        {
                            appController.OpenFile(args[1]);
                        }

                        viewController.Run();
                    }
                    Debug.Close();
                }
                else
                {
                    //is already running
                    string message = "FScruiser is already running\r\n";
                    if (ViewController.PlatformType == FMSC.Controls.PlatformType.WM)
                    {
                        message += "To halt or activate background programs, go to Settings->System->Memory";
                    }

                    MessageBox.Show(message);
                    return;
                }
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            Globals.WriteToDebugFile("--- Init ---");

            using (NamedMutex mutex = new NamedMutex(false, "Global\\LocationScheduler\\LSCore"))
            {
                if (!mutex.WaitOne(0, false))
                {
                    Globals.WriteToDebugFile("Instance already running");
                    return;
                }

                GC.Collect();

                // We have to force the cursor to the default one, otherwise
                // it will stay in the "wait" cursor". This is probably because
                // of the fact that the thread locks right at the startup...
                Cursor.Current = Cursors.Default;
                TasksMonitor tm = new TasksMonitor();

            }

            Globals.WriteToDebugFile("--- Shutdown ---");
        }
예제 #5
0
 private void menuItemStopDaemon_Click(object sender, EventArgs e)
 {
     // Just to make sure that a daemon is running...
     using (NamedMutex mutex = new NamedMutex(false, "Global\\LocationScheduler\\LSCore"))
     {
         if (!mutex.WaitOne(0, false))
         {
             // Could not grab mutex-> daemon is running
             _MsgQueueMgr.Write(NotifMessages.NOTIF_STOP);
         }
         else
         {
             SenseAPIs.SenseMessageBox.Show("No daemon running!", "Error", SenseMessageBoxButtons.OK);
         }
     }
 }
예제 #6
0
        /// <summary>
        /// Opens an existing named mutex.
        /// </summary>
        /// <param name="name">The name of a system-wide named mutex object.</param>
        /// <returns>A <see cref="NamedMutex"/> object that represents a named system mutex.</returns>
        /// <remarks>The OpenExisting method attempts to open an existing named mutex.
        /// If the system mutex does not exist, this method throws an exception instead of creating the system object.
        /// Two calls to this method with the same value for name do not necessarily return the same <see cref="NamedMutex"/> object, even though they represent the same named system mutex.</remarks>
        /// <exception cref="ArgumentException">name is a zero-length string.
        /// -or-
        /// name is longer than 260 characters.</exception>
        /// <exception cref="ArgumentNullException">name is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="WaitHandleCannotBeOpenedException">The named mutex does not exist.</exception>
        public static NamedMutex OpenExisting(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (name.Length < 1)
            {
                throw new ArgumentException("name is a zero-length string.");
            }
            if (name.Length > 260)
            {
                throw new ArgumentException("name is longer than 260 characters.");
            }

            bool created;
            NamedMutex m = new NamedMutex(false, name, out created);
            if (created)
            {
                //mutex doesnt already exist
                m.Dispose(true);
                throw new WaitHandleCannotBeOpenedException();
            }
            return m;
        }
예제 #7
0
        /// <summary>   Gets the 7zip library path.</summary>
        /// <exception cref="TimeoutException"> Thrown when a Timeout error condition occurs.</exception>
        /// <returns>   The library path.</returns>
        /// <remarks> In WindowsCE, a file called 7z.dll in the same directory as this assembly.  If it does not exist,
        ///           an Embedded resource is extracted to this directory and used.  All other platforms use the following
        ///           logic:
        ///           1. [All] The value provided to a previous call to SetLibraryPath() is used.
        ///           2. [Full Framework] app.config AppSetting '7zLocation' which must be path to the proper bit 7z.dll
        ///           3. [All] Embedded resource is extracted to %TEMP% and used. (assuming build with embedded 7z.dll is used)
        ///           4. [All] 7z.dll from a x86 or x64 subdirectory of this assembly's directory.
        ///           5. [All] 7za.dll from a x86 or x64 subdirectory of this assembly's directory.
        ///           6. [All] 7z86.dll or 7z64.dll in the same directory as this assembly.
        ///           7. [All] 7za86.dll or 7za64.dll in the same directory as this assembly.
        ///           8. [All] A file called 7z.dll in the same directory as this assembly.
        ///           9. [All] A file called 7za.dll in the same directory as this assembly.
        ///           If not found, we give up and fail.
        /// </remarks>
        private static string GetLibraryPath()
        {
            if (_libraryFileName != null && (_modulePtr != IntPtr.Zero || File.Exists(_libraryFileName)))
            {
                return(_libraryFileName);
            }

            string default7zPath = null;

#if !WINCE && !MONO
            var sevenZipLocation = ConfigurationManager.AppSettings["7zLocation"];
            if (!string.IsNullOrEmpty(sevenZipLocation) && File.Exists(sevenZipLocation))
            {
                _libraryFileName = sevenZipLocation;
                return(_libraryFileName);
            }
            default7zPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
#endif
#if WINCE
            default7zPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var sevenZipLocation = Path.Combine(default7zPath, "7z.dll");
            if (File.Exists(sevenZipLocation))
            {
                _libraryFileName = sevenZipLocation;
                return(_libraryFileName);
            }
            var bitness = "arm";
#else
            var bitness = IntPtr.Size == 4 ? "x86" : "x64";
#endif
            var thisType = typeof(SevenZipLibraryManager);
#if WINCE
            _libraryFileName = sevenZipLocation;
#else
            var version = thisType.Assembly.GetName().Version.ToString(3);
            _libraryFileName = Path.Combine(Path.GetTempPath(), String.Join(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), new string[] { "SevenZipSharp", version, bitness, "7z.dll" }));
#endif
            if (File.Exists(_libraryFileName))
            {
                return(_libraryFileName);
            }

            //NOTE: This is the approach used in https://github.com/jacobslusser/ScintillaNET for handling the native component.
            //      I liked it, so I added it to this project.  We could have a build configuration that doesn't embed the dlls
            //      to make our assembly smaller and future proof, but you'd need to handle distributing and setting the dll yourself.
            // Extract the embedded DLL http://stackoverflow.com/a/768429/2073621
            // Synchronize access to the file across processes http://stackoverflow.com/a/229567/2073621
            var guid = ((GuidAttribute)thisType.Assembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(CultureInfo.InvariantCulture);
            var name = string.Format(CultureInfo.InvariantCulture, "Global\\{{{0}}}", guid);
            using (var mutex = new Mutex(false, name))
            {
#if !WINCE
                var access   = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var security = new MutexSecurity();
                security.AddAccessRule(access);
                mutex.SetAccessControl(security);
#endif
                var ownsHandle = false;
                try
                {
                    try
                    {
                        ownsHandle = mutex.WaitOne(5000, false); // 5 sec
                        if (!ownsHandle)
                        {
                            var timeoutMessage = string.Format(CultureInfo.InvariantCulture, "Timeout waiting for exclusive access to '{0}'.", _libraryFileName);
                            throw new TimeoutException(timeoutMessage);
                        }
                    }
#if WINCE
                    catch
#else
                    catch (AbandonedMutexException)
#endif
                    {
                        // Previous process terminated abnormally
                        ownsHandle = true;
                    }

                    // Double-checked (process) lock
                    if (File.Exists(_libraryFileName))
                    {
                        return(_libraryFileName);
                    }

                    // Write the embedded file to disk
                    var directory = Path.GetDirectoryName(_libraryFileName);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Exception ex = null;
                    try
                    {
#if WINCE
                        var resource = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.7z.dll.gz", thisType.Assembly.GetName().Name, bitness); //packing of resources differ
#else
                        var resource = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.7z.dll.gz", thisType.Namespace, bitness);               //packing of resources differ
#endif
                        var resourceStream = thisType.Assembly.GetManifestResourceStream(resource);
                        if (resourceStream == null)
                        {
                            ex = new InvalidProgramException(string.Format("Could not extract resource named '{0}' from assembly '{1}'", resource, thisType.Assembly.FullName));
                        }
                        else
                        {
                            using (var gzipStream = new GZipStream(resourceStream, System.IO.Compression.CompressionMode.Decompress))
                            {
                                using (var fileStream = File.Create(_libraryFileName))
                                {
                                    //Would normally use gzipStream.CopyTo(fileStream) but this is .NET 2.0 compliant.
                                    var buffer = new byte[4096];
                                    int count;
                                    while ((count = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        fileStream.Write(buffer, 0, count);
                                    }
                                    return(_libraryFileName);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ex = e;
                        if (File.Exists(_libraryFileName))
                        {
                            File.Delete(_libraryFileName);
                        }
                    }
#if !WINCE
                    if (default7zPath != null)
                    {
                        var testPath = Path.Combine(default7zPath, String.Concat(bitness, Path.DirectorySeparatorChar, "7z.dll"));
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, String.Concat(bitness, Path.DirectorySeparatorChar, "7za.dll"));
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        var bitnessSansX           = IntPtr.Size == 4 ? "86" : "64";
                        var sevenZipWithBitDllName = string.Format(CultureInfo.InvariantCulture, "7z{0}.dll", bitnessSansX);
                        testPath = Path.Combine(default7zPath, sevenZipWithBitDllName);
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        var sevenZipAWithBitDllName = string.Format(CultureInfo.InvariantCulture, "7za{0}.dll", bitnessSansX);
                        testPath = Path.Combine(default7zPath, sevenZipAWithBitDllName);
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, "7z.dll");
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, "7za.dll");
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                    }
#endif
                    _libraryFileName = null;
                    throw new SevenZipLibraryException("Unable to locate the 7z.dll. Please call SetLibraryPath() or set app.config AppSetting '7zLocation' " +
                                                       "which must be path to the proper bit 7z.dll", ex);
                }