/// <summary>
 ///
 /// </summary>
 public void OperationWarning(string warningMessage, TracerItem.PriorityEnum priority)
 {
     if (_enabledOperationWarning)
     {
         SystemMonitor.OperationWarning(warningMessage, priority);
     }
 }
 /// <summary>
 /// Report operation warning; it is a normal occurence in the work of the system. It can be caused
 /// for example by the lack of access to a resource or some error in a data stream.
 /// </summary>
 /// <param name="warningMessage"></param>
 public void OperationWarning(string warningMessage)
 {
     if (_enabledOperationWarning)
     {
         SystemMonitor.OperationWarning(warningMessage);
     }
 }
Exemple #3
0
        /// <summary>
        /// Perform the actual update of feeds.
        /// </summary>
        public void UpdateFeeds()
        {
            if (_isUpdating)
            {// Already updating.
                return;
            }

            _isUpdating = true;

            EventSource[] sources = NewsSourcesArray;

            if (UpdatingStartedEvent != null)
            {
                UpdatingStartedEvent(this);
            }

            foreach (EventSource source in sources)
            {
                try
                {
                    source.Update();
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationWarning("Failed to update news source [" + source.Name + ", " + ex.Message + "].");
                }
            }

            _isUpdating = false;

            if (UpdatingFinishedEvent != null)
            {
                UpdatingFinishedEvent(this);
            }
        }
        /// <summary>
        /// On update, update items.
        /// </summary>
        protected override void OnUpdate()
        {
            try
            {
                if (_feed == null)
                {
                    _feed = RssFeed.Read(base.Address);

                    if (_feed.Channels.Count == 1)
                    {
                        // Some feeds have those symbols in their names.
                        _name = _feed.Channels[0].Title.Replace("\r", "").Replace("\n", "").Trim();
                    }
                    else
                    {
                        _name = _feed.Url.ToString();
                    }

                    List <string> names = new List <string>();
                    foreach (RssChannel channel in _feed.Channels)
                    {
                        names.Add(channel.Title);
                    }

                    foreach (string name in names)
                    {
                        if (ChannelsNames.Contains(name) == false)
                        {
                            EventSourceChannel channel = new EventSourceChannel(name, true);
                            channel.Initialize(this);
                            base.AddChannel(channel);
                        }
                    }
                }
                else
                {
                    _feed = RssFeed.Read(_feed);
                }

                //OperationalStateEnum newState = OperationalStateEnum.Operational;
            }
            catch (WebException we)
            {// Feed not found or some other problem.
                SystemMonitor.OperationWarning("Failed to initialize feed [" + Address + ", " + we.Message + "]");
                ChangeOperationalState(OperationalStateEnum.NotOperational);
            }
            catch (Exception ex)
            {// RssFeed class launches IOExceptions too, so get safe here.
                SystemMonitor.OperationWarning("Failed to initialize feed [" + Address + ", " + ex.Message + "]");
                ChangeOperationalState(OperationalStateEnum.NotOperational);
            }

            DoUpdateItems();

            //RaisePersistenceDataUpdatedEvent();
        }
Exemple #5
0
        /// <summary>
        /// Add items to channel.
        /// The items added may be with no assiged Id, or a duplication of other items.
        /// </summary>
        public virtual void AddItems(IEnumerable <EventBase> items)
        {
            SystemMonitor.CheckError(_source != null, "Source not assigned.");

            if (this.Enabled == false)
            {
                SystemMonitor.OperationWarning("Will not add items to disabled channel.");
                return;
            }

            List <EventBase> itemsAdded = new List <EventBase>();

            foreach (EventBase item in items)
            {
                if (item.DateTime.HasValue == false)
                {
                    SystemMonitor.OperationError("Event with no date time assigned can not be processed.");
                    continue;
                }

                lock (this)
                {
                    if (_items.ContainsKey(item) &&
                        _itemsUpdateEnabled == false)
                    {// Already an item with this Id is known.
                        continue;
                    }

                    if (_enableLatestEventTitleDuplicationProtection &&
                        ((DateTime.Now - item.DateTime) < _latestEventsFilterPeriod))
                    {
                        if (_latestEvents.ContainsKey(item.Title) == false)
                        {// Gather items from the last X days.
                            _latestEvents.Add(item.Title, item);
                        }
                        else
                        {// Item wit this title already known.
                            continue;
                        }
                    }

                    _items[item] = item;
                }

                if (ItemsAddedEvent != null)
                {
                    itemsAdded.Add(item);
                }
            }

            if (ItemsAddedEvent != null)
            {
                ItemsAddedEvent(_source, this, itemsAdded);
            }
        }
