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)); }
protected override CompletionDataList GetAttributeValueCompletions(IAttributedXObject attributedOb, XAttribute att) { var list = base.GetAttributeValueCompletions(attributedOb, att) ?? new CompletionDataList(); var ctx = document.Compilation; GetType(attributedOb, delegate(IType type, ICompilation dom) { foreach (IProperty prop in type.GetProperties()) { if (prop.Name != att.Name.FullName) { continue; } //boolean completion if (prop.ReturnType.Equals(ctx.FindType(typeof(bool)))) { list.Add("true", "md-literal"); list.Add("false", "md-literal"); return; } //color completion if (prop.ReturnType.ReflectionName == "System.Windows.Media.Color") { System.Drawing.ColorConverter conv = new System.Drawing.ColorConverter(); foreach (System.Drawing.Color c in conv.GetStandardValues(null)) { if (c.IsSystemColor) { continue; } string hexcol = string.Format("#{0:x2}{1:x2}{2:x2}", c.R, c.G, c.B); list.Add(c.Name, hexcol); } return; } //enum completion var retCls = prop.ReturnType; if (retCls != null && retCls.Kind == TypeKind.Enum) { foreach (var enumVal in retCls.GetFields()) { if (enumVal.IsPublic && enumVal.IsStatic) { list.Add(enumVal.Name, "md-literal", enumVal.Documentation); } } return; } } }); return(list.Count > 0? list : null); }
protected override CompletionDataList GetAttributeValueCompletions(IAttributedXObject attributedOb, XAttribute att) { var list = base.GetAttributeValueCompletions(attributedOb, att) ?? new CompletionDataList(); GetType(attributedOb, delegate(IType type, ProjectDom dom) { foreach (IProperty prop in GetAllProperties(dom, type)) { if (prop.Name != att.Name.FullName) { continue; } //boolean completion if (prop.ReturnType.FullName == "System.Boolean") { list.Add("true", "md-literal"); list.Add("false", "md-literal"); return; } //color completion if (prop.ReturnType.FullName == "System.Windows.Media.Color") { System.Drawing.ColorConverter conv = new System.Drawing.ColorConverter(); foreach (System.Drawing.Color c in conv.GetStandardValues(null)) { if (c.IsSystemColor) { continue; } string hexcol = string.Format("#{0:x2}{1:x2}{2:x2}", c.R, c.G, c.B); list.Add(c.Name, hexcol); } return; } //enum completion MonoDevelop.Projects.Dom.IType retCls = dom.GetType(prop.ReturnType); if (retCls != null && retCls.ClassType == MonoDevelop.Projects.Dom.ClassType.Enum) { foreach (MonoDevelop.Projects.Dom.IField enumVal in retCls.Fields) { if (enumVal.IsPublic && enumVal.IsStatic) { list.Add(enumVal.Name, "md-literal", enumVal.Documentation); } } return; } } }); return(list.Count > 0? list : null); }
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; } }
/// <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)); } }
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"); }
/// <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); } } }
public MainWindow() { InitializeComponent(); System.Drawing.KnownColor t = new System.Drawing.KnownColor(); foreach (System.Drawing.KnownColor kc in System.Enum.GetValues(t.GetType())) { System.Drawing.ColorConverter cc = new System.Drawing.ColorConverter(); System.Drawing.Color c = System.Drawing.Color.FromName(kc.ToString()); if (!c.IsSystemColor) { cbColors.Items.Add(c); } } cbColors.SelectedIndex = 0; Render(); }
/// <summary> /// Converts the given <paramref name="value"/> into a <see cref="Color"/> and returns it as <paramref name="color"/>. /// It supports <c>Color</c> and <see cref="string"/> (color names, #RRGGBB or #AARRGGBB) input values. /// </summary> /// <param name="value">Value.</param> /// <param name="color">Outputs color.</param> /// <returns><c>true if successful.</c></returns> public static bool ConvertColor(object value, out Color color) { if (value is Color) { color = (Color)value; return true; } if (value is System.Drawing.Color) { color = ((System.Drawing.Color)value).FromDrawingColor(); return true; } var convertFrom = new System.Drawing.ColorConverter().ConvertFrom(value); if (convertFrom == null) { color = new Color(); return false; } color = ((System.Drawing.Color)convertFrom).FromDrawingColor(); return true; }
/// <summary> /// Converts the given <paramref name="value"/> into a <see cref="Color"/> and returns it as <paramref name="color"/>. /// It supports <c>Color</c> and <see cref="string"/> (color names, #RRGGBB or #AARRGGBB) input values. /// </summary> /// <param name="value">Value.</param> /// <param name="color">Outputs color.</param> /// <returns><c>true if successful.</c></returns> public static bool ConvertColor(object value, out Color color) { if (value is Color) { color = (Color)value; return(true); } if (value is System.Drawing.Color) { color = ((System.Drawing.Color)value).FromDrawingColor(); return(true); } var convertFrom = new System.Drawing.ColorConverter().ConvertFrom(value); if (convertFrom == null) { color = new Color(); return(false); } color = ((System.Drawing.Color)convertFrom).FromDrawingColor(); return(true); }
void AddAspAttributeValueCompletionData(CompletionDataList list, XName tagName, XName attName, string id) { Debug.Assert(tagName.IsValid && tagName.HasPrefix); Debug.Assert(attName.IsValid && !attName.HasPrefix); INamedTypeSymbol controlClass = refman.GetControlType(tagName.Prefix, tagName.Name); if (controlClass == null) { return; } //find the codebehind class INamedTypeSymbol codeBehindClass; GetCodeBehind(out codeBehindClass); //if it's an event, suggest compatible methods if (codeBehindClass != null && attName.Name.StartsWith("On", StringComparison.Ordinal)) { string eventName = attName.Name.Substring(2); foreach (IEventSymbol ev in controlClass.GetAccessibleMembersInThisAndBaseTypes <IEventSymbol> (controlClass)) { if (ev.Name == eventName) { var domMethod = BindingService.MDDomToCodeDomMethod(ev); if (domMethod == null) { return; } foreach (IMethodSymbol meth in BindingService.GetCompatibleMethodsInClass(codeBehindClass, ev)) { list.Add(meth.Name, "md-method", GettextCatalog.GetString("A compatible method in the CodeBehind class")); } string suggestedIdentifier = ev.Name; if (id != null) { suggestedIdentifier = id + "_" + suggestedIdentifier; } else { suggestedIdentifier = tagName.Name + "_" + suggestedIdentifier; } domMethod.Name = BindingService.GenerateIdentifierUniqueInClass (codeBehindClass, suggestedIdentifier); domMethod.Attributes = (domMethod.Attributes & ~System.CodeDom.MemberAttributes.AccessMask) | System.CodeDom.MemberAttributes.Family; list.Add( new SuggestedHandlerCompletionData(project, domMethod, codeBehindClass, CodeBehind.GetNonDesignerClassLocation(codeBehindClass)) ); return; } } } //if it's a property and is an enum or bool, suggest valid values foreach (IPropertySymbol prop in GetAllMembers <IPropertySymbol> (controlClass)) { if (prop.Name != attName.Name) { continue; } //boolean completion if (prop.GetReturnType().Equals(refman.Compilation.GetTypeByMetadataName("System.Boolean"))) { AddBooleanCompletionData(list); return; } //color completion if (prop.GetReturnType().Equals(refman.Compilation.GetTypeByMetadataName("System.Drawing.Color"))) { var conv = new System.Drawing.ColorConverter(); foreach (System.Drawing.Color c in conv.GetStandardValues(null)) { if (c.IsSystemColor) { continue; } string hexcol = string.Format("#{0:x2}{1:x2}{2:x2}", c.R, c.G, c.B); list.Add(c.Name, hexcol); } return; } //enum completion var retCls = prop.GetReturnType() as INamedTypeSymbol; if (retCls != null && retCls.TypeKind == TypeKind.Enum) { foreach (var enumVal in GetAllMembers <IFieldSymbol> (retCls)) { if (enumVal.DeclaredAccessibility == Accessibility.Public && enumVal.IsStatic) { list.Add(enumVal.Name, "md-literal", Ambience.GetSummaryMarkup(enumVal)); } } return; } } }
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; } }
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")); }
private static System.Drawing.Color getColor(string rgb) { System.Drawing.ColorConverter cc = new System.Drawing.ColorConverter(); return((System.Drawing.Color)cc.ConvertFromString(rgb)); }
private object[] getDataPointsPie(Dictionary<string, int> data) { System.Drawing.ColorConverter cc = new System.Drawing.ColorConverter(); object[] points = new object[data.Count]; for (int x = 0; x < data.Count; x++) { //points[x] = new object() { x = data.Keys.ToArray()[x], y = data.Values.ToArray()[x] }; System.Drawing.Color color = System.Drawing.Color.Empty; switch (data.Keys.ToArray()[x]) { case "Grün" : color = System.Drawing.ColorTranslator.FromHtml("#89A54E"); break; case "Schwarz" : color = System.Drawing.ColorTranslator.FromHtml("#000"); break; case "Blau" : color = System.Drawing.ColorTranslator.FromHtml("#4572A7"); break; case "Rot" : color = System.Drawing.ColorTranslator.FromHtml("#AA4643"); break; case "Weiß" : color = System.Drawing.ColorTranslator.FromHtml("#FFF"); break; default : color = System.Drawing.Color.Empty; break; } if(!color.IsEmpty) { points[x] = new Point() { Name = data.Keys.ToArray()[x], Y = data.Values.ToArray()[x], Color = color }; } else { points[x] = new Point() { Name = data.Keys.ToArray()[x], Y = data.Values.ToArray()[x] }; } } return points; }
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; }
void AddAspAttributeValueCompletionData(CompletionDataList list, S.XName tagName, S.XName attName, string id) { Debug.Assert(tagName.IsValid && tagName.HasPrefix); Debug.Assert(attName.IsValid && !attName.HasPrefix); IType controlClass = HasDoc ? refman.GetControlType(tagName.Prefix, tagName.Name) : null; if (controlClass == null) { LoggingService.LogWarning("Could not obtain IType for {0}", tagName.FullName); var database = WebTypeContext.GetSystemWebDom(project); controlClass = ReflectionHelper.ParseReflectionName("System.Web.UI.WebControls.WebControl").Resolve(database); if (controlClass == null) { LoggingService.LogWarning("Could not obtain IType for System.Web.UI.WebControls.WebControl"); return; } } //find the codebehind class IType codeBehindClass; ICompilation projectDatabase; GetCodeBehind(out codeBehindClass, out projectDatabase); //if it's an event, suggest compatible methods if (codeBehindClass != null && attName.Name.StartsWith("On")) { string eventName = attName.Name.Substring(2); foreach (IEvent ev in controlClass.GetEvents()) { if (ev.Name == eventName) { var domMethod = BindingService.MDDomToCodeDomMethod(ev); if (domMethod == null) { return; } foreach (IMethod meth in BindingService.GetCompatibleMethodsInClass(codeBehindClass, ev)) { list.Add(meth.Name, "md-method", GettextCatalog.GetString("A compatible method in the CodeBehind class")); } string suggestedIdentifier = ev.Name; if (id != null) { suggestedIdentifier = id + "_" + suggestedIdentifier; } else { suggestedIdentifier = tagName.Name + "_" + suggestedIdentifier; } domMethod.Name = BindingService.GenerateIdentifierUniqueInClass (codeBehindClass, suggestedIdentifier); domMethod.Attributes = (domMethod.Attributes & ~System.CodeDom.MemberAttributes.AccessMask) | System.CodeDom.MemberAttributes.Family; list.Add( new SuggestedHandlerCompletionData(project, domMethod, codeBehindClass, MonoDevelop.DesignerSupport.CodeBehind.GetNonDesignerClass(codeBehindClass)) ); return; } } } if (projectDatabase == null) { projectDatabase = WebTypeContext.GetSystemWebDom(project); if (projectDatabase == null) { LoggingService.LogWarning("Could not obtain type database in AddAspAttributeCompletionData"); return; } } //if it's a property and is an enum or bool, suggest valid values foreach (IProperty prop in controlClass.GetProperties()) { if (prop.Name != attName.Name) { continue; } //boolean completion if (prop.ReturnType.Equals(projectDatabase.FindType(KnownTypeCode.Boolean))) { AddBooleanCompletionData(list); return; } //color completion if (prop.ReturnType.Equals(projectDatabase.FindType(typeof(System.Drawing.Color)))) { System.Drawing.ColorConverter conv = new System.Drawing.ColorConverter(); foreach (System.Drawing.Color c in conv.GetStandardValues(null)) { if (c.IsSystemColor) { continue; } string hexcol = string.Format("#{0:x2}{1:x2}{2:x2}", c.R, c.G, c.B); list.Add(c.Name, hexcol); } return; } //enum completion IType retCls = prop.ReturnType; if (retCls != null && retCls.Kind == TypeKind.Enum) { foreach (var enumVal in retCls.GetFields()) { if (enumVal.IsPublic && enumVal.IsStatic) { list.Add(enumVal.Name, "md-literal", AmbienceService.GetSummaryMarkup(enumVal)); } } return; } } }
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); }
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; } }
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))); }
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))); }
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; }
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); } }
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))); }
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); } }
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))); }
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); }