Exemplo n.º 1
0
        public static Color GetSfmlColor(string colorHex)
        {
            var conv = new System.Drawing.ColorConverter();

            System.Drawing.Color myColor = (System.Drawing.Color)conv.ConvertFromString(colorHex);
            return(new Color(myColor.R, myColor.G, myColor.B, myColor.A));
        }
Exemplo n.º 2
0
        private void bgColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs <System.Windows.Media.Color?> e)
        {
            string currentColor = bgColorPicker.SelectedColor.ToString();

            if (currentColor != null)
            {
                string c = currentColor;
                textboxBgBrushColor.Text = c;
                System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter();
                System.Drawing.Color          color      = (System.Drawing.Color)colConvert.ConvertFromString(c);
                GlobalSettings.cBgColor = color;
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// 将 string 转换为 Brush
 /// </summary>
 /// <param name="color"></param>
 /// <returns></returns>
 public static Brush ConvertBrushFromString(string color)
 {
     System.Drawing.ColorConverter colorConverter = new System.Drawing.ColorConverter();
     try
     {
         System.Drawing.Color brushColor = (System.Drawing.Color)colorConverter.ConvertFromString(color);
         return(new SolidColorBrush(Windows.UI.Color.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B)));
     }
     catch (Exception)
     {
         return(new SolidColorBrush(Windows.UI.Colors.Gray));
     }
 }
Exemplo n.º 4
0
        /// <summary>
        ///  This Function is used to set the ForeColor of error message label from configuration settings.
        /// </summary>
        /// <param name="ErrorLabel"></param>
        /// <returns></returns>
        /// <author>Rohit Verma</author>
        /// <CreatedDate>12/dec/2008 </CreatedDate>
        public static void SetErrorMegssageForeColor(Label ErrorLabel)
        {
            string _foreColor = System.Configuration.ConfigurationSettings.AppSettings["ErrorMessageForeColor"];

            if (_foreColor != null)
            {
                try
                {
                    System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter();
                    ErrorLabel.ForeColor = (System.Drawing.Color)colConvert.ConvertFromString(_foreColor);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        }
Exemplo n.º 5
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            // Преобразование из строки в цвет
            System.Drawing.Color redColor = (System.Drawing.Color)
                                            System.ComponentModel.TypeDescriptor.GetConverter(
                typeof(System.Drawing.Color)).ConvertFromString("Red");
            // Преобразование из цвета в строку
            string redString =
                System.ComponentModel.TypeDescriptor.GetConverter(
                    typeof(System.Drawing.Color)).ConvertToString(System.Drawing.Color.Red);

            label1.Text = redString;

            // Использование класса ColorConverter
            System.Drawing.ColorConverter ccv = new System.Drawing.ColorConverter();
            this.BackColor = (System.Drawing.Color)ccv.ConvertFromString("Red");
        }
Exemplo n.º 6
0
        protected void fillOverlayPopupRemove()
        {
            int sizeOfBox = 6;
            int currentBoxCount = 0;
            removeOverlayInteriorPanel.Controls.Clear();
            removeOverlayInteriorPanel.Controls.Add(new LiteralControl("<table class=\"boxPopupStyle2\" cellpadding=\"5\">\n"));
            if (overlayListAvailableToRemove.Count == 0)
            {
                removeOverlayInteriorPanel.Controls.Add(new LiteralControl("<tr><td class=\"tableTD\">No overlays currently exist for this connection.</td></tr>\n"));
            }
            else
            {
                foreach (Overlay over in overlayListAvailableToRemove)
                {
                    if (currentBoxCount == sizeOfBox)
                    {
                        removeOverlayInteriorPanel.Controls.Add(new LiteralControl("</tr>\n"));
                        currentBoxCount = 0;
                    }
                    if (currentBoxCount == 0)
                    {
                        removeOverlayInteriorPanel.Controls.Add(new LiteralControl("<tr>\n"));
                    }

                    removeOverlayInteriorPanel.Controls.Add(new LiteralControl("<td class=\"iconBox\">"));
                    ImageButton imgBtn = new ImageButton();
                    imgBtn.ID = "overlayLib_" + over.getId().ToString();
                    System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter();
                    imgBtn.BackColor = (System.Drawing.Color)colConvert.ConvertFromString("#" + over.getColor());
                    imgBtn.CssClass = "overlayBox";
                    imgBtn.BorderColor = (System.Drawing.Color)colConvert.ConvertFromString("#000000");
                    imgBtn.BorderWidth = Unit.Pixel(2);
                    imgBtn.Click += new ImageClickEventHandler(removeOverlayColorFromConn);
                    imgBtn.CommandArgument = over.getColor().ToString();
                    imgBtn.ImageUrl = "graphics/overlayBack.gif";

                    imgBtn.AlternateText = " Remove ";

                    removeOverlayInteriorPanel.Controls.Add(imgBtn);
                    removeOverlayInteriorPanel.Controls.Add(new LiteralControl("</td>"));

                    currentBoxCount += 1;
                }
            }
            removeOverlayInteriorPanel.Controls.Add(new LiteralControl("</table>\n"));
        }
    TryGetColor
    (
        String sKey,
        out System.Drawing.Color oColor
    )
    {
        Debug.Assert( !String.IsNullOrEmpty(sKey) );
        AssertValid();

        oColor = System.Drawing.Color.Black;

        String sColor;

        if ( m_oCollapsedGroupAttributes.TryGetValue(sKey, out sColor) )
        {
            System.Drawing.ColorConverter oColorConverter =
                new System.Drawing.ColorConverter();

            try
            {
                oColor = (System.Drawing.Color)
                    oColorConverter.ConvertFromString(sColor);

                return (true);
            }
            catch (Exception)
            {
                // (Format errors raise a System.Exception with an inner
                // exception of type FormatException.  Go figure.)
            }
        }

        return (false);
    }
Exemplo n.º 8
0
        internal static void LoadNoteCustomProperties(PNote note, DataRow r)
        {
            try
            {
                if (!PNData.IsDBNull(r["BACK_COLOR"]) || !PNData.IsDBNull(r["CAPTION_FONT_COLOR"]) || !PNData.IsDBNull(r["CAPTION_FONT"]))
                {
                    var drawingColorConverter = new System.Drawing.ColorConverter();
                    var wfc = new WPFFontConverter();
                    var mediaColorConverter = new ColorConverter();

                    note.Skinless = new PNSkinlessDetails();
                    if (!PNData.IsDBNull(r["BACK_COLOR"]))
                    {
                        try
                        {
                            var clr = mediaColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["BACK_COLOR"]);
                            if (clr != null)
                            {
                                note.Skinless.BackColor = (Color)clr;
                            }
                        }
                        catch (FormatException)
                        {
                            //possible FormatException after synchronization with old database
                            var clr = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["BACK_COLOR"]);
                            if (clr != null)
                            {
                                var drawingColor = (System.Drawing.Color)clr;
                                note.Skinless.BackColor = Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G,
                                    drawingColor.B);
                                var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET BACK_COLOR = '");
                                sb.Append(mediaColorConverter.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.BackColor));
                                sb.Append("' WHERE NOTE_ID = '");
                                sb.Append(r["NOTE_ID"]);
                                sb.Append("'");
                                PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                            }
                        }
                    }
                    if (!PNData.IsDBNull(r["CAPTION_FONT_COLOR"]))
                    {
                        try
                        {
                            var clr = mediaColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["CAPTION_FONT_COLOR"]);
                            if (clr != null)
                            {
                                note.Skinless.CaptionColor = (Color)clr;
                            }
                        }
                        catch (FormatException)
                        {
                            //possible FormatException after synchronization with old database
                            var clr = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["CAPTION_FONT_COLOR"]);
                            if (clr != null)
                            {
                                var drawingColor = (System.Drawing.Color)clr;
                                note.Skinless.CaptionColor = Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G,
                                    drawingColor.B);
                                var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT_COLOR = '");
                                sb.Append(mediaColorConverter.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionColor));
                                sb.Append("' WHERE NOTE_ID = '");
                                sb.Append(r["NOTE_ID"]);
                                sb.Append("'");
                                PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                            }
                        }
                    }
                    if (!PNData.IsDBNull(r["CAPTION_FONT"]))
                    {
                        var fontString = (string)r["CAPTION_FONT"];
                        //try
                        //{
                        var fonts = new InstalledFontCollection();
                        var arr = fontString.Split(',');
                        if (fontString.Any(ch => ch == '^'))
                        {
                            //old format font string
                            var lfc = new PNStaticFonts.LogFontConverter();
                            var lf = lfc.ConvertFromString((string)r["CAPTION_FONT"]);
                            note.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                            var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                            sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionFont));
                            sb.Append("' WHERE NOTE_ID = '");
                            sb.Append(r["NOTE_ID"]);
                            sb.Append("'");
                            PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        }
                        else if (fonts.Families.Any(ff => ff.Name == arr[0]))
                        {
                            note.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString((string)r["CAPTION_FONT"]);
                        }
                        else
                        {
                            //possible note existing font name
                            arr[0] = PNStrings.DEF_CAPTION_FONT;
                            fontString = string.Join(",", arr);
                            note.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                            var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                            sb.Append(fontString);
                            sb.Append("' WHERE NOTE_ID = '");
                            sb.Append(r["NOTE_ID"]);
                            sb.Append("'");
                            PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        }
                        //}
                        //catch (IndexOutOfRangeException)
                        //{
                        //    //possible IndexOutOfRangeException after synchronization with old database
                        //    var lfc = new PNStaticFonts.LogFontConverter();
                        //    var lf = lfc.ConvertFromString((string)r["CAPTION_FONT"]);
                        //    note.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                        //    var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                        //    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionFont));
                        //    sb.Append("' WHERE NOTE_ID = '");
                        //    sb.Append(r["NOTE_ID"]);
                        //    sb.Append("'");
                        //    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        //}
                    }
                }
                if (!PNData.IsDBNull(r["SKIN_NAME"]))
                {
                    note.Skin = new PNSkinDetails { SkinName = (string)r["SKIN_NAME"] };
                    var path = Path.Combine(PNPaths.Instance.SkinsDir, note.Skin.SkinName);
                    path += ".pnskn";
                    if (File.Exists(path))
                    {
                        PNSkinsOperations.LoadSkin(path, note.Skin);
                    }
                }
                if (!PNData.IsDBNull(r["CUSTOM_OPACITY"]))
                {
                    note.CustomOpacity = (bool)r["CUSTOM_OPACITY"];
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Exemplo n.º 9
0
        public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReportType)
        {
            Microsoft.Office.Interop.Excel.Application excel;
            Microsoft.Office.Interop.Excel.Workbook    excelworkBook;
            Microsoft.Office.Interop.Excel.Worksheet   excelSheet;
            Microsoft.Office.Interop.Excel.Range       excelCellrange;
            try
            {
                excel                  = new Microsoft.Office.Interop.Excel.Application();                    // Start Excel and get Application object.
                excel.Visible          = false;                                                               // for making Excel visible
                excel.DisplayAlerts    = false;
                excelworkBook          = excel.Workbooks.Add(Type.Missing);                                   // Creation a new Workbook
                excelSheet             = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet; // Workk sheet
                excelSheet.Name        = worksheetName;
                excelSheet.Cells[1, 1] = ReportType;

                System.Drawing.ColorConverter cc = new System.Drawing.ColorConverter();

                if (dataTable.Columns.Count == 14)
                {
                    excelSheet.get_Range("A1", "N1").Merge(Type.Missing);
                    excelSheet.get_Range("A1", "N1").Font.Size           = 20;
                    excelSheet.get_Range("A1", "N1").Font.Bold           = true;
                    excelSheet.get_Range("A1", "N1").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelSheet.get_Range("A1", "N1").VerticalAlignment   = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelCellrange = excelSheet.get_Range("A1", "N1");

                    excelCellrange.RowHeight = 25;
                    int rowcount = 2;  // loop through each row and add values to our sheet
                    foreach (DataRow datarow in dataTable.Rows)
                    {
                        rowcount += 1;
                        for (int i = 1; i <= dataTable.Columns.Count; i++)
                        {
                            if (rowcount == 3) // on the first iteration we add the column headers
                            {
                                excelSheet.Cells[2, i]      = dataTable.Columns[i - 1].ColumnName;
                                excelCellrange.RowHeight    = 25;
                                excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
                            }
                            excelCellrange = excelSheet.Range[excelSheet.Cells[2, i], excelSheet.Cells[2, dataTable.Columns.Count]];
                            FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
                            excelSheet.Cells[1, i].Interior.Color    = System.Drawing.ColorTranslator.ToOle((System.Drawing.Color)cc.ConvertFromString("#F0F8FF")); // First Cell
                            excelSheet.Cells[rowcount, i]            = datarow[i - 1].ToString();
                            excelCellrange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                            if (rowcount > 3)  //for alternate rows
                            {
                                if (i == dataTable.Columns.Count)
                                {
                                    if (rowcount % 2 == 0)
                                    {
                                        excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
                                        FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
                                    }
                                }
                            }
                        }
                    }
                    excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];  // now we resize the columns
                    excelCellrange.EntireColumn.AutoFit();
                    Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
                    border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    border.Weight    = 2d;
                    //Namrata: 09/12/2017
                    excelSheet.EnableAutoFilter = true;                                                              //Enable Auto-filter.
                    Microsoft.Office.Interop.Excel.Range range = excelSheet.get_Range("A1", "N1");                   //Create the range.
                    range.AutoFilter("1", "<>", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, "", true); //Auto-filter the range.
                    excelSheet.get_Range("A1", "N1").EntireColumn.AutoFit();                                         //Auto-fit the second column.
                }
                if (dataTable.Columns.Count == 21)
                {
                    excelSheet.get_Range("A1", "U1").Merge(Type.Missing);
                    excelSheet.get_Range("A1", "U1").Font.Size           = 20;
                    excelSheet.get_Range("A1", "U1").Font.Bold           = true;
                    excelSheet.get_Range("A1", "U1").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelSheet.get_Range("A1", "U1").VerticalAlignment   = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelCellrange           = excelSheet.get_Range("A1", "U1");
                    excelCellrange.RowHeight = 25;
                    int rowcount = 2;  // loop through each row and add values to our sheet
                    foreach (DataRow datarow in dataTable.Rows)
                    {
                        rowcount += 1;
                        for (int i = 1; i <= dataTable.Columns.Count; i++)
                        {
                            if (rowcount == 3) // on the first iteration we add the column headers
                            {
                                excelSheet.Cells[2, i]      = dataTable.Columns[i - 1].ColumnName;
                                excelCellrange.RowHeight    = 25;
                                excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
                            }
                            excelCellrange = excelSheet.Range[excelSheet.Cells[2, i], excelSheet.Cells[2, dataTable.Columns.Count]];
                            FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
                            excelSheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle((System.Drawing.Color)cc.ConvertFromString("#F0F8FF")); // First Cell
                            excelSheet.Cells[rowcount, i]         = datarow[i - 1].ToString();

                            if (rowcount > 3)  //for alternate rows
                            {
                                if (i == dataTable.Columns.Count)
                                {
                                    if (rowcount % 2 == 0)
                                    {
                                        excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
                                        FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
                                    }
                                }
                            }
                        }
                    }
                    excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];  // now we resize the columns
                    excelCellrange.EntireColumn.AutoFit();
                    Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
                    border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    border.Weight    = 2d;
                    excelCellrange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                    //Namrata: 09/12/2017
                    excelSheet.EnableAutoFilter = true;                                                              //Enable Auto-filter.
                    Microsoft.Office.Interop.Excel.Range range = excelSheet.get_Range("A1", "U1");                   //Create the range.
                    range.AutoFilter("1", "<>", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, "", true); //Auto-filter the range.
                    excelSheet.get_Range("A1", "U1").EntireColumn.AutoFit();                                         //Auto-fit the second column.
                }
                if (dataTable.Columns.Count == 13)
                {
                    excelSheet.get_Range("A1", "M1").Merge(Type.Missing);
                    excelSheet.get_Range("A1", "M1").Font.Size           = 20;
                    excelSheet.get_Range("A1", "M1").Font.Bold           = true;
                    excelSheet.get_Range("A1", "M1").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelSheet.get_Range("A1", "M1").VerticalAlignment   = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelCellrange           = excelSheet.get_Range("A1", "M1");
                    excelCellrange.RowHeight = 25;
                    int rowcount = 2;  // loop through each row and add values to our sheet
                    foreach (DataRow datarow in dataTable.Rows)
                    {
                        rowcount += 1;
                        for (int i = 1; i <= dataTable.Columns.Count; i++)
                        {
                            if (rowcount == 3) // on the first iteration we add the column headers
                            {
                                excelSheet.Cells[2, i]      = dataTable.Columns[i - 1].ColumnName;
                                excelCellrange.RowHeight    = 25;
                                excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
                            }
                            excelCellrange = excelSheet.Range[excelSheet.Cells[2, i], excelSheet.Cells[2, dataTable.Columns.Count]];
                            FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
                            excelSheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle((System.Drawing.Color)cc.ConvertFromString("#F0F8FF")); // First Cell
                            excelSheet.Cells[rowcount, i]         = datarow[i - 1].ToString();
                            if (rowcount > 3)                                                                                                                    //for alternate rows
                            {
                                if (i == dataTable.Columns.Count)
                                {
                                    if (rowcount % 2 == 0)
                                    {
                                        excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
                                        FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
                                    }
                                }
                            }
                        }
                    }
                    excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];  // now we resize the columns
                    excelCellrange.EntireColumn.AutoFit();
                    Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
                    border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    border.Weight    = 2d;
                    excelCellrange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                    //Namrata: 09/12/2017
                    excelSheet.EnableAutoFilter = true;                                                              //Enable Auto-filter.
                    Microsoft.Office.Interop.Excel.Range range = excelSheet.get_Range("A1", "M1");                   //Create the range.
                    range.AutoFilter("1", "<>", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, "", true); //Auto-filter the range.
                    excelSheet.get_Range("A1", "M1").EntireColumn.AutoFit();                                         //Auto-fit the second column.
                }
                excelworkBook.SaveAs(saveAsLocation);                                                                //now save the workbook and exit Excel
                MessageBox.Show("File Exported Successfully", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                excelworkBook.Close();
                excel.Quit();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
            finally
            {
                excelSheet     = null;
                excelCellrange = null;
                excelworkBook  = null;
            }
        }