Exemple #6
0
        /// <summary>
        /// Helper, process the items gathered in the execution queue.
        /// </summary>
        void ProcessQueue()
        {
            SystemMonitor.Variables.SetValue(this, this.Name + ".Queue", _queue.Count);
            lock (_queue)
            {
                if (_queue.Count == 0)
                {
                    return;
                }
            }

            SystemMonitor.Variables.SetValue(this, this.Name + ".TotalThreads", _threads.Count);
            SystemMonitor.Variables.SetValue(this, this.Name + ".ActiveThreads", _activeRunningThreadsCount);

            lock (_threads)
            {
                if (MaximumTotalThreadsAllowed <= _threads.Count)
                {
                    SystemMonitor.OperationWarning("[" + _name + "] Too many total threads, suspeding.");
                    return;
                }

                // Keep these inside the lock section.
                if (_activeRunningThreadsCount >= MaximumSimultaniouslyRunningThreadsAllowed)
                {
                    SystemMonitor.OperationWarning("[" + _name + "] Too many running threads, suspeding.");
                    return;
                }

                foreach (ThreadInfo info in _threads.Values)
                {
                    if (info.Activated == false)
                    {// Found a sleeping thread - wake it up and do the job.
                        info.Event.Set();
                        return;
                    }
                }

                // Running threads are below limit and nobody is sleeping, so run a new one.
                Thread newThread = new Thread(new ThreadStart(Execute));
                newThread.SetApartmentState(_threadsApartmentState);
                _threads.Add(newThread, new ThreadInfo()
                {
                    Activated = true, Event = new ManualResetEvent(false)
                });
                _activeRunningThreadsCount++;

                newThread.Name = this.GetType().Name;
                newThread.Start();
            }
        }
