示例#1
0
        /// <summary>
        /// Helper.
        /// </summary>
        void SetObjectPropertyValueByTag(object tag, object value)
        {
            if (tag is string)
            {// This is a dynamic generic property.
                SystemMonitor.CheckThrow(SelectedContainerObject != null);
                SelectedContainerObject.SetGenericDynamicPropertyValue(tag as string, value);
            }
            else if (tag is PropertyInfo)
            {// Direct property of the indicator.
                PropertyInfo info = (PropertyInfo)tag;
                if (info.CanWrite)
                {
                    info.SetValue(_selectedObject, value, null);
                }
                else
                {
                    SystemMonitor.OperationError("Property set method not found [" + info.DeclaringType.Name + ":" + info.Name + "].");
                }
            }
            else
            {
                SystemMonitor.Error("Unrecognized tag type for indicator property.");
            }

            if (SelectedContainerObject != null)
            {
                SelectedContainerObject.PropertyChanged();
            }
        }
示例#2
0
        /// <summary>
        /// Collect them from a given assembly.
        /// </summary>
        static public List <Type> GetTypeChildrenTypes(Type typeSearched, System.Reflection.Assembly assembly)
        {
            List <Type> result = new List <Type>();

            Type[] types;

            try
            {
                types = assembly.GetTypes();
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError("Failed to load assembly types [" + ex.Message + "].");
                return(result);
            }

            foreach (Type type in types)
            {
                if (typeSearched.IsInterface)
                {
                    List <Type> interfaces = new List <Type>(type.GetInterfaces());
                    if (interfaces.Contains(typeSearched))
                    {
                        result.Add(type);
                    }
                }
                else
                if (type.IsSubclassOf(typeSearched))
                {
                    result.Add(type);
                }
            }
            return(result);
        }
示例#3
0
        /// <summary>
        /// It is needed to specify the item type here, since otherwise when the result is empty,
        /// it can not be cast to the actual type in real time and causes an exception.
        /// The problem is casting an array ot base type to children type is not possible, when the array
        /// is coming from a list of base types converted with ToArray().
        /// </summary>
        public SortedList <ItemType, ItemType> GetAllItems <ItemType>()
            where ItemType : EventBase
        {
            SortedList <ItemType, ItemType> result = new SortedList <ItemType, ItemType>();

            foreach (EventSourceChannel channel in Channels)
            {
                if (channel.Enabled)
                {
                    lock (channel)
                    {
                        foreach (ItemType item in channel.ItemsUnsafe.Values)
                        {
                            //string id = item.GetFullId();
                            if (result.ContainsKey(item))
                            {// If there is id duplication, resolve with additional guid.
                                SystemMonitor.OperationError("Item hash code duplication [" + item.GetFullId() + "], item skipped.");
                                //id += "." + Guid.NewGuid().ToString();
                            }

                            result.Add(item, item);
                        }
                    }
                }
            }

            return(result);
        }
            /// <summary>
            ///
            /// </summary>
            public void Perform()
            {
                try
                {
                    Result = DelegateInstance.Method.Invoke(DelegateInstance.Target, Parameters);
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        throw;
                    }
                    else
                    {
                        string message = "Invoke threw an exception [" + DelegateInstance.Method.Name + " , " + ex.Message + "]";
                        if (ex.InnerException != null)
                        {
                            message += ", Inner[" + ex.InnerException.GetType().Name + ", " + ex.InnerException.Message + "]";
                        }

                        SystemMonitor.OperationError(message);
                    }
                }

                CompletedEvent.Set();
            }
示例#5
0
        /// <summary>
        /// Send general email, fully configurable.
        /// </summary>
        /// <returns></returns>
        public static bool SendEmailAsync(string username, string password, string smtpServer, int port, string from, string to,
                                          string subject, string body, SendCompletedEventHandler handler)
        {
            SmtpClient client = new SmtpClient(smtpServer, port);

            client.EnableSsl   = true;
            client.Credentials = new System.Net.NetworkCredential(username, password);

            MailMessage message = new MailMessage(from, to);

            message.Body    = body;
            message.Subject = subject;

            try
            {
                client.SendAsync(message, null);
                if (handler != null)
                {
                    client.SendCompleted += handler;
                }
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError("Failed to send mail.", ex);
                return(false);
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        public void UnInitialize()
        {
            lock (this)
            {// This is required since we might receive an item after/during dispose.
                try
                {
                    if (_writer != null)
                    {
                        _writer.Flush();
                        _writer.Close();
                        _writer.Dispose();
                    }

                    if (_stream != null)
                    {
                        _stream.Flush();
                        _stream.Close();
                        _stream.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationError(ex.Message);
                }
                finally
                {
                    _writer = null;
                    _stream = null;
                }

                _initialFilePath = string.Empty;
                _actualFilePath  = string.Empty;
            }
        }
示例#7
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);
            }
        }
示例#8
0
        /// <summary>
        ///
        /// </summary>
        public bool Initialize(Tracer tracer)
        {
            if (_tracer != null)
            {
                SystemMonitor.OperationError("Filter already initialized.");
                return(false);
            }

            _tracer = tracer;
            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        public bool Initialize(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                SystemMonitor.OperationError("Failed to initialize File Tracer Item sink with file [" + filePath + "]");
                return(false);
            }

            UnInitialize();

            _initialFilePath = filePath;
            filePath         = GeneralHelper.ReplaceFileNameCompatibleDateTime(filePath, DateTime.Now);

            lock (this)
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
                    {
                        DirectoryInfo info = Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                        if (info == null)
                        {// Failed to create folder.
                            SystemMonitor.OperationError("Failed to create directory of file [" + filePath + "].");
                            return(false);
                        }
                    }

                    _actualFilePath = filePath;
                    _stream         = new FileStream(_actualFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
                    _writer         = new StreamWriter(_stream);
                }
                catch (Exception ex)
                {
                    UnInitialize();

                    SystemMonitor.OperationError(ex.Message);
                    return(false);
                }
                finally
                {
                    if (_writer == null)
                    {
                        _initialFilePath = string.Empty;
                        _actualFilePath  = null;
                    }
                }
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        public bool CompleteOperation(string operationId, object result)
        {
            lock (this)
            {
                if (_pendingOperations.ContainsKey(operationId))
                {
                    _pendingOperations[operationId].Complete(result);
                    return(true);
                }
            }

            // Timed out and was removed.
            SystemMonitor.OperationError("Operation responce received [" + ImplementationName + ", " + result.GetType().Name + "], but request operation already timed out.");
            return(false);
        }
示例#11
0
        public static TracerItem ParseFileItem(string line)
        {
            if (string.IsNullOrEmpty(line))
            {
                return(null);
            }

            try
            {
                string[] substrings = line.Split('|');

                if (substrings.Length < 4)
                {
                    SystemMonitor.OperationError("Failed to parse tracer item line [" + line + ", Not enough substrings generated].");
                    return(null);
                }

                TracerItem.TypeEnum     fullType = (TracerItem.TypeEnum) int.Parse(substrings[0]);
                TracerItem.PriorityEnum priority = (TracerItem.PriorityEnum) int.Parse(substrings[1]);

                long index = 0;
                long.TryParse(substrings[2], out index);

                DateTime time;
                try
                {
                    string   dateTime      = substrings[3];
                    string[] dateTimeParts = dateTime.Split('/');
                    string[] subParts      = dateTimeParts[2].Split(' ');
                    TimeSpan timeSpan      = TimeSpan.Parse(subParts[1]);

                    time = new DateTime(int.Parse(subParts[0]), int.Parse(dateTimeParts[1]),
                                        int.Parse(dateTimeParts[0]), timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
                }
                catch (Exception ex2)
                {
                    SystemMonitor.OperationError("Failed to parse tracer item line [" + line + ", " + ex2.Message + "].");
                    time = DateTime.MinValue;
                }

                return(new TracerItem(fullType, time, priority, index.ToString() + "  " + substrings[substrings.Length - 1]));
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError("Failed to parse tracer item line [" + line + ", " + ex.Message + "].");
                return(null);
            }
        }
示例#12
0
        /// <summary>
        /// Collect them from a given assembly.
        /// </summary>
        static public List <Type> GetTypeChildrenTypes(Type typeSearched, System.Reflection.Assembly assembly)
        {
            List <Type> result = new List <Type>();

            Type[] types;

            try
            {
                types = assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                string message = string.Empty;
                foreach (Exception subEx in ex.LoaderExceptions)
                {
                    message += "{" + GeneralHelper.GetExceptionMessage(subEx) + "}";
                }

                SystemMonitor.OperationError("Failed to load assembly types for [" + typeSearched.Name + ", " + assembly.GetName().Name + "] [" + GeneralHelper.GetExceptionMessage(ex) + ", " + message + "].");
                return(result);
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError("Failed to load assembly types for [" + typeSearched.Name + ", " + assembly.GetName().Name + "] [" + GeneralHelper.GetExceptionMessage(ex) + "].");
                return(result);
            }

            foreach (Type type in types)
            {
                if (typeSearched.IsInterface)
                {
                    List <Type> interfaces = new List <Type>(type.GetInterfaces());
                    if (interfaces.Contains(typeSearched))
                    {
                        result.Add(type);
                    }
                }
                else
                if (type.IsSubclassOf(typeSearched))
                {
                    result.Add(type);
                }
            }
            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="encryptedValue"></param>
        /// <param name="key"></param>
        /// <param name="decryptedValue"></param>
        /// <returns></returns>
        public bool Decrypt(string encryptedValue, SecureString key, out SecureString decryptedValue)
        {
            decryptedValue = null;
            string Password = GeneralHelper.SecureStringToString(key);

            string decryptedText;

            try
            {
                byte[] encryptedData = Convert.FromBase64String(encryptedValue);
                byte[] Salt          = Encoding.ASCII.GetBytes(Password.Length.ToString());

                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = _rijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText      = new byte[encryptedData.Length];
                        int    decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);

                        //Converting to string
                        decryptedText = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError("Failed to decrypt, reason [" + ex.Message + "]");
                return(false);
            }

            return(true);
        }
        void ProcessUpdate(WatcherChangeTypes changeType)
        {
            lock (_syncRoot)
            {
                // File created, deleted, or first call, setup the reader.
                if (_fileStream == null ||
                    changeType == WatcherChangeTypes.Deleted ||
                    changeType == WatcherChangeTypes.Created)
                {
                    if (_reader != null)
                    {
                        _reader.Dispose();
                        _reader = null;
                    }

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

                    if (changeType == WatcherChangeTypes.Deleted)
                    {
                        return;
                    }

                    try
                    {
                        _fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        _reader     = new StreamReader(_fileStream);
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.Error(ex.Message);

                        _reader = null;
                        _fileStream.Dispose();
                        _fileStream = null;
                    }
                }

                if (_fileStream == null || _fileStream.CanRead == false)
                {
                    return;
                }

                if (_fileStream.Length < _lastFilePos - 10)
                {// File was rewritten start from beggining.
                    _lastFilePos = 0;
                }

                try
                {
                    _fileStream.Seek(_lastFilePos, SeekOrigin.Begin);

                    string line = _reader.ReadLine();
                    while (line != null)
                    {
                        DataUpdateDelegate delegateInstance = NewLineReadEvent;
                        if (delegateInstance != null)
                        {
                            delegateInstance(this, line);
                        }

                        line = _reader.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationError("Failed to read file", ex);
                }

                _lastFilePos = _fileStream.Position;
            }
        }
        /// <summary>
        ///
        /// </summary>
        public void AddControl(CommonBaseControl control)
        {
            Point?location = null;
            Size? size     = null;

            if (control.PersistenceData != null && control.PersistenceData.ContainsValue("combinedContainer.Size"))
            {
                size = control.PersistenceData.GetValue <Size>("combinedContainer.Size");
            }

            if (control.PersistenceData != null && control.PersistenceData.ContainsValue("combinedContainer.Location"))
            {
                location = control.PersistenceData.GetValue <Point>("combinedContainer.Location");
            }

            if (control.PersistenceData != null && control.PersistenceData.ContainsValue("combinedContainer.Floating"))
            {
                CombinedHostingForm form = SetControlFloating(control);
                if (location.HasValue)
                {
                    form.Location = location.Value;
                }

                // Sometimes persistence may be wrong, so make sure to bring control to view when added.
                form.Left = Math.Max(form.Left, 0);
                form.Top  = Math.Max(form.Top, 0);

                form.Left = Math.Min(Screen.PrimaryScreen.WorkingArea.Width, form.Left);
                form.Top  = Math.Min(Screen.PrimaryScreen.WorkingArea.Height, form.Top);

                form.Width  = Math.Max(form.Width, 200);
                form.Height = Math.Max(form.Height, 150);

                if (size.HasValue)
                {
                    form.Size = size.Value;
                }
            }
            else if (control.PersistenceData != null && control.PersistenceData.ContainsValue("combinedContainer.Tabbed"))
            {
                AddTabbedControl(control);
            }
            else if (control.PersistenceData != null && control.PersistenceData.ContainsValue("combinedContainer.Docked") &&
                     control.PersistenceData.ContainsValue("combinedContainer.Guid"))
            {
                Guid        guid        = control.PersistenceData.GetValue <Guid>("combinedContainer.Guid");
                DragControl dragControl = dragContainerControl.GetDragControlByGuid(guid);
                if (dragControl == null)
                {
                    SystemMonitor.OperationError("Guid drag control not found. Using a default new one.");
                    AddTabbedControl(control);
                }
                else
                {// Reuse the existing drag control and place the new control inside it.
                    SetControlToDragControl(control, dragControl, Point.Empty);
                    dragControl.Visible = true;
                }
            }
            else
            {// By default add tabbed.
                AddTabbedControl(control);
            }
        }
示例#16
0
        /// <summary>
        /// Update user interface based on the underlying information.
        /// </summary>
        public void UpdateUI()
        {
            toolStripButtonSettings.Enabled       = _manager != null;
            toolStripButtonSearchClear.Enabled    = _manager != null;
            toolStripButtonSearch.Enabled         = _manager != null;
            toolStripButtonMarkRead.Enabled       = _manager != null;
            toolStripLabelSources.Enabled         = _manager != null;
            toolStripLabelUpdating.Enabled        = _manager != null;
            toolStripButtonUpdate.Enabled         = _manager != null;
            toolStripButtonMark.Enabled           = _manager != null;
            toolStripDropDownButtonSource.Enabled = _manager != null;

            toolStripButtonDetails.Checked = newsItemControl1.Visible;

            if (_manager == null || this.DesignMode)
            {
                return;
            }

            toolStripLabelSources.Text    = "Feeds [" + _manager.NewsSourcesArray.Length + "]";
            toolStripButtonUpdate.Enabled = !_manager.IsUpdating;

            if (_manager.IsUpdating)
            {
                toolStripLabelUpdating.DisplayStyle = ToolStripItemDisplayStyle.Image;
            }
            else
            {
                toolStripLabelUpdating.DisplayStyle = ToolStripItemDisplayStyle.Text;
            }

            // Obtain all items sorted by time.
            SortedList <FinancialNewsEvent, FinancialNewsEvent> combinedSortedItems =
                new SortedList <FinancialNewsEvent, FinancialNewsEvent>();

            foreach (EventSource source in _manager.NewsSourcesArray)
            {
                if ((_selectedSource != null && source != _selectedSource) || source.Enabled == false)
                {// Source filter limitation.
                    continue;
                }

                SortedList <FinancialNewsEvent, FinancialNewsEvent> sourceItems = source.GetAllItems <FinancialNewsEvent>();

                foreach (KeyValuePair <FinancialNewsEvent, FinancialNewsEvent> eventPair in sourceItems)
                {
                    if (combinedSortedItems.ContainsKey(eventPair.Key))
                    {
                        SystemMonitor.OperationError("Item already added to combined container.");
                    }
                    else
                    {
                        combinedSortedItems[eventPair.Key] = eventPair.Value;
                    }
                }
            }

            _items.Clear();

            // Filter
            foreach (FinancialNewsEvent item in combinedSortedItems.Values)
            {
                switch (_showMode)
                {
                case ShowMode.Default:
                    if (item.IsVisible == false)
                    {    // All non deleted.
                        continue;
                    }
                    break;

                case ShowMode.Deleted:
                    if (item.IsVisible)
                    {    // Only deleted.
                        continue;
                    }
                    break;

                case ShowMode.Read:
                    if (item.IsVisible == false || item.IsRead == false)
                    {    // Visible read.
                        continue;
                    }
                    break;

                case ShowMode.UnRead:
                    if (item.IsVisible == false || item.IsRead)
                    {    // Visible non read.
                        continue;
                    }
                    break;

                case ShowMode.Favourite:
                    if (item.IsVisible == false || item.IsFavourite == false)
                    {    // Visible favourites.
                        continue;
                    }
                    break;

                default:
                    break;
                }

                if (_mode != Mode.Searching || IsItemSearched(item))
                {
                    _items.Insert(0, item);
                }
                if (MaximumItemsShown > 0 && _items.Count >= MaximumItemsShown)
                {
                    break;
                }

                if (MaximumItemsShown > 0 && _items.Count >= MaximumItemsShown)
                {
                    break;
                }
            }

            //_items.Reverse();

            listView.VirtualListSize = _items.Count;

            listView.Invalidate();
            listView.UpdateColumnWidths();

            // Needed to update scroll state and evade a bug in the list control (problem in any win list control).
            //this.listView.Scrollable = false;
            //this.listView.Scrollable = true;
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="errorMessage"></param>
 public void OperationError(string errorMessage, TracerItem.PriorityEnum priority)
 {
     SystemMonitor.OperationError(errorMessage, priority);
 }
 /// <summary>
 /// Report operation error; it is a lighter version of a error, and may be expected to
 /// occur during normal operation of the application (for. ex. a given non critical
 /// resource was not retrieved, operation has timed out etc.)
 /// </summary>
 /// <param name="errorMessage"></param>
 public void OperationError(string errorMessage)
 {
     SystemMonitor.OperationError(errorMessage);
 }