Exemplo n.º 10
0
        public void TestConvertTo_Converter_InvalidConversions()
        {
            // Primitive types.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, "true")
                .ConvertTo(v => Int32.Parse(v, CultureInfo.InvariantCulture)));
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, "12345")
                .ConvertTo(Boolean.Parse));

            // Enumerations.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, "Moscow")
                .ConvertTo(v => (ActivationMode)Enum.Parse(typeof(ActivationMode), v, false)));
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, "Singleton")
                .ConvertTo(v => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), v, false)));

            // Value types.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, UnitTestHelper.SAMPLE_STRING)
                .ConvertTo(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));
            var colorConverter = new ColorConverter();
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, "Box")
                .ConvertTo(v =>
                {
                    var convertFromString = colorConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v);
                    return (convertFromString != null ? (Color)convertFromString : new Color());
                }));

            // Classes.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME, UnitTestHelper.SAMPLE_STRING)
                .ConvertTo(v => (Account)new AccountTypeConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v)));
        }
Exemplo n.º 11
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var str = value as string;
            if (str == null) return base.ConvertFrom(context, culture, value);
            var skl = new PNSkinlessDetails();
            var values = str.Split(DEL_INNER);
            if (values.Length != 3) return skl;
            var cr = new ColorConverter();
            var wpfFontConverter = new WPFFontConverter();
            var lfc = new LogFontConverter();
            object convertFromString;

            try
            {
                convertFromString = cr.ConvertFromString(null, PNStatic.CultureInvariant, values[0]);
                if (convertFromString != null)
                    skl.BackColor = (Color)convertFromString;
            }
            catch (FormatException)
            {
                var drawingColorConverter = new System.Drawing.ColorConverter();
                convertFromString = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                    values[0]);
                if (convertFromString != null)
                {
                    var clr = (System.Drawing.Color)convertFromString;
                    skl.BackColor = Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
                }
            }

            try
            {
                convertFromString = cr.ConvertFromString(null, PNStatic.CultureInvariant, values[1]);
                if (convertFromString != null)
                    skl.CaptionColor = (Color)convertFromString;
            }
            catch (FormatException)
            {
                var drawingColorConverter = new System.Drawing.ColorConverter();
                convertFromString = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                    values[1]);
                if (convertFromString != null)
                {
                    var clr = (System.Drawing.Color)convertFromString;
                    skl.CaptionColor = Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
                }
            }

            if (values[2].Any(c => c == '^'))
            {
                var logFont = lfc.ConvertFromString(values[2]);
                skl.CaptionFont = PNStatic.FromLogFont(logFont);
            }
            else
            {
                skl.CaptionFont = (PNFont) wpfFontConverter.ConvertFromString(values[2]);
            }
            return skl;
        }
