Example #1
0
 /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
 public void Dispose()
 {
     Stop();
     _mutex?.ReleaseMutex();
     _mutex?.Dispose();
     _mutex = null;
 }
        static void Main(string[] args)
        {
            string instance = Name + " " + String.Join(" ", args);

            Console.WriteLine("Instance: " + instance);

            // do check arguments here. application can exit for invalid requests before getting mutex.

            var mutex = new Mutex(false, instance);

            Console.Write("Waiting...");

            try
            {
                mutex.WaitOne();

                RunProcess();  // do critical work here
            }
            finally
            {
                mutex.ReleaseMutex();
                mutex.Dispose();
            }

            Console.WriteLine("Closing...");
            Thread.Sleep(2000);  // do some less critical work here
        }
Example #3
0
        public static IEnumerable<TwitterStatus> GetFromCache(TwitterResource resource)
        {
            string fileName = GetCacheName(resource);
            var serializer = new SharpSerializer(SerializerSettings);
            Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName);
            IEnumerable<TwitterStatus> statuses = null;

            if (mutex.WaitOne(1000))
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        statuses = serializer.Deserialize(stream) as IEnumerable<TwitterStatus>;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

            mutex.Dispose();
            return statuses ?? new List<TwitterStatus>();
        }
Example #4
0
        public void Extract()
        {
            TraceUtils.WriteLine("ModuleManager.Extract");

            AssemblyDirectory = Library.Path;

            if (string.IsNullOrEmpty(AssemblyDirectory) || (DirectoryExists(AssemblyDirectory) && Directory.GetFiles(AssemblyDirectory).Length > 0))
                return;

            var mutexName = string.Format(@"Global\{0}-{1}", Id, Library.Id);
            var mutex = new Mutex(false, mutexName);
            mutex.WaitOne();

            try
            {
                CreateDirectory(AssemblyDirectory);
                Modules["AnyCPU_zip"].Extract(AssemblyDirectory);
                if (!Environment.Is64BitProcess)
                {
                    Modules["x32_zip"].Extract(AssemblyDirectory);
                }
                else
                {
                    Modules["x64_zip"].Extract(AssemblyDirectory);
                }
            }
            finally
            {
                mutex.ReleaseMutex();
                mutex.Dispose();
            }
        }
