示例#1
0
        static void Main()
        {
#if false
            // テスト用に英語モードにする
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en", false);
#endif

            // Mutexを利用して、二重起動を防止
            using (var mutex = new MutexLock(Application.ProductName))
            {
                try
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    // 起動時にFormを表示したくないので、Runメソッドに渡さない
                    var form = new PreferenceForm();
                    form.Init();

                    Application.Run();
                }
                catch (Exception)
                {
                    MessageBox.Show(Properties.Resources.ItHasAlreadyLaunched);
                }
            }
        }
示例#2
0
        public ObjectCache()
        {
            _lastCleanupTime = DateTime.UtcNow;
            _cache           = new ObjectCache <_KEY_TYPE, _OBJECT_TYPE> .TypeCache();

            _lock = new MutexLock();
        }
示例#3
0
 public static int Main(string[] args)
 {
     Thread.Sleep(2000);
     MutexLock.Lock();
     try
     {
         ExternalFunctionalityManager.Init(new UtLibFunctions());
         RootCommand rootCommand = new RootCommand();
         Command     install     = new Command("install", "Install UpTool")
         {
             new Option <bool>(new[] { "--noPrep", "-p" }, "Doesn't initialize repos. Use with caution!")
         };
         install.AddAlias("-i");
         install.AddAlias("i");
         install.Handler = CommandHandler.Create <bool>(Install);
         rootCommand.AddCommand(install);
         return(rootCommand.InvokeAsync(args).Result);
     }
     catch (Exception e)
     {
         Console.WriteLine($"FAILED: {e}");
         return(1);
     }
     finally
     {
         MutexLock.Unlock();
     }
 }
示例#4
0
        /// <summary>
        /// Activate the options on the file appender.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is part of the <see cref="IOptionHandler"/> delayed object
        /// activation scheme. The <see cref="ActivateOptions"/> method must
        /// be called on this object after the configuration properties have
        /// been set. Until <see cref="ActivateOptions"/> is called this
        /// object is in an undefined state and must not be used.
        /// </para>
        /// <para>
        /// If any of the configuration properties are modified then
        /// <see cref="ActivateOptions"/> must be called again.
        /// </para>
        /// <para>
        /// This will cause the file to be opened.
        /// </para>
        /// </remarks>
        override public void ActivateOptions()
        {
            base.ActivateOptions();

            if (m_securityContext == null)
            {
                m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
            }

            if (m_lockingModel == null)
            {
                m_lockingModel = new MutexLock();
            }

            m_lockingModel.CurrentAppender = this;

            using (SecurityContext.Impersonate(this))
            {
                m_fileName = ConvertToFullPath(m_fileName.Trim());
            }

            if (m_fileName != null)
            {
                SafeOpenFile(m_fileName, m_appendToFile);
            }
            else
            {
                LogLog.Warn(typeof(FileAppender), "FileAppender: File option not set for appender [" + Name + "].");
                LogLog.Warn(typeof(FileAppender), "FileAppender: Are you using FileAppender instead of ConsoleAppender?");
            }
        }
示例#5
0
        public static int Main(string[] args)
        {
            MutexLock.Lock();
            try
            {
                XmlTool.FixXml();
                ExternalFunctionalityManager.Init(Functions);
                RootCommand rootCommand = new RootCommand();

                PackageManagement.RegisterCommands(rootCommand);
                CacheManagement.RegisterCommands(rootCommand);
                ReposManagement.RegisterCommands(rootCommand);
                Other.RegisterCommands(rootCommand);

                return(rootCommand.InvokeAsync(args).Result);
            }
            catch (Exception e)
            {
                Console.WriteLine($"FAILED: {e}");
                return(1);
            }
            finally
            {
                MutexLock.Unlock();
            }
        }
示例#6
0
 protected RateMonitor(int maxEventsPerPeriod, TimeSpan period)
 {
     _eventList = new List <RateMonitorEvent>();
     _lock      = new MutexLock();
     _maxEvents = maxEventsPerPeriod;
     _period    = period;
 }
 public LogRotationThread(Log log, StreamWriter fileWriter, MutexLock fileLock)
     : base("LogRotationThread")
 {
     Interval     = TimeSpan.FromMilliseconds(0);
     _logToRotate = log;
     _fileWriter  = fileWriter;
     _fileLock    = fileLock;
 }
示例#8
0
 public BufferedOutput(LogLevel level, DateTime createTime, String text)
 {
     _level      = level;
     _text       = text;
     _createTime = createTime;
     _listLock   = new MutexLock();
     _outputList = new List <BufferedLine>();
 }
示例#9
0
 public void TestMutexIsLocked()
 {
     using (MutexLock lck = new MutexLock(Guid.NewGuid().ToString()))
     {
         Assert.IsTrue(lck.IsLocked);
         lck.Dispose();
         Assert.IsFalse(lck.IsLocked);
     }
 }
        public DatabasePerformanceLog(String fileName)
            : base(fileName)
        {
            m_Lock = new MutexLock();

            m_TextWriter = File.CreateText(fileName);
            m_TextWriter.WriteLine("Timestamp,Type,Elapsed,Method,Sql");
            m_TextWriter.Flush();
        }
示例#11
0
        public AsynchLogThread(TextWriter tw, BinaryWriter bw)
            : base("AsynchLogThread")
        {
            _fileTextWriter = tw;
            _binaryWriter   = bw;

            _logLines        = new List <Object>();
            _logLineListLock = new MutexLock();
        }
示例#12
0
        public LogOutputAggregator(Log log, TimeSpan mininumLogInterval)
        {
            _log = log;
            _minumumOutputInterval = mininumLogInterval;
            _lastCacheCheckTime    = DateTime.UtcNow;

            _outputByText   = new Dictionary <String, BufferedOutput>();
            _outputListLock = new MutexLock();
        }
示例#13
0
        /// <summary>
        /// Prepares an atomic read operation.
        /// </summary>
        /// <param name="path">The path of the file that will be read.</param>
        public AtomicRead([NotNull, Localizable(false)] string path)
        {
            #region Sanity checks
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            #endregion

            _lock = new MutexLock("atomic-file-" + path.GetHashCode());
        }
示例#14
0
        //
        // Constructor & Destructor
        //
        /// <summary>
        /// Specify the local IP and Port to listen for connections on.  Call start to begin listening for connections.
        /// </summary>
        TcpServer(String name)
            : base(name)
        {
            _listeners       = new Dictionary <int, TcpListener>();
            _clientLock      = new MutexLock();
            _clientsHandleIO = false;

            if (Log == null)
            {
                Log = Log.SystemLog;
            }
        }
示例#15
0
 private static void Main()
 {
     try
     {
         MutexLock.Lock();
         Application.SetHighDpiMode(HighDpiMode.SystemAware);
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new InstallerForm());
     }
     finally
     {
         MutexLock.Unlock();
     }
 }
示例#16
0
        /// <summary>
        /// Prepares an atomic write operation.
        /// </summary>
        /// <param name="path">The file path of the final destination.</param>
        public AtomicWrite([NotNull, Localizable(false)] string path)
        {
            DestinationPath = path ?? throw new ArgumentNullException(nameof(path));

            // Make sure the containing directory exists
            string directory = Path.GetDirectoryName(Path.GetFullPath(path));

            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // Prepend random string for temp file name
            WritePath = directory + Path.DirectorySeparatorChar + "temp." + Path.GetRandomFileName() + "." + Path.GetFileName(path);

            _lock = new MutexLock("atomic-file-" + path.GetHashCode());
        }
示例#17
0
        public void CtorTest()
        {
            const string mutexName = "test1";
            var          mutex     = new MutexLock(mutexName);

            var task = Task.Run(() => CreateMutexLock(mutexName));

            Task.Delay(5000);

            Assert.False(task.IsCompleted);

            mutex.Dispose();

            task.Wait();

            Assert.True(task.IsCompleted);

            Assert.NotNull(mutex);
        }