Exemplo n.º 12
0
 private static System.Drawing.Color getColor(string rgb)
 {
     System.Drawing.ColorConverter cc = new System.Drawing.ColorConverter();
     return((System.Drawing.Color)cc.ConvertFromString(rgb));
 }
Exemplo n.º 13
0
        private Dictionary<int, int> importGroups()
        {
            try
            {
                var dict = new Dictionary<int, int>();
                var size = 1024;

                string iniPath = txtIniPath.Text.Trim();
                // get all notes ids
                string buffer = new string(' ', size);
                while (PNInterop.GetPrivateProfileString(null, null, null, buffer, size, iniPath) == size - 2)
                {
                    // loop until sufficient buffer size
                    size *= 2;
                    buffer = new string(' ', size);
                }
                // section names are delimeted by '\0' character with additional '\0' character at the end
                var names = buffer.ToString(CultureInfo.InvariantCulture).Split('\0');
                var groupSection = names.FirstOrDefault(s => s == "groups");
                if (groupSection == null) return null;
                // get ids of all groups under section
                size = 1024;
                buffer = new string(' ', size);
                while (PNInterop.GetPrivateProfileString(groupSection, null, null, buffer, size, iniPath) == size - 2)
                {
                    // loop until sufficient buffer size
                    size *= 2;
                    buffer = new string(' ', size);
                }
                names =
                    buffer.ToString(CultureInfo.InvariantCulture)
                          .Split('\0')
                          .Where(s => s.Trim().Length > 0 && s.Trim() != "0")
                          .ToArray();
                var png = new PNGROUP();
                var crc = new ColorConverter();
                var crd = new System.Drawing.ColorConverter();
                foreach (var id in names)
                {
                    int structSize = Marshal.SizeOf(typeof(PNGROUP));
                    int intSize = Marshal.SizeOf(typeof(int));
                    int boolSize = Marshal.SizeOf(typeof(bool));
                    int hkSize = Marshal.SizeOf(typeof(HK_TYPE));
                    png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                    if (png.Equals(default(PNGROUP)))
                    {
                        structSize -= (intSize * 3 + boolSize * 4 + 2 * 64);
                        png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                        if (png.Equals(default(PNGROUP)))
                        {
                            structSize -= 2 * 256;
                            png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                            if (png.Equals(default(PNGROUP)))
                            {
                                structSize -= hkSize * 2;
                                png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                                if (!png.Equals(default(PNGROUP)))
                                {
                                    png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                                    png.szSkin = "";
                                    png.szLock = "";
                                    png.hotKeyHide = png.hotKeyShow = default(HK_TYPE);
                                }
                            }
                            else
                            {
                                png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                                png.szSkin = "";
                                png.szLock = "";
                            }
                        }
                        else
                        {
                            png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                            png.szSkin = "";
                        }
                    }
                    if (png.Equals(default(PNGROUP))) return null;

                    var pg = new PNGroup();
                    var idNew = PNData.GetNewGroupID();
                    var idOld = png.id;
                    pg.Name = png.szName;
                    pg.ID = idNew;
                    pg.ParentID = -1;
                    if (png.customCRWindow)
                    {
                        var fromString = crc.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToColorString(png.crWindow));
                        if (fromString != null)
                            pg.Skinless.BackColor = (Color)fromString;
                    }
                    if (png.customCRCaption)
                    {
                        var fromString = crc.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToColorString(png.crCaption));
                        if (fromString != null)
                            pg.Skinless.CaptionColor = (Color)fromString;
                    }
                    if (png.customCRFont)
                    {
                        var fromString = crd.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToDrawinfColorString(png.crFont));
                        if (fromString != null)
                            pg.FontColor = (System.Drawing.Color)fromString;
                    }
                    if (png.customSkin)
                    {
                        pg.Skin.SkinName = png.szSkin;
                        var path = Path.Combine(PNPaths.Instance.SkinsDir, pg.Skin.SkinName + PNStrings.SKIN_EXTENSION);
                        if (File.Exists(path))
                        {
                            PNSkinsOperations.LoadSkin(path, pg.Skin);
                        }
                    }
                    pg.Image = TryFindResource("gr") as BitmapImage;
                    pg.IsDefaultImage = true;
                    var parent = PNStatic.Groups.GetGroupByID((int)SpecialGroups.AllGroups);
                    if (parent == null) continue;
                    parent.Subgroups.Add(pg);
                    PNData.InsertNewGroup(pg);
                    dict.Add(idOld, idNew);
                }
                return dict;
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
                return null;
            }
        }
