//static System.Diagnostics.Process currentProcess = null;

        /// <summary>
        /// If it return false, exit program.  (ex. call if (Application.Current != null) { Application.Current.Shutdown(); })
        /// </summary>
        public static bool TryGetMutexOnTheBeginningOfApplicationConstructor()
        {
            // Refer to: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
            var entryAssemblyFullName = Assembly.GetEntryAssembly().FullName;

            mutex = new System.Threading.Mutex(false, entryAssemblyFullName);
            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            if (mutex.WaitOne(TimeSpan.Zero, false))
            {
                //currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                //currentProcess.Exited += (sender, e) => { ReleaseMutex(); };
                return(true);
            }

            mutex.Close();
            mutex = null;
            return(false);
        }
예제 #2
0
파일: Program.cs 프로젝트: khonsoe/keymagic
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            string title = "KeyMagic";

            bool beta = Properties.Settings.Default.BetaRelease;

            if (beta) title += " (beta)";

            string mutexName = "\u1000\u1001";

            // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
            using (var mutex = new Mutex(false, mutexName))
            {
                // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
                // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                //edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        // note, you may want to time out here instead of waiting forever
                        //edited by acidzombie24
                        //mutex.WaitOne(Timeout.Infinite, false);
                        hasHandle = mutex.WaitOne(100, false);
                        if (hasHandle == false) //another instance exist
                        {
                            IntPtr pWnd = NativeMethods.FindWindow(null, title);
                            if (pWnd != IntPtr.Zero)
                            {
                                NativeMethods.ShowWindow(pWnd, 0x05);
                            }
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                    }

                    frmMain f = new frmMain();
                    Application.Run();
                }
                finally
                {
                    //edit by acidzombie24, added if statemnet
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
예제 #3
0
        public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity)
        {
            if (mutex == null)
            {
                throw new ArgumentNullException(nameof(mutex));
            }

            mutex.SetAccessControl(mutexSecurity);
        }
예제 #4
0
        private void InitMutex(Guid appGuid)
        {
            var mutexId = string.Format("Global\\{{{0}}}", appGuid);
            _mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
예제 #5
0
        private void InitMutex()
        {
            var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
            var mutexId = string.Format("Global\\{{{0}}}", appGuid);
            _mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
예제 #6
0
        public static bool TryGetMutex()
        {
            //source: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c

            // get application GUID as defined in AssemblyInfo.cs
            //string appGuid = "SjUpdater\\v" +Assembly.GetExecutingAssembly().GetName().Version.Major;
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            mutex = new Mutex(false, mutexId);

            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            // edited by acidzombie24
            try
            {
                try
                {
                    // note, you may want to time out here instead of waiting forever
                    // edited by acidzombie24
                    // mutex.WaitOne(Timeout.Infinite, false);
                    hasHandle = mutex.WaitOne(5000, false);
                    if (hasHandle == false)
                        throw new TimeoutException("Timeout waiting for exclusive access");
                }
                catch (AbandonedMutexException)
                {
                    // Log the fact the mutex was abandoned in another process, it will still get aquired
                    hasHandle = true;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);
            using (var mutex = new Mutex(false, mutexId))
            {

                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                // edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(2000, false);
                        if (hasHandle == false)
                        {
                            MessageBox.Show("osu!StreamCompanion is already running.", "Error");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        hasHandle = true;
                    }
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    AppDomain.CurrentDomain.UnhandledException +=
                    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    _initializer = new Initializer();
                    _initializer.Start();
                    Application.Run(_initializer);

                }
                finally
                {
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
예제 #8
0
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            client = new WlanClient();
            //Miofile = "C:\\" + DateTime.Now.ToLongDateString() + "-" +DateTime.Now.ToShortTimeString() + "_catture.txt";
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");

            // Initialize data structure
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = default_interval;
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");

            //initialize the mutex
            mut = new Mutex(false,"Global\\ServiceMutex");
            MutexSecurity mSec = mut.GetAccessControl();
            var rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                               MutexRights.Modify
                                | MutexRights.Synchronize
                                | MutexRights.TakeOwnership
                                | MutexRights.ReadPermissions,
                               AccessControlType.Allow);
            mSec.AddAccessRule(rule);
            mut.SetAccessControl(mSec);
            // Set the time interval

            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");
            // File Mapping creation
            try
            {
                mmf = MemoryMappedFile.CreateNew("Global\\Broadcast", MappedFileDimension, MemoryMappedFileAccess.ReadWrite);
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText("c:\\catture.txt", e.ToString());
            }
            var mmfSec = mmf.GetAccessControl();
            mmfSec.SetAccessRule(new AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null),MemoryMappedFileRights.FullControl | MemoryMappedFileRights.Read, AccessControlType.Allow));
            mmf.SetAccessControl(mmfSec);
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");
            stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.ReadWrite);
            //System.IO.File.AppendAllText("c:\\catture.txt", "FINISCO PARTENZA\r\n");

            aTimer.Enabled = true;
        }
