Пример #1
0
        /// <summary>
        ///   Adds a cell value to the HTML and Text
        /// </summary>
        /// <param name="cell">The cell.</param>
        /// <param name="stringBuilder">The buffer.</param>
        /// <param name="sbHtml">The StringBuilder for HTML.</param>
        /// <param name="appendTab">if set to <c>true</c> [append tab].</param>
        /// <param name="addErrorInfo">if set to <c>true</c> [add error info].</param>
        /// <param name="cutLength">Maximum length of the resulting text</param>
        private void AddCell(
            [NotNull] DataGridViewCell cell,
            [NotNull] StringBuilder stringBuilder,
            [NotNull] StringBuilder sbHtml,
            bool appendTab,
            bool addErrorInfo,
            bool cutLength, HTMLStyle style)
        {
            var cellValue = cell.FormattedValue?.ToString() ?? string.Empty;

            if (cellValue.Length > 500 && cutLength)
            {
                cellValue = cellValue.Substring(0, 80) + " […] " + cellValue.Substring(cellValue.Length - 20, 20);
            }

            if (appendTab)
            {
                stringBuilder.Append('\t');
            }
            stringBuilder.Append(EscapeTab(cellValue));
            style.AddHtmlCell(
                sbHtml,
                cell.ValueType == typeof(string) ? m_HtmlStyle.TD : m_HtmlStyle.TDNonText,
                cellValue,
                cell.ErrorText,
                addErrorInfo);
        }
Пример #2
0
        /// <summary>
        ///   Adds a cell value to the HTML and Text
        /// </summary>
        /// <param name="cell">The cell.</param>
        /// <param name="buffer">The buffer.</param>
        /// <param name="sbHtml">The StringBuilder for HTML.</param>
        /// <param name="appendTab">if set to <c>true</c> [append tab].</param>
        /// <param name="addErrorInfo">if set to <c>true</c> [add error info].</param>
        /// <param name="cutLength">Maximum length of the resulting text</param>
        private static void AddCell(DataGridViewCell cell, StringBuilder buffer, StringBuilder sbHtml, bool appendTab,
                                    bool addErrorInfo, bool cutLength)
        {
            Contract.Requires(cell != null);
            Contract.Requires(buffer != null);
            Contract.Requires(sbHtml != null);

            if (cell == null)
            {
                return;
            }
            var cellValue = cell.FormattedValue?.ToString() ?? string.Empty;

            if (cellValue.Length > 500 && cutLength)
            {
                cellValue = cellValue.Substring(0, 80) + " [...] " + cellValue.Substring(cellValue.Length - 20, 20);
            }

            if (appendTab)
            {
                buffer.Append('\t');
            }
            buffer.Append(EscapeTab(cellValue));

            HTMLStyle.AddHtmlCell(sbHtml, cell.ValueType == typeof(string) ? m_HtmlStyle.TD : m_HtmlStyle.TDNonText,
                                  cellValue, cell.ErrorText, addErrorInfo);
        }
Пример #3
0
 /// <summary>
 ///   Appends a row error to the HTML Buffer
 /// </summary>
 /// <param name="buffer">The buffer.</param>
 /// <param name="sbHtml">The StringBuilder for HTML.</param>
 /// <param name="errorText">The error Text</param>
 /// <param name="addErrorInfo">if set to <c>true</c> [add error info].</param>
 private static void AppendRowError(StringBuilder buffer, StringBuilder sbHtml, string errorText, bool addErrorInfo)
 {
     Contract.Requires(buffer != null);
     Contract.Requires(sbHtml != null);
     if (!addErrorInfo)
     {
         return;
     }
     if (string.IsNullOrEmpty(errorText))
     {
         sbHtml.Append(m_HtmlStyle.TDEmpty);
     }
     else
     {
         HTMLStyle.AddHtmlCell(sbHtml, m_HtmlStyle.TD, string.Empty, errorText, true);
     }
     buffer.Append('\t');
     buffer.Append(EscapeTab(errorText));
 }
Пример #4
0
        public string TabTableToHTML(string text, bool firstLineHeader, bool addTable)
        {
            var sbHtml = new StringBuilder();

            if (addTable)
            {
                sbHtml.Append(TableOpen);
            }

            var lineNo = 0;

            foreach (var line in text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                lineNo++;
                if (lineNo == 1 && firstLineHeader)
                {
                    sbHtml.Append(TROpenAlt);
                    foreach (var column in line.Split(new[] { '\t' }, StringSplitOptions.None))
                    {
                        sbHtml.Append(HTMLStyle.AddTd(TH, column));
                    }
                    sbHtml.AppendLine(TRClose);
                }
                else
                {
                    sbHtml.Append(TROpen);
                    foreach (var column in line.Split(new[] { '\t' }, StringSplitOptions.None))
                    {
                        sbHtml.Append(HTMLStyle.AddTd(TD, column));
                    }
                    sbHtml.AppendLine(TRClose);
                }
            }
            if (addTable)
            {
                sbHtml.Append(TableClose);
            }
            return(sbHtml.ToString());
        }