Exemplo n.º 14
0
        public void TestConvertTo_Converter()
        {
            // Primitive types.
            Assert.AreEqual(123, new XElement(ELEMENT_NAME, " 123 \n\t")
                .ConvertTo(v => Int32.Parse(v, CultureInfo.InvariantCulture)));
            Assert.AreEqual(-3.1415926, new XElement(ELEMENT_NAME, "-3.1415926 ")
                .ConvertTo(v => Double.Parse(v, CultureInfo.InvariantCulture)));
            Assert.IsTrue(new XElement(ELEMENT_NAME, "TRue").ConvertTo(Boolean.Parse));

            // Enumerations.
            Assert.AreEqual(ActivationMode.SingleCall, new XElement(ELEMENT_NAME, "singlecall")
                .ConvertTo(v => (ActivationMode)Enum.Parse(typeof(ActivationMode), v, true)));
            Assert.AreEqual(DayOfWeek.Saturday, new XElement(ELEMENT_NAME, "saturDay")
                .ConvertTo(v => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), v, true)));

            // Value types.
            Assert.AreEqual(DATE_SAMPLE, new XElement(ELEMENT_NAME, DATE_STRING_SAMPLE)
                .ConvertTo(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));
            Assert.AreEqual(DATE_SAMPLE, new XElement(ELEMENT_NAME, DATE_SAMPLE)
                .ConvertTo(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));

            var colorConverter = new ColorConverter();
            Assert.AreEqual(Color.Red, new XElement(ELEMENT_NAME, "red")
                .ConvertTo(v =>
                {
                    var convertFromString = colorConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v);
                    return (convertFromString != null ? (Color)convertFromString : new Color());
                }));
            var countryConverter = new CountryTypeConverter();
            Assert.AreEqual(Country.UnitedStates, new XElement(ELEMENT_NAME, "us")
                .ConvertTo(v =>
                {
                    var fromString = countryConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v);
                    return (fromString != null ? (Country)fromString : new Country());
                }));

            // Classes.
            var account = new XElement(ELEMENT_NAME, UnitTestHelper.ACCOUNT_NUMBER)
                .ConvertTo(v => (Account)new AccountTypeConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v));
            Assert.IsNotNull(account);
            Assert.AreEqual(UnitTestHelper.ACCOUNT_NUMBER, account.Number);

            Assert.AreEqual(UnitTestHelper.SAMPLE_STRING, new XElement(ELEMENT_NAME, UnitTestHelper.SAMPLE_STRING).ConvertTo(v => v));
            Assert.AreEqual("123", new XElement(ELEMENT_NAME, 123).ConvertTo(v => v));

            var brush = new XElement(ELEMENT_NAME, "azure")
                .ConvertTo(v => (SolidColorBrush)new BrushConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v));
            Assert.IsNotNull(brush);
            Assert.IsInstanceOf(typeof(SolidColorBrush), brush);
            Assert.AreEqual(Colors.Azure, brush.Color);

            Assert.AreEqual(new CultureInfo("en-US"), new XElement(ELEMENT_NAME, "en-US")
                .ConvertTo(v => (CultureInfo)new CultureInfoConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v)));
        }