Example #5
0
        static void Main()
        {
            try
            {
                mutex = new Mutex(true, Settings.MutexGuid);
                if (mutex.WaitOne(TimeSpan.Zero, true))

                    try
                    {
                        RunProgram();
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }

                else
                    Platform.User32.PostMessage(

                        (IntPtr)Platform.PlatformApi.HWND_BROADCAST,
                        Platform.PlatformApi.WM_SHOWME,
                        IntPtr.Zero,
                        IntPtr.Zero);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                if (mutex != null)
                    mutex.Dispose();
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppPath = (Application.StartupPath.ToLower());
            AppPath = AppPath.Replace(@"\bin\debug", @"\").Replace(@"\bin\release", @"\");
            AppPath = AppPath.Replace(@"\bin\x86\debug", @"\").Replace(@"\bin\x86\release", @"\");

            AppPath = AppPath.Replace(@"\\", @"\");

            if (!AppPath.EndsWith(@"\"))
                AppPath += @"\";

            if (args.Length > 0)
            {
                ProgramName = args[0];
                AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\" + ProgramName +
                              @"\";
                bool firstInstance;
                var mutex = new Mutex(false, "iSpyMonitor", out firstInstance);
                if (firstInstance)
                    Application.Run(new Monitor());
                mutex.Close();
                mutex.Dispose();
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            bool createdNew = false;

            System.Threading.Mutex m = new System.Threading.Mutex(false, "{BE450405-C3CF-45D3-A1F4-29F0C0A0E02D}", out createdNew);

            if (args.Length > 0)
            {
                try
                {
                    if (createdNew)
                    {
                        m.Dispose();
                        Process p = Process.Start(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

                        p.WaitForInputIdle(10000);
                    }

                    Thread.Sleep(10000);

                    string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SJackHook.dll");

                    List <string> argList = new List <string>();

                    for (int i = 1; i < args.Length; ++i)
                    {
                        if (args[i].Contains(" "))
                        {
                            argList.Add(String.Format("\"{0}\"", args[i]));
                        }
                        else
                        {
                            argList.Add(args[i]);
                        }
                    }

                    string cmdLine = argList.Count > 0 ? String.Join(" ", argList) : null;

                    Detours.CreateProcessWithDll(args[0], cmdLine, dllPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                }
                else
                {
                    MessageBox.Show("Already a copy running");
                }
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            bool createdNew = false;
            System.Threading.Mutex m = new System.Threading.Mutex(false, "{BE450405-C3CF-45D3-A1F4-29F0C0A0E02D}", out createdNew);

            if (args.Length > 0)
            {
                try
                {
                    if (createdNew)
                    {
                        m.Dispose();
                        Process p = Process.Start(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

                        p.WaitForInputIdle(10000);
                    }

                    Thread.Sleep(10000);

                    string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SJackHook.dll");

                    List<string> argList = new List<string>();

                    for (int i = 1; i < args.Length; ++i)
                    {
                        if (args[i].Contains(" "))
                        {
                            argList.Add(String.Format("\"{0}\"", args[i]));
                        }
                        else
                        {
                            argList.Add(args[i]);
                        }
                    }

                    string cmdLine = argList.Count > 0 ? String.Join(" ", argList) : null;

                    Detours.CreateProcessWithDll(args[0], cmdLine, dllPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                }
                else
                {
                    MessageBox.Show("Already a copy running");
                }
            }
        }
Example #9
0
        /// <summary>
        /// Called when the application shuts down.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            if (_mutex != null)
            {
                _mutex.Dispose();
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #region wait for running instance to exit

            do
            {
                bool createdNewMutex;

                Mutex app = new Mutex(true, args[0], out createdNewMutex);

                app.Dispose();

                if (createdNewMutex)
                    break;

                Thread.Sleep(1000);
            }
            while (true);

            #endregion

            try
            {
                string pkgFile;

                switch (Environment.OSVersion.Platform)
                {
                    case PlatformID.Win32NT:
                        pkgFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace("/", "\\")), "update.pkg");
                        break;

                    case PlatformID.Unix:
                        pkgFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file://", "")), "update.pkg");
                        break;

                    default:
                        throw new Exception("Platform not supported.");
                }

                using (Package package = new Package(pkgFile, PackageMode.Open))
                {
                    package.ExtractAll(ExtractLocation.Custom, args[1], true);
                }

                MessageBox.Show("Update was installed successfully. Click OK to continue.", "Update Installed - Technitium Automatic Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while updating application:\r\n\r\n" + ex.Message + "\r\n\r\nChanges were automatically rolled back.", "Update Error - Technitium Automatic Update", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #11
0
        public PortReserver(int basePort = 50231)
        {
            if (basePort <= 0)
            {
                throw new InvalidOperationException();
            }

            // Grab a cross appdomain/cross process/cross thread lock, to ensure only one port is reserved at a time.
            using (Mutex mutex = GetGlobalMutex())
            {
                try
                {
                    int port = basePort - 1;

                    while (true)
                    {
                        port++;

                        if (port > 65535)
                        {
                            throw new InvalidOperationException("Exceeded port range");
                        }

                        // AppDomainOwnedPorts check enables reserving two ports from the same thread in sequence.
                        // ListUsedTCPPort prevents port contention with other apps.
                        if (_appDomainOwnedPorts.Contains(port) ||
                            ListUsedTCPPort().Any(endPoint => endPoint.Port == port))
                        {
                            continue;
                        }

                        string mutexName = "WebStack-Port-" + port.ToString(CultureInfo.InvariantCulture); // Create a well known mutex
                        _portMutex = new Mutex(initiallyOwned: false, name: mutexName);

                        // If no one else is using this port grab it.
                        if (_portMutex.WaitOne(millisecondsTimeout: 0))
                        {
                            break;
                        }

                        // dispose this mutex since the port it represents is not available.
                        _portMutex.Dispose();
                        _portMutex = null;
                    }

                    PortNumber = port;
                    _appDomainOwnedPorts.Add(port);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }
        }
Example #12
0
        public CodeCacheManager(XtallStrategy strategy)
        {
            if (strategy == null)
                throw new ArgumentNullException("strategy");
            if (strategy.Context.Url == null)
                throw new ArgumentNullException("strategy.Context.Url");
            if (strategy.Context.Manifest == null)
                throw new ArgumentNullException("strategy.Context.Manifest");
            _strategy = strategy;

            var manifest = _strategy.Context.Manifest;

            if (manifest.ProductName == null)
                throw new ArgumentNullException("The manifest must specify a product name");

            UrlKey = Uri.EscapeDataString(strategy.Context.Url.ToLower());

            _strategy.LogAction("determining the product folder");
            ProductFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), manifest.ProductName);
            _strategy.LogStatus("assigned the product folder as '{0}'", ProductFolder);

            _strategy.LogAction("determining the site folder");
            SiteFolder = Path.Combine(ProductFolder, "Sites", UrlKey);
            _strategy.LogStatus("assigned the site folder as '{0}'", SiteFolder);

            _strategy.LogAction("determining the cache folder");
            CacheFolder = Path.Combine(ProductFolder, "Cache");
            _strategy.LogStatus("assigned the cache folder as '{0}'", CacheFolder);

            _strategy.LogAction("determining the run folder");
            RunFolder = Path.Combine(ProductFolder, "Run", manifest.Md5Hash);
            _strategy.LogStatus("assigned the run folder as '{0}'", RunFolder);

            _strategy.LogAction("creating a mutex to guard the cache");
            _mutex = new Mutex(false, "XtallCacheGuard:" + manifest.ProductName);
            _strategy.LogAction("acquiring the mutex to guard the cache");
            try
            {
                _strategy.LogAction("waiting for access to the cache");
                if (!_mutex.WaitOne(TimeSpan.FromSeconds(5)))
                {
                    _mutex.Dispose();
                    _mutex = null;
                    throw new Exception("Another instance of this application is currently updating your computer. You may retry after it has finished.");
                }
            }
            catch (AbandonedMutexException)
            {
                // suppressed; this is OK (for us...prolly not for the poor sot that died)
            }
            _strategy.LogStatus("acquired access to the cache");
        }
Example #13
0
        static void Main(string[] args)
        {
            bool createdNew;
            _mutex = new Mutex(true, "KCB2 existing flag", out createdNew);
            if (createdNew == false)
            {
                //ミューテックスの初期所有権が付与されなかったときは
                //すでに起動していると判断して終了
                MessageBox.Show("多重起動を検出しました。終了します", "KCB2");
                return;
            }
            //mutexを非シグナル状態へ
            _mutex.WaitOne();

#if !DEBUG
            try
#endif
            {
#if !DEBUG
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
                System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
                bool bPortable = false;
                foreach (var argv in args)
                switch (argv)
                {
                    case "init":
                        Properties.Settings.Default.Reset();
                        break;
                    case "portable":
                        bPortable = true;
                        break;
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FormMain(bPortable));
            }
#if !DEBUG
            catch (Exception exc)
            {
                String message = exc.ToString();
                System.Diagnostics.Debug.WriteLine("Unexpected Exception:"+message);
                MessageBox.Show(message, "Unexpected Exception");
            }
            finally{
#endif
            _mutex.Dispose();
#if !DEBUG
            }
#endif
        }
Example #14
0
        public static void Main()
        {
            if (ExecuteSoloUpdate())
            {
                return;
            }

            bool first;
            string applicationIdentifier = "RadioStreamer" + Environment.UserName;

            string channelName = string.Concat(applicationIdentifier, ":", "SingeInstanceIPCChannel");
            var mutex = new Mutex(true, applicationIdentifier, out first);

            try
            {
                if (!first)
                    SignalFirstInstance(channelName, applicationIdentifier);

                var domain = AppDomain.CurrentDomain;
                domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                domain.UnhandledException += OnUnhandledException;

                #if !DEBUG
                LoadApplication();
                #endif

                if (_installUpdatesSolo)
                {
                    SheduleSoloUpdate();
                    mutex.Dispose();
                    return;
                }

                StartApp(mutex, channelName);
            }
            catch
            {
                _isRestart = false;
                throw;
            }
            finally
            {
                CleanUp();
            }

            if (_isRestart)
                Process.Start(Assembly.GetEntryAssembly().CodeBase);
        }
Example #15
0
        /************************************************************/
        /********************HELPER FUNCTIONS************************/
        /************************************************************/



        /// <summary>
        /// Returns true if the QA401 application is running.
        /// </summary>
        /// <returns></returns>
        bool IsAppAlreadyRunning()
        {
            System.Threading.Mutex mutex;

            mutex = new System.Threading.Mutex(false, MutexName);

            if (mutex.WaitOne(1))
            {
                // Here we were able to grab ownership. The app must not be running
                mutex.ReleaseMutex();
                mutex.Dispose();
                return(false);
            }

            return(true);
        }
Example #16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uniqueHandlerName">Can be name of APP, both syncronized processes must use the same name and it must be unique among the OS</param>
        /// <param name="bufferCapacity"></param>
        /// <param name="dataArrived">MsgId of the sender, payload</param>
        public SharedMemory(string uniqueHandlerName, Action<eMsgType, ulong, byte[]> dataArrived, long bufferCapacity = 50000, int maxQueueSizeInBytes = 20000000)
        {
            if (dataArrived == null)
                throw new Exception("tiesky.com.SharmIpc: dataArrived callback can't be empty");

            if (String.IsNullOrEmpty(uniqueHandlerName) || uniqueHandlerName.Length > 200)
                throw new Exception("tiesky.com.SharmIpc: uniqueHandlerName can't be empty or more then 200 symbols");

            if (bufferCapacity < 256)
                bufferCapacity = 256;

            if (bufferCapacity > 1000000)    //max 1MB
                bufferCapacity = 1000000;

            this.uniqueHandlerName = uniqueHandlerName;
            this.bufferCapacity = bufferCapacity;

            try
            {
                mt = new Mutex(true, uniqueHandlerName + "SharmNet_MasterMutex");

                if (mt.WaitOne(500))
                {
                    instanceType = eInstanceType.Master;
                }
                else
                {
                    instanceType = eInstanceType.Slave;
                    if (mt != null)
                    {
                        //mt.ReleaseMutex();
                        mt.Close();
                        mt.Dispose();
                        mt = null;
                    }
                }              
            }
            catch (System.Threading.AbandonedMutexException)
            {
                instanceType = eInstanceType.Master;
            }

            Console.WriteLine("tiesky.com.SharmIpc: " + instanceType + " of " + uniqueHandlerName);

            rwh = new ReaderWriterHandler(this, dataArrived);          
        }
Example #17
0
 public static void CleanUp()
 {
     try
     {
         if (_cleanUp)
         {
             return;
         }
         //只有有相关功能打开时,才在退出时关闭代理设置,避免触发杀毒软件
         if (Properties.Settings.Default.IsNetworkImageTurnOn || Properties.Settings.Default.IsPornWebsiteProtectionTurnOn)
         {
             DisableProxy();
         }
         try
         {
             systemMutex.Dispose();
         }
         catch (Exception exp)
         { log.Error(exp.ToString()); }
         //dispose timer and wait for callback complete
         WaitHandle[] whs = new WaitHandle[] {
             new AutoResetEvent(false),
             new AutoResetEvent(false)
         };
         //WaitHandle wh = new AutoResetEvent(false);
         delete_history_timer.Dispose(whs[0]);
         update_domain_list_timer.Dispose(whs[1]);
         foreach (WaitHandle wh in whs)
         {
             wh.WaitOne();
         }
         //updateTask.Wait();
         //exitMailTask.Wait();
         _cleanUp = true;
         log.Info("Exit gracefully!");
     }
     catch (Exception exception)
     {
         log.Error(exception.ToString());
     }
 }
Example #18
0
 static void Main(string[] args)
 {
     Mutex mutex;
     if (Mutex.TryOpenExisting("cgta5d", out mutex))
     {
         return;
     }
     mutex = new Mutex(true, "cgta5d");
     var now = DateTime.Now;
     var d = new DateTime(2015, 04, 01, now.Hour, now.Minute, now.Second);
     var p = new Process();
     p.StartInfo = new ProcessStartInfo();
     p.StartInfo.FileName = @"Launcher.exe";
     var stopwatch = Stopwatch.StartNew();
     try
     {
         SetDate(d);
         p.Start();
         p.WaitForExit((int)TimeSpan.FromMinutes(5).TotalMilliseconds);
         var processes = Process.GetProcessesByName("gta5");
         if (processes != null && processes.Length > 0)
         {
             processes[0].WaitForExit((int)TimeSpan.FromMinutes(5).TotalMilliseconds);
         }
     }
     catch (TimeoutException ex)
     {
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     finally
     {
         stopwatch.Stop();
         var ts = stopwatch.Elapsed;
         d = now + ts;
         SetDate(d);
         mutex.Dispose();
     }
 }
Example #19
0
        static void Main()
        {
            bool mutexCreated = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, @"xcapSnappingTool", out mutexCreated);

            if (mutexCreated)
            {
                Thread t1 = new Thread(new ThreadStart(SplashForm));
                t1.Name = "Splash";
                t1.Start();
                Thread.Sleep(1000);
                t1.Abort();
                new Snap();
            }
            else
            {
                mutex.Dispose();
                Application.Exit();
                return;
            }
        }
Example #20
0
        static void Main()
        {
            bool mutexCreated = false;

            System.Threading.Mutex mutex = new System.Threading.Mutex(true, @"xcapSnappingTool", out mutexCreated);

            if (mutexCreated)
            {
                Thread t1 = new Thread(new ThreadStart(SplashForm));
                t1.Name = "Splash";
                t1.Start();
                Thread.Sleep(1000);
                t1.Abort();
                new Snap();
            }
            else
            {
                mutex.Dispose();
                Application.Exit();
                return;
            }
        }
Example #21
0
        static void Main()
        {
            bool createdNew;
            _mutex = new Mutex(true, "KCBTimer existing flag", out createdNew);
            if (createdNew == false)
            {
                //ミューテックスの初期所有権が付与されなかったときは
                //すでに起動していると判断して終了
                MessageBox.Show("多重起動を検出しました。終了します","KCBTimer");
                return;
            }
            //mutexを非シグナル状態へ
            _mutex.WaitOne();
            

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            Properties.Settings.Default.Save();

            _mutex.Dispose();
        }
Example #22
0
        private static void Init()
        {
            if (bInitialized == true) return;

            Mutex mxInit = new Mutex(false, "AppSettings-5F686A35-3B20-4c84-BA5A-3F79B4715450");

            try
            {
                mxInit.WaitOne();

                if (bInitialized == false)
                {
                    ReadSettings();

                    bInitialized = true;
                }
            }
            finally
            {
                mxInit.ReleaseMutex();
                mxInit.Dispose();
            }
        }
Example #23
0
        public static void Main(string[] args)
        {
            Mutex singleInstanceMutex = null;
            bool restartOnExit = false;

            try {
                bool createdNew;
                singleInstanceMutex = new Mutex(true, @"Local\" + typeof (Program).Assembly.GetName().Name, out createdNew);

                if (!createdNew) {
                    singleInstanceMutex = null;
                    return;
                }

                string appPath = Process.GetCurrentProcess().MainModule.FileName;
                var appPaths = new ApplicationPaths(appPath);
                var logManager = new NlogManager(appPaths.LogDirectoryPath, "theater");
                logManager.ReloadLogger(LogSeverity.Debug);

                bool updateInstalling = InstallUpdatePackage(appPaths, logManager);
                if (!updateInstalling) {
                    restartOnExit = LaunchApplication(appPaths, logManager);
                }
            }
            finally {
                if (singleInstanceMutex != null) {
                    singleInstanceMutex.ReleaseMutex();
                    singleInstanceMutex.Close();
                    singleInstanceMutex.Dispose();
                }
            }

            if (restartOnExit) {
                Application.Restart();
            }
        }
        /// <summary>
        /// Creates all the performance counters. If they already exists, they are destroyed and recreated.
        /// </summary>
        public void SetupPerformanceCounters()
        {
            Mutex globalLock = null;

            try
            {
                this.IsPerformanceCountersReady = false;

                // Utilizzo un lock globale di sistema, per non eseguire il setup contemporaneo tra 2 processi diversi
                globalLock = new Mutex(false, MUTEX_NAME);

                // Aspetto fino a che il lock non viene rilasciato, assegno un timeout di 30 secondi per sicurezza.
                if (!globalLock.WaitOne(TimeSpan.FromSeconds(30)))
                {
                    log.WarnFormat("Cannot setup the performance counter: timeout acquiring the lock on '{0}' mutex lock. Setup aborted.", MUTEX_NAME);

                    // Imposto il manager come se avesse installato correttamente i counter, perchè se entro in questo timeout, vuol dire che un'altra applicazione li sta installando.
                    this.IsPerformanceCountersReady = true;

                    return;
                }

                // Se la categoria non esiste,
                if (PerformanceCounterCategory.Exists(PERFCOUNTER_CATEGORY_KEY))
                {
                    PerformanceCounterCategory.Delete(PERFCOUNTER_CATEGORY_KEY);

                    CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection();

                    //Avarage Counter
                    CounterCreationData perfCouterCustom1Counter = new CounterCreationData();
                    perfCouterCustom1Counter.CounterType = PerformanceCounterType.NumberOfItems64;
                    perfCouterCustom1Counter.CounterName = PERCOUNTER_CUSTOM1;
                    perfCouterCustom1Counter.CounterHelp = "help about counter... bla bla bla";
                    counterCreationDataCollection.Add(perfCouterCustom1Counter);

                   PerformanceCounterCategory.Create(
                        PERFCOUNTER_CATEGORY_KEY,
                        "Contains the counters.",
                        PerformanceCounterCategoryType.SingleInstance,
                        counterCreationDataCollection);
                }
                this.IsPerformanceCountersReady = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
            finally
            {
                try
                {
                    if (globalLock != null)
                    {
                        globalLock.ReleaseMutex();
                        globalLock.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Error while trying to ReleaseMutex on the global lock.", ex);
                }
            }
        }
Example #25
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // enable multi-core JIT.
            // see reference: http://msdn.microsoft.com/en-us/library/system.runtime.profileoptimization.aspx
            if (IsMulticoreJitEnabled)
            {
                ProfileOptimization.SetProfileRoot(ConfigurationDirectoryPath);
                ProfileOptimization.StartProfile(ProfileFileName);
            }

            // initialize dispatcher helper
            DispatcherHelper.UIDispatcher = Dispatcher;
            DispatcherHolder.Initialize(Dispatcher);

            // set rendering mode
            if (!IsHardwareRenderingEnabled)
            {
                System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
            }

            // Check run duplication
            string mutexStr = null;
            switch (ExecutionMode)
            {
                case ExecutionMode.Default:
                case ExecutionMode.Roaming:
                    mutexStr = ExecutionMode.ToString();
                    break;
                case ExecutionMode.Standalone:
                    mutexStr = "Standalone_" + ExeFilePath.Replace('\\', '*');
                    break;
            }
            _appMutex = new Mutex(true, "Krile_StarryEyes_" + mutexStr);
            if (_appMutex.WaitOne(0, false) == false)
            {
                MessageBox.Show("Krileは既に起動しています。");
                Environment.Exit(0);
            }

            // set exception handlers
            Current.DispatcherUnhandledException += (sender2, e2) => HandleException(e2.Exception);
            AppDomain.CurrentDomain.UnhandledException += (sender2, e2) => HandleException(e2.ExceptionObject as Exception);

            // set exit handler
            Current.Exit += (_, __) => AppFinalize(true);

            // Initialize service points
            ServicePointManager.Expect100Continue = false; // disable expect 100 continue for User Streams connection.
            ServicePointManager.DefaultConnectionLimit = Int32.MaxValue; // Limit Break!

            // Initialize special image handlers
            SpecialImageResolvers.Initialize();

            // Load plugins
            PluginManager.Load();

            // Load settings
            if (!Setting.LoadSettings())
            {
                Current.Shutdown();
                return; // fail
            }

            // Set CK/CS for accessing twitter.
            ApiEndpoint.DefaultConsumerKey = Setting.GlobalConsumerKey.Value ?? ConsumerKey;
            ApiEndpoint.DefaultConsumerSecret = Setting.GlobalConsumerSecret.Value ?? ConsumerSecret;
            ApiEndpoint.UserAgent = Setting.UserAgent.Value;

            // Load key assigns
            KeyAssignManager.Initialize();

            // Load cache store
            CacheStore.Initialize();

            // Initialize core systems
            if (Setting.DatabaseCorruption.Value)
            {
                var option = new TaskDialogOptions
                {
                    MainIcon = VistaTaskDialogIcon.Error,
                    Title = "Krile データストア初期化エラー",
                    MainInstruction = "データストアの破損が検出されています。",
                    Content = "データストアが破損している可能性があります。" + Environment.NewLine +
                    "データストアを初期化するか、またはKrileを終了してバックアップを取ることができます。",
                    CommandButtons = new[] { "データストアを初期化して再起動", "Krileを終了", "無視して起動を続ける" }
                };
                var result = TaskDialog.Show(option);
                if (result.CommandButtonResult.HasValue)
                {
                    switch (result.CommandButtonResult.Value)
                    {
                        case 0:
                            StatusStore.Shutdown();
                            UserStore.Shutdown();
                            // clear data
                            ClearStoreData();
                            Setting.DatabaseCorruption.Value = false;
                            Setting.Save();
                            _appMutex.Dispose();
                            Process.Start(ResourceAssembly.Location);
                            Current.Shutdown();
                            Process.GetCurrentProcess().Kill();
                            return;
                        case 1:
                            _appMutex.Dispose();
                            // shutdown
                            Current.Shutdown();
                            Process.GetCurrentProcess().Kill();
                            return;
                        case 2:
                            Setting.DatabaseCorruption.Value = false;
                            break;
                    }
                }
            }

            StatusStore.Initialize();
            UserStore.Initialize();
            AccountsStore.Initialize();
            StatisticsService.Initialize();
            PostLimitPredictionService.Initialize();
            StreamingEventsHub.Initialize();
            ReceiveInbox.Initialize();

            // Activate plugins
            PluginManager.LoadedPlugins.ForEach(p => p.Initialize());

            // Activate scripts
            ScriptingManager.ExecuteScripts();

            // finalize handlers
            StreamingEventsHub.RegisterDefaultHandlers();
            ReceiversManager.Initialize();
            BackstageModel.Initialize();
            RaiseSystemReady();
        }
Example #26
0
        /// <summary>
        /// The program main method
        /// </summary>
        /// <param name="args">No arguments</param>
        static void Main(string[] args)
        {
            List<string> fileInputs = new List<string>();
            // Build the list of input directories
            RecursiveParseDictionary(@"E:\loldata", fileInputs);
            Global511Statistics = new Dictionary<int, ChampionItemBuilds>();
            Global514Statistics = new Dictionary<int, ChampionItemBuilds>();
            GlobalMutex = new Mutex();

            List<string>[] threadPaths = new List<string>[NumThreads];
            int nextThread = 0;

            // Load balance the input directories across all available threads
            for (int i = 0; i < NumThreads; i++)
            {
                threadPaths[i] = new List<string>();
            }
            for (int i = 0; i < fileInputs.Count(); i++)
            {
                threadPaths[nextThread].Add(fileInputs[i]);
                nextThread = (nextThread + 1) % NumThreads;
            }

            // Construct and start our threads
            Thread[] t = new Thread[NumThreads];
            for (int i = 0; i < NumThreads; i++) {
                t[i] = new Thread(new ParameterizedThreadStart(WorkerThread));
                t[i].Start((object)threadPaths[i]);
            }

            // Wait for all threads to complete
            for (int i = 0; i < NumThreads; i++)
            {
                t[i].Join();
            }

            // Construct our final JSON output, one per patch
            BuildJsonObject(Global511Statistics, Version._511);
            BuildJsonObject(Global514Statistics, Version._514);

            // Dispose of our mutex
            GlobalMutex.Dispose();
        }
        private void TryCleanupUnusedAdminBuildpacks(StagingStartRequestAdminBuildpack[] adminBuildpacks, string adminBuildpackDir)
        {
            if (!Directory.Exists(adminBuildpackDir))
            {
                return;
            }

            var cachedAdminBuilpacks = new DirectoryInfo(adminBuildpackDir).EnumerateDirectories().ToDictionary(di => di.Name, di => di.FullName);

            var adminBuildpacksLookup = adminBuildpacks.ToLookup(ab => ab.Key);

            foreach (var cachedBuildpack in cachedAdminBuilpacks)
            {
                if (adminBuildpacksLookup.Contains(cachedBuildpack.Key))
                {
                    continue;
                }

                bool signaled = false;
                var buildpackMutex = new Mutex(false, AdminBuildpackMutexName(cachedBuildpack.Key));

                try
                {
                    signaled = buildpackMutex.WaitOne(0);

                    if (signaled)
                    {
                        Logger.Info("Deleting old admin buildpack {0} from {1}", cachedBuildpack.Key, cachedBuildpack.Value);

                        Directory.Delete(cachedBuildpack.Value, true);
                    }
                }
                finally
                {
                    if (signaled)
                    {
                        buildpackMutex.ReleaseMutex();
                    }

                    buildpackMutex.Dispose();
                }
            }
        }
        public bool InitializeAdminBuildpack(StagingStartRequestAdminBuildpack adminBuildpack, string adminBuildpackDir, bool checkWindowsCompatibility)
        {
            var dir = Path.Combine(adminBuildpackDir, adminBuildpack.Key);
            var buildpackMutex = new Mutex(false, AdminBuildpackMutexName(adminBuildpack.Key));

            try
            {
                buildpackMutex.WaitOne();

                DownloadAdminBuildpack(adminBuildpack, adminBuildpackDir);

                if (checkWindowsCompatibility)
                {
                    var winBuildpack = BuildpackHasWindowsCompatibleBinaries(dir);
                    if (!winBuildpack)
                    {
                        Logger.Info("Ignoring buildpack {1}. Staging task {0}. Unable to detect compatible windows executables in buildpack bin.", this.Properties.TaskId, dir);
                        return false;
                    }
                }

                DEAUtilities.DirectoryCopy(dir, Path.Combine(this.Workspace.TempDir, "buildpack"), true);
            }

            finally
            {
                buildpackMutex.ReleaseMutex();
                buildpackMutex.Dispose();
            }

            return true;
        }
Example #29
0
        private static void Init()
        {
            if (bInitialized)
            {
                return;
            }

            Mutex mxInit = new Mutex(false, sSubSystem + "8A556883-DA8B-4323-B795-F5BD4124E3EA");

            try
            {
                mxInit.WaitOne();

                if (bInitialized == false)
                {
                    log = new Log(sSubSystem, sSubSystem + "F4CAB138-2162-4261-BEA5-FB9B01B63B9D", sSubSystem + "1154027A-55A6-41b5-B342-76C1F5FC65C9");
                    log.InitLoggerFromGlobalOptions(sOptionPrefix);

                    bInitialized = true;
                }
            }
            finally
            {
                mxInit.ReleaseMutex();
                mxInit.Dispose();
            }
        }
Example #30
0
        private void AddTrayIcon()
        {
            if (_trayIcon != null)
            {
                return;
            }
            _trayIcon = new NotifyIcon
            {
                Icon = _appIcon = new System.Drawing.Icon(LogoIcon),
                Text = "满金店客服"
            };
            _trayIcon.Visible     = true;
            _trayIcon.MouseClick += (s, e) =>
            {
                if (e.Button == MouseButtons.Right)
                {
                    return;
                }

                if (AppData.MainMV != null && AppData.MainMV.ChatListVM != null)
                {
                    int count = AppData.MainMV.ChatListVM.Items.Where(info => !info.Chat.Chat.IsNotDisturb && info.UnReadCount > 0 && !string.IsNullOrEmpty(info.Chat.Chat.DisplayName)).Count();
                    if (count == 0)
                    {
                        MainWindow_OnCloseTrayWindow();
                    }
                    else if (count == 1)
                    {
                        AppData.MainMV.ChatListVM.SelectedItem = AppData.MainMV.ChatListVM.Items.Where(info => !info.Chat.Chat.IsNotDisturb && info.UnReadCount > 0 && !string.IsNullOrEmpty(info.Chat.Chat.DisplayName)).First();

                        MainWindow_OnCloseTrayWindow();
                    }
                    else
                    {
                        AppData.MainMV.ChatListVM.SelectedItem = AppData.MainMV.ChatListVM.Items.Where(info => !info.Chat.Chat.IsNotDisturb && info.UnReadCount > 0 && !string.IsNullOrEmpty(info.Chat.Chat.DisplayName)).First();
                    }
                }

                if (this.MainWindow.WindowState == WindowState.Minimized)
                {
                    this.MainWindow.WindowState = WindowState.Normal;
                }

                this.MainWindow.Visibility = Visibility.Visible;
                this.MainWindow.Activate();
            };

            ContextMenu menu = new ContextMenu();

            MenuItem openItem = new MenuItem();

            openItem.Text   = "打开主面板";
            openItem.Click += new EventHandler(delegate
            {
                if (this.MainWindow.WindowState == WindowState.Minimized)
                {
                    this.MainWindow.WindowState = WindowState.Normal;
                }
                this.MainWindow.Visibility = Visibility.Visible;
                this.MainWindow.Activate();
            });

            MenuItem closeItem = new MenuItem();

            closeItem.Text   = "退出";
            closeItem.Click += new EventHandler(delegate
            {
                if (MUTEX != null)
                {
                    App.MUTEX.ReleaseMutex();
                    MUTEX.Dispose();
                }
                this.Shutdown();
            });

            menu.MenuItems.Add(openItem);
            menu.MenuItems.Add(closeItem);

            _trayIcon.ContextMenu = menu;
        }
Example #31
0
 /**
  * Method startProgram - проверяет свободен ли мьютекс,
  * если свободен запускает процесс, и переводит мьютекс в режим ожидания
  * (ждет, когда мьютекс будет свободен), чтобы закрыть поток).
  * Если мьютекс занят выводит сообщение об ошибке.
  *
  * @return void
  *
  */
 void startProgram()
 {
     bool existed;
     Mutex mutexObj = new Mutex(true, "MutexControllProcess", out existed);
     if(existed)
     {
         label4.Invoke(new Action(() => label4.Text = ""));
         StarterMutex = mutexObj;
         mutexObj.WaitOne();
         StarterProcess = Process.Start(textBox1.Text);
     }
     else
     {
         label4.Invoke(new Action(() => label4.Text = "Приложение уже было запущено!"));
         mutexObj.Dispose();
     }
 }
Example #32
0
 void createCode()
 {
     bool existed;
     Mutex mutexObj = new Mutex(true, "MutexControllProcess", out existed);
     if(existed)
     {
         Invoke(new Action( () =>textBox3.Text = ""));
         string alphabet=readAlphabet(@"C:\Users\Глеб\Desktop\kript\alphabet.txt");
         string key=textBox2.Text;
         string t = textBox1.Text.Replace("\r\n","¶");
         for(int i=0;i<t.Length;i++)
         {
             //Thread.Sleep(100);
             Invoke(new Action( () =>
                               textBox3.Text += scrambler(alphabet, key[i % textBox2.Text.Length], t[i], true)));
             Invoke(new Action( () => progressBar1.Value = progressBar1.Maximum*(i+1) / t.Length ));
             if (i % 3 == 0) Invoke(new Action( () => label6.Text = "Идет обработка данных ." ));
             if (i % 3 == 1) Invoke(new Action( () => label6.Text = "Идет обработка данных . ." ));
             if (i % 3 == 2) Invoke(new Action( () => label6.Text = "Идет обработка данных . . ." ));
         }
         Invoke(new Action( () => label6.Text = "Исходный текст успешно зашифрован!" ));
     }
     else Invoke(new Action( () => label6.Text = "Шифрование текста уже началось!" ));
     mutexObj.Dispose();
 }
            public async Task ServerShutdownsDuringProcessing()
            {
                using (var readyMre = new ManualResetEvent(initialState: false))
                using (var doneMre = new ManualResetEvent(initialState: false))
                {
                    var pipeName = Guid.NewGuid().ToString();
                    var mutexName = BuildServerConnection.GetServerMutexName(pipeName);
                    bool created = false;
                    bool connected = false;

                    var thread = new Thread(() =>
                    {
                        using (var stream = new NamedPipeServerStream(pipeName))
                        {
                            var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created);
                            readyMre.Set();

                            stream.WaitForConnection();
                            connected = true;

                            // Client is waiting for a response.  Close the mutex now.  Then close the connection 
                            // so the client gets an error.
                            mutex.ReleaseMutex();
                            mutex.Dispose();
                            stream.Close();

                            doneMre.WaitOne();
                        }
                    });

                    // Block until the mutex and named pipe is setup.
                    thread.Start();
                    readyMre.WaitOne();

                    var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false);

                    // Let the fake server exit.
                    doneMre.Set();
                    thread.Join();

                    Assert.Equal(CommonCompiler.Succeeded, exitCode);
                    Assert.True(connected);
                    Assert.True(created);
                }
            }
Example #34
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();
        }
Example #35
0
        //  Creates a pair of filedescriptors that will be used
        //  to pass the signals.
        private void MakeFDpair()
        {
            Mutex sync;

            try
            {
                sync = new Mutex(false, "Global\\netmq-signaler-port-sync");
            }
            catch (UnauthorizedAccessException)
            {
                sync = Mutex.OpenExisting("Global\\netmq-signaler-port-sync", MutexRights.Synchronize | MutexRights.Modify);
            }

            Debug.Assert(sync != null);

            sync.WaitOne();

            Socket listner = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified);
            listner.NoDelay = true;
            listner.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, Config.SignalerPort);

            listner.Bind(endpoint);
            listner.Listen(1);

            m_w = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified);

            m_w.NoDelay = true;

            m_w.Connect(endpoint);

            m_r = listner.Accept();

            listner.Close();

            sync.ReleaseMutex();

            // Release the kernel object
            sync.Dispose();
        }
Example #36
0
        private bool SingleInstanceCheck()
        {
            _singleInstanceMutex = new Mutex(false, "Shary");

            var hasSignal = _singleInstanceMutex.WaitOne(1000, false);

            if (hasSignal)
            {
                Exit += (s, e) =>
                {
                    _singleInstanceMutex.ReleaseMutex();
                    _singleInstanceMutex.Dispose();
                };
            }
            else
            {
                MessageBox.Show("Shary is already running", "Shary", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }

            return hasSignal;
        }
        /// <summary>
        /// Executes the benchmarks.
        /// </summary>
        /// <param name="numOfThreads">The num of threads.</param>
        /// <param name="benchmarkType">Type of the benchmark.</param>
        /// <param name="constructorParameters">The constructor parameters.</param>
        /// <returns></returns>
        private static BenchmarkBase[] ExecuteBenchmarks(int numOfThreads, Type benchmarkType, params object[] constructorParameters) {
            BenchmarkBase[] benchmarks = new BenchmarkBase[numOfThreads];

            //Create threads
            Mutex mutex = new Mutex(true, Settings.MUTEX_NAME);

            #if THREADS
                Thread[] tasks = new Thread[numOfThreads];
            #else
                Task[] tasks = new Task[numOfThreads];
            #endif

            for (int i = 0; i < numOfThreads; i++) {
                benchmarks[i] = Activator.CreateInstance(benchmarkType, constructorParameters) as BenchmarkBase;

                #if THREADS
                    tasks[i] = new Thread(new ThreadStart(benchmarks[i].ExecuteBenchmark));
                #else
                    tasks[i] = new Task(new Action(benchmarks[i].ExecuteBenchmark));
                #endif
                tasks[i].Start();
            }

            //Start nechmark execution
            mutex.ReleaseMutex();
            mutex.Dispose();

            //Wait for threads to complete execution
            #if THREADS
                while (tasks.Any(t => t.IsAlive)) { }
            #else
                while (tasks.Any(t => !t.IsCompleted)) { }
            #endif

            return benchmarks;
        }