Пример #5
0
        protected string TextEncodeField([NotNull] IFileFormat fileFormat, object dataObject,
                                         [NotNull] WriterColumn columnInfo, bool isHeader,
                                         [CanBeNull] IDataReader reader, [CanBeNull] Func <string, DataType, IFileFormat, string> handleQualify)
        {
            if (columnInfo is null)
            {
                throw new ArgumentNullException(nameof(columnInfo));
            }

            if (fileFormat.IsFixedLength && columnInfo.FieldLength == 0)
            {
                throw new FileWriterException("For fix length output the length of the columns needs to be specified.");
            }

            string displayAs;

            if (isHeader)
            {
                if (dataObject is null)
                {
                    throw new ArgumentNullException(nameof(dataObject));
                }
                displayAs = dataObject.ToString();
            }
            else
            {
                try
                {
                    if (dataObject == null || dataObject is DBNull)
                    {
                        displayAs = columnInfo.ValueFormat.DisplayNullAs;
                    }
                    else
                    {
                        switch (columnInfo.ValueFormat.DataType)
                        {
                        case DataType.Integer:
                            displayAs = Convert.ToInt64(dataObject).ToString(columnInfo.ValueFormat.NumberFormat, CultureInfo.InvariantCulture).Replace(
                                CultureInfo.InvariantCulture.NumberFormat.NumberGroupSeparator, columnInfo.ValueFormat.GroupSeparator);
                            break;

                        case DataType.Boolean:
                            displayAs = (bool)dataObject
                  ? columnInfo.ValueFormat.True
                  : columnInfo.ValueFormat.False;
                            break;

                        case DataType.Double:
                            displayAs = StringConversion.DoubleToString(
                                dataObject is double d ? d : Convert.ToDouble(dataObject.ToString(), CultureInfo.InvariantCulture),
                                columnInfo.ValueFormat);
                            break;

                        case DataType.Numeric:
                            displayAs = StringConversion.DecimalToString(
                                dataObject is decimal @decimal
                    ? @decimal
                    : Convert.ToDecimal(dataObject.ToString(), CultureInfo.InvariantCulture),
                                columnInfo.ValueFormat);
                            break;

                        case DataType.DateTime:
                            displayAs = reader == null
                  ? StringConversion.DateTimeToString((DateTime)dataObject, columnInfo.ValueFormat)
                  : StringConversion.DateTimeToString(HandleTimeZone((DateTime)dataObject, columnInfo, reader),
                                                      columnInfo.ValueFormat);

                            break;

                        case DataType.Guid:
                            // 382c74c3-721d-4f34-80e5-57657b6cbc27
                            displayAs = ((Guid)dataObject).ToString();
                            break;

                        case DataType.String:
                        case DataType.TextToHtml:
                        case DataType.TextToHtmlFull:
                        case DataType.TextPart:
                            displayAs = dataObject.ToString();
                            if (columnInfo.ValueFormat.DataType == DataType.TextToHtml)
                            {
                                displayAs = HTMLStyle.TextToHtmlEncode(displayAs);
                            }

                            // a new line of any kind will be replaced with the placeholder if set
                            if (fileFormat.NewLinePlaceholder.Length > 0)
                            {
                                displayAs = StringUtils.HandleCRLFCombinations(displayAs, fileFormat.NewLinePlaceholder);
                            }

                            if (fileFormat.DelimiterPlaceholder.Length > 0 && fileFormat.FieldDelimiterChar != '\0')
                            {
                                displayAs = displayAs.Replace(fileFormat.FieldDelimiterChar.ToStringHandle0(),
                                                              fileFormat.DelimiterPlaceholder);
                            }

                            if (fileFormat.QuotePlaceholder.Length > 0 && fileFormat.FieldQualifierChar != '\0')
                            {
                                displayAs = displayAs.Replace(fileFormat.FieldQualifierChar.ToStringHandle0(), fileFormat.QuotePlaceholder);
                            }
                            break;

                        default:
                            displayAs = string.Empty;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // In case a cast did fail (eg.g trying to format as integer and providing a text, use the
                    // original value
                    displayAs = dataObject?.ToString() ?? string.Empty;
                    if (string.IsNullOrEmpty(displayAs))
                    {
                        HandleError(columnInfo.Name, ex.Message);
                    }
                    else
                    {
                        HandleWarning(columnInfo.Name,
                                      "Value stored as: " + displayAs +
                                      $"\nExpected {columnInfo.ValueFormat.DataType} but was {dataObject?.GetType()}" + ex.Message);
                    }
                }
            }

            // Adjust the output in case its is fixed length
            if (fileFormat.IsFixedLength)
            {
                if (displayAs.Length <= columnInfo.FieldLength || columnInfo.FieldLength <= 0)
                {
                    return(displayAs.PadRight(columnInfo.FieldLength, ' '));
                }
                HandleWarning(columnInfo.Name,
                              $"Text with length of {displayAs.Length} has been cut off after {columnInfo.FieldLength} character");
                return(displayAs.Substring(0, columnInfo.FieldLength));
            }

            // Qualify text if required
            if (fileFormat.FieldQualifierChar != '\0' && handleQualify != null)
            {
                return(handleQualify(displayAs, columnInfo.ValueFormat.DataType, fileFormat));
            }

            return(displayAs);
        }
Пример #6
0
        /// <summary>
        ///   Stores that data in the given stream.
        /// </summary>
        /// <param name="reader">The data reader.</param>
        /// <param name="writer">The writer.</param>
        /// <param name="readerFileSetting">The file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        ///   Number of rows written
        /// </returns>
        protected void DataReader2Stream(IDataReader reader, TextWriter writer,
                                         CancellationToken cancellationToken)
        {
            Contract.Requires(reader != null);
            Contract.Requires(writer != null);

            var columnInfos = GetColumnInformation(reader);
            var enumerable  = columnInfos.ToList();

            if (enumerable.IsEmpty())
            {
                throw new ApplicationException("No columns defined to be written.");
            }
            var recordEnd = m_StructuredWriterFile.FileFormat.NewLine.Replace("CR", "\r").Replace("LF", "\n").Replace(" ", "")
                            .Replace("\t", "");

            HandleWriteStart();

            var numEmptyRows = 0;
            var numColumns   = enumerable.Count();
            var
                sb = new StringBuilder(1024); // Assume a capacity of 1024 characters to start , data is flushed every 512 chars

            if (!string.IsNullOrEmpty(m_StructuredWriterFile.Header))
            {
                sb.Append(ReplacePlaceHolder(m_StructuredWriterFile.Header));
                if (!m_StructuredWriterFile.Header.EndsWith(recordEnd, StringComparison.Ordinal))
                {
                    sb.Append(recordEnd);
                }
            }

            var withHeader = m_StructuredWriterFile.Row;
            var colNum     = 0;

            foreach (var columnInfo in enumerable)
            {
                var placeHolder = string.Format(System.Globalization.CultureInfo.CurrentCulture, cHeaderPlaceholder, colNum);
                if (m_StructuredWriterFile.XMLEncode)
                {
                    withHeader = withHeader.Replace(placeHolder, HTMLStyle.XmlElementName(columnInfo.Header));
                }
                else if (m_StructuredWriterFile.JSONEncode)
                {
                    withHeader = withHeader.Replace(placeHolder, HTMLStyle.JsonElementName(columnInfo.Header));
                }
                else
                {
                    withHeader = withHeader.Replace(placeHolder, columnInfo.Header);
                }
                colNum++;
            }

            withHeader = withHeader.Trim();
            while (reader.Read() && !cancellationToken.IsCancellationRequested)
            {
                NextRecord();

                if (sb.Length > 512)
                {
                    writer.Write(sb.ToString());
                    sb.Length = 0;
                }

                // Start a new line
                sb.Append(recordEnd);
                var emptyColumns = 0;
                var row          = withHeader;
                colNum = 0;
                foreach (var columnInfo in enumerable)
                {
                    Contract.Assume(columnInfo != null);
                    var placeHolder1 = string.Format(System.Globalization.CultureInfo.CurrentCulture, cFieldPlaceholderByNumber, colNum);
                    var value        = string.Empty;
                    var placeHolder2 = string.Format(System.Globalization.CultureInfo.CurrentCulture, cFieldPlaceholderByName, columnInfo.Header);

                    var col = reader.GetValue(columnInfo.ColumnOridinalReader);
                    if (col == DBNull.Value)
                    {
                        emptyColumns++;
                    }
                    else
                    {
                        value = TextEncodeField(m_StructuredWriterFile.FileFormat, col, columnInfo, false, reader, null);
                        if (m_StructuredWriterFile.XMLEncode)
                        {
                            value = SecurityElement.Escape(value);
                        }
                        else if (m_StructuredWriterFile.JSONEncode)
                        {
                            value = HTMLStyle.JsonEncode(value);
                        }
                    }

                    row = row.Replace(placeHolder1, value).Replace(placeHolder2, value);
                    colNum++;
                }

                if (emptyColumns == numColumns)
                {
                    numEmptyRows++;
                }
                else
                {
                    sb.Append(row);
                    numEmptyRows = 0;
                }
            }

            sb.Append(ReplacePlaceHolder(m_StructuredWriterFile.Footer));
            writer.Write(sb.ToString());
        }
Пример #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FormShowMaxLength" /> class.
 /// </summary>
 /// <param name="dataTable">The data table.</param>
 /// <param name="dataRows">The data rows.</param>
 /// <param name="visibleColums">The visible columns.</param>
 /// <param name="hTMLStyle">The h TML style.</param>
 /// <exception cref="ArgumentNullException">
 /// dataTable
 /// or
 /// dataRows
 /// or
 /// visibleColums
 /// </exception>
 public FormShowMaxLength(DataTable dataTable, DataRow[] dataRows, IList <string> visibleColumns, HTMLStyle hTMLStyle)
 {
     m_DataTable      = dataTable ?? throw new ArgumentNullException(nameof(dataTable));
     m_DataRow        = dataRows ?? throw new ArgumentNullException(nameof(dataRows));
     m_VisibleColumns = visibleColumns ?? throw new ArgumentNullException(nameof(visibleColumns));
     InitializeComponent();
     m_DataGridView.HTMLStyle = hTMLStyle;
 }
        public string SelectedToClipboard()
        {
            if (SelectedTreeNode.Count == 0)
            {
                return(string.Empty);
            }

            var minLevel = int.MaxValue;
            var maxLevel = int.MinValue;

            foreach (var item in SelectedTreeNode)
            {
                if (minLevel > item.Level)
                {
                    minLevel = item.Level;
                }

                if (maxLevel < item.Level)
                {
                    maxLevel = item.Level;
                }
            }

            var buffer = new StringBuilder();
            var sbHtml = new StringBuilder();

            sbHtml.AppendLine(HTMLStyle.TableOpen);
            // Should follow display of nodes...
            foreach (var item in SelectedTreeNode)
            {
                var text = item.Text;

                sbHtml.Append(HTMLStyle.TROpen);
                // TreeData Tag is teh first column
                if (item.Tag is FormHierarchyDisplay.TreeData data)
                {
                    text = data.Title;
                    if (!string.IsNullOrEmpty(data.Tag))
                    {
                        sbHtml.Append(HTMLStyle.AddTd("<td>{0}</td>", data.Tag));
                        buffer.Append(data.Tag);
                        buffer.Append("\t");
                        if (text.StartsWith(data.Tag, StringComparison.Ordinal))
                        {
                            text = text.Substring(data.Tag.Length).TrimStart(' ', '-');
                        }
                    }
                    else
                    {
                        sbHtml.Append(HTMLStyle.TDEmpty);
                    }
                }
                // Depending on Level add columns
                for (var level = minLevel; level < item.Level; level++)
                {
                    buffer.Append("\t");
                    sbHtml.Append(HTMLStyle.TDEmpty);
                }

                sbHtml.Append(
                    HTMLStyle.AddTd(
                        "<td colspan='{0}'>{1}</td>",
                        ((maxLevel - item.Level) + 1).ToString(CultureInfo.InvariantCulture),
                        text));
                buffer.Append(text);
                for (var level = item.Level + 1; level < maxLevel; level++)
                {
                    buffer.Append("\t");
                }
                // TreeData Children Count is the last column
                if (item.Tag is FormHierarchyDisplay.TreeData data2)
                {
                    sbHtml.Append(HTMLStyle.AddTd("<td>{0}</td>", data2.Children.Count));
                    buffer.Append(data2.Children.Count);
                }
                sbHtml.AppendLine(HTMLStyle.TRClose);
                buffer.AppendLine();
            }

            sbHtml.AppendLine(HTMLStyle.TableClose);

            var dataObject = new DataObject();

            dataObject.SetData(DataFormats.Html, true, HTMLStyle.ConvertToHtmlFragment(sbHtml.ToString()));
            dataObject.SetData(DataFormats.Text, true, buffer.ToString());

            Clipboard.Clear();
            Clipboard.SetDataObject(dataObject, false, 5, 200);

            return(buffer.ToString());
        }
        /// <summary>
        ///   Writes the specified file reading from the given reader
        /// </summary>
        /// <param name="reader">A Data Reader with the data</param>
        /// <param name="output">The output.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        protected override async Task WriteReaderAsync([NotNull] IFileReader reader, [NotNull] Stream output,
                                                       CancellationToken cancellationToken)
        {
            using (var writer = new StreamWriter(output, new UTF8Encoding(true), 4096))
            {
                SetColumns(reader);
                var numColumns = Columns.Count();
                if (numColumns == 0)
                {
                    throw new FileWriterException("No columns defined to be written.");
                }
                var recordEnd = NewLine;
                HandleWriteStart();

                // Header
                if (!string.IsNullOrEmpty(Header))
                {
                    var sbH = new StringBuilder();
                    sbH.Append(Header);
                    if (!Header.EndsWith(recordEnd, StringComparison.Ordinal))
                    {
                        sbH.Append(recordEnd);
                    }
                    await writer.WriteAsync(sbH.ToString()).ConfigureAwait(false);
                }

                // Static template for the row, built once
                var withHeader         = m_Row;
                var colNum             = 0;
                var placeHolderLookup1 = new Dictionary <int, string>();
                var placeHolderLookup2 = new Dictionary <int, string>();

                foreach (var columnInfo in Columns)
                {
                    var placeHolder = string.Format(CultureInfo.CurrentCulture, c_HeaderPlaceholder, colNum);
                    if (m_XMLEncode)
                    {
                        withHeader = withHeader.Replace(placeHolder, HTMLStyle.XmlElementName(columnInfo.Name));
                    }
                    else if (m_JSONEncode)
                    {
                        withHeader = withHeader.Replace(placeHolder, HTMLStyle.JsonElementName(columnInfo.Name));
                    }
                    else
                    {
                        withHeader = withHeader.Replace(placeHolder, columnInfo.Name);
                    }

                    placeHolderLookup1.Add(colNum, string.Format(CultureInfo.CurrentCulture, c_FieldPlaceholderByNumber, colNum));
                    placeHolderLookup2.Add(colNum,
                                           string.Format(CultureInfo.CurrentCulture, cFieldPlaceholderByName, columnInfo.Name));
                    colNum++;
                }

                withHeader = withHeader.Trim();
                var
                    sb = new StringBuilder(
                    1024); // Assume a capacity of 1024 characters to start, data is flushed every 512 chars
                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false) &&
                       !cancellationToken.IsCancellationRequested)
                {
                    NextRecord();

                    // Start a new line
                    sb.Append(recordEnd);
                    var row = withHeader;
                    colNum = 0;
                    foreach (var value in from columnInfo in Columns
                             let col = reader.GetValue(columnInfo.ColumnOrdinal)
                                       select m_XMLEncode
                                  ? SecurityElement.Escape(TextEncodeField(FileFormat, col, columnInfo, false,
                                                                           reader,
                                                                           null))
                                  : JsonConvert.ToString(col))
                    {
                        row = row.Replace(placeHolderLookup1[colNum], value).Replace(placeHolderLookup2[colNum], value);
                        colNum++;
                    }

                    sb.Append(row);

                    if (sb.Length <= 512)
                    {
                        continue;
                    }
                    await writer.WriteAsync(sb.ToString()).ConfigureAwait(false);

                    sb.Length = 0;
                }

                if (sb.Length > 0)
                {
                    await writer.WriteAsync(sb.ToString()).ConfigureAwait(false);
                }

                // Footer
                if (!string.IsNullOrEmpty(Footer()))
                {
                    await writer.WriteAsync(Footer()).ConfigureAwait(false);
                }

                await writer.FlushAsync();
            }
        }
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FormDuplicatesDisplay" /> class.
 /// </summary>
 /// <param name="dataTable">The data table.</param>
 /// <param name="dataRows">The filtered rows.</param>
 /// <param name="initialColumn">The starting column</param>
 /// <param name="hTMLStyle">The HTML style.</param>
 /// <exception cref="ArgumentNullException">
 /// hTMLStyle
 /// or
 /// dataTable
 /// or
 /// dataRows
 /// </exception>
 public FormDuplicatesDisplay([NotNull] DataTable dataTable, [NotNull] DataRow[] dataRows, [CanBeNull] string initialColumn, [NotNull] HTMLStyle hTMLStyle)
 {
     if (hTMLStyle is null)
     {
         throw new ArgumentNullException(nameof(hTMLStyle));
     }
     m_DataTable     = dataTable ?? throw new ArgumentNullException(nameof(dataTable));
     m_DataRow       = dataRows ?? throw new ArgumentNullException(nameof(dataRows));
     m_InitialColumn = initialColumn;
     InitializeComponent();
     detailControl.HTMLStyle = hTMLStyle;
 }