Exemplo n.º 15
0
        private void fillGroup(PNGroup gr, DataRow r)
        {
            try
            {
                var c = new ColorConverter();
                var wfc = new WPFFontConverter();
                var lfc = new LogFontConverter();
                var dcc = new System.Drawing.ColorConverter();

                gr.ID = (int)r["GROUP_ID"];
                gr.ParentID = (int)r["PARENT_ID"];
                gr.Name = (string)r["GROUP_NAME"];
                gr.PasswordString = (string)r["PASSWORD_STRING"];
                gr.IsDefaultImage = (bool)r["IS_DEFAULT_IMAGE"];
                if (!PNData.IsDBNull(r["ICON"]))
                {
                    var base64String = (string)r["ICON"];
                    if (!base64String.EndsWith(PNStrings.PNG_EXT))
                    {
                        try
                        {
                            var buffer = Convert.FromBase64String(base64String);
                            if (gr.ID.In((int)SpecialGroups.AllGroups, 0, (int)SpecialGroups.Diary,
                                (int)SpecialGroups.Backup, (int)SpecialGroups.SearchResults,
                                (int)SpecialGroups.Favorites, (int)SpecialGroups.Incoming, (int)SpecialGroups.Docking,
                                (int)SpecialGroups.RecycleBin) || base64String.StartsWith("resource."))
                            {
                                //possible image data stored as string when data directory just copied into new edition folder
                                upgradeGroupIcon(gr, gr.ID, (string)r["ICON"]);
                            }
                            else
                            {
                                using (var ms = new MemoryStream(buffer))
                                {
                                    ms.Position = 0;
                                    gr.Image = new BitmapImage();
                                    gr.Image.BeginInit();
                                    gr.Image.CacheOption = BitmapCacheOption.OnLoad;
                                    gr.Image.StreamSource = ms;
                                    gr.Image.EndInit();
                                }
                                if (gr.IsDefaultImage)
                                {
                                    gr.IsDefaultImage = false;
                                    var sb = new StringBuilder("UPDATE GROUPS SET IS_DEFAULT_IMAGE = 0");
                                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                                }
                            }
                        }
                        catch (FormatException)
                        {
                            //possible exception when data directory just copied into new edition folder
                            upgradeGroupIcon(gr, gr.ID, (string)r["ICON"]);
                        }
                    }
                    else
                    {
                        gr.Image = TryFindResource(Path.GetFileNameWithoutExtension(base64String)) as BitmapImage;// new BitmapImage(new Uri(base64String));
                    }
                }

                try
                {
                    var clr = c.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["BACK_COLOR"]);
                    if (clr != null)
                        gr.Skinless.BackColor = (Color)clr;
                }
                catch (FormatException)
                {
                    //possible FormatException after synchronization with old database
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["BACK_COLOR"]);
                    if (clr != null)
                    {
                        var drawingColor = (System.Drawing.Color)clr;
                        gr.Skinless.BackColor = Color.FromArgb(drawingColor.A, drawingColor.R,
                            drawingColor.G, drawingColor.B);
                        var sb = new StringBuilder("UPDATE GROUPS SET BACK_COLOR = '");
                        sb.Append(c.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.BackColor));
                        sb.Append("' WHERE GROUP_ID = ");
                        sb.Append(gr.ID);
                        PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                    }
                }

                try
                {
                    var clr = c.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CAPTION_FONT_COLOR"]);
                    if (clr != null)
                        gr.Skinless.CaptionColor = (Color)clr;
                }
                catch (FormatException)
                {
                    //possible FormatException after synchronization with old database
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CAPTION_FONT_COLOR"]);
                    if (clr != null)
                    {
                        var drawingColor = (System.Drawing.Color)clr;
                        gr.Skinless.CaptionColor = Color.FromArgb(drawingColor.A, drawingColor.R,
                            drawingColor.G, drawingColor.B);
                        var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT_COLOR = '");
                        sb.Append(c.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionColor));
                        sb.Append("' WHERE GROUP_ID = ");
                        sb.Append(gr.ID);
                        PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                    }
                }

                var fontString = (string)r["CAPTION_FONT"];
                //try
                //{
                var fonts = new InstalledFontCollection();
                var arr = fontString.Split(',');
                if (fontString.Any(ch => ch == '^'))
                {
                    //old format font string
                    var lf = lfc.ConvertFromString(fontString);
                    gr.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionFont));
                    sb.Append("' WHERE GROUP_ID = ");
                    sb.Append(gr.ID);
                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                }
                else if (fonts.Families.Any(ff => ff.Name == arr[0]))
                {
                    //normal font string
                    gr.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                }
                else
                {
                    //possible not existing font name
                    arr[0] = PNStrings.DEF_CAPTION_FONT;
                    fontString = string.Join(",", arr);
                    gr.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                    sb.Append(fontString);
                    sb.Append("' WHERE GROUP_ID = ");
                    sb.Append(gr.ID);
                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                }
                //}
                //catch (IndexOutOfRangeException)
                //{
                //    //possible IndexOutOfRangeException after synchronization with old database
                //    var lf = lfc.ConvertFromString(fontString);
                //    gr.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                //    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                //    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionFont));
                //    sb.Append("' WHERE GROUP_ID = ");
                //    sb.Append(gr.ID);
                //    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                //}

                var skinName = (string)r["SKIN_NAME"];
                if (skinName != PNSkinDetails.NO_SKIN)
                {
                    gr.Skin.SkinName = skinName;
                    //load skin
                    var path = Path.Combine(PNPaths.Instance.SkinsDir, gr.Skin.SkinName) + ".pnskn";
                    if (File.Exists(path))
                    {
                        PNSkinsOperations.LoadSkin(path, gr.Skin);
                    }
                }
                if (!PNData.IsDBNull(r["FONT"]))
                {
                    gr.Font = lfc.ConvertFromString((string)r["FONT"]);
                }
                if (!PNData.IsDBNull(r["FONT_COLOR"]))
                {
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["FONT_COLOR"]);
                    if (clr != null)
                        gr.FontColor = (System.Drawing.Color)clr;
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Exemplo n.º 16
0
        public void TestConvertTo_Converter_EmptySource()
        {
            // Primitive types.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME)
                .ConvertTo(v => Int32.Parse(v, CultureInfo.InvariantCulture)));
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo<int?>(v => Int32.Parse(v, CultureInfo.InvariantCulture)));
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME)
                .ConvertTo(Boolean.Parse));
            Assert.IsNull(new XElement(ELEMENT_NAME).ConvertTo<bool?>(v => Boolean.Parse(v)));

            // Enumerations.
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME)
                .ConvertTo(v => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), v, true)));
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo<DayOfWeek?>(v => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), v, true)));

            // Value types.
            var colorConverter = new ColorConverter();
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME)
                .ConvertTo(v =>
                {
                    var convertFromString = colorConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v);
                    return (convertFromString != null ? (Color)convertFromString : new Color());
                }));
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo(v => (Color?)new ColorConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v)));
            Assert.Throws<InvalidOperationException>(() => new XElement(ELEMENT_NAME)
                .ConvertTo(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo<DateTime?>(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));

            // Classes.
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo(v => (Account)new AccountTypeConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v)));
            Assert.IsNull(new XElement(ELEMENT_NAME)
                .ConvertTo(v => (SolidColorBrush)new BrushConverter().ConvertFromString(null, CultureInfo.InvariantCulture, v)));
        }
