/// <summary> /// 使用一个XML文件的名字生成实例 /// </summary> /// <param name="filePathName"></param> /// <param name="type"></param> public CustomConfigBase(string filePathName, ConfigType type) { this.filePathName = filePathName; this.m_ConfigType = type; this.OpenConfigFile(type); }
public ColorPropertyData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.variableName = new StringData(configType, prefix + name, "VariableName", "Color variable name", "", "waferBackground"); AddChild(this.variableName); this.propertyName = new StringData(configType, prefix + name, "Name", "Color name", "", "Wafer background"); AddChild(this.propertyName); this.fontName = new StringData(configType, prefix + name, "FontName", "Font name", "", "Microsoft Sans Serif"); AddChild(this.fontName); this.fontSize = new IntegerData(configType, prefix + name, "FontSize", "Font size", "", 8); AddChild(this.fontSize); this.fontBold = new BooleanData(configType, prefix + name, "FontBold", "Font bold", "", false); AddChild(this.fontBold); this.foreground = new StringData(configType, prefix + name, "Foreground", "Foreground color", "", "White"); AddChild(this.foreground); this.background = new StringData(configType, prefix + name, "Background", "Background color", "", "White"); AddChild(this.background); NewFont(); NewForeColor(); NewBackColor(); }
/// <summary> /// 使用一个可执行文件(.exe或.dll)生成实例 /// </summary> /// <param name="assembly"></param> public CustomConfigBase(System.Reflection.Assembly assembly) { this.filePathName = assembly.Location + ".config"; this.m_ConfigType = ConfigType.Exe; this.OpenConfigFile(this.m_ConfigType); }
public CultureData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.cultureName = new StringData(configType, prefix + name, "Name", "Culture name", "", "English"); AddChild(this.cultureName); this.cultureCode = new StringData(configType, prefix + name, "Name", "Culture code", "", "en-US"); AddChild(this.cultureCode); }
public LaserscribeFormatData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.enabled = new BooleanData(configType, prefix + name, "Enabled", "Enabled", "", false); AddChild(this.enabled); this.mask = new StringData(configType, prefix + name, "Mask", "Mask", "", ""); AddChild(this.mask); }
/// <summary> /// Create a new config object /// </summary> /// <param name="p">The plugin that is using the config object</param> /// <param name="c">The config type you want</param> /// <param name="filename">The file name (DONT INCLUDE EXTENTION)</param> public Config(Plugin p, ConfigType c, string filename) { this.filename = filename; if (!Directory.Exists("plugins/" + p.name)) Directory.CreateDirectory("plugins/" + p.name); if (!File.Exists("plugins/" + p.name + "/" + filename + ".config") && c == ConfigType.Setting) File.Create("plugins/" + p.name + "/" + filename + ".config"); if (!File.Exists("plugins/" + p.name + "/" + filename + ".file") && c == ConfigType.SaveFile) File.Create("plugins/" + p.name + "/" + filename + ".file"); this.p = p; this.c = c; }
public LaserscribeLotFilterData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.mask = new StringData(configType, prefix + name, "Mask", "Lot ID mask", "", ""); AddChild(this.mask); this.checksum = new BooleanData(configType, prefix + name, "Checksum", "Laserscribe has semi checksum", "", false); AddChild(this.checksum); }
protected ValueData(ConfigType configType, string prefix, string name, string description, string editor, object defaultValue) : base(configType, prefix, name, description, editor) { this.defaultValue = this.currentValue = defaultValue; changed = wasRead = hasValue = false; }
public IConfig CreateConfig(string file, ConfigType type) { switch (type) { case ConfigType.XML: return new XMLConfig(file); case ConfigType.Json: return new JsonConfig(file); } return null; }
public BinListData(ConfigType configType, string prefix, string name, string description, string editor, List<int> defaultValue) : base(configType, prefix, name, description, editor, null) { this.currentValue = new List<int>(); this.defaultValue = new List<int>(); if ((defaultValue != null) && (defaultValue.Count > 0)) { (this.currentValue as List<int>).AddRange(defaultValue); (this.defaultValue as List<int>).AddRange(defaultValue); } }
public GuiConfigData(ConfigType configType, string configVersion, XmlDocument templateDoc, int levelCount) { this.configType = configType; this.configVersion = configVersion; this.templateDoc = templateDoc; this.levelCount = levelCount; childList = new List<BaseData>[levelCount]; for (int idx = 0; idx < levelCount; idx++) childList[idx] = new List<BaseData>(); CreateChildList(); }
protected BaseData(ConfigType configType, string prefix, string name, string description, string editor) { this.configType = configType; this.prefix = prefix; this.name = name; this.description = description; this.editor = editor; this.fireEvent = 0; this.dataChangedDelegate = null; }
private void BindConfigType() { DataSet list = new ConfigType().GetList(""); this.dropConfigType.DataSource = list; this.dropConfigType.DataTextField = "TypeName"; this.dropConfigType.DataValueField = "KeyType"; this.dropConfigType.DataBind(); this.dropConfigTypeSearch.DataSource = list; this.dropConfigTypeSearch.DataTextField = "TypeName"; this.dropConfigTypeSearch.DataValueField = "KeyType"; this.dropConfigTypeSearch.DataBind(); this.dropConfigTypeSearch.Items.Insert(0, Site.PleaseSelect); }
public string GetConfigSchema(ConfigType configType) { if ( configType == ConfigType.TransmitLocation ) { string resName = NS + "." + "SendPortSchema.xsd"; Assembly asm = Assembly.GetExecutingAssembly(); Stream stream = asm.GetManifestResourceStream(resName); using ( StreamReader reader = new StreamReader(stream) ) { return reader.ReadToEnd(); } } return null; }
/// <summary> /// 构造函数 /// </summary> /// <param name="configType"></param> public ConfigurationOperator(ConfigType configType) { this.configType = configType; if (configType == ConfigType.ExeConfig) { configPath = Application.ExecutablePath; ; } else { configPath = HttpContext.Current.Request.ApplicationPath; } Initialize(); }
public Server(ConfigType configType) { ConfigType = configType; Modules.Add(new ModuleSCON(this)); Modules.Add(new ModuleNPC(this)); Modules.Add(new ModuleP3D(this)); Modules.Add(new ModulePokeD(this)); Modules.AddRange(LoadModules()); CommandManager = new CommandManager(this); ChatChannelManager = new ChatChannelManager(this); }
public BinData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.value = new IntegerData(configType, prefix + name, "Value", "Value", "", 0); AddChild(this.value); this.good = new BooleanData(configType, prefix + name, "Good", "Die is good", "", false); AddChild(this.good); this.reprobable = new BooleanData(configType, prefix + name, "Reprobed", "Die is reprobable", "", false); AddChild(this.reprobable); this.inkable = new BooleanData(configType, prefix + name, "Inked", "Die is inkable", "", false); AddChild(this.inkable); NewBin(); }
public PassData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.id = new StringData(configType, prefix + name, "Id", "ID", "", ""); AddChild(this.id); this.previousStr = new StringData(configType, prefix + name, "PreviousList", "Pass's previous bin value list", "", ""); AddChild(this.previousStr); this.actualStr = new StringData(configType, prefix + name, "ActualList", "Pass's actual bin value list", "", ""); AddChild(this.actualStr); previousList = new List<int>(); actualList = new List<int>(); NewList(); }
public string GetConfigSchema(ConfigType type) { switch (type) { case ConfigType.ReceiveHandler: case ConfigType.ReceiveLocation: string receiveConfig = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<xs:schema targetNamespace=\"http://microservicebus.biztalk\"" + " elementFormDefault=\"qualified\"" + " xmlns=\"http://microservicebus.biztalk\"" + " xmlns:mstns=\"http://tempuri.org/XMLSchema.xsd\"" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"CustomProps\">" + " <xs:complexType>" + " <xs:sequence>" + " <xs:element name=\"uri\" type=\"xs:string\" />" + " </xs:sequence>" + " </xs:complexType>" + " </xs:element>" + "</xs:schema>"; return receiveConfig; case ConfigType.TransmitHandler: case ConfigType.TransmitLocation: string transmitConfig = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<xs:schema targetNamespace=\"http://microservicebus.biztalk\"" + " elementFormDefault=\"qualified\"" + " xmlns=\"http://microservicebus.biztalk\"" + " xmlns:mstns=\"http://tempuri.org/XMLSchema.xsd\"" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"CustomProps\">" + " <xs:complexType>" + " <xs:sequence>" + " <xs:element name=\"uri\" type=\"xs:string\" />" + " <xs:element name=\"address\" type=\"xs:string\" />" + " <xs:element name=\"port\" type=\"xs:integer\" />" + " <xs:element name=\"contentType\" type=\"xs:string\" />" + " </xs:sequence>" + " </xs:complexType>" + " </xs:element>" + "</xs:schema>"; return transmitConfig; default: return null; } }
public ConsecutiveFailCustomRuleData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.enabled = new BooleanData(configType, prefix + name, "Enabled", "Enabled", "", false); AddChild(enabled); this.threshold = new IntegerData(configType, prefix + name, "Threshold", "Threshold", "", 0); AddChild(threshold); this.message = new StringData(configType, prefix + name, "Message", "Message", "", ""); AddChild(message); this.binListStr = new StringData(configType, prefix + name, "BinList", "Bin list", "", ""); AddChild(binListStr); binList = new List<int>(); GetBinList(binListStr.Value); }
public CustomScriptData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { this.scriptName = new StringData(configType, prefix + name, "Name", "Script name", "", ""); AddChild(this.scriptName); this.enabled = new BooleanData(configType, prefix + name, "Enabled", "Enabled", "", false); AddChild(this.enabled); this.command = new StringData(configType, prefix + name, "Command", "Command", "", ""); AddChild(this.command); this.waitToComplete = new BooleanData(configType, prefix + name, "WaitToComplete", "Wait to complete", "", false); AddChild(this.waitToComplete); this.openInConsole = new BooleanData(configType, prefix + name, "OpenInConsole", "Open in console", "", false); AddChild(this.openInConsole); NewScript(); }
public string GetConfigSchema(ConfigType type) { string result = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<xs:schema targetNamespace=\"http://microservicebus.biztalk\"" + " elementFormDefault=\"qualified\"" + " xmlns=\"http://microservicebus.biztalk\"" + " xmlns:mstns=\"http://tempuri.org/XMLSchema.xsd\"" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"CustomProps\">" + " <xs:complexType>" + " <xs:sequence>" + " <xs:element name=\"uri\" type=\"xs:string\" />" + " </xs:sequence>" + " </xs:complexType>" + " </xs:element>" + "</xs:schema>"; if (type == 0) return result; return null; }
/// <summary> /// Validate the configuration of the send port. /// </summary> /// <param name="configType">Configuration Type</param> /// <param name="configuration">Configuration XML</param> /// <returns>The new Configuration XML</returns> /// <remarks> /// In here we load the configuration and create a new URI for /// the send port based on the value of the name /// attribute introduced by the user. /// </remarks> public string ValidateConfiguration(ConfigType configType, string configuration) { if ( configType != ConfigType.TransmitLocation ) return configuration; XmlDocument doc = new XmlDocument(); doc.LoadXml(configuration); XmlNode uriNode = doc.SelectSingleNode("CustomProps/uri"); if ( uriNode == null ) { uriNode = doc.CreateElement("uri"); doc.DocumentElement.AppendChild(uriNode); } XmlNode nameNode = doc.SelectSingleNode("CustomProps/name"); if ( nameNode == null || nameNode.InnerText.Trim().Length == 0 ) { throw new InvalidOperationException("Name cannot be blank"); } uriNode.InnerText = "null://" + nameNode.InnerText.Trim(); return doc.OuterXml; }
public DatabaseComponentConfigFile(ConfigType configType) : base(new ConfigFolder().CreateFile($"Database{configType.GetFileExtension()}", CreationCollisionOption.OpenIfExists)) => ConfigType = configType;
public object GetTypedConfigValue(ConfigType ct, System.Type type) => GetValueFromConfig(this.GetConfigValue(ct), type);
internal string GetConfigPath(Games game, ConfigType type) { switch((int)type) { case 0: if(game == Games.CS) { return Path.Combine(this.CsPath, "autoexec.cfg"); }else if(game == Games.CSS) { return Path.Combine(this.CssPath, "autoexec.cfg"); }else { return Path.Combine(this.CzPath, "autoexec.cfg"); } case 1: if(game == Games.CS) { return Path.Combine(this.CsPath, "config.cfg"); }else if(game == Games.CSS) { return Path.Combine(this.CssPath, "config.cfg"); }else { return Path.Combine(this.CzPath, "config.cfg"); } case 2: if(game == Games.CS) { return Path.Combine(this.CsPath, "czbind.cfg"); }else if(game == Games.CSS) { return Path.Combine(this.CssPath, "czbind.cfg"); }else { return Path.Combine(this.CzPath, "czbind.cfg"); } case 3: if(game == Games.CS) { return Path.Combine(this.CsPath, "userconfig.cfg"); }else if(game == Games.CSS) { return Path.Combine(this.CssPath, "userconfig.cfg"); }else { return Path.Combine(this.CzPath, "userconfig.cfg"); } case 4: if(game == Games.CSS) { return Path.Combine(this.CssPath, "compatibility.cfg"); } break; case 5: if(game == Games.CS) { return Path.Combine(this.CsPath, "clips.cfg"); }else if(game == Games.CSS) { return Path.Combine(this.CssPath, "clips.cfg"); }else { return Path.Combine(this.CzPath, "clips.cfg"); } } return ""; }
public ConfigType SaveConfigType(ConfigType data) { try { SetService(); return SerClient.SaveConfigType(data); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
// 根据生成的类,动态编译把json转成protobuf private static void ExportExcelProtobuf(ConfigType configType) { string classPath = GetClassDir(configType); List<SyntaxTree> syntaxTrees = new List<SyntaxTree>(); List<string> protoNames = new List<string>(); foreach (string classFile in Directory.GetFiles(classPath, "*.cs")) { protoNames.Add(Path.GetFileNameWithoutExtension(classFile)); syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile))); } List<PortableExecutableReference> references = new List<PortableExecutableReference>(); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { if (assembly.IsDynamic) { continue; } if (assembly.Location == "") { continue; } } catch (Exception e) { Console.WriteLine(e); throw; } PortableExecutableReference reference = MetadataReference.CreateFromFile(assembly.Location); references.Add(reference); } CSharpCompilation compilation = CSharpCompilation.Create( null, syntaxTrees.ToArray(), references.ToArray(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using MemoryStream memSteam = new MemoryStream(); EmitResult emitResult = compilation.Emit(memSteam); if (!emitResult.Success) { StringBuilder stringBuilder = new StringBuilder(); foreach (Diagnostic t in emitResult.Diagnostics) { stringBuilder.AppendLine(t.GetMessage()); } throw new Exception($"动态编译失败:\n{stringBuilder}"); } memSteam.Seek(0, SeekOrigin.Begin); Assembly ass = Assembly.Load(memSteam.ToArray()); string dir = GetProtoDir(configType); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (string protoName in protoNames) { Type type = ass.GetType($"ET.{protoName}Category"); Type subType = ass.GetType($"ET.{protoName}"); Serializer.NonGeneric.PrepareSerializer(type); Serializer.NonGeneric.PrepareSerializer(subType); string json = File.ReadAllText(Path.Combine(string.Format(jsonDir, configType), $"{protoName}.txt")); object deserialize = BsonSerializer.Deserialize(json, type); string path = Path.Combine(dir, $"{protoName}Category.bytes"); using FileStream file = File.Create(path); Serializer.Serialize(file, deserialize); } }
public static bool HasDarklandsPath(ConfigType type) { return(HasSetting( type, SettingDarklandsPath)); }
/// <summary> /// Writes an Object to a Configuration Node, using it's parser targets /// </summary> /// <returns></returns> public static ConfigNode WriteObjectToConfigNode <T>(string name, ref ConfigNode node, T target) { // Start ConfigNode config = node.AddNode(name); // Crawl it's member infos foreach (MemberInfo member in target.GetType().GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { // Get the first parser target ParserTarget[] targets = member.GetCustomAttributes(typeof(ParserTarget), false) as ParserTarget[]; if (targets.Length == 0) { continue; } // Is this a node or a value? RequireConfigType[] configTypes = (member.MemberType == MemberTypes.Field ? (member as FieldInfo).FieldType : (member as PropertyInfo).PropertyType).GetCustomAttributes(typeof(RequireConfigType), false) as RequireConfigType[]; // Write System.Object memberValue = member.GetValue(target); Type memberType = member.GetMemberType(); if (memberValue == null) { continue; } // Type ConfigType configType = configTypes.Length == 1 ? configTypes[0].Type : memberType.Name.StartsWith("MapSOParser_") || memberType == typeof(string) ? ConfigType.Value : ConfigType.Node; // Convert if (memberType != typeof(string) && (configType == ConfigType.Value || memberType == typeof(FloatCurveParser))) { memberValue = memberType == typeof(PhysicsMaterialParser) ? memberType.GetProperty("Value").GetValue(memberValue, null) : memberType == typeof(FloatCurveParser) ? memberType.GetProperty("Value").GetValue(memberValue, null) : memberType.GetProperty("Value").GetValue(memberValue); if (memberValue == null || memberType == typeof(StockMaterialParser)) { continue; } if (memberValue.GetType().GetInterface("IEnumerable") != null && memberType != typeof(string)) { memberValue = String.Join(memberType == typeof(StringCollectionParser) ? "," : " ", (memberValue as IEnumerable).Cast <System.Object>().Select(o => o.ToString()).ToArray()); } } // Format Unity types if (writeableTypes.Contains(memberType)) { if (memberValue is Vector2) { memberValue = ConfigNode.WriteVector((Vector2)memberValue); } if (memberValue is Vector3) { memberValue = ConfigNode.WriteVector((Vector3)memberValue); } if (memberValue is Vector3d) { memberValue = ConfigNode.WriteVector((Vector3d)memberValue); } if (memberValue is Vector4) { memberValue = ConfigNode.WriteVector((Vector4)memberValue); } if (memberValue is Quaternion) { memberValue = ConfigNode.WriteQuaternion((Quaternion)memberValue); } if (memberValue is QuaternionD) { memberValue = ConfigNode.WriteQuaternion((QuaternionD)memberValue); } if (memberValue is Color) { memberValue = ConfigNode.WriteColor((Color)memberValue); } } // Texture Type[] textureTypes = { typeof(Mesh), typeof(Texture2D), typeof(Texture), typeof(MapSO), typeof(CBAttributeMapSO) }; if (textureTypes.Contains(memberValue.GetType()) || textureTypes.Contains(memberValue.GetType().BaseType)) { memberValue = Format(memberValue as Object); } // Write if (configType == ConfigType.Value && memberValue.GetType() != typeof(FloatCurve) && memberValue.GetType() != typeof(AnimationCurve)) { config.AddValue(targets[0].FieldName, memberValue); } else if (memberValue.GetType() == typeof(FloatCurve)) { (memberValue as FloatCurve).Save(config.AddNode(targets[0].FieldName)); } else if (memberValue is AnimationCurve) { new FloatCurve((memberValue as AnimationCurve).keys).Save(config.AddNode(targets[0].FieldName)); } } return(config); }
public static string GetDarklandsPath(ConfigType type) { return(ReadSetting <string>( type, SettingDarklandsPath)); }
public Task <ConfigEntity> GetByKey(string key, ConfigType type = ConfigType.Custom, IUnitOfWork uow = null) { return(Db.Find(m => m.Key == key && m.Type == type).UseUow(uow).FirstAsync()); }
public Task <IList <ConfigEntity> > QueryByType(ConfigType type) { return(Db.Find(m => m.Type == type).ToListAsync()); }
public Task <bool> Exists(ConfigType type, string key) { return(ExistsAsync(m => m.Type == type && m.Key == key)); }
protected bool load(ConfigType type) { return(readFromLocalConfigFile(type, instance)); }
public Task <string> GetJson(ConfigType type, string code) { var json = ConfigJsons.FirstOrDefault(m => m.Key == $"{type.ToInt()}_{code.ToLower()}").Value; return(Task.FromResult(json)); }
static void ExportSheetJson(ExcelWorksheet worksheet, string name, Dictionary <string, HeadInfo> classField, ConfigType configType, StringBuilder sb) { string configTypeStr = configType.ToString(); for (int row = 6; row <= worksheet.Dimension.End.Row; ++row) { string prefix = worksheet.Cells[row, 2].Text.Trim(); if (prefix.Contains("#")) { continue; } if (prefix == "") { prefix = "cs"; } // 服务端因为机器人的存在必须包含客户端所有配置,所以单独的c字段没有意义,单独的c就表示cs if (prefix == "c") { prefix = "cs"; } if (!prefix.Contains(configTypeStr)) { continue; } if (worksheet.Cells[row, 3].Text.Trim() == "") { continue; } sb.Append("{"); sb.Append($"\"_t\":\"{name}\""); for (int col = 3; col <= worksheet.Dimension.End.Column; ++col) { string fieldName = worksheet.Cells[4, col].Text.Trim(); if (!classField.ContainsKey(fieldName)) { continue; } HeadInfo headInfo = classField[fieldName]; if (headInfo == null) { continue; } if (!headInfo.FieldCS.Contains(configTypeStr)) { continue; } string fieldN = headInfo.FieldName; if (fieldN == "Id") { fieldN = "_id"; } sb.Append($",\"{fieldN}\":{Convert(headInfo.FieldType, worksheet.Cells[row, col].Text.Trim())}"); } sb.Append("},\n"); } }
static void ExportClass(string protoName, Dictionary <string, HeadInfo> classField, ConfigType configType) { string dir = GetClassDir(configType); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string exportPath = Path.Combine(dir, $"{protoName}.cs"); using FileStream txt = new FileStream(exportPath, FileMode.Create); using StreamWriter sw = new StreamWriter(txt); StringBuilder sb = new StringBuilder(); foreach ((string _, HeadInfo headInfo) in classField) { if (headInfo == null) { continue; } if (!headInfo.FieldCS.Contains(configType.ToString())) { continue; } sb.Append($"\t\t/// <summary>{headInfo.FieldDesc}</summary>\n"); sb.Append($"\t\t[ProtoMember({headInfo.FieldIndex})]\n"); string fieldType = headInfo.FieldType; sb.Append($"\t\tpublic {fieldType} {headInfo.FieldName} {{ get; set; }}\n"); } string content = template.Replace("(ConfigName)", protoName).Replace(("(Fields)"), sb.ToString()); sw.Write(content); }
public IResultModel Edit(string code, ConfigType type) { return(ResultModel.Success(_configProvider.Get(code, type))); }
private static Assembly GetAssembly(ConfigType configType) { return(configAssemblies[(int)configType]); }
/// <summary> /// Writes the XML element as YAML. /// </summary> private void WriteElement(YamlFormatArgs args, XElement xml, ConfigType ct, ConfigurationEntity entity, Type type) { WriteComments(args, xml); args.Indent += 2; if (args.Indent == 2) { args.Writer.Write("- { "); } else if (args.Indent > 0) { args.Writer.Write($"{new string(' ', args.Indent)}{{ "); } WriteAttributes(args, ct, entity, type, xml); // Group by element name, then process as a collection. int i = 0; var coll = xml.Elements().GroupBy(x => x.Name).Select(g => new { g.Key, Children = xml.Elements(g.Key) }); foreach (var grp in coll) { var info = GetEntityConfigInfo(grp.Key.LocalName); if (info.entity == ConfigurationEntity.None) { return; } if (args.Indent > 0) { args.Writer.WriteLine(","); args.Indent += 2; args.Writer.Write($"{new string(' ', args.Indent)}{info.name}:"); } else { args.Writer.Write($"{info.name}:"); } if (args.Indent > 0) { args.Writer.Write(" ["); } args.Writer.WriteLine(); int j = 0; foreach (var child in grp.Children) { if (j++ > 0) { args.WriteClosingSquigglyBracket(); if (args.Indent > 0) { args.Writer.Write(","); } args.Writer.WriteLine(); } if (args.Indent == 0 && !child.Equals(xml.Document.Root.Elements().First())) { args.Writer.WriteLine(); } args.Level++; WriteElement(args, child, ct, info.entity, info.type); args.Level--; } args.WriteClosingSquigglyBracket(); args.Writer.WriteLine(); if (args.Indent > 0) { args.Writer.Write($"{new string(' ', args.Indent)}]"); args.Indent -= 2; } i++; if (i == coll.Count()) { args.Writer.WriteLine(); if (args.Indent > 0) { args.Writer.Write($"{new string(' ', args.Indent)}"); } } } args.Indent -= 2; }
/// <summary> /// Load collection for ParserTargetCollection /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChildren">Whether getters on the object should get called</param> private static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String configName = "Default", Boolean getChildren = true) { // Get the target attributes ParserTargetCollection[] targets = (ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true); // Process the target attributes foreach (ParserTargetCollection target in targets) { // Figure out if this field exists and if we care Boolean isNode = node.HasNode(target.FieldName) || target.FieldName == "self"; Boolean isValue = node.HasValue(target.FieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChildren) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // Get settings data ParserOptions.Data data = ParserOptions.Options[configName]; // Log data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.Optional && !(target.AllowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException( "Missing non-optional field: " + o.GetType() + "." + target.FieldName); } // Nothing to do, so return continue; } // If we are dealing with a generic collection if (targetType.IsGenericType) { // If the target is a generic dictionary if (typeof(IDictionary).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic dictionary requires sources to be nodes"); } // Get the target value as a dictionary IDictionary collection = targetValue as IDictionary; // Get the internal type of this collection Type genericTypeA = targetType.GetGenericArguments()[0]; Type genericTypeB = targetType.GetGenericArguments()[1]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IDictionary; targetValue = collection; } // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericTypeA.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0) { if (attributes[0].Type == ConfigType.Node) { throw new ParserTargetTypeMismatchException( "The key value of a generic dictionary must be a Value"); } } attributes = (RequireConfigType[])genericTypeB.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericTypeB == typeof(String)) { ConfigType type = genericTypeB == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection.Add(ProcessValue(genericTypeA, subnode.name), CreateObjectFromConfigNode(genericTypeB, subnode, configName, target.GetChild)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } else { // Iterate over all of the values in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: collection.Add(ProcessValue(genericTypeA, value.name), ProcessValue(genericTypeB, value.value)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } } } // If the target is a generic collection else if (typeof(IList).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic list requires sources to be nodes"); } // Get the target value as a collection IList collection = targetValue as IList; // Get the internal type of this collection Type genericType = targetType.GetGenericArguments()[0]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IList; targetValue = collection; } // Store the objects that were already patched List <Object> patched = new List <Object>(); // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericType.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericType == typeof(String)) { ConfigType type = genericType == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: case NameSignificance.Key when subnode.name == target.Key: // Check if the type represents patchable data Object current = null; if (typeof(IPatchable).IsAssignableFrom(genericType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != genericType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == collection.IndexOf(collection[i])) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(genericType); collection?.Add(current); } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == subnode.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Check if the type represents patchable data current = null; if (typeof(IPatchable).IsAssignableFrom(elementType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != elementType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == i) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(elementType); collection?.Add(current); if (typeof(ICreatable).IsAssignableFrom(elementType)) { ICreatable creatable = (ICreatable)current; creatable.Create(); } } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; default: continue; } } } else { // Iterate over all of the nodes in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == value.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Add the object to the collection collection?.Add(ProcessValue(elementType, value.value)); break; case NameSignificance.Key when value.name == target.Key: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; default: continue; } } } } } } // If we are dealing with a non generic collection else { // Check for invalid scenarios if (target.NameSignificance == NameSignificance.None) { throw new Exception( "Can not infer type from non generic target; can not infer type from zero name significance"); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } } }
private static IAsyncResult QueryItemFromServerAsync(string key, ConfigType type, Action <ConfigItem, Exception> callback) { string url = new UrlBuilder() .SetPath("/ActiveConfig/v1/GetKey") .AddParam("appid", _appKey) .AddParam("secretkey", _appSecret) .AddParam("key", key + ":" + (int)type) .GetUrl(); return(Http.GetStringAsync(url, (s, e) => { ConfigItem result = null; if (e == null) { result = null; try { var dict = JSON.Parse(s); if (dict != null) { string code = dict["code"].Value; string msg = dict["msg"].Value; string data = dict["data"].Value; if (code != "0") { Debug.WriteLine("Server return error {0}: {1}", code, msg); e = new ActiveConfigException(msg); } else { if (dict["data"].Count == 1) { var item = dict["data"][0]; result = new ConfigItem(); result.Key = item["key"].Value; result.Value = item["value"].Value; result.Type = (ConfigType)Enum.Parse(typeof(ConfigType), item["type"].Value, true); result.ExpireTime = Helper.ConvertTime(item["endtime"].Value); result.MD5 = item["md5"].Value; result.ID = string.Format("{0}:{1}", (int)result.Type, result.Key); if (result.Status == ItemStatus.KeyNotFound) { e = new KeyNotFoundException(key); } } else { e = new KeyNotFoundException(key); } } } else { e = new ActiveConfigException("Parsing json failed"); } } catch (Exception err) { e = new ActiveConfigException("Parsing json failed", err); } } callback(result, e); })); }
public ConfigPathAttribute(string name, ConfigType typ, bool stable = true) { assetName = name; isStable = stable; configType = typ; }
static void ExportSheetClass(ExcelWorksheet worksheet, List<HeadInfo> classField, HashSet<string> uniqeField, ConfigType configType) { const int row = 2; for (int col = 3; col <= worksheet.Dimension.End.Column; ++col) { string fieldName = worksheet.Cells[row + 2, col].Text.Trim(); if (fieldName == "") { continue; } if (!uniqeField.Add(fieldName)) { continue; } string fieldCS = worksheet.Cells[row, col].Text.Trim(); string fieldDesc = worksheet.Cells[row + 1, col].Text.Trim(); string fieldType = worksheet.Cells[row + 3, col].Text.Trim(); classField.Add(new HeadInfo(fieldCS, fieldDesc, fieldName, fieldType)); } }
/// <summary> /// Displays a parser target in the window /// </summary> private void DisplayParserTarget(ParserTarget target, MemberInfo member) { // Don't display hidden options if (Tools.HasAttribute <KittopiaHideOption>(member) && !Tools.GetAttributes <KittopiaHideOption>(member)[0].Show) { return; } // Check if the object is a list or a single element if (!Tools.IsCollection(target)) { GUIHorizontalLayout(() => { GUILabel(target.FieldName, modifier: Alignment(TextAlignmentOptions.Left)); GUIFlexibleSpace(); GUILabel(target.Optional ? "Optional" : "Required", modifier: Alignment(TextAlignmentOptions.Right) .And(TextColor(Color.gray))); }); // Display a KittopiaDescription String description = Tools.GetDescription(member); if (!String.IsNullOrEmpty(description)) { GUISpace(2f); GUILabel(description, modifier: TextColor(Color.gray)); } GUISpace(5f); // If the element is loaded from a config node, it needs a new window // Simply values can be edited with an inline textfield ConfigType configType = Tools.GetConfigType(Tools.GetValue(member, Info.Value)?.GetType() ?? Tools.MemberType(member)); if (configType == ConfigType.Node) { GUIHorizontalLayout(() => { // Edit Button GUIToggleButton( () => Children.ContainsKey(target.FieldName) && Children[target.FieldName].IsVisible, "Edit", e => ToggleSubEditor(target, member, e), -1f, 25f, Enabled <DialogGUIToggleButton>(() => Tools.GetValue(member, Info.Value) != null)); // Button to create or destroy the element if (Tools.HasAttribute <KittopiaUntouchable>(member)) { GUIButton(Tools.GetValue(member, Info.Value) != null ? "x" : "+", () => { }, 25f, 25f, false, () => { }, Enabled <DialogGUIButton>(() => false)); } else { GUIButton(() => Tools.GetValue(member, Info.Value) != null ? "x" : "+", () => { Object value = Tools.GetValue(member, Info.Value); if (value != null) { Tools.Destruct(value); Tools.SetValue(member, Info.Value, null); SetValue(null); } else { Object v = Tools.Construct(Tools.MemberType(member), Info.Body); Tools.SetValue(member, Info.Value, v); SetValue(v); } }, 25f, 25f, false, () => { }); } }); } else { GUIHorizontalLayout(() => { GUITextInput("", false, Int32.MaxValue, s => Tools.ApplyInput(member, s, Info.Value), () => Tools.FormatParsable(Tools.GetValue(member, Info.Value)) ?? "", TMP_InputField.ContentType.Standard, 25f); GUIToggleButton( () => ValueEditors.ContainsKey(target.FieldName) && ValueEditors[target.FieldName].IsVisible, ">", e => ToggleValueEditor(target, member, e), 25f, 25f, Enabled <DialogGUIToggleButton>(() => HasValueEditor(member))); }); } } else { ParserTargetCollection collection = (ParserTargetCollection)target; // Is the collection parsing a subnode, or this one? if (collection.FieldName != "self") { GUIHorizontalLayout(() => { GUILabel(target.FieldName, modifier: Alignment(TextAlignmentOptions.Left)); GUIFlexibleSpace(); GUILabel(target.Optional ? "Optional" : "Required", modifier: Alignment(TextAlignmentOptions.Right) .And(TextColor(Color.gray))); }); // Display a KittopiaDescription String description = Tools.GetDescription(member); if (!String.IsNullOrEmpty(description)) { GUISpace(2f); GUILabel(description, modifier: TextColor(Color.gray)); } GUISpace(5f); GUIHorizontalLayout(() => { // Edit Button GUIToggleButton(() => Children.ContainsKey(target.FieldName) && Children[target.FieldName].IsVisible, "Edit", e => ToggleCollectionEditor(target, member, e), -1f, 25f, Enabled <DialogGUIToggleButton>(() => Tools.GetValue(member, Info.Value) != null)); // Button to create or destroy the element if (Tools.HasAttribute <KittopiaUntouchable>(member)) { GUIButton(Tools.GetValue(member, Info.Value) != null ? "x" : "+", () => { }, 25f, 25f, false, () => { }, Enabled <DialogGUIButton>(() => false)); } else { GUIButton(() => Tools.GetValue(member, Info.Value) != null ? "x" : "+", () => { Object value = Tools.GetValue(member, Info.Value); if (value != null) { Tools.Destruct(value); Tools.SetValue(member, Info.Value, null); SetValue(null); } else { Object v = Tools.Construct(Tools.MemberType(member), Info.Body); Tools.SetValue(member, Info.Value, v); SetValue(v); } }, 25f, 25f, false, () => { }); } }); } else { new CollectionEditor(() => Tools.GetValue(member, Info.Value), v => Tools.SetValue(member, Info.Value, v), Info.Body, Info.Body.transform.name + " - " + target.FieldName, member, (ParserTargetCollection)target, () => Info.Value).DisplayCollection(); } } if (target.FieldName != "self") { // Use a box as a seperator GUISpace(5f); GUIBox(-1f, 1f, () => { }); GUISpace(5f); } }
public void DeleteConfigType(ConfigType data) { try { SetService(); SerClient.DeleteConfigType(data); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public void GetString_NullResourceKey_ThrowsArgumentNullException(ConfigType config) { var localizer = NewLocalizer(config); Assert.Throws <ArgumentNullException>(() => localizer[null]); }
public Config(ConfigType type) { this.type = type; }
///----------------------------------------------------------------------------- /// <summary> /// Removes profanity words in the provided input string. /// </summary> /// <remarks> /// The words to search could be defined in two different places: /// 1) In an external file. (NOT IMPLEMENTED) /// 2) In System/Site lists. /// The name of the System List is "ProfanityFilter". The name of the list in each portal is composed using the following rule: /// "ProfanityFilter-" + PortalID. /// </remarks> /// <param name="inputString">The string to search the words in.</param> /// <param name="configType">The type of configuration.</param> /// <param name="configSource">The external file to search the words. Ignored when configType is ListController.</param> /// <param name="filterScope">When using ListController configType, this parameter indicates which list(s) to use.</param> /// <returns>The original text with the profanity words removed.</returns> ///----------------------------------------------------------------------------- public string Remove(string inputString, ConfigType configType, string configSource, FilterScope filterScope) { switch (configType) { case ConfigType.ListController: const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline; const string listName = "ProfanityFilter"; var listController = new ListController(); PortalSettings settings; IEnumerable<ListEntryInfo> listEntryHostInfos; IEnumerable<ListEntryInfo> listEntryPortalInfos; switch (filterScope) { case FilterScope.SystemList: listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + removeItem.Text + @"\b", string.Empty, options)); break; case FilterScope.SystemAndPortalList: settings = PortalController.GetCurrentPortalSettings(); listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + removeItem.Text + @"\b", string.Empty, options)); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + removeItem.Text + @"\b", string.Empty, options)); break; case FilterScope.PortalList: settings = PortalController.GetCurrentPortalSettings(); listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + removeItem.Text + @"\b", string.Empty, options)); break; } break; case ConfigType.ExternalFile: throw new NotImplementedException(); default: throw new ArgumentOutOfRangeException("configType"); } return inputString; }
public DoubleData(ConfigType configType, string prefix, string name, string description, string editor, double defaultValue) : base(configType, prefix, name, description, editor, defaultValue) { }
public ListData(ConfigType configType, string prefix, string name, string description, string editor) : base(configType, prefix, name, description, editor) { childStruct = null; }
public void WithCultureGetAllStrings_WithoutParentCulture_ReturnsSpecificCultureStrings(ConfigType config) { var localizer = NewLocalizer(config); var expected = new[] { new LocalizedString("Colour", "Colour", false), new LocalizedString("Overridden", "Overriding an earlier config", false) }; var auLocalizer = localizer.WithCulture(new CultureInfo("en-AU")); var values = auLocalizer.GetAllStrings(includeParentCultures: false); Assert.Equal(expected, values.ToArray(), LocalizedStringEqualityComparer); }
// 动态编译生成的cs代码 private static Assembly DynamicBuild(ConfigType configType) { string classPath = GetClassDir(configType); List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); List <string> protoNames = new List <string>(); foreach (string classFile in Directory.GetFiles(classPath, "*.cs")) { protoNames.Add(Path.GetFileNameWithoutExtension(classFile)); syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile))); } List <PortableExecutableReference> references = new List <PortableExecutableReference>(); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { if (assembly.IsDynamic) { continue; } if (assembly.Location == "") { continue; } } catch (Exception e) { Console.WriteLine(e); throw; } PortableExecutableReference reference = MetadataReference.CreateFromFile(assembly.Location); references.Add(reference); } CSharpCompilation compilation = CSharpCompilation.Create(null, syntaxTrees.ToArray(), references.ToArray(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using MemoryStream memSteam = new MemoryStream(); EmitResult emitResult = compilation.Emit(memSteam); if (!emitResult.Success) { StringBuilder stringBuilder = new StringBuilder(); foreach (Diagnostic t in emitResult.Diagnostics) { stringBuilder.AppendLine(t.GetMessage()); } throw new Exception($"动态编译失败:\n{stringBuilder}"); } memSteam.Seek(0, SeekOrigin.Begin); Assembly ass = Assembly.Load(memSteam.ToArray()); return(ass); }
/// <summary> /// Outputs an ARTag configuration file based on the marker layout. /// </summary> /// <param name="configFilename">The name of the configuration file to be generated</param> /// <param name="type">The type of config file depending on different tracking libraries</param> /// <exception cref="InvalidOperationException"></exception> public void OutputConfig(String configFilename, ConfigType type) { int id = 0; foreach (int key in configs.Keys) { id = key; break; } float ratio = markerSize / configs[id].Size.Width; try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "no"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); if (type == ConfigType.ALVAR) { XmlElement xmlRootNode = xmlDoc.CreateElement("multimarker"); xmlRootNode.SetAttribute("markers", markerIDs.Count.ToString()); xmlDoc.AppendChild(xmlRootNode); foreach (int markerID in markerIDs) { XmlElement markerXml = xmlDoc.CreateElement("marker"); markerXml.SetAttribute("index", markerID.ToString()); markerXml.SetAttribute("status", "2"); MarkerConfig config = configs[markerID]; int x = config.Position.X - configCenter.X; int y = config.Position.Y - configCenter.Y; PointF configPos = new PointF(x * ratio, y * ratio); SizeF configSize = new SizeF(config.Size.Width * ratio, config.Size.Height * ratio); XmlElement[] cornerXml = new XmlElement[4]; cornerXml[0] = xmlDoc.CreateElement("corner"); cornerXml[0].SetAttribute("x", configPos.X.ToString()); cornerXml[0].SetAttribute("y", "" + (-(configPos.Y + configSize.Height))); cornerXml[0].SetAttribute("z", "0"); cornerXml[1] = xmlDoc.CreateElement("corner"); cornerXml[1].SetAttribute("x", "" + (configPos.X + configSize.Width)); cornerXml[1].SetAttribute("y", "" + (-(configPos.Y + configSize.Height))); cornerXml[1].SetAttribute("z", "0"); cornerXml[2] = xmlDoc.CreateElement("corner"); cornerXml[2].SetAttribute("x", "" + (configPos.X + configSize.Width)); cornerXml[2].SetAttribute("y", "" + (-configPos.Y)); cornerXml[2].SetAttribute("z", "0"); cornerXml[3] = xmlDoc.CreateElement("corner"); cornerXml[3].SetAttribute("x", "" + configPos.X); cornerXml[3].SetAttribute("y", "" + (-configPos.Y)); cornerXml[3].SetAttribute("z", "0"); foreach (XmlElement corner in cornerXml) markerXml.AppendChild(corner); xmlRootNode.AppendChild(markerXml); } } else if (type == ConfigType.NyARToolkitPattern) { XmlElement xmlRootNode = xmlDoc.CreateElement("multimarker"); xmlRootNode.SetAttribute("markers", markerIDs.Count.ToString()); xmlDoc.AppendChild(xmlRootNode); foreach (int markerID in markerIDs) { XmlElement markerXml = xmlDoc.CreateElement("marker"); MarkerConfig config = configs[markerID]; string patternName = ""; int patternWidth = 16; int patternHeight = 16; float patternSize = markerSize; float confidence = 0.5f; if (config.AdditionalInfo != null) { foreach (KeyValuePair<string, string> pair in config.AdditionalInfo) { switch (pair.Key) { case "patternName": patternName = pair.Value; break; case "patternWidth": patternWidth = int.Parse(pair.Value); break; case "patternHeight": patternHeight = int.Parse(pair.Value); break; case "confidence": confidence = float.Parse(pair.Value); break; } } } if (String.IsNullOrEmpty(patternName)) throw new Exception("You need to have a patternName information for marker: "); markerXml.SetAttribute("patternName", patternName); markerXml.SetAttribute("patternWidth", patternWidth.ToString()); markerXml.SetAttribute("patternHeight", patternHeight.ToString()); markerXml.SetAttribute("patternSize", patternSize.ToString()); markerXml.SetAttribute("confidence", confidence.ToString()); int x = config.Position.X - configCenter.X; int y = config.Position.Y - configCenter.Y; float fx = x * ratio; float fy = y * ratio; markerXml.SetAttribute("upperLeftCorner", fx + "," + fy); xmlRootNode.AppendChild(markerXml); } } else if(type == ConfigType.NyARToolkitID) { XmlElement xmlRootNode = xmlDoc.CreateElement("multimarker"); xmlRootNode.SetAttribute("markers", markerIDs.Count.ToString()); xmlDoc.AppendChild(xmlRootNode); foreach (int markerID in markerIDs) { XmlElement markerXml = xmlDoc.CreateElement("marker"); MarkerConfig config = configs[markerID]; string patternId = ""; float patternSize = markerSize; if (config.AdditionalInfo != null) { foreach (KeyValuePair<string, string> pair in config.AdditionalInfo) { switch (pair.Key) { case "patternId": patternId = pair.Value; break; } } } if (String.IsNullOrEmpty(patternId)) throw new Exception("You need to have a patternName information for marker: "); markerXml.SetAttribute("patternId", patternId); markerXml.SetAttribute("patternSize", patternSize.ToString()); int x = config.Position.X - configCenter.X + (config.Size.Width / 2); int y = config.Position.Y - configCenter.Y + (config.Size.Height / 2); float fx = x * ratio; float fy = y * ratio; markerXml.SetAttribute("center", fx + "," + fy); xmlRootNode.AppendChild(markerXml); } } if (!Path.GetExtension(configFilename).Equals(".xml")) configFilename += ".xml"; xmlDoc.Save(configFilename); } catch (Exception exp) { Console.WriteLine(exp.Message + exp.StackTrace); } }
/// <summary> /// Adds a multi-value ParserTarget to the ConfigNode tree /// </summary> private static void ProcessCollection(ParserTarget parserTarget, MemberInfo memberInfo, Object reference, ref ConfigNode node) { // Get the type of the collection Type memberType = Tools.MemberType(memberInfo); // Is the collection a dictionary? if (typeof(IDictionary).IsAssignableFrom(memberType)) { // Is the dictionary null? if (!(Tools.GetValue(memberInfo, reference) is IDictionary dictionary)) { return; } // Create the new ConfigNode ConfigNode targetNode = null; // Iterate over the elements of the dictionary foreach (DictionaryEntry value in dictionary) { // Null-Check if (value.Key == null || value.Value == null) { continue; } // Create the node if necessary if (targetNode == null) { targetNode = node; if (parserTarget.FieldName != "self") { // Get a description String description = Tools.GetDescription(memberInfo); // Add it to the config targetNode = String.IsNullOrEmpty(description) ? node.AddNode(parserTarget.FieldName) : node.AddNode(parserTarget.FieldName, description); } } // The first generic type has to be ConfigType.Value, figure out the type of the second one ConfigType type = Tools.GetConfigType(value.Value.GetType()); // If it is a node, add it to the node if (type == ConfigType.Node) { ConfigNode valueNode = targetNode.AddNode(Tools.FormatParsable(value.Key)); WriteToConfig(value.Value, ref valueNode); } else { targetNode.AddValue(Tools.FormatParsable(value.Key), Tools.FormatParsable(value.Value)); } } } else if (typeof(IList).IsAssignableFrom(memberType)) { // Is the dictionary null? if (!(Tools.GetValue(memberInfo, reference) is IList list)) { return; } // Create the new ConfigNode ConfigNode targetNode = null; // Iterate over the elements of the list foreach (Object value in list) { // Null-Check if (value == null) { continue; } // Create the node if necessary if (targetNode == null) { targetNode = node; if (parserTarget.FieldName != "self") { // Get a description String description = Tools.GetDescription(memberInfo); // Add it to the config targetNode = String.IsNullOrEmpty(description) ? node.AddNode(parserTarget.FieldName) : node.AddNode(parserTarget.FieldName, description); } } // Figure out the config type of type ConfigType type = Tools.GetConfigType(value.GetType()); // If it is a node, add it to the node if (type == ConfigType.Node) { String name = "Value"; switch (parserTarget.NameSignificance) { case NameSignificance.Key: name = parserTarget.Key; break; case NameSignificance.Type: name = value.GetType().Name; break; case NameSignificance.None: break; default: throw new ArgumentOutOfRangeException(); } ConfigNode valueNode = targetNode.AddNode(name); WriteToConfig(value, ref valueNode); } else { String name = "value"; switch (parserTarget.NameSignificance) { case NameSignificance.Key: name = parserTarget.Key; break; case NameSignificance.Type: name = value.GetType().Name; break; case NameSignificance.None: break; default: throw new ArgumentOutOfRangeException(); } targetNode.AddValue(name, Tools.FormatParsable(value)); } } } }
public bool Set(ConfigType type, string plugin, string key, object value) { if (!this.IsRegistered(plugin, key)) { return(false); } ConfigType dbType = this.GetType(plugin, key); if (dbType != type) { throw new InvalidCastException("Can't replace type " + dbType.ToString() + " with type " + type.ToString() + " at " + key + "@" + plugin); } if (type == ConfigType.Custom) { throw new ArgumentException("Can not set type Custom!"); } plugin = plugin.ToLower(); key = key.ToLower(); string format; if (!this.Exists(plugin, key)) { format = "INSERT INTO CORE_Settings VALUES ('{0}', '{1}', '{2}', '{3}')"; } else { format = "UPDATE CORE_Settings SET Value = '{3}', Type = '{2}' WHERE Section = '{0}' AND Key = '{1}'"; } try { string valueString; switch (type) { case ConfigType.Color: if (!Regex.Match((string)value, "^[#]?[0-9a-f]{6}$", RegexOptions.IgnoreCase).Success) { return(false); } valueString = (string)value; if (valueString.Length == 7) { valueString = valueString.Substring(1); } break; case ConfigType.String: valueString = (string)value; ConfigurationEntry stringEntry = this.GetEntry(plugin, key); if (stringEntry.Values != null && stringEntry.Values.Length > 0) { List <object> values = new List <object>(stringEntry.Values); if (!values.Contains(value)) { return(false); } } break; case ConfigType.Password: valueString = (string)value; break; case ConfigType.Integer: valueString = ((Int32)value).ToString(); ConfigurationEntry intEntry = this.GetEntry(plugin, key); bool result = (intEntry.Values.Length < 1); foreach (object intEntryValue in intEntry.Values) { try { if ((Int32)intEntryValue == (Int32)value) { result = true; } } catch { } } if (!result) { return(false); } break; case ConfigType.Boolean: valueString = "false"; if ((Boolean)value) { valueString = "true"; } break; case ConfigType.Date: valueString = TimeStamp.FromDateTime((DateTime)value).ToString(); break; case ConfigType.Time: valueString = ((TimeSpan)value).Ticks.ToString(); break; case ConfigType.Dimension: valueString = ((Server)value).ToString(); break; case ConfigType.Username: if (this.Parent.GetUserID((string)value) < 1) { return(false); } valueString = (string)value; break; default: return(false); } string query = string.Format(format, Config.EscapeString(plugin), Config.EscapeString(key), type.ToString(), Config.EscapeString(valueString)); if (this.Config.ExecuteNonQuery(query) > 0) { ConfigurationChangedArgs args = new ConfigurationChangedArgs(type, plugin, key, value); this.Parent.Events.OnConfigurationChanged(this.Parent, args); return(true); } } catch { } return(false); }
public object Get(ConfigType type, string plugin, string key, object defaultValue) { if (!this.IsRegistered(plugin, key)) { return(defaultValue); } ConfigType dbType = this.GetType(plugin, key); bool exists = this.Exists(plugin, key); if (dbType != type) { throw new InvalidCastException("Can't lookup type " + type.ToString() + " because it's registered as " + dbType.ToString() + " at " + key + "@" + plugin); } if (type == ConfigType.Custom) { throw new ArgumentException("Can not get type Custom!"); } if (!exists) { lock (this.ConfigurationEntries) if (this.ConfigurationEntries[plugin.ToLower()][key.ToLower()].Type != type) { throw new InvalidCastException(); } else { return(this.ConfigurationEntries[plugin.ToLower()][key.ToLower()].DefaultValue); } } plugin = Config.EscapeString(plugin.ToLower()); key = Config.EscapeString(key.ToLower()); object result = null; try { using (IDbCommand command = this.Config.Connection.CreateCommand()) { command.CommandText = "SELECT Value FROM CORE_Settings WHERE Section = '" + plugin + "' AND Key = '" + key + "'"; IDataReader reader = command.ExecuteReader(); if (reader.Read()) { switch (type) { case ConfigType.String: case ConfigType.Username: case ConfigType.Color: case ConfigType.Password: result = reader.GetString(0); break; case ConfigType.Integer: result = (Int32)reader.GetInt64(0); break; case ConfigType.Boolean: result = false; if (reader.GetString(0).ToLower() == "true") { result = true; } break; case ConfigType.Date: result = TimeStamp.ToDateTime(reader.GetInt64(0)); break; case ConfigType.Time: result = new TimeSpan(reader.GetInt64(0)); break; case ConfigType.Dimension: result = (Server)Enum.Parse(typeof(Server), reader.GetString(0)); break; } } reader.Close(); } } catch { return(defaultValue); } return(result); }
public Task <ConfigEntity> GetByKeyWithLike(string key, ConfigType type = ConfigType.Custom) { return(Db.Find(m => m.Key.Contains(key) && m.Type == type).FirstAsync()); }
public void SetConfigType(ConfigType type) { this.ConfigType = type; }