Пример #11
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="DataGridViewCopyPaste" /> class.
 /// </summary>
 /// <param name="htmlStyle">The HTML style.</param>
 public DataGridViewCopyPaste(HTMLStyle htmlStyle)
 {
     m_HtmlStyle = htmlStyle ?? new HTMLStyle();
 }
Пример #12
0
        /// <summary>
        ///   Copies the selected cells into the clipboard.
        /// </summary>
        /// <param name="addErrorInfo">if set to <c>true</c> [add error information].</param>
        /// <param name="cutLength">if set to <c>true</c> [cut length].</param>
        /// <param name="alternatingRows">if set to <c>true</c> [alternating rows].</param>
        /// <param name="columns">The columns.</param>
        /// <param name="rows">The rows.</param>
        /// <param name="selectedCells">The selected cells.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private void CopySelectedCellsIntoClipboard(
            bool addErrorInfo,
            bool cutLength,
            bool alternatingRows,
            [NotNull] DataGridViewColumnCollection columns,
            [NotNull] DataGridViewRowCollection rows,
            [NotNull] DataGridViewSelectedCellCollection selectedCells,
            CancellationToken cancellationToken)
        {
            var buffer     = new StringBuilder();
            var dataObject = new DataObject();

            // If there are multiple cells Add a header and a neat HTML table
            var sbHtml = new StringBuilder(m_HtmlStyle.TableOpen);

            var leftCol   = int.MaxValue;
            var rightCol  = int.MinValue;
            var topRow    = int.MaxValue;
            var bottomRow = int.MinValue;

            foreach (DataGridViewCell cell in selectedCells)
            {
                if (cell.OwningColumn.DisplayIndex < leftCol)
                {
                    leftCol = cell.OwningColumn.DisplayIndex;
                }
                if (cell.OwningColumn.DisplayIndex > rightCol)
                {
                    rightCol = cell.OwningColumn.DisplayIndex;
                }
                if (cell.RowIndex < topRow)
                {
                    topRow = cell.RowIndex;
                }
                if (cell.RowIndex > bottomRow)
                {
                    bottomRow = cell.RowIndex;
                }
            }

            var hasRowError    = HasRowErrors(topRow, bottomRow + 1, rows);
            var visibleColumns = new List <int>();

            sbHtml.Append(m_HtmlStyle.TROpenAlt);
            for (var col = leftCol; col <= rightCol; col++)
            {
                foreach (DataGridViewColumn diplayCol in columns)
                {
                    if (diplayCol.DisplayIndex == col && diplayCol.Visible && diplayCol.HeaderText != ReaderConstants.cErrorField)
                    {
                        visibleColumns.Add(col);
                        sbHtml.Append(HTMLStyle.AddTd(m_HtmlStyle.TH, diplayCol.HeaderText));
                        if (buffer.Length > 0)
                        {
                            buffer.Append('\t');
                        }

                        buffer.Append(EscapeTab(diplayCol.HeaderText));
                        break;
                    }
                }
            }

            if (hasRowError && addErrorInfo)
            {
                sbHtml.Append(HTMLStyle.AddTd(m_HtmlStyle.TH, c_ErrorInfo));
                buffer.Append('\t');
                buffer.Append(c_ErrorInfo);
            }

            sbHtml.AppendLine(m_HtmlStyle.TRClose);
            buffer.AppendLine();

            var trAlternate = false;
            var lastRefresh = DateTime.Now;

            for (var row = topRow; row <= bottomRow; row++)
            {
                if (rows[row].IsNewRow)
                {
                    continue;
                }
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }
                sbHtml.Append(trAlternate ? m_HtmlStyle.TROpenAlt : m_HtmlStyle.TROpen);
                if (alternatingRows)
                {
                    trAlternate = !trAlternate;
                }
                var written = false;
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }
                for (var col = leftCol; col <= rightCol; col++)
                {
                    if (!visibleColumns.Contains(col))
                    {
                        continue;
                    }
                    foreach (DataGridViewCell cell in selectedCells)
                    {
                        if (cell.RowIndex != row)
                        {
                            continue;
                        }
                        if (cell.OwningColumn.DisplayIndex != col)
                        {
                            continue;
                        }
                        AddCell(cell, buffer, sbHtml, col > leftCol, addErrorInfo, cutLength, m_HtmlStyle);
                        written = true;
                        break;
                    }

                    if (written)
                    {
                        continue;
                    }
                    buffer.Append('\t');
                    sbHtml.Append(m_HtmlStyle.TDEmpty);
                }

                AppendRowError(buffer, sbHtml, rows[row].ErrorText, addErrorInfo && hasRowError, m_HtmlStyle);

                sbHtml.AppendLine(m_HtmlStyle.TRClose);
                buffer.AppendLine();
                if (!((DateTime.Now - lastRefresh).TotalSeconds > 0.2))
                {
                    continue;
                }
                lastRefresh = DateTime.Now;
                Extensions.ProcessUIElements();
            }

            sbHtml.AppendLine(m_HtmlStyle.TableClose);
            dataObject.SetData(DataFormats.Html, true, m_HtmlStyle.ConvertToHtmlFragment(sbHtml.ToString()));
            dataObject.SetData(DataFormats.Text, true, buffer.ToString());
            dataObject.SetClipboard();
        }
