コード例 #1
0
        static List <string> GetRootToLeafNodes(string strLeafToRoot)
        {
            if (string.IsNullOrEmpty(strLeafToRoot))
            {
                AppInsights.LogException("GetRootToLeafNodes", "strLeafToRoot is null");
                return(null);
            }

            List <string> listRet = new List <string>();
            string        patNode = "/[^\n]+\n";

            System.Text.RegularExpressions.Regex regNode = new System.Text.RegularExpressions.Regex(patNode, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (regNode != null && string.IsNullOrEmpty(strLeafToRoot) == false)
            {
                System.Text.RegularExpressions.Match matchNode = regNode.Match(strLeafToRoot);
                while (matchNode.Success)
                {
                    listRet.Insert(0, matchNode.Value.Substring(0, matchNode.Value.Length - 1));
                    matchNode = matchNode.NextMatch();
                }
            }

            return(listRet);
        }
コード例 #2
0
        /// <summary>
        ///		Convierte una serie de coincidencias a minúsculas en una cadena
        /// </summary>
        private string ConvertToLower(string value, System.Text.RegularExpressions.Match match)
        {
            string output    = string.Empty;
            int    lastIndex = 0;

            // Mientras haya una coincidencia
            while (match.Success)
            {
                // Añade la parte anterior a la cadena de salida y cambia el índice de último elemento encontrado
                output   += value.Substring(lastIndex, match.Index - lastIndex);
                lastIndex = match.Index + match.Length;
                // Añade el valor del parámetro a la cadena de salida
                output += value.Substring(match.Index, match.Length).ToLower();
                // Pasa a la siguiente coincidencia
                match = match.NextMatch();
            }
            // Añade el resto de la cadena inicial
            if (lastIndex < value.Length)
            {
                output += value.Substring(lastIndex);
            }
            // Devuelve la colección de parámetros para la base de datos
            return(output);
        }
コード例 #3
0
        /// <summary>
        /// 登録されている「%1%」、「%2%」といった記号の数字を一覧します。
        /// リストに「1」、「2」といった数字に置き換えて返します。
        /// </summary>
        /// <returns></returns>
        public List <int> ExistsP1pNumbers(
            ExprStringMap ecDic_Attr,
            Log_Reports log_Reports
            )
        {
            Log_Method log_Method = new Log_MethodImpl();

            log_Method.BeginMethod(Info_Syntax.Name_Library, this, "GetP1pNumbers", log_Reports);

            //
            //
            //
            //

            List <int> list = new List <int>();


            Dictionary <string, Expr_String> .KeyCollection ecDic_Key = ecDic_Attr.Keys(log_Reports);

            foreach (string sKey in ecDic_Key)
            {
                //
                //
                //
                // p1p,p2p,p3p...といった名前かどうかを判定。
                //
                //
                //
                int nParamNameMatchedCount = 0;
                int nP1pNumber             = 0;
                {
                    //正規表現
                    System.Text.RegularExpressions.Regex regexp =
                        new System.Text.RegularExpressions.Regex(
                            @"p([0-9])+p",
                            //                            @"p[0-9]+p",
                            System.Text.RegularExpressions.RegexOptions.IgnoreCase
                            );

                    //文字列検索を1回する。
                    System.Text.RegularExpressions.Match match = regexp.Match(sKey);

                    while (match.Success)
                    {
                        nParamNameMatchedCount++;

                        bool parsedSuccessful = int.TryParse(match.Groups[1].Value, out nP1pNumber);

                        match = match.NextMatch();
                    }
                }

                if (1 == nParamNameMatchedCount)
                {
                    //
                    //
                    //
                    // p1p,p2p,p3p...といった名前。
                    //
                    //
                    //
                    list.Add(nP1pNumber);
                }
                else
                {
                }
            }


            //
            //
            log_Method.EndMethod(log_Reports);
            return(list);
        }
コード例 #4
0
        public static List <jSonObject> GetHavaDurumlariLive(string sehir)
        {
            List <jSonObject> rv = new List <jSonObject>();

            using (System.Data.DataTable dt = Core.CreateHavaDurumuTable())
            {
                System.Data.DataRow dr = null;
                int    index = 0, count = 0, orjinalIndex = 0;
                string tempContent = BAYMYO.UI.Web.Pages.HtmlRead(string.Format("http://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?m={0}", sehir.ToUpperInvariant().ToLowerInvariant().Replace("İçel", "Mersin")).Replace("Kahramanmaraş", "K.MARAS").Replace("Afyon", "Afyonkarahisar").ToUpperInvariant(), "text/*", "client", System.Text.Encoding.UTF8);
                string tempDeyim   = "(.*?)Trh\">(?<tarih>.+?)</th>(.*?)";
                System.Text.RegularExpressions.Match matchTemp = System.Text.RegularExpressions.Regex.Match(tempContent, tempDeyim, System.Text.RegularExpressions.RegexOptions.Multiline);
                DateTime date = DateTime.Now;
                while (matchTemp.Success)
                {
                    dr               = dt.NewRow();
                    dr["tarih"]      = date.AddDays(index).ToString("dd/MM/yyyy");
                    dr["tarihgelen"] = matchTemp.Groups["tarih"].Value;
                    dr["sehir"]      = sehir.Replace("İçel", "Mersin");
                    dt.Rows.Add(dr);
                    matchTemp = matchTemp.NextMatch();
                    index++;
                }
                count     = dt.Rows.Count;
                tempDeyim = "(.*?)minS\">(?<endusuk>[0-9\\-]{1,3})</td>(.*?)";
                matchTemp = System.Text.RegularExpressions.Regex.Match(tempContent, tempDeyim, System.Text.RegularExpressions.RegexOptions.Multiline);
                if (count > 0)
                {
                    orjinalIndex = count - 5;
                }
                index = orjinalIndex;
                while (matchTemp.Success)
                {
                    if (index < count)
                    {
                        dt.Rows[index]["endusuk"] = BAYMYO.UI.Converts.NullToInt16(matchTemp.Groups["endusuk"].Value);
                        matchTemp = matchTemp.NextMatch();
                    }
                    else
                    {
                        break;
                    }
                    index++;
                }
                tempDeyim = "(.*?)maxS\">(?<enyuksek>[0-9\\-]{1,3})</td>(.*?)";
                matchTemp = System.Text.RegularExpressions.Regex.Match(tempContent, tempDeyim, System.Text.RegularExpressions.RegexOptions.Multiline);
                index     = orjinalIndex;
                while (matchTemp.Success)
                {
                    if (index < count)
                    {
                        dt.Rows[index]["enyuksek"] = BAYMYO.UI.Converts.NullToInt16(matchTemp.Groups["enyuksek"].Value);
                        matchTemp = matchTemp.NextMatch();
                    }
                    else
                    {
                        break;
                    }
                    index++;
                }
                tempDeyim = "(.*?)title=\"(?<bilgi>.+?)\"(.*?)src=\"(?<resim>.+?)\"(.*?)</td>";
                matchTemp = System.Text.RegularExpressions.Regex.Match(tempContent, tempDeyim, System.Text.RegularExpressions.RegexOptions.Multiline);
                index     = orjinalIndex;
                int    lastIndex = 0, textLenght = 0;
                string resimUrl = string.Empty;
                while (matchTemp.Success)
                {
                    if (index < count)
                    {
                        dt.Rows[index]["bilgi"] = matchTemp.Groups["bilgi"].Value;
                        resimUrl   = matchTemp.Groups["resim"].Value.Replace(".gif", "").Replace(".jpg", "").Replace(".png", "");
                        lastIndex  = resimUrl.LastIndexOf('/') + 1;
                        textLenght = resimUrl.Length - lastIndex;
                        dt.Rows[index]["resim"] = string.Format("{0}{1}", Settings.ImagesPath + "havadurumu/", resimUrl.Substring(lastIndex, textLenght) + ".png");
                        matchTemp  = matchTemp.NextMatch();
                        lastIndex  = 0;
                        textLenght = 0;
                    }
                    else
                    {
                        break;
                    }
                    index++;
                }
                DateTime currentDate;
                foreach (System.Data.DataRow item in dt.Rows)
                {
                    currentDate = BAYMYO.UI.Converts.NullToDateTime(item["tarih"]);
                    rv.Add(new jSonObject {
                        Resim = item["resim"].ToString(), Baslik = currentDate.ToString("ddddd"), Ozet = item["bilgi"].ToString(), Deger = item["endusuk"].ToString(), Degisim = item["enyuksek"].ToString(), Tarih = currentDate.ToString("dd MMMMM yyyy"), Saat = currentDate.ToShortTimeString(), Yeni = ((currentDate - DateTime.Now).Days == 0)
                    });
                }
            }
            return(rv);
        }
コード例 #5
0
        public static void PasteDataGridViewSelectedCellsFromClipboard(
            DataGridView dataGridView, int leftColumnOverwrite, int rightColumnOverwrite, int topRowOverwrite, int buttomRowOverwrite, bool removeTag,
            out bool textBoxSelectionCanRestore, out int textBoxSelectionStart, out int textBoxSelectionLength)
        {
            textBoxSelectionStart      = 0;
            textBoxSelectionLength     = 0;
            textBoxSelectionCanRestore = false;

            #region Html Format
            // Try to process as html format (data from excel) since it keeps the row information intact, instead of assuming
            // a new row for every new line if we just process it as text
            String HtmlFormat = Clipboard.GetData("HTML Format") as String;
            List <List <string> > rowContents = new List <List <string> >();
            if (HtmlFormat != null)
            {
                try
                {
                    // Remove html tags to just extract row information and store it in rowContents
                    System.Text.RegularExpressions.Regex TRregex = new System.Text.RegularExpressions.Regex(@"<( )*tr([^>])*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    System.Text.RegularExpressions.Regex TDregex = new System.Text.RegularExpressions.Regex(@"<( )*td([^>])*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    System.Text.RegularExpressions.Match trMatch = TRregex.Match(HtmlFormat);

                    while (!string.IsNullOrWhiteSpace(trMatch.Value))
                    {
                        int rowStart = trMatch.Index + trMatch.Length;
                        int rowEnd   = HtmlFormat.IndexOf("</tr>", rowStart, StringComparison.InvariantCultureIgnoreCase);
                        System.Text.RegularExpressions.Match tdMatch = TDregex.Match(HtmlFormat, rowStart, rowEnd - rowStart);
                        List <string> rowContent = new List <string>();
                        while (!string.IsNullOrWhiteSpace(tdMatch.Value))
                        {
                            int    cellStart   = tdMatch.Index + tdMatch.Length;
                            int    cellEnd     = HtmlFormat.IndexOf("</td>", cellStart, StringComparison.InvariantCultureIgnoreCase);
                            string cellContent = HtmlFormat.Substring(cellStart, cellEnd - cellStart);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*br( )*>", "\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*li( )*>", "\r\n - ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*div([^>])*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*code([^>])*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*/code([^>])*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            cellContent = System.Text.RegularExpressions.Regex.Replace(cellContent, @"<( )*p([^>])*>", "\r\n\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            if (!cellContent.StartsWith("<B>")) //Don't paste Row Header
                            {
                                //cellContent = cellContent.Replace("&nbsp;", " ");
                                cellContent = System.Net.WebUtility.HtmlDecode(cellContent);
                                rowContent.Add(cellContent);
                            }
                            tdMatch = tdMatch.NextMatch();
                        }
                        if (rowContent.Count > 0)
                        {
                            rowContents.Add(rowContent);
                        }
                        trMatch = trMatch.NextMatch();
                    }
                } catch
                {
                    rowContents.Clear();
                }
            }
            #endregion

            #region Text format
            if (rowContents.Count == 0)
            {
                // Clipboard is not in html format, read as text
                String   CopiedText = Clipboard.GetText();
                String[] lines      = CopiedText.Split('\n');
                foreach (string line in lines)
                {
                    List <string> rowContent = new List <string>(line.Split('\t'));
                    if (rowContent.Count > 0)
                    {
                        rowContents.Add(rowContent);
                    }
                }
            }
            #endregion

            #region Paste into Edit cell
            if (IsCurrentCellTextBoxAndInEditMode(dataGridView))
            {
                if (rowContents.Count >= 1)
                {
                    string clipboardText = "";
                    foreach (List <string> textsInLine in rowContents)
                    {
                        string clipboardLine = "";
                        foreach (string text in textsInLine)
                        {
                            clipboardLine = clipboardLine + (string.IsNullOrWhiteSpace(clipboardLine) ? "" : " ") + text;
                        }
                        clipboardText = clipboardText + (string.IsNullOrWhiteSpace(clipboardText) ? "" : "\r\n") + clipboardLine;
                    }

                    Clipboard.SetText(clipboardText);
                }
                TextBox textBox = dataGridView.EditingControl as TextBox;
                if (textBox != null)
                {
                    textBox.Paste();
                    TextBoxGetSelction(textBox, out textBoxSelectionCanRestore, out textBoxSelectionStart, out textBoxSelectionLength);
                    textBoxSelectionCanRestore = true;
                }
                return; //Can return - don't need push to stach, Edit cell did push to stacj
            }
            #endregion

            // -----------------------------------------------------------------------------
            // Put the feach data to cells
            // -----------------------------------------------------------------------------

            Stack <CellLocation> selectedCells = new Stack <CellLocation>();

            #region Find all - SelectedCells - and - topRow and leftColumn -
            int topRow     = int.MaxValue;
            int leftColumn = int.MaxValue;
            foreach (DataGridViewCell dataGridViewCell in dataGridView.SelectedCells)
            {
                topRow     = Math.Min(topRow, dataGridViewCell.RowIndex);
                leftColumn = Math.Min(leftColumn, dataGridViewCell.ColumnIndex);

                selectedCells.Push(new CellLocation(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex));
            }
            int iRow = topRow;
            #endregion

            #region Add Rows if needed
            if (dataGridView.AllowUserToAddRows)
            {
                // DataGridView's rowCount has one extra row (the temporary new row)
                if (iRow + rowContents.Count > dataGridView.Rows.Count - 1)
                {
                    int iNumNewRows = iRow + rowContents.Count - dataGridView.Rows.Count + 1;
                    // Simply add to a new row to the datagridview if it is not binded to a datasource
                    if (dataGridView.DataSource == null)
                    {
                        //dataGridView.Rows.Add(iNumNewRows); //This will change the selected cell
                        for (int i = 0; i < iNumNewRows; i++)
                        {
                            dataGridView.Rows.Add();
                        }
                        dataGridView.ClearSelection(); //Remove the selection and select it back after
                    }
                    // Otherwise, add rows to binded data source
                    else
                    {
                        try
                        {
                            BindingSource bindingSource = dataGridView.DataSource as BindingSource;
                            if (bindingSource != null)
                            {
                                // This is important!!
                                // Cancel Edit before adding new entries into bindingsource
                                // If the UI is currently adding a new line (you have your cursor on the last time)
                                // You will System.InvalidOperationException
                                bindingSource.CancelEdit();
                                for (int i = 0; i < iNumNewRows; i++)
                                {
                                    Object obj = bindingSource.AddNew();
                                    dataGridView.ClearSelection();
                                }
                            }
                        }
                        catch
                        {
                            // failed adding row to binding data source
                            // It was okay for my application to ignore the error
                        }
                    }
                }
            }
            #endregion

            #region New rows added, and selection forgoten. Need to reselect
            if (dataGridView.SelectedCells.Count == 0)
            {
                while (selectedCells.Count > 0)
                {
                    CellLocation cell = selectedCells.Pop();
                    dataGridView[cell.ColumnIndex, cell.RowIndex].Selected = true;
                }
            }
            #endregion

            //Paste one clipboard "cell/text" to all selected (Only one text to more than one selected cell)
            //Paste many clipbaord "cell/text" to selected fields (Paste to more than one selected cell)
            //Paste many clipbaord "cell/text" bases on current location (Paste to one selected cell)

            Dictionary <CellLocation, DataGridViewGenericCell> undoCells = new Dictionary <CellLocation, DataGridViewGenericCell>();

            #region Count rows and columns in selctions
            List <int> columnsSelected = new List <int>();
            List <int> rowsSelected    = new List <int>();
            foreach (CellLocation cellLocationCount in selectedCells)
            {
                if (!columnsSelected.Contains(cellLocationCount.ColumnIndex))
                {
                    columnsSelected.Add(cellLocationCount.ColumnIndex);
                }
                if (!rowsSelected.Contains(cellLocationCount.RowIndex))
                {
                    rowsSelected.Add(cellLocationCount.RowIndex);
                }
            }
            #endregion

            int columnConentsCount = 0;
            if (rowContents.Count > 0)
            {
                columnConentsCount = rowContents[0].Count;
            }

            #region Paste one clipboard "cell/text" to all selected (Only one text to more than one selected cell)
            #region Paste - Source: Nothing selected - nothing to do
            if (rowContents.Count == 0 && columnConentsCount == 0)
            {
                //Nothing found
            }
            #endregion
            #region Paste - Sourec: One Cell Selected (rowContents.Count == 1 && columnConentsCount == 1)
            else if (rowContents.Count == 1 && columnConentsCount == 1)
            {
                NuberOfItemsToEdit = dataGridView.SelectedCells.Count;
                IsClipboardActive  = true;
                foreach (DataGridViewCell dataGridViewCell in dataGridView.SelectedCells)
                {
                    String cellContent = rowContents[0][0];
                    try
                    {
                        if (!dataGridViewCell.ReadOnly ||
                            (dataGridViewCell.ColumnIndex >= leftColumnOverwrite && dataGridViewCell.ColumnIndex <= rightColumnOverwrite &&
                             dataGridViewCell.RowIndex >= topRowOverwrite && dataGridViewCell.RowIndex <= buttomRowOverwrite)
                            )
                        {
                            //Rememebr in the current value in cell before changed so we can "ReDo" in current DataGridView
                            CellLocation cellPosition = new CellLocation(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                            undoCells.Add(cellPosition, DataGridViewHandler.CopyCellDataGridViewGenericCell(dataGridView[dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex]));

                            DataGridViewHandler.SetCellValue(dataGridView, dataGridViewCell, Convert.ChangeType(cellContent, dataGridViewCell.ValueType));
                            if (removeTag)
                            {
                                DataGridViewHandler.SetCellStatusSwichStatus(dataGridView, dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, SwitchStates.Undefine);
                            }
                            dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                        }
                    } catch { }
                }
                NuberOfItemsToEdit = 0;
                IsClipboardActive  = false;
            }
            #endregion
            #region Paste - One row, and multimple columns, Only cell selected / one row from clipboard to multiple rows
            else if (
                rowContents.Count == 1 && columnConentsCount > 1 &&   //One row, and multimple columns
                columnsSelected.Count > 1 && rowsSelected.Count >= 1) //Only cell selected
            {
                if (columnConentsCount != columnsSelected.Count)
                {
                    KryptonMessageBox.Show("Can't paste selection. Can only paste selection when have selected equal numbers of columns.\r\n" +
                                           "Columns selected for copy: " + columnConentsCount + "\r\n" +
                                           "Columns selected for paste: " + columnsSelected.Count,
                                           "Can't paste selected text", MessageBoxButtons.OK, MessageBoxIcon.Warning, showCtrlCopy: true);
                    return;
                }

                NuberOfItemsToEdit = columnsSelected.Count * rowsSelected.Count;
                IsClipboardActive  = true;

                columnsSelected.Sort();
                for (int columnIndex = 0; columnIndex < rowContents[0].Count; columnIndex++)
                {
                    String cellContent      = rowContents[0][columnIndex]; //Row content will always be 1
                    int    columnIndexPaste = columnsSelected[columnIndex];

                    foreach (DataGridViewCell dataGridViewCell in dataGridView.SelectedCells)
                    {
                        if (dataGridViewCell.ColumnIndex == columnIndexPaste)
                        {
                            try
                            {
                                if (!dataGridViewCell.ReadOnly ||
                                    (dataGridViewCell.ColumnIndex >= leftColumnOverwrite && dataGridViewCell.ColumnIndex <= rightColumnOverwrite &&
                                     dataGridViewCell.RowIndex >= topRowOverwrite && dataGridViewCell.RowIndex <= buttomRowOverwrite)
                                    )
                                {
                                    //Rememebr in the current value in cell before changed so we can "ReDo" in current DataGridView
                                    CellLocation cellPosition = new CellLocation(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                                    undoCells.Add(cellPosition, DataGridViewHandler.CopyCellDataGridViewGenericCell(dataGridViewCell));

                                    DataGridViewHandler.SetCellValue(dataGridView, dataGridViewCell, Convert.ChangeType(cellContent, dataGridViewCell.ValueType));
                                    if (removeTag)
                                    {
                                        DataGridViewHandler.SetCellStatusSwichStatus(dataGridView, dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, SwitchStates.Undefine);
                                    }
                                    dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                                }
                            }
                            catch { }
                        }
                    }
                }
                NuberOfItemsToEdit = 0;
                IsClipboardActive  = false;
            }
            #endregion
            #region Paste - one column from clipboard to multiple columns / Only cell selected
            else if (rowContents.Count > 1 && columnConentsCount == 1 &&       //One column, and multimple rows
                     !(columnsSelected.Count == 1 && rowsSelected.Count == 1)) //Only cell selected
            {
                if (rowContents.Count != rowsSelected.Count)
                {
                    KryptonMessageBox.Show("Can't paste selection. Can only paste selection when have selected equal numbers of rows.\r\n" +
                                           "Rows selected for copy: " + rowContents.Count + "\r\n" +
                                           "Rows selected for paste: " + rowsSelected.Count,
                                           "Can't paste selected text", MessageBoxButtons.OK, MessageBoxIcon.Warning, showCtrlCopy: true);
                    return;
                }

                NuberOfItemsToEdit = columnsSelected.Count * rowsSelected.Count;
                IsClipboardActive  = true;
                rowsSelected.Sort();
                for (int rowIndex = 0; rowIndex < rowContents.Count; rowIndex++)
                {
                    String cellContent = rowContents[rowIndex][0];

                    foreach (DataGridViewCell dataGridViewCell in dataGridView.SelectedCells)
                    {
                        int columnIndexPaste = rowsSelected[rowIndex];

                        if (dataGridViewCell.RowIndex == columnIndexPaste)
                        {
                            try
                            {
                                if (!dataGridViewCell.ReadOnly ||
                                    (dataGridViewCell.ColumnIndex >= leftColumnOverwrite && dataGridViewCell.ColumnIndex <= rightColumnOverwrite &&
                                     dataGridViewCell.RowIndex >= topRowOverwrite && dataGridViewCell.RowIndex <= buttomRowOverwrite)
                                    )
                                {
                                    //Rememebr in the current value in cell before changed so we can "ReDo" in current DataGridView
                                    CellLocation cellPosition = new CellLocation(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                                    undoCells.Add(cellPosition, DataGridViewHandler.CopyCellDataGridViewGenericCell(dataGridViewCell));

                                    DataGridViewHandler.SetCellValue(dataGridView, dataGridViewCell, Convert.ChangeType(cellContent, dataGridViewCell.ValueType));
                                    if (removeTag)
                                    {
                                        DataGridViewHandler.SetCellStatusSwichStatus(dataGridView, dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, SwitchStates.Undefine);
                                    }
                                    dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex);
                                }
                            }
                            catch { }
                        }
                    }
                }
                NuberOfItemsToEdit = 0;
                IsClipboardActive  = false;
            }
            #endregion
            #region Paste - rest
            else
            {
                NuberOfItemsToEdit = columnsSelected.Count * rowsSelected.Count;
                IsClipboardActive  = true;

                foreach (List <string> rowContent in rowContents)
                {
                    int iCol = leftColumn;
                    foreach (string cellContent in rowContent)
                    {
                        try
                        {
                            bool cellOk = false;
                            if (dataGridView.SelectedCells.Count == 1)
                            {
                                cellOk = true;
                            }
                            else
                            {
                                foreach (DataGridViewCell dataGridViewCell in dataGridView.SelectedCells)
                                {
                                    if (dataGridViewCell.ColumnIndex == iCol && dataGridViewCell.RowIndex == iRow)
                                    {
                                        cellOk = true;
                                    }
                                }
                            }

                            if (cellOk)
                            {
                                if (iCol < dataGridView.Columns.Count)
                                {
                                    DataGridViewCell cell = dataGridView[iCol, iRow];
                                    //if (!cell.ReadOnly)
                                    if (!cell.ReadOnly ||
                                        (cell.ColumnIndex >= leftColumnOverwrite && cell.ColumnIndex <= rightColumnOverwrite &&
                                         cell.RowIndex >= topRowOverwrite && cell.RowIndex <= buttomRowOverwrite)
                                        )
                                    {
                                        //Rememebr in the current value in cell before changed so we can "ReDo" in current DataGridView
                                        CellLocation cellPosition = new CellLocation(iCol, iRow);
                                        undoCells.Add(cellPosition, DataGridViewHandler.CopyCellDataGridViewGenericCell(dataGridView, iCol, iRow));
                                        DataGridViewHandler.SetCellValue(dataGridView, cell, Convert.ChangeType(cellContent, cell.ValueType));
                                        if (removeTag)
                                        {
                                            DataGridViewHandler.SetCellStatusSwichStatus(dataGridView, cell.ColumnIndex, cell.RowIndex, SwitchStates.Undefine);
                                        }
                                        dataGridView.InvalidateCell(iCol, iRow);
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        iCol++;
                    }
                    iRow++;
                    if (iRow >= dataGridView.Rows.Count)
                    {
                        break;
                    }
                }
                NuberOfItemsToEdit = 0;
                IsClipboardActive  = false;
                dataGridView.ResumeLayout();
            }
            #endregion
            #endregion

            //CAN BE REMOVED foreach (CellLocation cellLocation in undoCells.Keys) dataGridView[cellLocation.ColumnIndex, cellLocation.RowIndex].Selected = true; //Already done, can be removed after check
            PushToUndoStack(dataGridView, undoCells);
        }
コード例 #6
0
        /// <summary>
        /// step 3.
        /// </summary>
        /// <param name="result"></param>
        protected void Render(ReportRequest rRequest, ref ReportExecuteResult result, string findString = null)
        {
            try
            {
                AspNetCore.Report.DeviceInfos.DeviceInfo deviceInfo = this.GenerateDeviceInfo(rRequest);
                ReportViewer.Versions.TryGetValue(this.ReportSettings.ReportServer, out System.Version version);
                string           format;
                ReportRenderType reportRenderType;
                switch (rRequest.RenderType)
                {
                case ReportRenderType.Html4_0:
                    format = "Html4.0";
                    break;

                case ReportRenderType.ExcelOpenXml:
                    if (version.Major < 11)
                    {
                        reportRenderType = ReportRenderType.Excel;
                        format           = reportRenderType.ToString();
                    }
                    else
                    {
                        reportRenderType = ReportRenderType.ExcelOpenXml;
                        format           = reportRenderType.ToString();
                    }
                    break;

                case ReportRenderType.WordOpenXml:
                    if (version.Major < 11)
                    {
                        reportRenderType = ReportRenderType.Word;
                        format           = reportRenderType.ToString();
                    }
                    else
                    {
                        reportRenderType = ReportRenderType.WordOpenXml;
                        format           = reportRenderType.ToString();
                    }
                    break;

                default:
                    reportRenderType = rRequest.RenderType;
                    format           = reportRenderType.ToString();
                    break;
                }
                string strDeviceInfo = deviceInfo.ToString();
                AspNetCore.Report.ReportExecutionService.Render2Request  request  = new AspNetCore.Report.ReportExecutionService.Render2Request(format, strDeviceInfo, AspNetCore.Report.ReportExecutionService.PageCountMode.Actual);
                AspNetCore.Report.ReportExecutionService.Render2Response response = this.ReportClient.Render2Async(request).GetAwaiter().GetResult();
                if (rRequest.RenderType == ReportRenderType.Html4_0 || rRequest.RenderType == ReportRenderType.Html5)
                {
                    string content = System.Text.Encoding.UTF8.GetString(response.Result);
                    System.Text.StringBuilder            sb     = new System.Text.StringBuilder(content);
                    System.Text.RegularExpressions.Regex reg    = new System.Text.RegularExpressions.Regex("(<img [^>]*? src=\"([^\"]+&rs%3AImageID=([^\"']+))\")", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    System.Text.RegularExpressions.Match matchs = reg.Match(content);
                    while (matchs.Success)
                    {
                        string a = matchs.Result("$1");
                        string b = matchs.Result("$2");
                        string c = matchs.Result("$3");
                        AspNetCore.Report.ReportExecutionService.RenderStreamResponse cc = this.ReportClient.RenderStreamAsync(new AspNetCore.Report.ReportExecutionService.RenderStreamRequest(format, c, strDeviceInfo)).GetAwaiter().GetResult();
                        string img = $"data:{cc.MimeType};base64,{System.Convert.ToBase64String(cc.Result)}";
                        string aa  = a.Replace(b, img);
                        sb.Replace(a, aa);
                        matchs = matchs.NextMatch();
                    }
                    result.Contents = sb.ToString();
                }
                result.Stream    = response.Result;
                result.Encoding  = response.Encoding;
                result.Extension = response.Extension;
                result.MimeType  = response.MimeType;
            }
            catch (System.Exception ex)
            {
                throw new ReportException("Render error: " + ex.Message, ex);
            }
        }
コード例 #7
0
ファイル: Form1.cs プロジェクト: Monkeybin11/Kitware.VTK
        /// <summary>
        /// Recursive function that finds and
        /// graphs Wikipedia links
        /// </summary>
        /// <param name="g">The graph</param>
        /// <param name="lookupValue">Name of orgin article</param>
        /// <param name="hops">How many degrees of separation from the original article</param>
        private void addLinks(Kitware.VTK.vtkMutableDirectedGraph g, string lookupValue, int hops)
        {
            vtkStringArray label  = (vtkStringArray)g.GetVertexData().GetAbstractArray("label");
            long           parent = label.LookupValue(lookupValue);

            //if lookupValue is not in the graph add it
            if (parent < 0)
            {
                rotateLogo();
                parent = g.AddVertex();
                label.InsertNextValue(lookupValue);
                arrListSmall.Add(lookupValue);
            }
            //Parse Wikipedia for the lookupValue
            string underscores = lookupValue.Replace(' ', '_');

            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://en.wikipedia.org/wiki/Special:Export/" + underscores);
            webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            webRequest.Accept      = "text/xml";
            try
            {
                System.Net.HttpWebResponse webResponse    = (System.Net.HttpWebResponse)webRequest.GetResponse();
                System.IO.Stream           responseStream = webResponse.GetResponseStream();
                System.Xml.XmlReader       reader         = new System.Xml.XmlTextReader(responseStream);
                String NS = "http://www.mediawiki.org/xml/export-0.4/";
                System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader);
                reader.Close();
                webResponse.Close();
                System.Xml.XPath.XPathNavigator    myXPahtNavigator = doc.CreateNavigator();
                System.Xml.XPath.XPathNodeIterator nodesText        = myXPahtNavigator.SelectDescendants("text", NS, false);

                String fullText = "";
                //Parse the wiki page for links
                while (nodesText.MoveNext())
                {
                    fullText += nodesText.Current.InnerXml + " ";
                }
                System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(fullText, "\\[\\[.*?\\]\\]");
                int max;
                try
                {
                    max = System.Convert.ToInt32(toolStripTextBox2.Text);
                }
                catch (Exception)
                {
                    max = -1;
                }
                int count = 0;
                while (m.Success && ((count < max) || (max < 0)))
                {
                    String s         = m.ToString();
                    int    index     = s.IndexOf('|');
                    String substring = "";
                    if (index > 0)
                    {
                        substring = s.Substring(2, index - 2);
                    }
                    else
                    {
                        substring = s.Substring(2, s.Length - 4);
                    }
                    //if the new substring is not already there add it
                    long v = label.LookupValue(substring);
                    if (v < 0)
                    {
                        rotateLogo();
                        v = g.AddVertex();
                        label.InsertNextValue(substring);
                        arrListSmall.Add(substring);
                        if (hops > 1)
                        {
                            addLinks(g, substring, hops - 1);
                        }
                    }
                    else if (arrListSmall.IndexOf(substring) < 0)
                    {
                        arrListSmall.Add(substring);
                        if (hops > 1)
                        {
                            addLinks(g, substring, hops - 1);
                        }
                    }
                    //Make sure nothing is linked to twice by expanding the graph
                    vtkAdjacentVertexIterator avi = vtkAdjacentVertexIterator.New();
                    g.GetAdjacentVertices((int)parent, avi);
                    m = m.NextMatch();
                    ++count;

                    while (avi.HasNext())
                    {
                        long id = avi.Next();
                        if (id == v)
                        {
                            return;
                        }
                    }
                    rotateLogo();
                    g.AddGraphEdge((int)parent, (int)v);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
コード例 #8
0
        /// <summary>
        /// CSVをArrayListに変換
        /// </summary>
        /// <param name="csvText">CSVの内容が入ったString</param>
        /// <returns>変換結果のArrayList</returns>
        public ArrayList CsvToArrayList1(string csvText)
        {
            System.Collections.ArrayList csvRecords =
                new System.Collections.ArrayList();

            //前後の改行を削除しておく
            csvText = csvText.Trim(new char[] { '\r', '\n' });

            //一行取り出すための正規表現
            System.Text.RegularExpressions.Regex regLine =
                new System.Text.RegularExpressions.Regex(
                    "^.*(?:\\n|$)",
                    System.Text.RegularExpressions.RegexOptions.Multiline);

            //1行のCSVから各フィールドを取得するための正規表現
            System.Text.RegularExpressions.Regex regCsv =
                new System.Text.RegularExpressions.Regex(
                    "\\s*(\"(?:[^\"]|\"\")*\"|[^,]*)\\s*,",
                    System.Text.RegularExpressions.RegexOptions.None);

            System.Text.RegularExpressions.Match mLine = regLine.Match(csvText);
            while (mLine.Success)
            {
                //一行取り出す
                string line = mLine.Value;
                //改行記号が"で囲まれているか調べる
                while ((CountString(line, "\"") % 2) == 1)
                {
                    mLine = mLine.NextMatch();
                    if (!mLine.Success)
                    {
                        throw new ApplicationException("不正なCSV");
                    }
                    line += mLine.Value;
                }
                //行の最後の改行記号を削除
                line = line.TrimEnd(new char[] { '\r', '\n' });
                //最後に「,」をつける
                line += ",";

                //1つの行からフィールドを取り出す
                System.Collections.ArrayList csvFields =
                    new System.Collections.ArrayList();
                System.Text.RegularExpressions.Match m = regCsv.Match(line);
                while (m.Success)
                {
                    string field = m.Groups[1].Value;
                    //前後の空白を削除
                    field = field.Trim();
                    //"で囲まれている時
                    if (field.StartsWith("\"") && field.EndsWith("\""))
                    {
                        //前後の"を取る
                        field = field.Substring(1, field.Length - 2);
                        //「""」を「"」にする
                        field = field.Replace("\"\"", "\"");
                    }
                    csvFields.Add(field);
                    m = m.NextMatch();
                }

                csvFields.TrimToSize();
                csvRecords.Add(csvFields);

                mLine = mLine.NextMatch();
            }

            csvRecords.TrimToSize();
            return(csvRecords);
        }
コード例 #9
0
ファイル: COCFillManager.cs プロジェクト: qwdingyu/C-
        private List <Hashtable> ReadRowSheet(Hashtable columnData)
        {
            Hashtable        current = null, last = null;
            List <Hashtable> list         = new List <Hashtable>();
            Hashtable        columnHeader = new Hashtable();

            if (sheet1.ReadFollowingRow(5))
            {
                while (sheet1.ReadNextCell(false))
                {
                    columnHeader.Add(sheet1.CurrentCell.ColumnIndex, sheet1.GetContent());
                }
                System.Text.RegularExpressions.Match match = null;
                string str = "";
                while (sheet1.ReadNextRow())
                {
                    match   = null;
                    current = new Hashtable();
                    while (sheet1.ReadNextCell(false))
                    {
                        object content = sheet1.GetContent();
                        str = content == null ? "" : content.ToString();
                        switch (columnHeader[sheet1.CurrentCell.ColumnIndex] as string)
                        {
                        case "Model":
                            current.Add("车型系列代号", str);
                            break;

                        case "CoC No. regulation":
                            current.Add("车辆一致性证书编号", str);
                            if (last == null)
                            {
                                current.Add("Key", str);
                            }
                            break;

                        case "Product":
                            if (string.IsNullOrEmpty(str) && last != null)
                            {
                                if (current.ContainsKey("Key") == false)
                                {
                                    current.Add("Key", last["Key"]);
                                }
                                current.Add("车型名称", last["车型名称"]);
                            }
                            else
                            {
                                match = System.Text.RegularExpressions.Regex.Match(str, "(?<=\r\n).*");
                                if (match.Success)
                                {
                                    current.Add("车型名称", match.Value);
                                }
                            }
                            break;

                        case "Model Code":
                            if (string.IsNullOrEmpty(str) && last != null)
                            {
                                current.Add("单元代号", last["单元代号"]);
                            }
                            else
                            {
                                match = System.Text.RegularExpressions.Regex.Match(str, ".*(?=\r\n)");
                                if (match.Success)
                                {
                                    current.Add("单元代号", match.Value);
                                }
                            }
                            break;

                        case "轮胎规格":
                            if (str == null)
                            {
                                continue;
                            }
                            match = System.Text.RegularExpressions.Regex.Match(str, @"[0-9]{3,}/[0-9]+\s*R[0-9]+");
                            if (match.Success)
                            {
                                string first = match.Value, second = "";
                                current.Add("轮胎规格(第一轴)", first);
                                match = match.NextMatch();
                                if (match.Success)
                                {
                                    second = match.Value;
                                }
                                else
                                {
                                    second = first;
                                }
                                current.Add("轮胎规格(第二轴)", second);
                            }
                            break;

                        case "前轮距":
                            current.Add("前轮距", str);
                            break;

                        case "后轮距":
                            current.Add("轮距(mm)", string.Format("{0}/{1}", current["前轮距"], str));
                            current.Remove("前轮距");
                            break;

                        case "车长":
                            current.Add("车长(mm)", str);
                            break;

                        case "前悬":
                            current.Add("前悬(mm)", str);
                            break;

                        case "后悬":
                            current.Add("后悬(mm)", str);
                            break;

                        case "接近角":
                            current.Add("接近角(º)", str);
                            break;

                        case "离去角":
                            current.Add("离去角(º)", str);
                            break;
                        }
                    }
                    string key = current["Key"] as string;
                    if (key == null)
                    {
                        continue;
                    }
                    Hashtable otherData = columnData[key] as Hashtable;
                    if (otherData != null)
                    {
                        foreach (DictionaryEntry entry in otherData)
                        {
                            if (current.ContainsKey(entry.Key))
                            {
                                if (string.IsNullOrEmpty(current[entry.Key] as string))
                                {
                                    current[entry.Key] = entry.Value;
                                }
                            }
                            else
                            {
                                current.Add(entry.Key, entry.Value);
                            }
                        }
                        current.Add("长度/前悬/轴距/后悬(mm)", string.Format("{0}/{1}/{2}/{3}", current["车长(mm)"], current["前悬(mm)"], current["轴距(mm)"], current["后悬(mm)"]));
                    }
                    list.Add(current);
                    last = current;
                }
            }
            return(list);
        }
コード例 #10
0
ファイル: COCFillManager.cs プロジェクト: qwdingyu/C-
        private Hashtable ReadColumnSheet()
        {
            Hashtable data    = new Hashtable();
            Hashtable keyList = new Hashtable();

            if (sheet2.ReadFollowingRow(6))
            {
                string content       = null;
                object cellContent   = null;
                string parameterName = "";
                while (sheet2.ReadNextCell(false))
                {
                    if (sheet2.CurrentCell.ColumnIndex == 3)
                    {
                        parameterName = sheet2.GetContent() as string;
                    }
                    else if (sheet2.CurrentCell.ColumnIndex > 3)
                    {
                        if (parameterName == null)
                        {
                            break;
                        }
                        cellContent = sheet2.GetContent();
                        content     = cellContent == null ? null : cellContent.ToString();
                        Hashtable innerData = new Hashtable();
                        if (content != null)
                        {
                            innerData.Add(parameterName, content);
                            data.Add(content, innerData);
                            keyList.Add(sheet2.CurrentCell.ColumnIndex, content);
                        }
                    }
                }
                while (sheet2.ReadNextRow())
                {
                    parameterName = null;
                    while (sheet2.ReadNextCell(false))
                    {
                        short columnIndex = sheet2.CurrentCell.ColumnIndex;
                        if (columnIndex == 3)
                        {
                            parameterName = sheet2.GetContent() as string;
                        }
                        else if (columnIndex > 3)
                        {
                            if (parameterName == null)
                            {
                                break;
                            }
                            string key = keyList[columnIndex] as string;
                            cellContent = sheet2.GetContent();
                            content     = cellContent == null ? null : cellContent.ToString();
                            Hashtable innerData = data[key] as Hashtable;
                            if (innerData != null)
                            {
                                System.Text.RegularExpressions.Match match = null;
                                switch (parameterName)
                                {
                                case "CCC认证引用的标准号和实施阶段":
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @",?\s*(?<standard>GB[^0-9]*[0-9]+(\.[0-9]+)?\-[0-9]{4})\s*(?<em>[^,\s]*)\s*");
                                    while (match.Success)
                                    {
                                        string standard = match.Groups["standard"].Value;
                                        if (string.IsNullOrEmpty(standard) == false)
                                        {
                                            innerData.Add(standard, match.Groups["em"].Value);
                                            innerData["CCC认证引用的标准号和实施阶段"] = string.Format("{0}{1}",
                                                                                          innerData["CCC认证引用的标准号和实施阶段"] == null ? null : string.Format("{0}|", innerData["CCC认证引用的标准号和实施阶段"]), standard);
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                case "CCC认证引用的标准号":
                                    innerData.Add("CCC认证引用的标准号", content == null ? "" : content.Replace(',', '|'));
                                    break;

                                case "排气(液体燃料)":
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @"(?<name>[^:]+)\s*:\s*(?<value>[^\s]*)\s*");
                                    while (match.Success)
                                    {
                                        string name  = match.Groups["name"].Value;
                                        string value = match.Groups["value"].Value;
                                        if (string.IsNullOrEmpty(name) == false)
                                        {
                                            innerData.Add(string.Format("{0}(液体)", name), value);
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                case "排气(气体燃料)":
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @"(?<name>[^:]+)\s*:\s*(?<value>[^\s]*)\s*");
                                    while (match.Success)
                                    {
                                        string name  = match.Groups["name"].Value;
                                        string value = match.Groups["value"].Value;
                                        if (string.IsNullOrEmpty(name) == false)
                                        {
                                            innerData.Add(string.Format("{0}(气体)", name), value);
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                case "轮距(mm)":
                                    //前:1600  后:1627
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @"前:(?<front>[0-9]+)\s*后:(?<back>[0-9]+)\s*");
                                    if (match.Success)
                                    {
                                        string front = match.Groups["front"].Value;
                                        string back  = match.Groups["back"].Value;
                                        if (string.IsNullOrEmpty(front) == false)
                                        {
                                            innerData.Add("轮距(mm)", string.Format("{0}/{1}", front, back));
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                case "轮胎规格":
                                    //第1轴:225/55 R17  第2轴:225/55 R17
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @"第1轴:(?<first>[0-9]+/[0-9]+\s*R[0-9]+)\s*第2轴:(?<second>[0-9]+/[0-9]+\s*R[0-9]+)?\s*");
                                    if (match.Success)
                                    {
                                        string first  = match.Groups["first"].Value;
                                        string second = match.Groups["second"].Success ? match.Groups["second"].Value : first;
                                        if (string.IsNullOrEmpty(first) == false)
                                        {
                                            innerData.Add("轮胎规格(第一轴)", first);
                                            innerData.Add("轮胎规格(第二轴)", second);
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                case "CCC证书号(须包含版本号)":
                                    if (string.IsNullOrEmpty(content))
                                    {
                                        continue;
                                    }
                                    match = System.Text.RegularExpressions.Regex.Match(content, @"(?<cert>[0-9]+)\s*\((?<version>[0-9]+)\)");
                                    if (match.Success)
                                    {
                                        string cert    = match.Groups["cert"].Value;
                                        string version = match.Groups["version"].Success ? match.Groups["version"].Value : "";
                                        if (string.IsNullOrEmpty(cert) == false)
                                        {
                                            innerData.Add("CCC证书编号", cert);
                                            innerData.Add("CCC证书版本号", version);
                                        }
                                        match = match.NextMatch();
                                    }
                                    break;

                                default:
                                    innerData.Add(parameterName, content);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return(data);
        }