Ejemplo n.º 1
0
 void CheckSession(object state)
 {
     try
     {
         CheckSession();
     }
     catch (WebServerException ex)
     {
         switch (ex.Error)
         {
         case WebError.AuthenticationRequired:
         case WebError.SessionRequired:
         {
             UserSession session = Session;
             session.Expiration = DateTime.UtcNow.AddSeconds(-1);
             Session            = session;
         }
         break;
         }
     }
     catch (Exception ex)
     {
         Trace.TraceWarning("CheckSession error!\n{0}", ex);
     }
     if (Session.IsExpired())
     {
         timer?.Dispose();
         timer = null;
         OnSessionUpdated(new EventArgs());
     }
 }
Ejemplo n.º 2
0
        public static Action Debounce(Action action, int delay)
        {
            System.Threading.Timer timer = null;
            void callback(object o)
            {
                action();
                timer?.Dispose();
                timer = null;
            }

            System.Threading.Timer CreateTimer()
            {
                return(new System.Threading.Timer(
                           callback,
                           null,
                           delay,
                           System.Threading.Timeout.Infinite));
            }

            return(() =>
            {
                timer?.Dispose();
                timer = CreateTimer();
            });
        }
Ejemplo n.º 3
0
 public void Handle(object sender, T args)
 {
     _lastSender = sender;
     _lastArgs   = args;
     _timer?.Dispose();
     _timer = new System.Threading.Timer(TimerFired, null, _timeout, int.MaxValue);
 }
Ejemplo n.º 4
0
 protected override void OnStart(string[] args)
 {
     UpdateLog(@"服务启动");
     if (args.Length == 5)
     {
         Domain          = args[0];
         RR              = args[1];
         accessKeyId     = args[2];
         accessKeySecret = args[3];
         logPath         = args[4];
     }
     threadTimer?.Dispose();
     threadTimer = new System.Threading.Timer(Update, null, 0, 6 * minute);
 }
Ejemplo n.º 5
0
        public void Dispose()
        {
#if !CONTRACTS_ONLY
            if (!_IsDisposed)
            {
#if SUPPORTS_APPDOMAIN
                AppDomain.CurrentDomain.DomainUnload       -= CurrentDomain_DomainUnload;
                AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
                AppDomain.CurrentDomain.ProcessExit        -= CurrentDomain_ProcessExit;
#endif

                _IsDisposed = true;
                _BufferTimeoutTimer?.Dispose();

                _WriteBufferedEventsSignal?.Set();
                WaitForBackgroundThreadToExit();

                (_LogWriter as IDisposable)?.Dispose();
                _WriteBufferedEventsSignal?.Dispose();

                var emptySignal = _QueueEmptySignal;
                _QueueEmptySignal = null;
                emptySignal?.Dispose();

                _LogEventPool?.Dispose();
            }
#endif
        }
Ejemplo n.º 6
0
 private void FCrop_FormClosed(object sender, FormClosedEventArgs e)
 {
     workingImage.Dispose();
     workingImage2.Dispose();
     pictureBox.Image?.Dispose();
     previewTimer?.Dispose();
 }
Ejemplo n.º 7
0
        public static void BuildSample(IAppBuilder app)
        {
            // add eventsource middleware
            app.EventSource(envKey);
            app.Run(context => {

                // get the event stream (not captured yet)
                var eventStream = context.Environment[envKey] as IEventStream;

                // create some timers to send mesages
                var timer = new System.Threading.Timer(_ => {
                    var ts = DateTime.UtcNow.ToString("O");
                    eventStream.WriteAsync("Timer1:" + ts + message + "\n");
                }, null, 1,  50);
                var timer2 = new System.Threading.Timer(_ => {
                    var ts = DateTime.UtcNow.ToString("O");
                    eventStream.WriteAsync("Timer 2:" + ts + "\n");
                }, null, 1,  25);

                // Capture the eventstream by calling Open and pass in the 
                // clean-up logic for when this client closes the stream
                var task =  eventStream.Open(() => {
                    Console.WriteLine("Closed");
                    timer.Dispose();
                    timer2.Dispose();
                });

                eventStream.WriteAsync("Started\n");
                return task;
            });
        }
Ejemplo n.º 8
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                _logMsgTimer?.Dispose();
                _logMsgTimer = null;

                _taskbarProgressTimer?.Dispose();
                _taskbarProgressTimer = null;


                if (_configuration.Layout.LogListViewColumnsWidths == null ||
                    _configuration.Layout.LogListViewColumnsWidths.Length != logListView.Columns.Count)
                {
                    _configuration.Layout.LogListViewColumnsWidths = new int[logListView.Columns.Count];
                }

                for (var i = 0; i < logListView.Columns.Count; i++)
                {
                    _configuration.Layout.LogListViewColumnsWidths[i] = logListView.Columns[i].Width;
                }

                _configuration.Layout.Set(_windowRestorer.WindowPosition, _windowRestorer.WindowState, logDetailPanel,
                                          loggerPanel);

                _configuration.Save();
                _configuration.Close();
            }
            catch
            {
                // ignored
            }
        }