示例#18
0
        public void TestMutexAbandond()
        {
            using (Mutex mtx = new Mutex())
            {
                Thread t = new Thread(
                    delegate()
                    { GC.KeepAlive(new MutexLock(1, mtx)); }
                    );
                t.Start();
                t.Join();

                //So the previous thread abandoned the mutex...
                using (MutexLock lck = new MutexLock(mtx))
                {
                    Assert.IsTrue(lck.WasAbandonded);
                    Assert.AreEqual(mtx, lck.MutexHandle);
                }
            }
        }
示例#19
0
        public async Task Run()
        {
            var sem   = new SemaphoreLock();
            var mut   = new MutexLock();
            var tasks = new List <Task>();

            Console.WriteLine("Running blocking lock function...");
            for (var i = 0; i < 3; i++)
            {
                tasks.Add(Task.Run(() => RunLock(sem)));
                tasks.Add(Task.Run(() => RunLock(mut)));
            }
            await Task.WhenAll(tasks);

            tasks = new List <Task>();
            Console.WriteLine("Running non-blocking lock function...");
            for (var i = 0; i < 3; i++)
            {
                tasks.Add(RunLockAsync(sem));
                tasks.Add(RunLockAsync(mut));
            }
            await Task.WhenAll(tasks);
        }
        public ILearner GetLearner(int result)
        {
            ILearner learner = null;

            switch (result)
            {
            case 1:
                learner = new ContextSwitching(1000);
                break;

            case 2:
                learner = new SharedResources();
                break;

            case 3:
                learner = new LocalMemory();
                break;

            case 4:
                learner = new ThreadPoolDemo();
                break;

            case 5:
                learner = new Concepts();
                break;

            case 6:
                learner = new ExceptionHandling();
                break;

            case 7:
                learner = new TasksIntro();
                break;

            case 8:
                learner = new TasksIOBound();
                break;

            case 9:
                learner = new TasksChaining();
                break;

            case 10:
                learner = new LocksAndMonitor();
                break;

            case 11:
                learner = new NestedLocks();
                break;

            case 12:
                learner = new DeadLocks();
                break;

            case 13:
                learner = new ReaderWriterLock();
                break;

            case 14:
                learner = new MutexLock();
                break;

            case 15:
                learner = new Semaphores();
                break;

            default:
                learner = new ContextSwitching(10);
                break;
            }
            return(learner);
        }
 internal Buffer(MutexLock s, int bufferSize)
 {
     _byteBuffer = new byte[bufferSize];
     _byteBufferType = 0x0;
     this.s = s;
 }
 //Constructors
 internal Buffer(MutexLock s)
 {
     _byteBuffer = new byte[_defaultBufferSize];
     _byteBufferType = 0x0;
     this.s = s;
 }
示例#23
0
 public void TestMutexIsNew()
 {
     using (MutexLock lck = new MutexLock(Guid.NewGuid().ToString()))
         Assert.IsTrue(lck.WasNew);
 }