Exemplo n.º 17
0
        public async Task ChangeRole(params string[] args)
        {
            if (args.Length < 2)
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "Insufficient Parameters",
                    Description = $"The way to use the command is `{await SqliteClass.PrefixGetter(Context.Guild.Id)}color <@role> <color>`",
                    Color       = Color.Red
                }.WithCurrentTimestamp());

                return;
            }
            var role = GetRole(args[0]);

            if (role == null)
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "That role is invalid",
                    Description = $"I couldn't parse `{args[0]}` as a role!",
                    Color       = Color.Red
                }.WithCurrentTimestamp());

                return;
            }
            if (!(Context.User as SocketGuildUser).Roles.Any(rl => rl.Position > role.Position) && Context.Guild.OwnerId != Context.User.Id && Context.User.Id != 701029647760097361 && Context.User.Id != 615873008959225856)
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "Oops!",
                    Description = "You're below the role you want to edit!",
                    Color       = Color.Red
                }.WithCurrentTimestamp());

                return;
            }
            if (args[1].ToLower() == "none" || args[1].ToLower() == "invisible")
            {
                await role.ModifyAsync(x => x.Color = new Color());
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "Done!!",
                    Description = $"The role {role.Name}'s color is removed!",
                    Color       = Blurple
                }.WithCurrentTimestamp());

                return;
            }
            System.Drawing.ColorConverter c   = new System.Drawing.ColorConverter();
            System.Drawing.Color          col = new System.Drawing.Color();
            bool hasC   = false;
            var  hArgs1 = args[1][0] != '#' ? $"#{args[1]}" : args[1];

            if (Regex.IsMatch(hArgs1, "^(#[0-9A-Fa-f]{3})$|^(#[0-9A-Fa-f]{6})$"))
            {
                col  = (System.Drawing.Color)c.ConvertFromString(hArgs1);
                hasC = true;
            }
            else
            {
                System.ComponentModel.TypeConverter.StandardValuesCollection svc = (System.Drawing.ColorConverter.StandardValuesCollection)c.GetStandardValues();
                foreach (System.Drawing.Color o in svc)
                {
                    if (o.Name.Equals(args[1], StringComparison.OrdinalIgnoreCase))
                    {
                        col  = (System.Drawing.Color)c.ConvertFromString(args[1]);
                        hasC = true;
                    }
                }
            }
            if (hasC == false)
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "What color??",
                    Description = $"Couldn't parse `{args[1]}` as a color!",
                    Color       = Color.Red
                }.WithCurrentTimestamp());

                return;
            }
            await role.ModifyAsync(x => x.Color = new Color(col.R, col.G, col.B));

            await ReplyAsync("", false, new EmbedBuilder
            {
                Title       = "Done!!",
                Description = $"The role {role.Name} is now set to the color of this embed!",
                Color       = new Color(col.R, col.G, col.B) == new Color(255, 255, 255) ? new Color(254, 254, 254) : new Color(col.R, col.G, col.B)
            }.WithCurrentTimestamp());

            return;
        }