Пример #13
0
        /// <summary>
        ///   Copies all cells to the clipboard
        /// </summary>
        /// <param name="addErrorInfo">if set to <c>true</c> [add error information].</param>
        /// <param name="cutLength">if set to <c>true</c> [cut length].</param>
        /// <param name="alternatingRows">if set to <c>true</c> [alternating rows].</param>
        /// <param name="columns">The columns.</param>
        /// <param name="rows">The rows.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private void CopyAllCellsIntoClipboard(
            bool addErrorInfo,
            bool cutLength,
            bool alternatingRows,
            [NotNull] DataGridViewColumnCollection columns,
            [NotNull] DataGridViewRowCollection rows,
            CancellationToken cancellationToken)
        {
            var buffer = new StringBuilder();
            var sbHtml = new StringBuilder(m_HtmlStyle.TableOpen);

            sbHtml.Append(m_HtmlStyle.TROpenAlt);
            var first = true;

            var visibleColumns = new SortedDictionary <int, DataGridViewColumn>();

            foreach (DataGridViewColumn c in columns)
            {
                // Do not include the error field it will be retrieved from the error collection with nice coloring
                if (c.Visible && c.HeaderText != ReaderConstants.cErrorField)
                {
                    visibleColumns.Add(c.DisplayIndex, c);
                }
            }
            var hasRowError = HasRowErrors(0, rows.Count, rows);

            foreach (var col in visibleColumns.Values)
            {
                var headerText = col.HeaderText;
                sbHtml.Append(HTMLStyle.AddTd(m_HtmlStyle.TH, headerText));
                if (!first)
                {
                    buffer.Append('\t');
                }
                else
                {
                    first = false;
                }

                buffer.Append(EscapeTab(headerText));
            }

            if (hasRowError && addErrorInfo)
            {
                sbHtml.Append(HTMLStyle.AddTd(m_HtmlStyle.TH, c_ErrorInfo));
                buffer.Append('\t');
                buffer.Append(c_ErrorInfo);
            }

            sbHtml.AppendLine(m_HtmlStyle.TRClose);
            buffer.AppendLine();

            var trAlternate = false;
            var lastRefresh = DateTime.Now;

            for (var row = 0; row < rows.Count; row++)
            {
                if (rows[row].IsNewRow)
                {
                    break;
                }
                sbHtml.Append(trAlternate ? m_HtmlStyle.TROpenAlt : m_HtmlStyle.TROpen);
                if (alternatingRows)
                {
                    trAlternate = !trAlternate;
                }
                first = true;
                foreach (var col in visibleColumns.Values)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    var cell = rows[row].Cells[col.Index];
                    AddCell(cell, buffer, sbHtml, !first, addErrorInfo, cutLength, m_HtmlStyle);
                    first = false;
                }

                AppendRowError(buffer, sbHtml, rows[row].ErrorText, addErrorInfo && hasRowError, m_HtmlStyle);
                sbHtml.AppendLine(m_HtmlStyle.TRClose);
                buffer.AppendLine();
                if (!((DateTime.Now - lastRefresh).TotalSeconds > 0.2))
                {
                    continue;
                }
                lastRefresh = DateTime.Now;
                Extensions.ProcessUIElements();
            }

            sbHtml.AppendLine(m_HtmlStyle.TableClose);

            var dataObject = new DataObject();

            dataObject.SetData(DataFormats.Html, true, m_HtmlStyle.ConvertToHtmlFragment(sbHtml.ToString()));
            dataObject.SetData(DataFormats.Text, true, buffer.ToString());
            dataObject.SetClipboard();
        }
