Example #1
0
        private void m_btnMiniMessageBox_Click(object sender, EventArgs e)
        {
            DialogResult result = DialogResult.None;
            var          lt     = _tests[(_index++) % _tests.Length];

            if (lt.IsModal == false && lt.Caption == null && lt.Message == null && lt.Icon == 0 && lt.Buttons == 0)
            {
                result = MiniMessageBox.Hide();
            }
            else if (lt.IsModal == false)
            {
                MiniMessageBox.Show(lt.Owner, lt.Message, lt.Caption, lt.Buttons, lt.Icon);
            }
            else
            {
                MiniMessageBox.MsgBoxColors myColors = null;
                if (lt.MmColors != null)
                {
                    myColors = MiniMessageBox.Colors.Backup();
                    MiniMessageBox.Colors.Restore(lt.MmColors);
                }
                result = MiniMessageBox.ShowDialog(lt.Owner, lt.Message, lt.Caption, lt.Buttons, lt.Icon);
                if (myColors != null)
                {
                    MiniMessageBox.Colors.Restore(myColors);
                }
            }

            m_lblPopupStatus.Text = "MiniMessageBox Result = " + result;
        }
Example #2
0
        private void m_grid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (m_grid.Columns[nameof(m_gridcolName)].Index != e.ColumnIndex)
            {
                return;
            }
            var newName = e.FormattedValue.ToString();

            if (KnownSeverities.Any(m => m.EqualsI(newName)))
            {
                MiniMessageBox.ShowDialog(m_grid, "Illegal Switch Name. Name cannot be the same as a trace level.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
                return;
            }

            foreach (DataGridViewRow row in m_grid.Rows)
            {
                if (row.Index == e.RowIndex)
                {
                    continue;
                }
                var name = row.Cells[nameof(m_gridcolName)].Value?.ToString();
                if (name.EqualsI(newName))
                {
                    MiniMessageBox.ShowDialog(m_grid, "Duplicate Switch Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                    return;
                }
            }
        }
        private void m_btnOK_Click(object sender, EventArgs e)
        {
            if (m_lvListeners.SelectedItems.Count == 0)
            {
                MiniMessageBox.ShowDialog(this, "No listener selected.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.DialogResult = DialogResult.OK;
        }
 private void removeToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (m_lvListeners.SelectedItems.Count > 0)
     {
         var item = m_lvListeners.SelectedItems[0];
         if (MiniMessageBox.ShowDialog(m_lvListeners, $"Are you sure you want to remove {item.Name} ({((IListener)item.Tag).Type.Name})?", "Remove Listener", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             m_lvListeners.Items.Remove(item);
             OnListenerListChanged();
         }
     }
 }
Example #5
0
        private ListViewItem AddListViewItem(SourceItem props)
        {
            const string toolTipText = "Source {0} is a special built-in source that copies these messages\r\nto a log. As there is no mechanism to to set severity for these sources,\r\nthere are no severity levels, logging is either On (All) or Off.";
            var          item        = new ListViewItem(props.Name);

            item.Name = props.Name;
            item.Tag  = props;
            if (SpecialSources.Any(m => m.EqualsI(props.Name)))
            {
                item.ToolTipText = string.Format(toolTipText, props.Name);
            }

            props.NamePropertyChanging += (s, e) =>
            {
                if (m_lvSources.Items.Cast <ListViewItem>().Any(m => m.Text.EqualsI(e.NewValue)))
                {
                    MiniMessageBox.ShowDialog(m_cmbName, "Duplicate Source Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;

                    //Callstack to this point:
                    // m_cmbName.TextUpdate => props.Name => props.NamePropertyChanging
                    // m_cmbName.SelectedValueChanged => props.Name => props.NamePropertyChanging

                    m_cmbName.Text = e.CurrentValue; //This works when the source is from TextUpdate, but not from SelectedValueChanged.
                    //To revert from SelectedValueChanged we need to update AFTER the event. Not within it. For TextUpdate this is merely redundent.
                    System.Threading.ThreadPool.QueueUserWorkItem((arg) =>
                    {
                        System.Threading.Thread.Sleep(5);
                        m_cmbName.BeginInvoke(new Action(() => { m_cmbName.Text = e.CurrentValue; }));
                    });
                    return;
                }

                if (SpecialSources.Any(m => m.EqualsI(e.NewValue)))
                {
                    item.ToolTipText = string.Format(toolTipText, e.NewValue);
                }
                else
                {
                    item.ToolTipText = "";
                }

                item.Text = e.NewValue;
            };

            m_lvSources.Items.Add(item);
            return(item);
        }
Example #6
0
        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_lvSources.SelectedItems.Count > 0)
            {
                var item = m_lvSources.SelectedItems[0];
                if (MiniMessageBox.ShowDialog(m_lvSources, $"Are you sure you want to remove {item.Name}?", "Remove Source", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    m_cmbName.Tag         = null;
                    m_cmbName.Text        = "";
                    m_cmbSourceLevel.Text = "";

                    m_lvSources.Items.Remove(item);
                    if (m_lvSources.Items.Count > 0)
                    {
                        var firstItem = m_lvSources.Items[0];
                        firstItem.Selected = true;
                        firstItem.Focused  = true;
                    }
                }
            }
        }
        /// <summary>
        /// Download a URL item into a local file.
        /// Due to network or server glitches or delays, this will try 3 times before giving up.
        /// Will not throw an exception. Errors are written to Logger.
        /// </summary>
        /// <param name="data">Job to download (url and suggested destination filename)</param>
        /// <returns>True if successfully downloaded</returns>
        public static DownloadState Download(Job data)
        {
            #region Initialize Static Variables
            const string UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0"; //DO NOT include "User-Agent: " prefix!
            Func <string, string, string> GetDefaultExtension = (mimeType, defalt) =>
            {
                if (mimeType.IsNullOrEmpty())
                {
                    return(defalt);
                }
                mimeType = mimeType.Split(';')[0].Trim();
                try { return(Registry.GetValue(@"HKEY_CLASSES_ROOT\MIME\Database\Content Type\" + mimeType, "Extension", string.Empty).ToString()); }
                catch { }
                return(defalt);
            };

            if (ResolvedHosts == null)
            {
                ResolvedHosts = new HashSet <string>(); //for name resolution or connection failure to determine if we should retry the download
                //Fix for exception: The request was aborted: Could not create SSL/TLS secure channel
                //https://stackoverflow.com/questions/10822509/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; //Skip validation of SSL/TLS certificate
            }
            #endregion

            Uri uri = new Uri(data.Url);
            data.Retries++;
            try
            {
                string   ext      = Path.GetExtension(data.Filename);
                string   mimetype = null;
                DateTime lastModified;

                //HACK: Empirically required for httpÅ›://m.media-amazon.com/images/ poster images.
                if (uri.Host.EndsWith("amazon.com", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                }
                else
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                }

                using (var web = new MyWebClient())
                {
                    web.Headers[HttpRequestHeader.UserAgent] = UserAgent;
                    if (!data.Referer.IsNullOrEmpty())
                    {
                        web.Headers[HttpRequestHeader.Referer] = data.Referer;
                    }
                    if (!data.Cookie.IsNullOrEmpty())
                    {
                        web.Headers[HttpRequestHeader.Cookie] = data.Cookie;
                    }
                    data.Filename = FileEx.GetUniqueFilename(data.Filename); //creates empty file as placeholder
                    //Diagnostics.WriteLine("{0} ==> {1}\r\n", data.Url, Path.GetFileName(data.Filename));

                    web.DownloadFile(data.Url, data.Filename);

                    data.Url = web.ResponseUrl; //update url to what the Web server thinks it is.
                    string cookie = web.ResponseHeaders[HttpResponseHeader.SetCookie];
                    if (!cookie.IsNullOrEmpty())
                    {
                        data.Cookie = cookie;
                    }
                    if (!DateTime.TryParse(web.ResponseHeaders[HttpResponseHeader.LastModified] ?? string.Empty, out lastModified))
                    {
                        lastModified = DateTime.Now;
                    }
                    mimetype = web.ResponseHeaders[HttpResponseHeader.ContentType];
                }
                ResolvedHosts.Add(uri.Host);  //for NameResolutionFailure handler statement.
                if (!File.Exists(data.Filename))
                {
                    throw new FileNotFoundException("File missing or truncated.");
                }

                //if (data.Retries < 1) return true; //do not validate. we want this file, always.

                if (new FileInfo(data.Filename).Length < 8)
                {
                    File.Delete(data.Filename); return(DownloadState.EmptyFile);
                }

                //Interlocked.Increment(ref mediaDownloaded);  //mediaDownloaded++;
                File.SetCreationTime(data.Filename, lastModified);
                File.SetLastAccessTime(data.Filename, lastModified);
                File.SetLastWriteTime(data.Filename, lastModified);

                ext = GetDefaultExtension(mimetype, ext);
                if (ext == ".html")
                {
                    ext = ".htm";
                }
                if (ext == ".jfif")
                {
                    ext = ".jpg";
                }

                if (!ext.EqualsI(Path.GetExtension(data.Filename)))
                {
                    var newfilename = Path.ChangeExtension(data.Filename, ext);
                    newfilename = FileEx.GetUniqueFilename(newfilename); //creates empty file as placeholder
                    File.Delete(newfilename);                            //delete the placeholder. Move will throw exception if it already exists
                    File.Move(data.Filename, newfilename);
                    data.Filename = newfilename;
                }

                return(DownloadState.Success);
            }
            catch (Exception ex)
            {
                File.Delete(data.Filename);
                if (ex is ThreadAbortException)
                {
                    return(DownloadState.ThreadAbort);
                }

                #region Handle Disk-full error
                const int ERROR_HANDLE_DISK_FULL = 0x27;
                const int ERROR_DISK_FULL        = 0x70;
                int       hResult = ex.HResult & 0xFFFF;

                if (hResult == ERROR_HANDLE_DISK_FULL || hResult == ERROR_DISK_FULL) //There is not enough space on the disk.
                {
                    LogWrite(TraceEventType.Critical, "<<<<<<< Disk Full >>>>>>>");
                    return(DownloadState.DiskFull);
                }
                #endregion Handle Disk-full error

                #region Log Error and Maybe Retry Download
                HttpStatusCode     responseStatus = (HttpStatusCode)0;
                WebExceptionStatus status         = WebExceptionStatus.Success;
                if (ex is WebException)
                {
                    WebException    we       = (WebException)ex;
                    HttpWebResponse response = we.Response as System.Net.HttpWebResponse;
                    responseStatus = (response == null ? (HttpStatusCode)0 : response.StatusCode);
                    status         = we.Status;
                }

                if ((data.Retries < 1 || data.Retries > 3) ||
                    responseStatus == HttpStatusCode.Forbidden || //403
                    responseStatus == HttpStatusCode.NotFound ||  //404
                    responseStatus == HttpStatusCode.Gone ||      //410
                    //responseStatus == HttpStatusCode.InternalServerError || //500
                    ((status == WebExceptionStatus.NameResolutionFailure || status == WebExceptionStatus.ConnectFailure) && !ResolvedHosts.Contains(uri.Host)) ||
                    ex.Message.Contains("URI formats are not supported"))
                {
                    LogWrite(TraceEventType.Error, $"{data.Url} ==> {Path.GetFileName(data.Filename)}: {ex.Message}");
                    return(DownloadState.NotFound);
                }

                if (status == WebExceptionStatus.NameResolutionFailure || status == WebExceptionStatus.ConnectFailure)
                {
                    if (MiniMessageBox.ShowDialog(null, "Network Connection Dropped.", "Name Resolution Failure", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                    {
                        return(DownloadState.NetworkConnectionFailure);
                    }
                }

                LogWrite(TraceEventType.Warning, $"Retry #{data.Retries}: {data.Url} ==> {Path.GetFileName(data.Filename)}: {ex.Message}");
                return(Download(data));  //try again

                #endregion Log Error and Maybe Retry Download
            }
        }