Ejemplo n.º 9
0
 public void UnhookEvents()
 {
     context.OnHealthChange        -= OnHealthChange;
     context.OnBrokenCounterChange -= OnBrokenCounterChange;
     visibilityTimer?.Dispose();
     context = null;
 }
Ejemplo n.º 10
0
 public void UnhookEvents()
 {
     Context.OnHealthChange        -= OnHealthChange;
     Context.OnBrokenCounterChange -= OnBrokenCounterChange;
     VisibilityTimer?.Dispose();
     this.Context = null;
 }
Ejemplo n.º 11
0
 public virtual void Dispose()
 {
     StopSelfCheckThreadTimer();
     StopTaskThreadTimer();
     _selfCheckThreadTimer?.Dispose();
     _taskThreadTimer?.Dispose();
 }
 public override void Stop()
 {
     base.Stop();
     _currentVideoCapture?.Dispose();
     _worker?.Dispose();
     _isRunning = false;
     SurrogateFramework.MainController.ProcessHandler.StartProcess(FrameworkConstants.ControllerProcessName);
 }
Ejemplo n.º 13
0
 public void UnhookEvents()
 {
     Context.OnBuildupChange  -= OnBuildupChange;
     Context.OnDurationChange -= OnDurationChange;
     Context.OnCounterChange  -= OnCounterChange;
     VisibilityTimer?.Dispose();
     Context = null;
 }
Ejemplo n.º 14
0
 private void ImageForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     workingImage?.Dispose();
     workingImage2?.Dispose();
     PictureBox.Image?.Dispose();
     previewTimer?.Dispose();
     closed = true;
 }
Ejemplo n.º 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Text = "A";

            System.Threading.Timer t = new System.Threading.Timer((o) => { }, null, 0, 1000);
            t.Dispose();
            string a = "";
        }
Ejemplo n.º 16
0
        private void StopListen()
        {
            button1.Enabled             = false;
            TriggerRun_MenuItem.Enabled = false;

            threadTimer?.Dispose();
            UpdateLog(@"已停止...");

            ID_Box.Enabled     = true;
            Secret_Box.Enabled = true;
            Domain_Box.Enabled = true;
            RR_Box.Enabled     = true;

            button1.Text                = @"Start";
            TriggerRun_MenuItem.Text    = @"Start";
            button1.Enabled             = true;
            TriggerRun_MenuItem.Enabled = true;
        }
Ejemplo n.º 17
0
 private void CommonInitialize()
 {
     // Create map
     Map = new Map();
     // Create timer for invalidating the control
     _invalidateTimer?.Dispose();
     _invalidateTimer = new System.Threading.Timer(InvalidateTimerCallback, null, System.Threading.Timeout.Infinite, 16);
     // Start the invalidation timer
     StartUpdates(false);
 }
Ejemplo n.º 18
0
    /*
     * Suspend the timer interrupt handling.
     */
    static void Timer_InterruptSuspend()
    {
        s_timer?.Change(Timeout.Infinite, Timeout.Infinite);
        s_timer?.Dispose();
        s_timer = null;

        //if (s_timerThread != IntPtr.Zero) Kernel32.DeleteTimerQueueTimer(Kernel32.TimerQueueHandle.NULL, s_timerThread, Kernel32.SafeEventHandle.Null);

        //s_timerThread = IntPtr.Zero;
    }
Ejemplo n.º 19
0
        public static Task Delay(int milliseconds)
        {
#if NET_4_0
            var tcs = new TaskCompletionSource<int>();
            var timer = new System.Threading.Timer(_ => tcs.SetResult(0), null, milliseconds, System.Threading.Timeout.Infinite);
            return tcs.Task.ContinueWith(t => timer.Dispose(), TaskScheduler.Default);
#else
            return Task.Delay(milliseconds);
#endif
        }
Ejemplo n.º 20
0
 public void Dispose()
 {
     if (disposed)
     {
         return;
     }
     Closed -= OnClosed;
     _timeoutTimer?.Dispose();
     disposed = true;
 }
Ejemplo n.º 21
0
        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                components?.Dispose();
                _screenShareServer?.Dispose();
                _fpsUpdateTimer?.Dispose();
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 22
0
        public MainWindow()
        {
            InitializeComponent();

            Loaded += MainWindow_Loaded;

            Unloaded += (sender, e) =>
            {
                _timer?.Dispose();
            };
        }
Ejemplo n.º 23
0
        private bool disposed = false;         // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    timer?.Dispose();
                }

                disposed = true;
            }
        }
Ejemplo n.º 24
0
        private void Callback(object state)
        {
            ProxyState proxyState = ChangeContextMenuStripItemsByProxyState();

            if (proxyState != _proxySwitcher.RequiredProxyState)
            {
                _proxySwitcher.Switch(_proxySwitcher.RequiredProxyState);
                ChangeContextMenuStripItemsByProxyState();
            }

            if (_stopwatch.IsRunning && _stopwatch.Elapsed >= TimeSpan.FromMinutes(1))
            {
                _timer?.Dispose();
                _timer = null;
                _stopwatch.Stop();
            }
        }
Ejemplo n.º 25
0
        public void Stop()
        {
            if (_poll != null)
            {
                _poll.Dispose();
                _poll = null;
            }

            _dispatcher.Invoke(() =>
            {
                if (_status.Status == ServerStatusEnum.Processing)
                {
                    _status.Status = ServerStatusEnum.Stopping;
                }
                else
                {
                    _status.Status = ServerStatusEnum.Stopped;
                }
            });
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Set Timer based on timespan parameter
        /// </summary>
        /// <param name="ts"></param>
        static Boolean setAlarm(TimeSpan ts)
        {
            log.Debug("setting alarm with timespan: " + ts + "which has " + ts.TotalHours + " of total hours and " + ts.TotalMinutes + " of total minutes");
            if (timer != null)
            {
                timer.Dispose();
            }
            if (ts.Seconds <= 0)
            {
                sendNotification("Y u no send me proper alarm time?");
                return(false);
            }
            else
            {
                timer = new System.Threading.Timer(new System.Threading.TimerCallback(ringAlarm), null, ts, TimeSpan.FromHours(24));
                sendNotification("Settings set successfully");

                return(true);
            }
        }
Ejemplo n.º 27
0
 private void DoScavenge(object notUsed)
 {
     if (this.State == Osrs.Runtime.RunState.Running)
     {
         try
         {
             prov.DeleteExpired();
         }
         catch { }
     }
     else if (scavengeTimer != null)
     {
         try
         {
             scavengeTimer.Change(System.Threading.Timeout.Infinite, 60000); //just to be safe here
             scavengeTimer.Dispose();
         }
         catch { }
     }
 }
 public void Stop()
 {
     // Wait for timer queue to be emptied, before we continue
     // (Timer threads should have left the callback method given)
     // - http://woowaabob.blogspot.dk/2010/05/properly-disposing-systemthreadingtimer.html
     // - http://blogs.msdn.com/b/danielvl/archive/2011/02/18/disposing-system-threading-timer.aspx
     lock (_threadLock)
     {
         if (_timer != null)
         {
             WaitHandle waitHandle = new AutoResetEvent(false);
             if (_timer.Dispose(waitHandle))
             {
                 // Timer has not been disposed by someone else
                 WaitHandle.WaitAll(new[] { waitHandle }, TimeSpan.FromMinutes(2));
                 _timer = null;
             }
         }
     }
 }
        public static void Shutdown()
        {
            try
            {
                if (!PersistentData.Instance.Telemetry)
                {
                    return;
                }

                _heartbeatTimer?.Dispose();
                Log.Debug("Telemetry heartbeat stopped.");
                CollectEvent("app", "stop", sessionControl: "end");
            }
            catch (Exception ex)
            {
#if DEBUG
                Log.Exception(ex);
#endif
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Stop connection to Ge.tt Live.
        /// </summary>
        public void Stop()
        {
            if (_webSocket != null)
            {
                lock (_watchDogSyncRoot)
                {
                    if (_watchDog != null)
                    {
                        _watchDog.Dispose();
                        _watchDog = null;
                    }
                }

                _webSocket.OnOpen    -= WebSocket_OnOpen;
                _webSocket.OnClose   -= WebSocket_OnClose;
                _webSocket.OnError   -= WebSocket_OnError;
                _webSocket.OnMessage -= WebSocket_OnMessage;
                _webSocket.Close();
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Reports the end of the process/time period to measure.
        /// </summary>
        public void Stop(bool report = true)
        {
            if (_memoryUsageTimer != null)
            { // only dispose and stop when there IS a timer.
                _memoryUsageTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                _memoryUsageTimer.Dispose();
            }
            if (_ticks.HasValue)
            {
                lock (_memoryUsageLog)
                {
                    var seconds = new TimeSpan(DateTime.Now.Ticks - _ticks.Value - _memoryUsageLoggingDuration).TotalMilliseconds / 1000.0;

                    //GC.Collect();
                    var p          = Process.GetCurrentProcess();
                    var memoryDiff = System.Math.Round((p.PrivateMemorySize64 - _memory.Value) / 1024.0 / 1024.0, 4);

                    if (_memoryUsageLog.Count > 0)
                    { // there was memory usage logging.
                        double max = _memoryUsageLog.Max();
                        if (report)
                        {
                            Itinero.Logging.Logger.Log("PF:" + _name, Itinero.Logging.TraceEventType.Information,
                                                       string.Format("Ended at at {0}, spent {1}s and {2}MB of memory diff with {3}MB max used.",
                                                                     new DateTime(_ticks.Value).ToShortTimeString(),
                                                                     seconds, memoryDiff, max));
                        }
                    }
                    else
                    { // no memory usage logged.
                        if (report)
                        {
                            Itinero.Logging.Logger.Log("PF:" + _name, Itinero.Logging.TraceEventType.Information,
                                                       string.Format("Ended at at {0}, spent {1}s and {2}MB of memory diff.",
                                                                     new DateTime(_ticks.Value).ToShortTimeString(),
                                                                     seconds, memoryDiff));
                        }
                    }
                }
            }
        }
Ejemplo n.º 32
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_sqlConn.State == ConnectionState.Open)
                {
                    _sqlConn.Close();
                }
                if (_internalsqlConn != null && _internalsqlConn.State == ConnectionState.Open)
                {
                    _internalsqlConn.Close();
                }

                PropertyChanged = null;

                _cmd.Dispose();
                _sqlConn.Dispose();

                if (_internalCmd != null)
                {
                    _internalCmd.Dispose();
                }
                if (_internalsqlConn != null)
                {
                    _internalsqlConn.Dispose();
                }
                if (_checkDBTrhead != null)
                {
                    _checkDBTrhead.Dispose();
                }
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
Ejemplo n.º 33
0
        private void ToInitialize()
        {
            if (!mInitialized)
            {
                mReceiveDispatchCenter = new Dispatchs.DispatchCenter <SocketAsyncEventArgsX>(ProcessReceiveArgs, Options.IOQueues);
                int maxBufferSize;
                if (Options.BufferPoolMaxMemory == 0)
                {
                    Options.BufferPoolMaxMemory = 500;
                }
                maxBufferSize = (int)(((long)Options.BufferPoolMaxMemory * 1024 * 1024) / Options.BufferSize / Options.BufferPoolGroups);
                if (maxBufferSize < Options.BufferPoolSize)
                {
                    maxBufferSize = Options.BufferPoolSize;
                }
                mReceiveBufferPoolGroup = new BufferPoolGroup(Options.BufferSize, Options.BufferPoolSize, maxBufferSize, Options.BufferPoolGroups);
                mSendBufferPoolGroup    = new BufferPoolGroup(Options.BufferSize, Options.BufferPoolSize, maxBufferSize, Options.BufferPoolGroups);
                mSessions         = new ConcurrentDictionary <long, ISession>();
                mInitialized      = true;
                mAcceptDispatcher = new Dispatchs.DispatchCenter <AcceptSocketInfo>(AcceptProcess, Math.Min(Environment.ProcessorCount, 16));
                if (Options.SessionTimeOut > 0)
                {
                    if (Options.SessionTimeOut * 1000 < mTimeOutCheckTime)
                    {
                        mTimeOutCheckTime = Options.SessionTimeOut * 1000;
                    }
                    else
                    {
                        mTimeOutCheckTime = Options.SessionTimeOut * 1000;
                    }

                    if (mDetectionTimer != null)
                    {
                        mDetectionTimer.Dispose();
                    }
                    mDetectionTimer = new System.Threading.Timer(OnDetectionHandler, null,
                                                                 mTimeOutCheckTime, mTimeOutCheckTime);
                    Log(LogType.Info, null, "detection sessions timeout with {0}s", Options.SessionTimeOut);
                }
            }
        }
Ejemplo n.º 34
0
 int RunMinimizeTest()
 {
     stateCount =-1;
     time1 = 0;
     time2 = 0;
     System.Threading.Timer timer = new System.Threading.Timer(KillTest, null, 1000, 1000);
     System.Threading.ThreadStart test = new System.Threading.ThreadStart(RunMinimize);
     currTest = new System.Threading.Thread(test);
     currTest.Start();
     while (stateCount == -1)
     {
         System.Threading.Thread.Sleep(50);
     }
     timer.Dispose();
     return stateCount;
 }
Ejemplo n.º 35
0
        private static void Wait()
        {
            Int32 intProcessWaitInMins = 1;
            if (System.Configuration.ConfigurationManager.AppSettings["ProcessWaitInMins"] != null)
                intProcessWaitInMins = Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["ProcessWaitInMins"].ToString(), out intProcessWaitInMins) ? intProcessWaitInMins : 1;

            WriteProcessToMonitor("Waiting " + intProcessWaitInMins.ToString("#,##0") + "Mins for next process...");

            // Create a Timer object that knows to call our TimerCallback
            // method once every 2000 milliseconds.
            iTmrCtr = 0;
            System.Threading.Timer t = new System.Threading.Timer(TimerCallback, null, 0, 2000);

            System.Threading.Thread.Sleep(60000 * intProcessWaitInMins);

            t.Dispose(); // Cancel the timer now
            Console.WriteLine();
        }
Ejemplo n.º 36
0
        public static void RealMain(string[] args)
        {
            //If we are on Windows, append the bundled "win-tools" programs to the search path
            //We add it last, to allow the user to override with other versions
            if (!Library.Utility.Utility.IsClientLinux)
            {
                Environment.SetEnvironmentVariable("PATH",
                    Environment.GetEnvironmentVariable("PATH") +
                    System.IO.Path.PathSeparator.ToString() +
                    System.IO.Path.Combine(
                        System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
                        "win-tools")
                );
            }

            //If this executable is invoked directly, write to console, otherwise throw exceptions
            bool writeConsole = System.Reflection.Assembly.GetEntryAssembly() == System.Reflection.Assembly.GetExecutingAssembly();

            //If we are on windows we encrypt the database by default
            //We do not encrypt on Linux as most distros use a SQLite library without encryption support,
            //Linux users can use an encrypted home folder, or install a SQLite library with encryption support
            if (!Library.Utility.Utility.IsClientLinux && string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DB_KEY_ENV_NAME)))
            {
                //Note that the password here is a default password and public knowledge
                //
                //The purpose of this is to prevent casual read of the database, as well
                // as protect from harddisk string scans, not to protect from determined
                // attacks.
                //
                //If you desire better security, start Duplicati once with the commandline option
                // --unencrypted-database to decrypt the database.
                //Then set the environment variable DUPLICATI_DB_KEY to the desired key,
                // and run Duplicati again without the --unencrypted-database option
                // to re-encrypt it with the new key
                //
                //If you change the key, please note that you need to supply the same
                // key when restoring the setup, as the setup being backed up will
                // be encrypted as well.
                Environment.SetEnvironmentVariable(DB_KEY_ENV_NAME, Library.AutoUpdater.AutoUpdateSettings.AppName + "_Key_42");
            }

            //Find commandline options here for handling special startup cases
            Dictionary<string, string> commandlineOptions = Duplicati.Library.Utility.CommandLineParser.ExtractOptions(new List<string>(args));

            foreach(string s in args)
                if (
                    s.Equals("help", StringComparison.InvariantCultureIgnoreCase) ||
                    s.Equals("/help", StringComparison.InvariantCultureIgnoreCase) ||
                    s.Equals("usage", StringComparison.InvariantCultureIgnoreCase) ||
                    s.Equals("/usage", StringComparison.InvariantCultureIgnoreCase))
                    commandlineOptions["help"] = "";

            //If the commandline issues --help, just stop here
            if (commandlineOptions.ContainsKey("help"))
            {
                if (writeConsole)
                {
                    Console.WriteLine(Strings.Program.HelpDisplayDialog);

                    foreach(Library.Interface.ICommandLineArgument arg in SupportedCommands)
                        Console.WriteLine(Strings.Program.HelpDisplayFormat(arg.Name, arg.LongDescription));

                    return;
                }
                else
                {
                    throw new Exception("Server invoked with --help");
                }

            }

            #if DEBUG
            //Log various information in the logfile
            if (!commandlineOptions.ContainsKey("log-file"))
            {
                commandlineOptions["log-file"] = System.IO.Path.Combine(StartupPath, "Duplicati.debug.log");
                commandlineOptions["log-level"] = Duplicati.Library.Logging.LogMessageType.Profiling.ToString();
            }
            #endif
            // Allow override of the environment variables from the commandline
            if (commandlineOptions.ContainsKey("server-datafolder"))
                Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, commandlineOptions["server-datafolder"]);
            if (commandlineOptions.ContainsKey("server-encryption-key"))
                Environment.SetEnvironmentVariable(DB_KEY_ENV_NAME, commandlineOptions["server-encryption-key"]);

            //Set the %DUPLICATI_HOME% env variable, if it is not already set
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DATAFOLDER_ENV_NAME)))
            {
            #if DEBUG
                //debug mode uses a lock file located in the app folder
                Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, StartupPath);
            #else
                bool portableMode = commandlineOptions.ContainsKey("portable-mode") ? Library.Utility.Utility.ParseBool(commandlineOptions["portable-mode"], true) : false;

                if (portableMode)
                {
                    //Portable mode uses a data folder in the application home dir
                    Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, System.IO.Path.Combine(StartupPath, "data"));
                }
                else
                {
                    //Normal release mode uses the systems "Application Data" folder
                    Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Library.AutoUpdater.AutoUpdateSettings.AppName));
                }
            #endif
            }

            try
            {
                try
                {
                    //This will also create Program.DATAFOLDER if it does not exist
                    Instance = new SingleInstance(Duplicati.Library.AutoUpdater.AutoUpdateSettings.AppName, Program.DATAFOLDER);
                }
                catch (Exception ex)
                {
                    if (writeConsole)
                    {
                        Console.WriteLine(Strings.Program.StartupFailure(ex));
                        return;
                    }
                    else
                    {
                        throw new Exception(Strings.Program.StartupFailure(ex));
                    }
                }

                if (!Instance.IsFirstInstance)
                {
                    if (writeConsole)
                    {
                        Console.WriteLine(Strings.Program.AnotherInstanceDetected);
                        return;
                    }
                    else
                    {
                        throw new SingleInstance.MultipleInstanceException(Strings.Program.AnotherInstanceDetected);
                    }
                }

                // Setup the log redirect
                Duplicati.Library.Logging.Log.CurrentLog = Program.LogHandler;

                if (commandlineOptions.ContainsKey("log-file"))
                {
                    if (System.IO.File.Exists(commandlineOptions["log-file"]))
                        System.IO.File.Delete(commandlineOptions["log-file"]);

                    var loglevel = Duplicati.Library.Logging.LogMessageType.Error;

                    if (commandlineOptions.ContainsKey("log-level"))
                        Enum.TryParse<Duplicati.Library.Logging.LogMessageType>(commandlineOptions["log-level"], true, out loglevel);

                    Program.LogHandler.SetServerFile(commandlineOptions["log-file"], loglevel);
                }

                Version sqliteVersion = new Version((string)Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType.GetProperty("SQLiteVersion").GetValue(null, null));
                if (sqliteVersion < new Version(3, 6, 3))
                {
                    if (writeConsole)
                    {
                        //The official Mono SQLite provider is also broken with less than 3.6.3
                        Console.WriteLine(Strings.Program.WrongSQLiteVersion(sqliteVersion, "3.6.3"));
                        return;
                    }
                    else
                    {
                        throw new Exception(Strings.Program.WrongSQLiteVersion(sqliteVersion, "3.6.3"));
                    }
                }

                //Create the connection instance
                System.Data.IDbConnection con = (System.Data.IDbConnection)Activator.CreateInstance(Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType);

                try
                {
                    DatabasePath = System.IO.Path.Combine(Program.DATAFOLDER, "Duplicati-server.sqlite");
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(DatabasePath)))
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(DatabasePath));

            #if DEBUG
                    //Default is to not use encryption for debugging
                    Program.UseDatabaseEncryption = commandlineOptions.ContainsKey("unencrypted-database") ? !Library.Utility.Utility.ParseBool(commandlineOptions["unencrypted-database"], true) : false;
            #else
                    Program.UseDatabaseEncryption = commandlineOptions.ContainsKey("unencrypted-database") ? !Library.Utility.Utility.ParseBool(commandlineOptions["unencrypted-database"], true) : true;
            #endif
                    con.ConnectionString = "Data Source=" + DatabasePath;

                    //Attempt to open the database, handling any encryption present
                    OpenDatabase(con);

                    Duplicati.Library.SQLiteHelper.DatabaseUpgrader.UpgradeDatabase(con, DatabasePath, typeof(Duplicati.Server.Database.Connection));
                }
                catch (Exception ex)
                {
                    //Unwrap the reflection exceptions
                    if (ex is System.Reflection.TargetInvocationException && ex.InnerException != null)
                        ex = ex.InnerException;

                    if (writeConsole)
                    {
                        Console.WriteLine(Strings.Program.DatabaseOpenError(ex.Message));
                        return;
                    }
                    else
                    {
                        throw new Exception(Strings.Program.DatabaseOpenError(ex.Message), ex);
                    }
                }

                DataConnection = new Duplicati.Server.Database.Connection(con);

                if (!DataConnection.ApplicationSettings.FixedInvalidBackupId)
                    DataConnection.FixInvalidBackupId();

                if (commandlineOptions.ContainsKey("webservice-password"))
                    Program.DataConnection.ApplicationSettings.SetWebserverPassword(commandlineOptions["webservice-password"]);

                ApplicationExitEvent = new System.Threading.ManualResetEvent(false);

                Duplicati.Library.AutoUpdater.UpdaterManager.OnError += (Exception obj) =>
                {
                    Program.DataConnection.LogError(null, "Error in updater", obj);
                };

                UpdatePoller = new UpdatePollThread();
                DateTime lastPurge = new DateTime(0);

                System.Threading.TimerCallback purgeTempFilesCallback = (x) => {
                    try
                    {
                        if (Math.Abs((DateTime.Now - lastPurge).TotalHours) < 23)
                            return;

                        lastPurge = DateTime.Now;

                        foreach(var e in Program.DataConnection.GetTempFiles().Where((f) => f.Expires < DateTime.Now))
                        {
                            try
                            {
                                if (System.IO.File.Exists(e.Path))
                                    System.IO.File.Delete(e.Path);
                            }
                            catch (Exception ex)
                            {
                                Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", e.Path), ex);
                            }

                            Program.DataConnection.DeleteTempFile(e.ID);
                        }

                        Duplicati.Library.Utility.TempFile.RemoveOldApplicationTempFiles((path, ex) => {
                            Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", path), ex);
                        });

                        string pts;
                        if (!commandlineOptions.TryGetValue("log-retention", out pts))
                            pts = DEFAULT_LOG_RETENTION;

                        Program.DataConnection.PurgeLogData(Library.Utility.Timeparser.ParseTimeInterval(pts, DateTime.Now, true));
                    }
                    catch (Exception ex)
                    {
                        Program.DataConnection.LogError(null, "Failed during temp file cleanup", ex);
                    }
                };

                try
                {
                    PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromDays(1));
                }
                catch (ArgumentOutOfRangeException)
                {
                    //Bugfix for older Mono, slightly more resources used to avoid large values in the period field
                    PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
                }

                LiveControl = new LiveControls(DataConnection.ApplicationSettings);
                LiveControl.StateChanged += new EventHandler(LiveControl_StateChanged);
                LiveControl.ThreadPriorityChanged += new EventHandler(LiveControl_ThreadPriorityChanged);
                LiveControl.ThrottleSpeedChanged += new EventHandler(LiveControl_ThrottleSpeedChanged);

                Program.WorkThread = new Duplicati.Library.Utility.WorkerThread<Runner.IRunnerData>((x) =>
                {
                    Runner.Run(x, true);
                }, LiveControl.State == LiveControls.LiveControlState.Paused);
                Program.Scheduler = new Scheduler(WorkThread);

                Program.WorkThread.StartingWork += (worker, task) => { SignalNewEvent(null, null); };
                Program.WorkThread.CompletedWork += (worker, task) => { SignalNewEvent(null, null); };
                Program.WorkThread.WorkQueueChanged += (worker) => { SignalNewEvent(null, null); };
                Program.Scheduler.NewSchedule += new EventHandler(SignalNewEvent);
                Program.WorkThread.OnError += (worker, task, exception) => { Program.DataConnection.LogError(task == null ? null : task.BackupID, "Error in worker", exception); };

                Action<long, Exception> registerTaskResult = (id, ex) => {
                    lock(Program.MainLock) {

                        // If the new results says it crashed, we store that instead of success
                        if (Program.TaskResultCache.Count > 0 && Program.TaskResultCache.Last().Key == id)
                        {
                            if (ex != null && Program.TaskResultCache.Last().Value == null)
                                Program.TaskResultCache.RemoveAt(Program.TaskResultCache.Count - 1);
                            else
                                return;
                        }

                        Program.TaskResultCache.Add(new KeyValuePair<long, Exception>(id, ex));
                        while(Program.TaskResultCache.Count > MAX_TASK_RESULT_CACHE_SIZE)
                            Program.TaskResultCache.RemoveAt(0);
                    }
                };

                Program.WorkThread.CompletedWork += (worker, task) => { registerTaskResult(task.TaskID, null); };
                Program.WorkThread.OnError += (worker, task, exception) => { registerTaskResult(task.TaskID, exception); };

                Program.WebServer = new WebServer.Server(commandlineOptions);

                if (Program.WebServer.Port != DataConnection.ApplicationSettings.LastWebserverPort)
                    ServerPortChanged = true;
                DataConnection.ApplicationSettings.LastWebserverPort = Program.WebServer.Port;

                if (Library.Utility.Utility.ParseBoolOption(commandlineOptions, "ping-pong-keepalive"))
                {
                    Program.PingPongThread = new System.Threading.Thread(PingPongMethod);
                    Program.PingPongThread.IsBackground = true;
                    Program.PingPongThread.Start();
                }

                ServerStartedEvent.Set();
                ApplicationExitEvent.WaitOne();
            }
            catch (SingleInstance.MultipleInstanceException mex)
            {
                System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(mex.ToString()));
                if (writeConsole)
                    Console.WriteLine(Strings.Program.SeriousError(mex.ToString()));
                else
                    throw mex;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(ex.ToString()));
                if (writeConsole)
                    Console.WriteLine(Strings.Program.SeriousError(ex.ToString()));
                else
                    throw new Exception(Strings.Program.SeriousError(ex.ToString()), ex);
            }
            finally
            {
                StatusEventNotifyer.SignalNewEvent();

                if (UpdatePoller != null)
                    UpdatePoller.Terminate();
                if (Scheduler != null)
                    Scheduler.Terminate(true);
                if (WorkThread != null)
                    WorkThread.Terminate(true);
                if (Instance != null)
                    Instance.Dispose();
                if (PurgeTempFilesTimer != null)
                    PurgeTempFilesTimer.Dispose();

                if (PingPongThread != null)
                    try { PingPongThread.Abort(); }
                    catch { }

                if (LogHandler != null)
                    LogHandler.Dispose();

            }
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Restart plex, wait for the specified delay between stop and start
 /// </summary>
 /// <param name="msDelay">The amount of time in ms to wait before starting after stop</param>
 internal void Restart(int delay)
 {
     Stop();
     State = PlexState.Pending;
     System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
     System.Threading.Timer t = new System.Threading.Timer((x) => { Start(); autoEvent.Set(); }, null, delay, System.Threading.Timeout.Infinite);
     autoEvent.WaitOne();
     t.Dispose();
 }