Пример #14
0
 /// <summary>
 ///   Appends a row error to the HTML Buffer
 /// </summary>
 /// <param name="stringBuilder">The buffer.</param>
 /// <param name="sbHtml">The StringBuilder for HTML.</param>
 /// <param name="errorText">The error Text</param>
 /// <param name="addErrorInfo">if set to <c>true</c> [add error info].</param>
 private void AppendRowError([NotNull] StringBuilder stringBuilder, [NotNull] StringBuilder sbHtml, [CanBeNull] string errorText, bool addErrorInfo, HTMLStyle style)
 {
     if (!addErrorInfo)
     {
         return;
     }
     if (string.IsNullOrEmpty(errorText))
     {
         sbHtml.Append(m_HtmlStyle.TDEmpty);
     }
     else
     {
         style.AddHtmlCell(sbHtml, m_HtmlStyle.TD, string.Empty, errorText, true);
     }
     stringBuilder.Append('\t');
     stringBuilder.Append(EscapeTab(errorText));
 }
Пример #15
0
        /// <summary>
        ///   Raises the <see cref="KeyDown" /> event.
        /// </summary>
        /// <param name="e">
        ///   A <see cref="KeyEventArgs" /> that contains the event data.
        /// </param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            // Handle CRTL -A
            if (e.Control && e.KeyCode == Keys.A)
            {
                SelectedTreeNode.Clear();
                foreach (TreeNode item in Nodes)
                {
                    AddNodeWithSubnodes(item);
                }

                PaintSelectedNodes();
                // SelectedTreeNode = this.Nodes;
            }

            // Handle CRTL -C
            if (!e.Control || e.KeyCode != Keys.C)
            {
                return;
            }
            {
                if (SelectedTreeNode.Count == 0)
                {
                    return;
                }

                var minLevel = int.MaxValue;
                var maxLevel = int.MinValue;
                foreach (var item in SelectedTreeNode)
                {
                    if (minLevel > item.Level)
                    {
                        minLevel = item.Level;
                    }

                    if (maxLevel < item.Level)
                    {
                        maxLevel = item.Level;
                    }
                }

                var buffer = new StringBuilder();
                var sbHtml = new StringBuilder();
                var style  = ApplicationSetting.HTMLStyle;

                sbHtml.AppendLine(style.TableOpen);
                foreach (var item in SelectedTreeNode.OrderBy(x => x.FullPath))
                {
                    var text = item.Text;
                    sbHtml.Append(style.TROpen);
                    if (item.Tag is FormHierachyDisplay.TreeData data)
                    {
                        text = data.Title;
                        if (!string.IsNullOrEmpty(data.Tag))
                        {
                            sbHtml.Append(HTMLStyle.AddTd("<td>{0}</td>", data.Tag));
                            if (text.StartsWith(data.Tag, StringComparison.Ordinal))
                            {
                                text = text.Substring(data.Tag.Length).TrimStart(' ', '-');
                            }
                        }
                        else
                        {
                            sbHtml.Append(style.TDEmpty);
                        }
                    }

                    for (var level = minLevel; level <= maxLevel; level++)
                    {
                        buffer.Append("\t");
                        if (level < item.Level)
                        {
                            sbHtml.Append(style.TDEmpty);
                        }
                        if (level != item.Level)
                        {
                            continue;
                        }
                        sbHtml.Append(HTMLStyle.AddTd("<td colspan='{0}'>{1}</td>", (maxLevel - level + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), text));
                        buffer.Append(item.Text);
                    }

                    sbHtml.AppendLine(style.TRClose);
                    buffer.AppendLine();
                }

                sbHtml.AppendLine(style.TableClose);

                var dataObject = new DataObject();
                dataObject.SetData(DataFormats.Html, true, style.ConvertToHtmlFragment(sbHtml.ToString()));
                dataObject.SetData(DataFormats.Text, true, buffer.ToString());

                Clipboard.Clear();
                Clipboard.SetDataObject(dataObject, false, 5, 200);
            }
        }
Пример #16
0
        /// <summary>
        ///  Reads the row of the CSV file
        /// </summary>
        /// <param name="regularDataRow">
        ///  Set to <c>true</c> if its not the header row and the maximum size should be determined.
        /// </param>
        /// <param name="storeWarnings">Set to <c>true</c> if the warnings should be issued.</param>
        /// <returns>
        ///  <c>NULL</c> if the row can not be read, array of string values representing the columns of
        ///  the row
        /// </returns>
        private string[] ReadNextRow(bool regularDataRow, bool storeWarnings)
        {
Restart:
            // Store the starting Line Number
            StartLineNumber = EndLineNumber;

            // If already at end of file, return null
            if (EndOfFile || CancellationToken.IsCancellationRequested || m_TextReader == null)
            {
                return(null);
            }

            var item = ReadNextColumn(0, storeWarnings);

            // An empty line does not have any data
            if (string.IsNullOrEmpty(item) && m_EndOfLine)
            {
                m_EndOfLine = false;
                if (m_CsvFile.SkipEmptyLines || !regularDataRow)
                {
                    // go to the next line
                    goto Restart;
                }

                // Return it as array of empty columns
                return(new string[FieldCount]);
            }

            // Skip commented lines
            if (m_CsvFile.FileFormat.CommentLine.Length > 0 &&
                !string.IsNullOrEmpty(item) &&
                item.StartsWith(m_CsvFile.FileFormat.CommentLine, StringComparison.Ordinal)
                ) // A commented line does start with the comment
            {
                if (m_EndOfLine)
                {
                    m_EndOfLine = false;
                }
                else
                {
                    // it might happen that the comment line contains a Delimiter
                    ReadToEOL();
                }
                goto Restart;
            }

            var col     = 0;
            var columns = new List <string>(FieldCount);

            while (item != null)
            {
                // If a column is quoted and does contain the delimiter and linefeed, issue a warning, we
                // might have an opening delimiter with a missing closing delimiter
                if (storeWarnings &&
                    EndLineNumber > StartLineNumber + 4 &&
                    item.Length > 1024 &&
                    item.IndexOf(m_CsvFile.FileFormat.FieldDelimiterChar) != -1)
                {
                    HandleWarning(col,
                                  $"Column has {EndLineNumber - StartLineNumber + 1} lines and has a length of {item.Length} characters".AddWarningId());
                }

                if (item.Length == 0)
                {
                    item = null;
                }
                else
                {
                    if (StringUtils.ShouldBeTreatedAsNull(item, m_CsvFile.TreatTextAsNull))
                    {
                        item = null;
                    }
                    else
                    {
                        item = item.ReplaceCaseInsensitive(m_CsvFile.FileFormat.NewLinePlaceholder, Environment.NewLine)
                               .ReplaceCaseInsensitive(m_CsvFile.FileFormat.DelimiterPlaceholder,
                                                       m_CsvFile.FileFormat.FieldDelimiterChar)
                               .ReplaceCaseInsensitive(m_CsvFile.FileFormat.QuotePlaceholder, m_CsvFile.FileFormat.FieldQualifierChar);

                        if (regularDataRow && col < FieldCount)
                        {
                            var column = GetColumn(col);
                            switch (column.DataType)
                            {
                            case DataType.TextToHtml:
                                var newitemE = HTMLStyle.TextToHtmlEncode(item);
                                if (!item.Equals(newitemE, StringComparison.Ordinal))
                                {
                                    HandleWarning(col, $"HTML encoding removed from {item}");
                                }
                                item = newitemE;
                                break;

                            case DataType.TextToHtmlFull:
                                var newitemS = HTMLStyle.HtmlEncodeShort(item);
                                if (!item.Equals(newitemS, StringComparison.Ordinal))
                                {
                                    HandleWarning(col, $"HTML encoding removed from {item}");
                                }
                                item = newitemS;
                                break;

                            case DataType.TextPart:
                                var part = GetPart(item, column);
                                if (part == null && item.Length > 0)
                                {
                                    HandleWarning(col,
                                                  $"Part {column.Part} of text {item} is empty.");
                                }
                                item = part;
                                break;
                            }

                            if (!string.IsNullOrEmpty(item) && column.Size < item.Length)
                            {
                                column.Size = item.Length;
                            }
                        }
                    }
                }

                columns.Add(item);

                col++;
                item = ReadNextColumn(col, storeWarnings);
            }

            return(columns.ToArray());
        }
Пример #17
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="FormHierarchyDisplay" /> class.
        /// </summary>
        /// <param name="dataTable">The data table.</param>
        /// <param name="dataRows">The filter.</param>
        /// <param name="hTMLStyle">The HTML style.</param>
        public FormHierarchyDisplay([NotNull] DataTable dataTable, [NotNull] DataRow[] dataRows, HTMLStyle hTMLStyle)
        {
            m_DataTable = dataTable;
            m_DataRow   = dataRows;
            InitializeComponent();

            m_TimerSearch.Elapsed  += FilterValueChangedElapsed;
            m_TimerSearch.Interval  = 200;
            m_TimerSearch.AutoReset = false;

            m_TimerDisplay.Elapsed  += TimerDisplayElapsed;
            m_TimerDisplay.Interval  = 1000;
            m_TimerDisplay.AutoReset = false;

            m_TreeView.HTMLStyle = hTMLStyle;
        }