Exemple #7
0
        /// <summary>
        /// Invoke synchronously.
        /// </summary>
        /// <param name="delegateInstance"></param>
        /// <param name="parameters"></param>
        public bool Invoke(Delegate delegateInstance, TimeSpan timeOut, out object result, params object[] parameters)
        {
            if (IsStarted == false)
            {
                Start();
            }

            result = null;
            if (_blockingInvokeInProgress)
            {
                SystemMonitor.OperationWarning("Another blocking invoke is already in progress.");
            }

            if (Thread.CurrentThread == _workerInternalThread)
            {// Invoke called from within the invoke thread, just execute directly to
                // evade "locking" problem (one invoke spawning another, and the other waiting for invocation).
                result = delegateInstance.Method.Invoke(delegateInstance.Target, parameters);
                return(true);
            }

            _blockingInvokeInProgress = true;

            InvocationData data;

            lock (this)
            {
                data = new InvocationData(delegateInstance, parameters);
                _pendingInvokes.Add(data);
            }

            if (timeOut == TimeSpan.MaxValue)
            {
                if (data.CompletedEvent.WaitOne() == false)
                {
                    return(false);
                }
            }
            else
            {
                if (data.CompletedEvent.WaitOne(timeOut) == false)
                {
                    return(false);
                }
            }

            _blockingInvokeInProgress = false;
            result = data.Result;

            return(true);
        }
        /// <summary>
        /// Helper, performs common actions on stopping a still running thread.
        /// </summary>
        /// <param name="thread"></param>
        public static void StopThread(Thread thread, bool systemMonitorReport, int preInterruptTimeout, int preAbortTimeout)
        {
            if (thread == null)
            {
                return;
            }

            if (thread.ThreadState != System.Threading.ThreadState.Running &&
                thread.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
            {
                return;
            }

            if (preInterruptTimeout > 0)
            {
                Thread.Sleep(preInterruptTimeout);
            }

            if (thread.ThreadState != System.Threading.ThreadState.Running &&
                thread.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
            {
                return;
            }

            if (systemMonitorReport)
            {
                SystemMonitor.OperationWarning(string.Format("Interrupting  thread [{0}, {1}].", thread.ManagedThreadId, thread.Name));
            }

            // Will awaken, if asleep, or cause exception if goes to sleep.
            thread.Interrupt();
            if (preAbortTimeout > 0)
            {
                Thread.Sleep(preAbortTimeout);
            }

            if (thread.ThreadState != System.Threading.ThreadState.Running &&
                thread.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
            {
                return;
            }

            if (systemMonitorReport)
            {
                SystemMonitor.OperationWarning(string.Format("Aborting thread [{0}, {1}].", thread.ManagedThreadId, thread.Name));
            }

            thread.Abort();
        }
        /// <summary>
        /// If implementation is null, it will only register the operation.
        /// </summary>
        public bool PlaceOperation(OperationInformation operationInfo, bool assignId)
        {
            if (RegisterOperation(operationInfo, assignId) == false)
            {
                return(false);
            }

            if (_implementation != null && _implementation.StartOperation(operationInfo) == false)
            {
                SystemMonitor.OperationWarning("Operation [" + _implementation.GetType().Name + ", " + operationInfo.Id + "] failed to start.");
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Helper.
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="timeZoneId"></param>
        /// <returns></returns>
        private static DateTime ConvertToLocalDateTime(string dateTime, string timeZoneId)
        {
            // Strip the time zone ID from the end of the dateTime string.
            dateTime = dateTime.Replace(timeZoneId, "").Trim();

            // Convert the timeZoneId to a TimeSpan.
            // (Leading + signs aren't allowed in the TimeSpan.Parse
            // parameter, although leading - signs are.
            // The purpose of the [+]*? at the beginning of the
            // regex is to account for, and ignore, any leading + sign).

            string ts = Regex.Replace(GetTimeZoneOffset(timeZoneId),
                                      @"^[+]*?(?<hours>[-]?\d\d)(?<minutes>\d\d)$",
                                      "${hours}:${minutes}:00");
            TimeSpan timeZoneOffset = TimeSpan.Parse(ts);

            TimeSpan localUtcOffset =
                TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);

            // Get the absolute time difference between the given
            // datetime's time zone and the local datetime's time zone.

            TimeSpan absoluteOffset = timeZoneOffset - localUtcOffset;

            absoluteOffset = absoluteOffset.Duration();

            // Now that the absolute time difference is known,
            // determine whether to add or subtract it from the
            // given dateTime, and then return the result.

            try
            {
                if (timeZoneOffset < localUtcOffset)
                {
                    return(DateTime.Parse(dateTime) + absoluteOffset);
                }
                else
                {
                    return(DateTime.Parse(dateTime) - absoluteOffset);
                }
            }
            catch
            {
                SystemMonitor.OperationWarning("Parsing of date time [" + dateTime + "] failed.");
                return(DateTime.MinValue);
            }
        }
        /// <summary>
        /// Change password.
        /// </summary>
        /// <param name="existingPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public bool ChangeMasterPassword(SecureString newPassword)
        {
            lock (this)
            {
                if (_masterPasswordEncryptedTestPhraze != null)
                {// Current data is already encoded.
                    if (_masterPassword == null)
                    {
                        SystemMonitor.OperationWarning("Can not change master password if previous password present but not set yet.");
                        return(false);
                    }
                }
                else
                {
                    _masterPassword = newPassword;
                    return(Encrypt(SecureMasterPasswordTestPhraze, out _masterPasswordEncryptedTestPhraze));
                }
            }

            return(false);
        }
Exemple #12
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>The style if must dock otherwise null.</returns>
        public DockStyle?DoEndDrag(Control control, Point location)
        {
            if (_isDragging == false)
            {
                SystemMonitor.OperationWarning("End drag not expected.");
                return(DockStyle.None);
            }

            _isDragging = false;

            DockStyle?dockStyle = _dragLabelsForm.GetDragPosition(location);

            _dragLabelsForm.Hide();

            if (control is DragControl && dockStyle.HasValue)
            {
                DockControl((DragControl)control, dockStyle.Value);
            }

            return(dockStyle);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="masterPassword"></param>
        /// <returns></returns>
        public bool SetMasterPassword(SecureString masterPassword)
        {
            lock (this)
            {
                if (_masterPasswordEncryptedTestPhraze == null)
                {
                    _masterPassword = masterPassword;
                    return(Encrypt(SecureMasterPasswordTestPhraze, out _masterPasswordEncryptedTestPhraze));
                }
                else
                {
                    if (TestMasterPassword(masterPassword))
                    {
                        _masterPassword = masterPassword;
                        return(true);
                    }
                }
            }

            SystemMonitor.OperationWarning("Master password already set.");

            // Master password already set.
            return(false);
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        void Execute()
        {
            while (_running)
            {
                TargetInfo targetInfo;
                lock (_queue)
                {
                    if (_queue.Count == 0)
                    {
                        targetInfo = null;
                    }
                    else
                    {
                        targetInfo = _queue[0];
                        _queue.RemoveAt(0);
                    }
                }

                if (targetInfo != null)
                {// New task found, get to executing it.
                    try
                    {
                        //Thread.CurrentThread.Name = this.GetType().Name + ":" + targetInfo.InvokerName + " >> " + targetInfo.Target.Method.Name;
                        object invokeResult = targetInfo.Target.DynamicInvoke(targetInfo.Args);
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.OperationWarning("[" + _name + "] Thread executed caused an exception: " + ex.Message, TracerItem.PriorityEnum.VeryHigh);
                    }

                    //Thread.CurrentThread.Name = this.GetType().Name + " Inactive";
                }
                else
                {// No new task found in pending tasks.
                    ThreadInfo threadInfo;
                    lock (_threads)
                    {
                        threadInfo = _threads[Thread.CurrentThread];
                        _activeRunningThreadsCount--;
                        threadInfo.Activated = false;
                    }

                    if (threadInfo.Event.WaitOne(TimeSpan.FromSeconds(4)))
                    {
                        _activeRunningThreadsCount++;
                        threadInfo.Activated = true;
                        threadInfo.Event.Reset();
                    }
                    else
                    {// We waited long enough, no new tasks, so release ourselves.
                        lock (_threads)
                        {
                            _threads.Remove(Thread.CurrentThread);
                        }

                        SystemMonitor.Variables.SetValue(this, this.Name + ".TotalThreads", _threads.Count);
                        SystemMonitor.Variables.SetValue(this, this.Name + ".ActiveThreads", _activeRunningThreadsCount);

                        return;
                    }
                }
            }

            ProcessQueue();
        }
        public override void OnUpdate()
        {
            OperationalStateEnum newState;

            try
            {
                if (_feed == null)
                {
                    _feed = RssFeed.Read(base.Address);

                    if (_feed.Channels.Count == 1)
                    {
                        // Some feeds have those symbols in their names.
                        _name = _feed.Channels[0].Title.Replace("\r", "").Replace("\n", "").Trim();
                    }
                    else
                    {
                        _name = _feed.Url.ToString();
                    }

                    List <string> names = new List <string>();
                    foreach (RssChannel channel in _feed.Channels)
                    {
                        names.Add(channel.Title);
                    }

                    foreach (string name in names)
                    {
                        if (ChannelsNames.Contains(name) == false)
                        {
                            base.AddChannel(name, true);
                        }
                    }

                    // Retrieve web site shortcut icon.
                    //if (_icon == null)
                    //{
                    //    _icon = GeneralHelper.GetWebSiteShortcutIcon(new Uri(Address));
                    //}
                }
                else
                {
                    _feed = RssFeed.Read(_feed);
                }

                newState = OperationalStateEnum.Operational;
            }
            catch (WebException we)
            {// Feed not found or some other problem.
                SystemMonitor.OperationWarning("Failed to initialize feed [" + Address + ", " + we.Message + "]");
                newState = OperationalStateEnum.NotOperational;
            }
            catch (Exception ex)
            {// RssFeed class launches IOExceptions too, so get safe here.
                SystemMonitor.OperationWarning("Failed to initialize feed [" + Address + ", " + ex.Message + "]");
                newState = OperationalStateEnum.NotOperational;
            }

            OperationalStateEnum oldState = _operationalState;

            _operationalState = newState;
            if (newState != _operationalState)
            {
                RaiseOperationalStatusChangedEvent(oldState);
            }

            UpdateItems();

            RaisePersistenceDataUpdatedEvent();
        }