Exemplo n.º 18
0
        public void TestConvertTo_Converter_Nullable()
        {
            // Primitive types.
            Assert.AreEqual(123, new XElement(ELEMENT_NAME, " 123 \n\t")
                .ConvertTo<int?>(v => Int32.Parse(v, CultureInfo.InvariantCulture)));
            Assert.AreEqual(-3.1415926, new XElement(ELEMENT_NAME, "-3.1415926 ")
                .ConvertTo<double?>(v => Double.Parse(v, CultureInfo.InvariantCulture)));
            Assert.AreEqual(true, new XElement(ELEMENT_NAME, "TRue")
                .ConvertTo<bool?>(v => Boolean.Parse(v)));

            // Enumerations.
            Assert.AreEqual(ActivationMode.SingleCall, new XElement(ELEMENT_NAME, "singlecall")
                .ConvertTo<ActivationMode?>(v => (ActivationMode)Enum.Parse(typeof(ActivationMode), v, true)));
            Assert.AreEqual(DayOfWeek.Saturday, new XElement(ELEMENT_NAME, "saturDay")
                .ConvertTo<DayOfWeek?>(v => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), v, true)));

            // Value types.
            Assert.AreEqual(DATE_SAMPLE, new XElement(ELEMENT_NAME, DATE_STRING_SAMPLE)
                .ConvertTo<DateTime?>(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));
            Assert.AreEqual(DATE_SAMPLE, new XElement(ELEMENT_NAME, DATE_SAMPLE)
                .ConvertTo<DateTime?>(v => DateTime.Parse(v, CultureInfo.InvariantCulture)));

            var colorConverter = new ColorConverter();
            Assert.AreEqual(Color.Red, new XElement(ELEMENT_NAME, "red")
                .ConvertTo(v => (Color?)colorConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v)));
            var countryConverter = new CountryTypeConverter();
            Assert.AreEqual(Country.UnitedStates, new XElement(ELEMENT_NAME, "us")
                .ConvertTo(v => (Country?)countryConverter.ConvertFromString(null, CultureInfo.InvariantCulture, v)));
        }