예제 #9
0
		public void CanSetAndGetMutexSecurity ()
		{
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore (); return;
			}

			MutexAccessRule rule; SecurityIdentifier sid;
			AuthorizationRuleCollection rulesA, rulesB, rulesC;
			bool createdNew; MutexSecurity security;
			string name = @"Local\MonoTestMutex";

			using (Mutex mutex = new Mutex(false, name, out createdNew)) {
				Assert.IsTrue (createdNew);

				security = mutex.GetAccessControl ();
				rulesA = security.GetAccessRules (true, false, typeof (SecurityIdentifier));
				Assert.AreNotEqual (0, rulesA.Count);

				// Contrary to what you'd expect, these classes only try to persist sections that
				// that were *changed*. Awful, eh? To be fair, if you retrieve and modify it's fine.
				security = new MutexSecurity ();
				mutex.SetAccessControl (security);

				security = mutex.GetAccessControl ();
				rulesB = security.GetAccessRules (true, false, typeof (SecurityIdentifier));
				Assert.AreEqual (rulesA.Count, rulesB.Count);

				// And here's our dummy change. Observe...
				sid = new SecurityIdentifier( "S-1-5-12-3456-7890");
				rule = new MutexAccessRule (sid, MutexRights.Synchronize, AccessControlType.Allow);

				security = new MutexSecurity ();
				security.RemoveAccessRuleSpecific (rule);
				mutex.SetAccessControl (security);

				security = mutex.GetAccessControl ();
				rulesC = security.GetAccessRules (true, false, typeof (SecurityIdentifier));
				Assert.AreEqual (0, rulesC.Count);
			}
		}
예제 #10
0
        public void CreateMutex(int timeOut = 100)
        {
            // Получаем GUID и формируем имя мутекса
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);
            // Создание мутекса
            mutex = new Mutex(false, mutexId);

            // Установка прав доступа к нему
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);
            try {
                // Попытка получить эксклюзивный доступ к мутексу с таким именем (если не получится, значит нас опередили)
                Success = mutex.WaitOne(timeOut, false);

            } catch (AbandonedMutexException) {
                // "Брошенный" мутекс (видимо завершили задачу в "Диспетчер задач")
                Success = true;
            }
        }
예제 #11
0
        protected GatewayBase(string mutexName, Guid uniqueIdentifier, int timeout, string customError, bool doNotAutoEnter)
        {
            if (string.IsNullOrWhiteSpace(mutexName)) throw new ArgumentException("mutexName cannot be empty");
            if (uniqueIdentifier == Guid.Empty) throw new ArgumentException("uniqueIdentifier cannot be empty");

            MutexName = mutexName;
            UniqueIdentifier = uniqueIdentifier.ToString().ToUpperInvariant();

            UniqueId = MutexName + UniqueIdentifier;
            mutexId = string.Format("Global\\{{{0}}}", UniqueId);
            mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            if (!doNotAutoEnter)
            {
                Enter(timeout, customError);
            }
        }
예제 #12
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            if (this.MutexName.StartsWith("Global\\"))
                throw new BuildException("Do not prefix the mutex ID with \"Global\\\". A global mutex is obtained by setting the property \"global\" to \"true\" (which is the default).");

            // A global mutex requires the prefix "Global\\"
            string mname = !this.Global ? this.MutexName : string.Format("Global\\{0}", this.MutexName);

            var mutex = new Mutex(false, mname);

            // A true global mutex needs some security settings
            if (this.Global)
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);
            }

            try
            {
                if (!mutex.WaitOne(this.Timeout)) throw new BuildException("Timeout waiting on mutex \"" + mname + "\".");
            }
            catch (AbandonedMutexException)
            {
                this.Log(Level.Warning, "A previous process abandoned mutex \"{0}\"", mname);
            }

            try
            {
                this.ExecuteChildTasks();
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
예제 #13
0
    /// <summary>
    /// Check if an application is running or not
    /// </summary>
    /// <returns>returns true if already running</returns>
    public static bool IsAlreadyRunning(string MUTEX_ID, out Mutex mutex)
    {
      // Allow only one instance
      mutex = new Mutex(false, MUTEX_ID);

      var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                  MutexRights.FullControl, AccessControlType.Allow);
      var securitySettings = new MutexSecurity();
      securitySettings.AddAccessRule(allowEveryoneRule);
      mutex.SetAccessControl(securitySettings);
      
      bool hasHandle = false;
      try
      {
        // Check if we can start the application
        hasHandle = mutex.WaitOne(500, false);
      }
      catch (AbandonedMutexException)
      {
        // The mutex was abandoned in another process, it will still get aquired
        hasHandle = true;
      }
      return !hasHandle;
    }
예제 #14
0
        private void Go()
        {
            _mutex = new Mutex(false, Kernel.MBSERVICE_MUTEX_ID);
            {
                //set up so everyone can access
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                try
                {
                    //don't bomb if this fails
                    securitySettings.AddAccessRule(allowEveryoneRule);
                    _mutex.SetAccessControl(securitySettings);
                }
                catch (Exception e)
                {
                    //just log the exception and go on
                    Logger.ReportException("Failed setting access rule for mutex.", e);
                }
                try
                {
                    try
                    {
                        _hasHandle = _mutex.WaitOne(5000, false);
                        if (_hasHandle == false)
                        {
                            if (App.Args.Length > 0 && App.Args[0].ToLower() == "/refresh") MBServiceController.SendCommandToService(IPCCommands.Refresh); //send on command
                            _forceClose = true;
                            this.Close(); //another instance exists
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get acquired
                        Logger.ReportWarning("Previous instance of service ended abnormally...");
                    }
                    this.WindowState = WindowState.Minimized;
                    Hide();
                    Kernel.Init(KernelLoadDirective.LoadServicePlugins);
                    _config = Kernel.Instance.ServiceConfigData;
                    //in case we crashed during a re-build...
                    _config.ForceRebuildInProgress = false;
                    _config.RefreshFailed = false; //reset this too
                    _config.Save();
                    CreateNotifyIcon();
                    RefreshInterface();
                    lblSinceDate.Content = "Since: "+_startTime;
                    CoreCommunications.StartListening(); //start listening for commands from core/configurator
                    //if (Kernel.Instance.ConfigData.UseSQLImageCache)
                    //{
                    //    //start the image server
                    //    Logger.ReportInfo("Starting SQL Image server on port: " + imagePort);
                    //    imageServer = new ImageCacheProxy(imagePort, 10);
                    //    imageServer.Start();
                    //}
                    Logger.ReportInfo("Service Started");
                    _mainLoop = Async.Every(60 * 1000, () => MainIteration()); //repeat every minute

                    if (App.Args.Length > 0 && App.Args[0].ToLower() == "/refresh") RefreshNow(); //kick off refresh if requested
                }
                catch (Exception e) //some sort of error - release
                {
                    if (_hasHandle)
                    {
                        _mutex.ReleaseMutex();
                    }
                    Logger.ReportException("Error initializing service.", e);
                    _forceClose = true;
                    this.Close();
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Provides a record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            //// Encode and encrypt the message with spoofed entropy

            Cryptkeeper mycrypt = new Cryptkeeper(this.Passphrase);
            byte[] cipherbytes = mycrypt.GetBytes(this.Message, Cryptkeeper.Action.Encrypt);

            int length = cipherbytes.Length;
            if (this.TargetEntropy > 0) length = length * 3;

            byte[] bytes = ShannonEntropy.Spoof(cipherbytes, this.TargetEntropy, length);

            //// Create a Memory Mapped File without an actual file

            string mappedName = string.Concat("Global\\", this.Mutex);
            string mutexName = string.Concat("Global\\{0}", this.Mutex, "-mutex");

            MemoryMappedFile map;
            try
            {
                map = MemoryMappedFile.CreateOrOpen(mappedName, bytes.Length, MemoryMappedFileAccess.ReadWrite);
            }
            catch (Exception ex)
            {
                this.WriteWarning(ex.Message);
                return;
            }

            // Define an access rules such that all processes on the OS can access it
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            // Grab the mutex and set the access rules
            Mutex mutex = new Mutex(false, mutexName);
            mutex.SetAccessControl(securitySettings);
            mutex.WaitOne();

            // Write the bytes
            BinaryWriter writer = new BinaryWriter(map.CreateViewStream(0, bytes.Length, MemoryMappedFileAccess.ReadWrite));
            writer.Write(bytes);
            writer.Close();
            mutex.ReleaseMutex();

            Console.WriteLine("Please check for the message now. Once you continue, the message will be scheduled for garbage collection.");
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
            Console.WriteLine();

            mutex.Dispose();
        }
 public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity)
 {
     mutex.SetAccessControl(mutexSecurity);
 }
예제 #17
0
            private Mutex CreateMutex()
            {
            	m_mutexname = GetMutexName(m_filename);

                try
                {
                    // Open the mutex.
                    m_mutex = Mutex.OpenExisting(m_mutexname);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    // The named mutex does not exist.
                    MutexSecurity mSec = new MutexSecurity();

                    MutexAccessRule rule = new MutexAccessRule(
                        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                        MutexRights.FullControl, AccessControlType.Allow);
                    mSec.AddAccessRule(rule);

                	bool mutexWasCreated;
                	m_mutex = new Mutex(false, m_mutexname, out mutexWasCreated, mSec);
                }
                catch (UnauthorizedAccessException)
                {
                    // The named mutex exists, but the user does not have the security access required to use it.
                    LogLog.Warn("The named mutex exists, but the user does not have the security access required to use it.");
                    try
                    {
                        m_mutex = Mutex.OpenExisting(m_mutexname, MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                        // Get the current ACL. This requires MutexRights.ReadPermissions.
                        MutexSecurity mSec = m_mutex.GetAccessControl();

                        // Now grant the user the correct rights.
                        MutexAccessRule rule = new MutexAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null), 
                            MutexRights.FullControl, AccessControlType.Allow);
                        mSec.AddAccessRule(rule);

                        // Update the ACL. This requires MutexRights.ChangePermissions.
                        m_mutex.SetAccessControl(mSec);

                        LogLog.Debug("Updated mutex security.");

                       m_mutex = Mutex.OpenExisting(m_mutexname);

                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        LogLog.Error("Unable to change permissions on mutex.", ex);
                        m_mutex = new Mutex(false, m_mutexname);
                    }
                }

                return m_mutex;
            }
예제 #18
0
파일: Program.cs 프로젝트: smo-key/NXTLib
        static void Main(string[] args)
        {
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var mutex = new Mutex(false, mutexId))
            {
                // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
                // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                // edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        // note, you may want to time out here instead of waiting forever
                        // edited by acidzombie24
                        // mutex.WaitOne(Timeout.Infinite, false);
                        hasHandle = mutex.WaitOne(500, false);
                        if (hasHandle == false)
                        {
                            if (args.Count() == 1)
                            {
                                if (args[0] == "update")
                                {
                                    //TODO: send message to pipe
                                    NamedPipeClientStream pipe = new NamedPipeClientStream(".", "NXTLibTesterGUI_forceupdatepipe", PipeDirection.Out);
                                    StreamWriter sw = new StreamWriter(pipe);
                                    pipe.Connect();
                                    sw.AutoFlush = true;
                                    sw.WriteLine("Force Update Now!");
                                    pipe.WaitForPipeDrain();
                                    pipe.Dispose();
                                }
                                return;
                            }

                            MessageBox.Show("Application already running!  Close the other instance and try again.",
                                   "Application Running", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                        hasHandle = true;
                    }

                    FindNXT.updatewaiting = false;
                    if (args.Count() == 1)
                    {
                        if (args[0] == "update")
                        {
                            FindNXT.updatewaiting = true;
                        }
                    }

                    // Perform your work here.
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FindNXT());
                }
                finally
                {
                    // edited by acidzombie24, added if statemnet
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
예제 #19
0
        private void InitMutex()
        {
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);
            mutex = new Mutex(false, mutexId);

            try
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);
            }
            catch (PlatformNotSupportedException)
            {
                System.Diagnostics.Trace.WriteLine("Unable to set mutex security");
            }
        }
예제 #20
0
        public void Launch(AddInHost host)
        {
            //  uncomment to debug
#if DEBUG
            host.MediaCenterEnvironment.Dialog("Attach debugger and hit ok", "debug", DialogButtons.Ok, 100, true); 
#endif

            using (Mutex mutex = new Mutex(false, Kernel.MBCLIENT_MUTEX_ID))
            {
                //set up so everyone can access
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                try
                {
                    //don't bomb if this fails
                    securitySettings.AddAccessRule(allowEveryoneRule);
                    mutex.SetAccessControl(securitySettings);
                }
                catch (Exception)
                {
                    //we don't want to die here and we don't have a logger yet so just go on
                }
                try
                {
                    if (mutex.WaitOne(100,false))
                    {

                        var config = GetConfig();
                        if (config == null)
                        {
                            AddInHost.Current.ApplicationContext.CloseApplication();
                            return;
                        }

                        Environment.CurrentDirectory = ApplicationPaths.AppProgramPath;
                        using (new Util.Profiler("Total Kernel Init"))
                        {
                            Kernel.Init(config);
                            while (!Kernel.ServerConnected)
                            {
                                if (!Kernel.ServerConnected)
                                {
                                    if (host.MediaCenterEnvironment.Dialog("Could not connect to Media Browser 3 Server.  Please be sure it is running on the local network.\n\nWould you like to re-try?", "Error", DialogButtons.Yes | DialogButtons.No, 100, true) != DialogResult.No)
                                    {
                                        Kernel.ConnectToServer(config);
                                    }
                                    else
                                    {
                                        AddInHost.Current.ApplicationContext.CloseApplication();
                                        return;
                                    }
                                }
                            }
                        }
                        using (new Util.Profiler("Application Init"))
                        {
                            App = new Application(new MyHistoryOrientedPageSession(), host);

                            App.Init();
                        }

                        Kernel.Instance.OnApplicationInitialized();

                        mutex.ReleaseMutex();
                    }
                    else
                    {
                        //another instance running and in initialization - just blow out of here
                        Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
                        return;
                    }

                }
                catch (AbandonedMutexException)
                {
                    // Log the fact the mutex was abandoned in another process, it will still get acquired
                    Logger.ReportWarning("Previous instance of core ended abnormally...");
                    mutex.ReleaseMutex();
                }
            }
        }
예제 #21
0
        private static bool LaunchInt(string filename)
        {
            string mutexId = "Global\\foxScreenMutex";

            mutex = new Mutex(false, mutexId);

            MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            MutexSecurity securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            bool hasHandle = false;
            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(100, false);
                    if (hasHandle == false)
                    {
                        mutex = null;
                        return false;
                    }
                }
                catch (AbandonedMutexException)
                {
                    hasHandle = true;
                }

                uploadOrganizer = new UploadOrganizer();
                screenshotManager = new ScreenshotManager(uploadOrganizer);

                if (filename != null)
                {
                    if (LoadCredentials())
                    {
                        uploadOrganizer.AddFileUpload(filename);
                    }
                }

                mainFrm = new frmMain();
                Application.Run(mainFrm);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.ToString());
                if (!hasHandle)
                {
                    mutex = null;
                }
                Stop();
            }

            return true;
        }
예제 #22
0
        private void CreateExcel(DateTime date)
        {
            DateTime dtNow = DateTime.Now;

            bool createdNew = false;
            using (Mutex mutex = new Mutex(false, "Global\\CreateExcel", out createdNew))
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                bool hasHandle = false;

                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne();

                        if (hasHandle == false)
                            throw new TimeoutException("Timeout waiting for exclusive access");
                    }
                    catch (AbandonedMutexException)
                    { hasHandle = true; }

                    objExcelSummary = new Application();

                    objWorkbookSummary = objExcelSummary.Workbooks.Add(System.Reflection.Missing.Value);

                    string spacer =
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString() +
                        Convert.ToChar(32).ToString();


                    // DELETE EXTRA SHEETS
                    //((Worksheet)objWorkbookSummary.Sheets[3]).Delete();
                    //((Worksheet)objWorkbookSummary.Sheets[2]).Delete();

                    objSummary = ((Worksheet)objWorkbookSummary.Sheets[1]);
                    objSummary.Name = "CALLS";

                    objSummary.PageSetup.PrintGridlines = false;
                    objSummary.PageSetup.CenterHorizontally = true;
                    objSummary.PageSetup.CenterVertically = false;
                    objSummary.PageSetup.FitToPagesWide = 1;
                    objSummary.PageSetup.FitToPagesTall = false;
                    objSummary.PageSetup.Zoom = false;
                    //objSummary.PageSetup.Zoom = 100;
                    objSummary.PageSetup.TopMargin = objExcelSummary.Application.InchesToPoints(0.50);
                    objSummary.PageSetup.BottomMargin = objExcelSummary.Application.InchesToPoints(0.25);
                    objSummary.PageSetup.LeftMargin = objExcelSummary.Application.InchesToPoints(0.25);
                    objSummary.PageSetup.RightMargin = objExcelSummary.Application.InchesToPoints(0.25); //0.25
                    objSummary.PageSetup.Orientation = XlPageOrientation.xlLandscape;

                    objSummary.PageSetup.HeaderMargin = objExcelSummary.Application.InchesToPoints(0.00);
                    objSummary.PageSetup.FooterMargin = objExcelSummary.Application.InchesToPoints(0.00);
                    //objSummary.PageSetup.RightFooter = "Page &P of &N";
                    //objSummary.PageSetup.RightFooter = "Run date for " + date.ToString("MMM/dd");
                    objSummary.PageSetup.RightFooter = "Run-Date: " + dtNow.ToString("MMM") + " " + dtNow.Day + GetOrdinal(dtNow.Day) + ", " +
                        dtNow.Year + " for " + date.ToString("MMM") + " " + date.Day + GetOrdinal(date.Day) + ", " + date.Year + Convert.ToChar(32) + Convert.ToChar(32) + Convert.ToChar(32) +
                        Convert.ToChar(13).ToString() + "Page &P of &N" + Convert.ToChar(32) + Convert.ToChar(32) + Convert.ToChar(32) +
                        Convert.ToChar(13).ToString();




                }
                finally
                {
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
예제 #23
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            Console.Title = "GhostBuster Agent";
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Clear();
            ShowHeader();

            // Check GhostBusterAgent is not already running on the system.

            MutexSecurity oMutexSecurity;

            //Set the security object
            oMutexSecurity = new MutexSecurity();
            oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow));

            //Create the global mutex and set its security
            bool firstInstance;
            Mutex moGlobalMutex = new Mutex(true, "Global\\{5076d41c-a40a-4f4d-9eed-bf274a5bedcb}", out firstInstance);
            moGlobalMutex.SetAccessControl(oMutexSecurity);

            if (!firstInstance)
            {
                Log.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("GhostBusterAgent is already running in this session or another session.");
                Console.WriteLine("Only one instance of GhostBusterAgent can run on a machine.");
                Console.WriteLine("This agent is not active and is only being used to report this error.");
                Log.WriteLine();
                Console.WriteLine("Press <enter> to quit.");
                Console.ReadLine();
                return;
            }

            #region Testing
            //Stopwatch sw = new Stopwatch();
            //GhostCastManager gcm = new GhostCastManager();
            //gcm.GetGhostCastSessions();
            //sw.Start();//\/\/\/\/\//\/\/\/\/\/\/\/\/\/\/
            //List<GhostCastSession> l = gcm.GetGhostCastSessionsFiltered("1");
            //int i = l.Count;
            //sw.Stop();//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            //Console.WriteLine("Total: " + sw.Elapsed.TotalMilliseconds);
            //sw.Reset();
            //sw.Start();//\/\/\/\/\//\/\/\/\/\/\/\/\/\/\/
            //sw.Stop();//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            //Console.WriteLine("Total: " + sw.Elapsed.TotalMilliseconds);
            //Console.ReadKey();
            //return;
            #endregion

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(GhostCastManager), BaseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                {
                    smb = new ServiceMetadataBehavior();
                    host.Description.Behaviors.Add(smb);
                }

                //Set Service Debug Behavior
                ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (sdb == null)
                {
                    sdb = new ServiceDebugBehavior();
                    sdb.IncludeExceptionDetailInFaults = true;
                    host.Description.Behaviors.Add(sdb);
                }
                else
                {
                    sdb.IncludeExceptionDetailInFaults = true;
                }

                // Add service end points.
                Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
                host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

                NetTcpBinding ntb = new NetTcpBinding();
                ntb.TransferMode = TransferMode.Streamed;
                ntb.Security.Mode = SecurityMode.None;
                ntb.ReceiveTimeout = TimeSpan.MaxValue;
                ntb.MaxReceivedMessageSize = long.MaxValue;

                host.AddServiceEndpoint(typeof(IGhostCastManager), ntb, "GhostCastManager");

                // Open the socket.
                host.Open();

                Log.Write(String.Format("The service is ready at {0}", BaseAddress));
                Log.Write("CLI Commands;");
                Log.Write(" 'show': Display agent details.");
                Log.Write(" 'exit': Close the agent.");
                Log.WriteLine();

                string userInput;
                while (true)
                {
                    userInput = Console.ReadLine();
                    if (userInput.ToUpper() == "SHOW")
                    {
                        ShowHeader();
                        if (Alert.RegisteredEmailAlerts.Count > 0)
                        {
                            Log.Write("List of registered e-mail alerts;");
                            foreach (Alert a in Alert.RegisteredEmailAlerts)
                            {
                                Log.Write(String.Format("Process Id: {0} Email Address: {1} Close On Completion: {2}", a.ProcessId, a.EmailAddress, a.CloseOnCompletion));
                            }
                        }
                    }
                    if (userInput.ToUpper() == "EXIT")
                    {
                        break;
                    }
                }

                // Close the ServiceHost.
                host.Close();
            }
        }
        private static void StartIfNotRunning()
        {
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var mutex = new Mutex(false, mutexId))
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(5000, false);
                        if (hasHandle == false)
                            {
                                Console.WriteLine("Instance already running, timeout expired");
                                return;
                            }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                        hasHandle = true;
                    }

                    if (IsService)
                    {
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[]
                        {
                            new Service()
                        };
                        ServiceBase.Run(ServicesToRun);
                    }
                    else
                    {
                        Run();
                    }
                }
                finally
                {
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
        private static void StartOrSignal(Action Run)
        {
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format(useGlobalMutex ? "Global\\{{{0}}}" : "{{{0}}}", appGuid);
            string SingleAppComEventName = mutexId + "_event";

            BackgroundWorker singleAppComThread = null;
            EventWaitHandle threadComEvent = null;

            using (var mutex = new Mutex(false, mutexId))
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(1000, false);
                        if (hasHandle == false)
                        {
                            Debug.WriteLine("Instance already running, timeout expired");

                            threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName);
                            threadComEvent.Set();  // signal the other instance.
                            threadComEvent.Close();

                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                        hasHandle = true;
                    }
                    threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName);

                    singleAppComThread = new BackgroundWorker();
                    singleAppComThread.WorkerReportsProgress = false;
                    singleAppComThread.WorkerSupportsCancellation = true;
                    singleAppComThread.DoWork += (object sender, DoWorkEventArgs e) =>
                        {
                            BackgroundWorker worker = sender as BackgroundWorker;
                            WaitHandle[] waitHandles = new WaitHandle[] { threadComEvent };

                            while (!worker.CancellationPending && !_Closing)
                            {
                                // check every second for a signal.
                                if (WaitHandle.WaitAny(waitHandles, 1000) == 0)
                                {
                                    // The user tried to start another instance. We can't allow that,
                                    // so bring the other instance back into view and enable that one.
                                    // That form is created in another thread, so we need some thread sync magic.
                                    if (OnAdditionalInstanceSignal != null)
                                        OnAdditionalInstanceSignal(sender, new EventArgs());
                                }
                            }
                        };
                    singleAppComThread.RunWorkerAsync();

                    Run();

                    singleAppComThread.CancelAsync();
                    while (singleAppComThread.IsBusy)
                        Thread.Sleep(50);
                    threadComEvent.Close();

                }
                finally
                {
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
        public void Launch(AddInHost host)
        {
            //  uncomment to debug
            #if DEBUG
            host.MediaCenterEnvironment.Dialog("Attach debugger and hit ok", "debug", DialogButtons.Ok, 100, true);
            #endif

            using (Mutex mutex = new Mutex(false, Kernel.MBCLIENT_MUTEX_ID))
            {
                //set up so everyone can access
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                try
                {
                    //don't bomb if this fails
                    securitySettings.AddAccessRule(allowEveryoneRule);
                    mutex.SetAccessControl(securitySettings);
                }
                catch (Exception)
                {
                    //we don't want to die here and we don't have a logger yet so just go on
                }
                try
                {
                    if (mutex.WaitOne(100,false))
                    {

                        var config = GetConfig();
                        if (config == null)
                        {
                            Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
                            return;
                        }

                        Environment.CurrentDirectory = ApplicationPaths.AppConfigPath;
                        try
                        {
                            CustomResourceManager.SetupStylesMcml(host);
                            CustomResourceManager.SetupFontsMcml(host);
                        }
                        catch (Exception ex)
                        {
                            host.MediaCenterEnvironment.Dialog(ex.Message, Application.CurrentInstance.StringData("CustomErrorDial"), DialogButtons.Ok, 100, true);
                            Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
                            return;
                        }
                        using (new MediaBrowser.Util.Profiler("Total Kernel Init"))
                        {
                            Kernel.Init(config);
                        }
                        using (new MediaBrowser.Util.Profiler("Application Init"))
                        {
                            Application app = new Application(new MyHistoryOrientedPageSession(), host);

                            app.GoToMenu();
                        }
                        mutex.ReleaseMutex();
                    }
                    else
                    {
                        //another instance running and in initialization - just blow out of here
                        Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
                        return;
                    }

                }
                catch (AbandonedMutexException)
                {
                    // Log the fact the mutex was abandoned in another process, it will still get acquired
                    Logger.ReportWarning("Previous instance of core ended abnormally...");
                    mutex.ReleaseMutex();
                }
            }
        }
예제 #27
0
파일: Program.cs 프로젝트: jlami/mutefm
        static void Main(string[] args)
        {
            /*
            if (System.DateTime.Compare(DateTime.Now, new DateTime(MuteFm.Constants.ExpireYear, MuteFm.Constants.ExpireMonth, MuteFm.Constants.ExpireDay, 23, 59, 59, DateTimeKind.Utc)) > 0)
            {
                MessageBox.Show("This version of mute.fm is beta software and has expired.  Thanks for demoing!  Get a new version at http://www.mute.fm/");
                return;
            }*/

            MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg(Constants.ProgramName + " loaded!");

            if (System.Environment.CommandLine.ToUpper().Contains("FIRSTTIME"))
                FirstTime = true;

            if (System.Environment.CommandLine.ToUpper().Contains("SERVICE"))
                IsService = true;

            if ((args.Length > 0) && (args[0].ToUpper().Contains("INTERNALBUILDMODE")))
                InternalBuildMode = true;

            // Initialize Awesomium (the browser control)
            /*            if (Awesomium.Core.WebCore.IsChildProcess)
            {
                Awesomium.Core.WebCore.ChildProcessMain();
                return;
            }*/
            #if !NOAWE
            Awesomium.Core.WebConfig config = new Awesomium.Core.WebConfig();
            //            config.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36";
            //TODO-AWE config.EnableDatabases = true;
            //TODO-AWE config.SaveCacheAndCookies = true;
            //config.LogLevel = Awesomium.Core.LogLevel.Verbose;

            #if !DEBUG
            config.LogLevel = Awesomium.Core.LogLevel.None;
            #else
            config.LogLevel = Awesomium.Core.LogLevel.Normal;
            #endif
            if (!InternalBuildMode)
            {
                string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                config.ChildProcessPath = path  +"/mute_fm_web";
                //TODO-AWE config.ChildProcessPath = Awesomium.Core.WebConfig.CHILD_PROCESS_SELF;
            }
            Awesomium.Core.WebCore.Initialize(config);
            #endif
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var mutex = new Mutex(false, mutexId))
            {
                // note: some of this is Windows-only

                // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
                // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                //edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        // note, you may want to time out here instead of waiting forever
                        //edited by acidzombie24
                        //mutex.WaitOne(Timeout.Infinite, false);
                        hasHandle = mutex.WaitOne(500, false); // was 5000 here

                        // We just show a UI here
                        if (hasHandle == false)
                        {
                            //MessageBox. Show(Constants.ProgramName + " is already running.  You can access it via the system tray.");
                            MuteFm.UiPackage.PlayerForm playerForm = new UiPackage.PlayerForm();
                            playerForm.Show();
                            playerForm.Init(true);
                            Application.Run(playerForm);
                            Environment.Exit(0);

                            //MessageBox. Show(Constants.ProgramName + " is already running.  You can access it via the system tray or the " + Constants.ProgramName + " Google Chrome extension.");
                            //Environment.Exit(1);
                            //throw new TimeoutException("Timeout waiting for exclusive access");
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                        hasHandle = true;
                    }

                    // Perform your work here.
                    Init(args);
                }
                finally
                {
                    //edit by acidzombie24, added if statemnet
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }

                //SmartVolManagerPackage.SoundServer.RestoreVolumes();
                Environment.Exit(0);
            }
        }
예제 #28
0
		public void PermissionsActuallyWork ()
		{
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore (); return;
			}

			bool createdNew; MutexSecurity security;
			string name = @"Local\MonoTestMutex";

			using (Mutex mutex = new Mutex (false, name, out createdNew)) {
				Assert.IsFalse (mutex.SafeWaitHandle.IsInvalid);
				Assert.IsTrue (createdNew);

				// Make sure our later error will be due to permissions and not some sharing bug.
				bool createdAnotherNew;
				using (Mutex anotherMutex = new Mutex (false, name, out createdAnotherNew)) {
					Assert.IsFalse (mutex.SafeWaitHandle.IsInvalid);
					Assert.IsFalse (createdAnotherNew);
				}

				// Let's make a deny all.
				security = mutex.GetAccessControl ();

				foreach (MutexAccessRule rule in security.GetAccessRules
				         (true, false, typeof (SecurityIdentifier))) {
					security.RemoveAccessRuleSpecific (rule);
				}

				Assert.AreEqual (0, security.GetAccessRules (true, false, typeof (SecurityIdentifier)).Count);
				mutex.SetAccessControl (security);

				security = mutex.GetAccessControl ();
				Assert.AreEqual (0, security.GetAccessRules (true, false, typeof (SecurityIdentifier)).Count);

				// MS.NET will throw on the first line below.
				// For Mono testing the latter verifies the rest until the Mutex bug is fixed.
				// Also, NUnit 2.4 appears to lacks Assert.Pass ().
				Mutex badMutex = new Mutex(false, name);
				if (badMutex.SafeWaitHandle.IsInvalid)
					throw new UnauthorizedAccessException ();
			}
		}
 public static void SetAccessControl(Mutex mutex, MutexSecurity mutexSecurity)
 {
     mutex.SetAccessControl(mutexSecurity);
 }
        private void InitMutex(string mutexId)
        {
            mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);
        }
예제 #31
0
        private static string GetModulePath()
        {
            // UI thread...
            if (modulePath == null)
            {
                // Extract the embedded SciLexer DLL
                // http://stackoverflow.com/a/768429/2073621
                var version = typeof(Scintilla).Assembly.GetName().Version.ToString(3);
                modulePath = Path.Combine(Path.GetTempPath(), "ScintillaNET", version, (IntPtr.Size == 4 ? "x86" : "x64"), "SciLexer.dll");

                if (!File.Exists(modulePath))
                {
                    // http://stackoverflow.com/a/229567/2073621
                    // Synchronize access to the file across processes
                    var guid = ((GuidAttribute)typeof(Scintilla).Assembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
                    var name = string.Format(CultureInfo.InvariantCulture, "Global\\{{{0}}}", guid);
                    using (var mutex = new Mutex(false, name))
                    {
                        var access = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                        var security = new MutexSecurity();
                        security.AddAccessRule(access);
                        mutex.SetAccessControl(security);

                        var ownsHandle = false;
                        try
                        {
                            try
                            {
                                ownsHandle = mutex.WaitOne(5000, false); // 5 sec
                                if (ownsHandle == false)
                                {
                                    var timeoutMessage = string.Format(CultureInfo.InvariantCulture, "Timeout waiting for exclusive access to '{0}'.", modulePath);
                                    throw new TimeoutException(timeoutMessage);
                                }
                            }
                            catch (AbandonedMutexException)
                            {
                                // Previous process terminated abnormally
                                ownsHandle = true;
                            }

                            // Double-checked (process) lock
                            if (!File.Exists(modulePath))
                            {
                                // Write the embedded file to disk
                                var directory = Path.GetDirectoryName(modulePath);
                                if (!Directory.Exists(directory))
                                    Directory.CreateDirectory(directory);

                                var resource = string.Format(CultureInfo.InvariantCulture, "ScintillaNET.{0}.SciLexer.dll.gz", (IntPtr.Size == 4 ? "x86" : "x64"));
                                using (var resourceStream = typeof(Scintilla).Assembly.GetManifestResourceStream(resource))
                                using (var gzipStream = new GZipStream(resourceStream, CompressionMode.Decompress))
                                using (var fileStream = File.Create(modulePath))
                                    gzipStream.CopyTo(fileStream);
                            }
                        }
                        finally
                        {
                            if (ownsHandle)
                                mutex.ReleaseMutex();
                        }
                    }
                }
            }

            return modulePath;
        }
예제 #32
0
        /// <summary>
        /// Creates the mutex that will be held for the duration of the application. The mutex is used to prevent
        /// multiple instances from running. Quits the program if another instance is seen.
        /// </summary>
        /// <returns></returns>
        private static Mutex CheckForOtherRunningInstances(out bool mutexAcquired, bool allowMultipleInstances)
        {
            mutexAcquired = false;
            var result = new Mutex(false, _SingleInstanceMutexName);

            var runtimeEnvironment = Factory.Singleton.Resolve<IRuntimeEnvironment>().Singleton;
            if(!runtimeEnvironment.IsMono) {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                result.SetAccessControl(securitySettings);

                if(!allowMultipleInstances) {
                    try {
                        mutexAcquired = result.WaitOne(1000, false);
                        if(!mutexAcquired) {
                            MessageBox.Show(Strings.AnotherInstanceRunningFull, Strings.AnotherInstanceRunningTitle);
                            Environment.Exit(1);
                        }
                    } catch(AbandonedMutexException) { }
                }
            }

            return result;
        }