Ejemplo n.º 38
0
        /// <summary>
        /// This event fires when the plex process we have a reference to exits
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void plex_Exited(object sender, EventArgs e)
        {
            OnPlexStatusChange(this, new StatusChangeEventArgs("Plex Media Server has stopped!"));
            //unsubscribe
            _plex.Exited -= plex_Exited;

            //kill the supporting processes.
            killSupportingProcesses();

            if (_plex != null)
            {
                _plex.Dispose();
                _plex = null;
            }

            //restart as required
            Settings settings = SettingsHandler.Load();
            if (State != PlexState.Stopping && settings.AutoRestart)
            {
                OnPlexStatusChange(this, new StatusChangeEventArgs(string.Format("Waiting {0} seconds before re-starting the Plex process.", settings.RestartDelay)));
                State = PlexState.Pending;
                System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
                System.Threading.Timer t = new System.Threading.Timer((x) => { Start(); autoEvent.Set(); }, null, settings.RestartDelay * 1000, System.Threading.Timeout.Infinite);
                autoEvent.WaitOne();
                t.Dispose();
            }
            else
            {
                //set the status
                State = PlexState.Stopped;
            }
        }
 /// <summary>
 /// This event fires when the process we have a refrence to exits
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void auxProcess_Exited(object sender, EventArgs e)
 {
     if (_aux.KeepAlive)
     {
         OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " has stopped!"));
         //unsubscribe
         _auxProcess.Exited -= auxProcess_Exited;
         end();
         //restart as required
         if (!_stopping)
         {
             OnStatusChange(this, new StatusChangeEventArgs("Re-starting " + _aux.Name));
             //wait some seconds first
             System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
             System.Threading.Timer t = new System.Threading.Timer((x) => { start(); autoEvent.Set(); }, null, 5000, System.Threading.Timeout.Infinite);
             autoEvent.WaitOne();
             t.Dispose();
         }
         else
         {
             OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " stopped"));
             Running = false;
         }
     }
     else
     {
         OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " has completed"));
         //unsubscribe
         _auxProcess.Exited -= this.auxProcess_Exited;
         _auxProcess.Dispose();
         Running = false;
     }
 }
Ejemplo n.º 40
0
        public static void Main(string[] args)
        {
            EventWithCallback ec = new EventWithCallback();
            for (int i = 0; i < 500; i++)
            {
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    ec.Wait(String.Format("world. From Thread {0:X}", System.Threading.Thread.CurrentThread.GetHashCode()));

                }));
                t.Start();
            }

            var timer = new System.Threading.Timer(new System.Threading.TimerCallback(timercb), ec, 0, 2000);
            Console.ReadLine();
            timer.Dispose();
        }
Ejemplo n.º 41
0
		private TempFileManager()
		{
			// set up timer to periodically remove expired entries
			_timer = new Timer(TimerCallback, null, SweepInterval, SweepInterval);

			// also remove all entries when the desktop is shutdown
			// (it isn't nice to have this dependency here, but seems to be no other easy way to do this)
			Desktop.Application.Quitting +=
				(sender, args) =>
					{
						_timer.Dispose();
						Clean(obj => true);
					};
		}