示例#24
0
        /// <summary>
        /// Handling client/clients.
        /// </summary>
        /// <param name="client">client to handle with</param>
        /// <param name="clients">all connected clients</param>
        public void HandleClient(TcpClient client, List <TcpClient> clientList)
        {
            try
            {
                //handle inside a thread
                new Task(() =>
                {
                    try
                    {
                        while (!stoppedRunning)
                        {
                            //create network transaction objects
                            NetworkStream ns = client.GetStream();
                            BinaryReader br  = new BinaryReader(ns);

                            //log the recieved command
                            string recieved = br.ReadString();
                            string message  = "Command recieved: " + recieved;

                            Logging.Log(message, MessageTypeEnum.INFO);
                            //Deserialize the client's command
                            CommandRecievedEventArgs commandArgs = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(recieved);
                            //if a close command was recieved
                            if (commandArgs.CommandID == (int)CommandEnum.DisconnectClient)
                            {
                                //remove client and close connection
                                this.Logging.Log("Disconnecting client", MessageTypeEnum.INFO);
                                clientList.Remove(client);
                                client.Close();
                                break;
                            }
                            //else, execute
                            else
                            {
                                bool indicator;
                                string executed = this.ImageController.ExecuteCommand((int)commandArgs.CommandID, commandArgs.Args, out indicator);

                                //create the network writing object
                                BinaryWriter bw = new BinaryWriter(ns);

                                //lock the writing
                                MutexLock.WaitOne();
                                bw.Write(executed);
                                MutexLock.ReleaseMutex();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //in case of exception, log the client's error and close connection
                        Logging.Log(e.ToString(), MessageTypeEnum.FAIL);
                        clientList.Remove(client);
                        client.Close();
                    }
                    //start handling
                }).Start();
            }
            catch (Exception e)
            {
                Logging.Log(e.Message, MessageTypeEnum.FAIL);
            }
        }
示例#25
0
        /// <summary>
        /// Activate the options on the file appender. 
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is part of the <see cref="IOptionHandler"/> delayed object
        /// activation scheme. The <see cref="ActivateOptions"/> method must 
        /// be called on this object after the configuration properties have
        /// been set. Until <see cref="ActivateOptions"/> is called this
        /// object is in an undefined state and must not be used. 
        /// </para>
        /// <para>
        /// If any of the configuration properties are modified then 
        /// <see cref="ActivateOptions"/> must be called again.
        /// </para>
        /// <para>
        /// This will cause the file to be opened.
        /// </para>
        /// </remarks>
        override public void ActivateOptions()
        {
            base.ActivateOptions();

            if (m_securityContext == null)
            {
                m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
            }

            if (m_lockingModel == null)
            {
                m_lockingModel = new MutexLock();
            }

            m_lockingModel.CurrentAppender = this;

            using (SecurityContext.Impersonate(this))
            {
                m_fileName = ConvertToFullPath(m_fileName.Trim());
            }

            if (m_fileName != null)
            {
                SafeOpenFile(m_fileName, m_appendToFile);
            }
            else
            {
                LogLog.Warn("FileAppender: File option not set for appender [" + Name + "].");
                LogLog.Warn("FileAppender: Are you using FileAppender instead of ConsoleAppender?");
            }
        }
示例#26
0
        private static void CreateMutexLock(string mutexName)
        {
            var mutexLock = new MutexLock(mutexName);

            mutexLock.Dispose();
        }
示例#27
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            BuildSplash();
            Splash.Show();
            //new Thread(() => { Splash.ShowDialog(); }).Start();
            try
            {
                MutexLock.Lock();
            }
            catch (MutexLockLockedException)
            {
                Console.WriteLine("Mutex property of other process, quitting");
                Process[] processes = Process.GetProcessesByName("UpTool2");
                if (processes.Length > 0)
                {
                    WindowHelper.BringProcessToFront(Process.GetProcessesByName("UpTool2")[0]);
                }
                return;
            }
#if !DEBUG
            try
            {
#endif
            ExternalFunctionalityManager.Init(new UtLibFunctions());
            SetSplash(1, "Initializing paths");
            if (!Directory.Exists(PathTool.Dir))
            {
                Directory.CreateDirectory(PathTool.Dir);
            }
            FixXml();
            SetSplash(2, "Performing checks");
            try
            {
                UpToolLib.UpdateCheck.Reload();
                Online = true;
            }
            catch
            {
                Online = false;
            }
            if (Application.ExecutablePath != PathTool.GetRelative("Install", "UpTool2.dll"))
            {
                Splash.Invoke((Action)(() => MessageBox.Show(Splash,
                                                             $"WARNING!{Environment.NewLine}Running from outside the install directory is not recommended!")
                                       ));
            }
            if (!Directory.Exists(PathTool.GetRelative("Apps")))
            {
                Directory.CreateDirectory(PathTool.GetRelative("Apps"));
            }
            if (!Online)
            {
                SetSplash(7, "Opening");
            }
            if (!Online || UpdateCheck())
            {
                Application.Run(new MainForm());
            }
#if !DEBUG
        }

        catch (Exception e1)
        {
            try
            {
                Splash.Invoke((Action)Splash.Hide);
            }
            catch
            {
                Console.WriteLine("Failed to hide splash");
            }
            MessageBox.Show(e1.ToString());
        }
        finally
        {
            MutexLock.Unlock();
        }
#endif
        }