Exemplo n.º 19
0
        public bool MakeMap(LayerEnum couche)
        {
            try
            {
                var dumpMaps = new List <MapEditor>(m_maps);
                var current  = dumpMaps.FirstOrDefault();


                if (current != null)
                {
                    var t = new System.Drawing.ColorConverter();
                    System.Drawing.Color color = (System.Drawing.Color)t.ConvertFromString(current.BackgroundColor);

                    this.Window.Clear(new SFML.Graphics.Color((byte)color.R, (byte)color.G, (byte)color.B, (byte)current.BackgroundAlpha));
                }
                foreach (var map in m_maps)
                {
                    if (map.Backgrounds != null)
                    {
                        foreach (BackgroundEditor bg in map.Backgrounds)
                        {
                            bg.Sprite.Position = new Vector2f(map.MapCells[0].Center.X + bg.Fixture.OffsetY, map.MapCells[0].Center.Y + bg.Fixture.OffsetY);
                            this.Window.Draw(bg.Sprite);
                        }
                    }
                }

                for (int i = 0; i < 4; i++)
                {
                    var layers = dumpMaps.Select(x => x.Layer.FirstOrDefault(y => y.Type == (LayerEnum)i)).ToArray();
                    Dictionary <int, List <Test> >       content = new Dictionary <int, List <Test> >();
                    Dictionary <MapEditor, LayerContent> list    = new Dictionary <MapEditor, LayerContent>();

                    foreach (var map in dumpMaps)
                    {
                        if (!map.Layer.Any(x => x.Type == (LayerEnum)i))
                        {
                            continue;
                        }

                        list.Add(map, map.Layer.First(x => x.Type == (LayerEnum)i));


                        foreach (var layer in map.Layer.First(x => x.Type == (LayerEnum)i).Cells)
                        {
                            var cell = map.MapCells[layer.CELLID];
                            if (content.ContainsKey(cell.Id))
                            {
                                content[cell.Id].AddRange(layer.Elements);
                            }
                            else
                            {
                                content.Add(cell.Id, layer.Elements);
                            }
                        }


                        foreach (var value in content.OrderBy(x => x.Key))
                        {
                            foreach (var element in value.Value)
                            {
                                if (element.Sprite == null)
                                {
                                    continue;
                                }

                                element.Sprite.Position = element.GetPosToDrawTexture();
                                this.Window.Draw(element.Sprite);

                                if (i == (int)couche)
                                {
                                    SFML.Graphics.CircleShape cercle = new CircleShape();
                                    element.Manager.MapCells[element.CellID].Cercle.FillColor = Color.Red;
                                    element.Manager.MapCells[element.CellID].Cercle.Radius    = 2;
                                    element.Manager.MapCells[element.CellID].Cercle.Position  = element.Manager.MapCells[element.CellID].Center;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }